xref: /freebsd/sys/ufs/ffs/ffs_softdep.c (revision d65cd7a57bf0600b722afc770838a5d0c1c3a8e1)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright 1998, 2000 Marshall Kirk McKusick.
5  * Copyright 2009, 2010 Jeffrey W. Roberson <jeff@FreeBSD.org>
6  * All rights reserved.
7  *
8  * The soft updates code is derived from the appendix of a University
9  * of Michigan technical report (Gregory R. Ganger and Yale N. Patt,
10  * "Soft Updates: A Solution to the Metadata Update Problem in File
11  * Systems", CSE-TR-254-95, August 1995).
12  *
13  * Further information about soft updates can be obtained from:
14  *
15  *	Marshall Kirk McKusick		http://www.mckusick.com/softdep/
16  *	1614 Oxford Street		mckusick@mckusick.com
17  *	Berkeley, CA 94709-1608		+1-510-843-9542
18  *	USA
19  *
20  * Redistribution and use in source and binary forms, with or without
21  * modification, are permitted provided that the following conditions
22  * are met:
23  *
24  * 1. Redistributions of source code must retain the above copyright
25  *    notice, this list of conditions and the following disclaimer.
26  * 2. Redistributions in binary form must reproduce the above copyright
27  *    notice, this list of conditions and the following disclaimer in the
28  *    documentation and/or other materials provided with the distribution.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
31  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33  * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
34  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
35  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
36  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
37  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
38  * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
39  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40  *
41  *	from: @(#)ffs_softdep.c	9.59 (McKusick) 6/21/00
42  */
43 
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
46 
47 #include "opt_ffs.h"
48 #include "opt_quota.h"
49 #include "opt_ddb.h"
50 
51 #include <sys/param.h>
52 #include <sys/kernel.h>
53 #include <sys/systm.h>
54 #include <sys/bio.h>
55 #include <sys/buf.h>
56 #include <sys/kdb.h>
57 #include <sys/kthread.h>
58 #include <sys/ktr.h>
59 #include <sys/limits.h>
60 #include <sys/lock.h>
61 #include <sys/malloc.h>
62 #include <sys/mount.h>
63 #include <sys/mutex.h>
64 #include <sys/namei.h>
65 #include <sys/priv.h>
66 #include <sys/proc.h>
67 #include <sys/racct.h>
68 #include <sys/rwlock.h>
69 #include <sys/stat.h>
70 #include <sys/sysctl.h>
71 #include <sys/syslog.h>
72 #include <sys/vnode.h>
73 #include <sys/conf.h>
74 
75 #include <ufs/ufs/dir.h>
76 #include <ufs/ufs/extattr.h>
77 #include <ufs/ufs/quota.h>
78 #include <ufs/ufs/inode.h>
79 #include <ufs/ufs/ufsmount.h>
80 #include <ufs/ffs/fs.h>
81 #include <ufs/ffs/softdep.h>
82 #include <ufs/ffs/ffs_extern.h>
83 #include <ufs/ufs/ufs_extern.h>
84 
85 #include <vm/vm.h>
86 #include <vm/vm_extern.h>
87 #include <vm/vm_object.h>
88 
89 #include <geom/geom.h>
90 #include <geom/geom_vfs.h>
91 
92 #include <ddb/ddb.h>
93 
94 #define	KTR_SUJ	0	/* Define to KTR_SPARE. */
95 
96 #ifndef SOFTUPDATES
97 
98 int
99 softdep_flushfiles(oldmnt, flags, td)
100 	struct mount *oldmnt;
101 	int flags;
102 	struct thread *td;
103 {
104 
105 	panic("softdep_flushfiles called");
106 }
107 
108 int
109 softdep_mount(devvp, mp, fs, cred)
110 	struct vnode *devvp;
111 	struct mount *mp;
112 	struct fs *fs;
113 	struct ucred *cred;
114 {
115 
116 	return (0);
117 }
118 
119 void
120 softdep_initialize()
121 {
122 
123 	return;
124 }
125 
126 void
127 softdep_uninitialize()
128 {
129 
130 	return;
131 }
132 
133 void
134 softdep_unmount(mp)
135 	struct mount *mp;
136 {
137 
138 	panic("softdep_unmount called");
139 }
140 
141 void
142 softdep_setup_sbupdate(ump, fs, bp)
143 	struct ufsmount *ump;
144 	struct fs *fs;
145 	struct buf *bp;
146 {
147 
148 	panic("softdep_setup_sbupdate called");
149 }
150 
151 void
152 softdep_setup_inomapdep(bp, ip, newinum, mode)
153 	struct buf *bp;
154 	struct inode *ip;
155 	ino_t newinum;
156 	int mode;
157 {
158 
159 	panic("softdep_setup_inomapdep called");
160 }
161 
162 void
163 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
164 	struct buf *bp;
165 	struct mount *mp;
166 	ufs2_daddr_t newblkno;
167 	int frags;
168 	int oldfrags;
169 {
170 
171 	panic("softdep_setup_blkmapdep called");
172 }
173 
174 void
175 softdep_setup_allocdirect(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
176 	struct inode *ip;
177 	ufs_lbn_t lbn;
178 	ufs2_daddr_t newblkno;
179 	ufs2_daddr_t oldblkno;
180 	long newsize;
181 	long oldsize;
182 	struct buf *bp;
183 {
184 
185 	panic("softdep_setup_allocdirect called");
186 }
187 
188 void
189 softdep_setup_allocext(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
190 	struct inode *ip;
191 	ufs_lbn_t lbn;
192 	ufs2_daddr_t newblkno;
193 	ufs2_daddr_t oldblkno;
194 	long newsize;
195 	long oldsize;
196 	struct buf *bp;
197 {
198 
199 	panic("softdep_setup_allocext called");
200 }
201 
202 void
203 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
204 	struct inode *ip;
205 	ufs_lbn_t lbn;
206 	struct buf *bp;
207 	int ptrno;
208 	ufs2_daddr_t newblkno;
209 	ufs2_daddr_t oldblkno;
210 	struct buf *nbp;
211 {
212 
213 	panic("softdep_setup_allocindir_page called");
214 }
215 
216 void
217 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
218 	struct buf *nbp;
219 	struct inode *ip;
220 	struct buf *bp;
221 	int ptrno;
222 	ufs2_daddr_t newblkno;
223 {
224 
225 	panic("softdep_setup_allocindir_meta called");
226 }
227 
228 void
229 softdep_journal_freeblocks(ip, cred, length, flags)
230 	struct inode *ip;
231 	struct ucred *cred;
232 	off_t length;
233 	int flags;
234 {
235 
236 	panic("softdep_journal_freeblocks called");
237 }
238 
239 void
240 softdep_journal_fsync(ip)
241 	struct inode *ip;
242 {
243 
244 	panic("softdep_journal_fsync called");
245 }
246 
247 void
248 softdep_setup_freeblocks(ip, length, flags)
249 	struct inode *ip;
250 	off_t length;
251 	int flags;
252 {
253 
254 	panic("softdep_setup_freeblocks called");
255 }
256 
257 void
258 softdep_freefile(pvp, ino, mode)
259 		struct vnode *pvp;
260 		ino_t ino;
261 		int mode;
262 {
263 
264 	panic("softdep_freefile called");
265 }
266 
267 int
268 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
269 	struct buf *bp;
270 	struct inode *dp;
271 	off_t diroffset;
272 	ino_t newinum;
273 	struct buf *newdirbp;
274 	int isnewblk;
275 {
276 
277 	panic("softdep_setup_directory_add called");
278 }
279 
280 void
281 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
282 	struct buf *bp;
283 	struct inode *dp;
284 	caddr_t base;
285 	caddr_t oldloc;
286 	caddr_t newloc;
287 	int entrysize;
288 {
289 
290 	panic("softdep_change_directoryentry_offset called");
291 }
292 
293 void
294 softdep_setup_remove(bp, dp, ip, isrmdir)
295 	struct buf *bp;
296 	struct inode *dp;
297 	struct inode *ip;
298 	int isrmdir;
299 {
300 
301 	panic("softdep_setup_remove called");
302 }
303 
304 void
305 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
306 	struct buf *bp;
307 	struct inode *dp;
308 	struct inode *ip;
309 	ino_t newinum;
310 	int isrmdir;
311 {
312 
313 	panic("softdep_setup_directory_change called");
314 }
315 
316 void
317 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
318 	struct mount *mp;
319 	struct buf *bp;
320 	ufs2_daddr_t blkno;
321 	int frags;
322 	struct workhead *wkhd;
323 {
324 
325 	panic("%s called", __FUNCTION__);
326 }
327 
328 void
329 softdep_setup_inofree(mp, bp, ino, wkhd)
330 	struct mount *mp;
331 	struct buf *bp;
332 	ino_t ino;
333 	struct workhead *wkhd;
334 {
335 
336 	panic("%s called", __FUNCTION__);
337 }
338 
339 void
340 softdep_setup_unlink(dp, ip)
341 	struct inode *dp;
342 	struct inode *ip;
343 {
344 
345 	panic("%s called", __FUNCTION__);
346 }
347 
348 void
349 softdep_setup_link(dp, ip)
350 	struct inode *dp;
351 	struct inode *ip;
352 {
353 
354 	panic("%s called", __FUNCTION__);
355 }
356 
357 void
358 softdep_revert_link(dp, ip)
359 	struct inode *dp;
360 	struct inode *ip;
361 {
362 
363 	panic("%s called", __FUNCTION__);
364 }
365 
366 void
367 softdep_setup_rmdir(dp, ip)
368 	struct inode *dp;
369 	struct inode *ip;
370 {
371 
372 	panic("%s called", __FUNCTION__);
373 }
374 
375 void
376 softdep_revert_rmdir(dp, ip)
377 	struct inode *dp;
378 	struct inode *ip;
379 {
380 
381 	panic("%s called", __FUNCTION__);
382 }
383 
384 void
385 softdep_setup_create(dp, ip)
386 	struct inode *dp;
387 	struct inode *ip;
388 {
389 
390 	panic("%s called", __FUNCTION__);
391 }
392 
393 void
394 softdep_revert_create(dp, ip)
395 	struct inode *dp;
396 	struct inode *ip;
397 {
398 
399 	panic("%s called", __FUNCTION__);
400 }
401 
402 void
403 softdep_setup_mkdir(dp, ip)
404 	struct inode *dp;
405 	struct inode *ip;
406 {
407 
408 	panic("%s called", __FUNCTION__);
409 }
410 
411 void
412 softdep_revert_mkdir(dp, ip)
413 	struct inode *dp;
414 	struct inode *ip;
415 {
416 
417 	panic("%s called", __FUNCTION__);
418 }
419 
420 void
421 softdep_setup_dotdot_link(dp, ip)
422 	struct inode *dp;
423 	struct inode *ip;
424 {
425 
426 	panic("%s called", __FUNCTION__);
427 }
428 
429 int
430 softdep_prealloc(vp, waitok)
431 	struct vnode *vp;
432 	int waitok;
433 {
434 
435 	panic("%s called", __FUNCTION__);
436 }
437 
438 int
439 softdep_journal_lookup(mp, vpp)
440 	struct mount *mp;
441 	struct vnode **vpp;
442 {
443 
444 	return (ENOENT);
445 }
446 
447 void
448 softdep_change_linkcnt(ip)
449 	struct inode *ip;
450 {
451 
452 	panic("softdep_change_linkcnt called");
453 }
454 
455 void
456 softdep_load_inodeblock(ip)
457 	struct inode *ip;
458 {
459 
460 	panic("softdep_load_inodeblock called");
461 }
462 
463 void
464 softdep_update_inodeblock(ip, bp, waitfor)
465 	struct inode *ip;
466 	struct buf *bp;
467 	int waitfor;
468 {
469 
470 	panic("softdep_update_inodeblock called");
471 }
472 
473 int
474 softdep_fsync(vp)
475 	struct vnode *vp;	/* the "in_core" copy of the inode */
476 {
477 
478 	return (0);
479 }
480 
481 void
482 softdep_fsync_mountdev(vp)
483 	struct vnode *vp;
484 {
485 
486 	return;
487 }
488 
489 int
490 softdep_flushworklist(oldmnt, countp, td)
491 	struct mount *oldmnt;
492 	int *countp;
493 	struct thread *td;
494 {
495 
496 	*countp = 0;
497 	return (0);
498 }
499 
500 int
501 softdep_sync_metadata(struct vnode *vp)
502 {
503 
504 	panic("softdep_sync_metadata called");
505 }
506 
507 int
508 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
509 {
510 
511 	panic("softdep_sync_buf called");
512 }
513 
514 int
515 softdep_slowdown(vp)
516 	struct vnode *vp;
517 {
518 
519 	panic("softdep_slowdown called");
520 }
521 
522 int
523 softdep_request_cleanup(fs, vp, cred, resource)
524 	struct fs *fs;
525 	struct vnode *vp;
526 	struct ucred *cred;
527 	int resource;
528 {
529 
530 	return (0);
531 }
532 
533 int
534 softdep_check_suspend(struct mount *mp,
535 		      struct vnode *devvp,
536 		      int softdep_depcnt,
537 		      int softdep_accdepcnt,
538 		      int secondary_writes,
539 		      int secondary_accwrites)
540 {
541 	struct bufobj *bo;
542 	int error;
543 
544 	(void) softdep_depcnt,
545 	(void) softdep_accdepcnt;
546 
547 	bo = &devvp->v_bufobj;
548 	ASSERT_BO_WLOCKED(bo);
549 
550 	MNT_ILOCK(mp);
551 	while (mp->mnt_secondary_writes != 0) {
552 		BO_UNLOCK(bo);
553 		msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
554 		    (PUSER - 1) | PDROP, "secwr", 0);
555 		BO_LOCK(bo);
556 		MNT_ILOCK(mp);
557 	}
558 
559 	/*
560 	 * Reasons for needing more work before suspend:
561 	 * - Dirty buffers on devvp.
562 	 * - Secondary writes occurred after start of vnode sync loop
563 	 */
564 	error = 0;
565 	if (bo->bo_numoutput > 0 ||
566 	    bo->bo_dirty.bv_cnt > 0 ||
567 	    secondary_writes != 0 ||
568 	    mp->mnt_secondary_writes != 0 ||
569 	    secondary_accwrites != mp->mnt_secondary_accwrites)
570 		error = EAGAIN;
571 	BO_UNLOCK(bo);
572 	return (error);
573 }
574 
575 void
576 softdep_get_depcounts(struct mount *mp,
577 		      int *softdepactivep,
578 		      int *softdepactiveaccp)
579 {
580 	(void) mp;
581 	*softdepactivep = 0;
582 	*softdepactiveaccp = 0;
583 }
584 
585 void
586 softdep_buf_append(bp, wkhd)
587 	struct buf *bp;
588 	struct workhead *wkhd;
589 {
590 
591 	panic("softdep_buf_appendwork called");
592 }
593 
594 void
595 softdep_inode_append(ip, cred, wkhd)
596 	struct inode *ip;
597 	struct ucred *cred;
598 	struct workhead *wkhd;
599 {
600 
601 	panic("softdep_inode_appendwork called");
602 }
603 
604 void
605 softdep_freework(wkhd)
606 	struct workhead *wkhd;
607 {
608 
609 	panic("softdep_freework called");
610 }
611 
612 #else
613 
614 FEATURE(softupdates, "FFS soft-updates support");
615 
616 static SYSCTL_NODE(_debug, OID_AUTO, softdep, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
617     "soft updates stats");
618 static SYSCTL_NODE(_debug_softdep, OID_AUTO, total,
619     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
620     "total dependencies allocated");
621 static SYSCTL_NODE(_debug_softdep, OID_AUTO, highuse,
622     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
623     "high use dependencies allocated");
624 static SYSCTL_NODE(_debug_softdep, OID_AUTO, current,
625     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
626     "current dependencies allocated");
627 static SYSCTL_NODE(_debug_softdep, OID_AUTO, write,
628     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
629     "current dependencies written");
630 
631 unsigned long dep_current[D_LAST + 1];
632 unsigned long dep_highuse[D_LAST + 1];
633 unsigned long dep_total[D_LAST + 1];
634 unsigned long dep_write[D_LAST + 1];
635 
636 #define	SOFTDEP_TYPE(type, str, long)					\
637     static MALLOC_DEFINE(M_ ## type, #str, long);			\
638     SYSCTL_ULONG(_debug_softdep_total, OID_AUTO, str, CTLFLAG_RD,	\
639 	&dep_total[D_ ## type], 0, "");					\
640     SYSCTL_ULONG(_debug_softdep_current, OID_AUTO, str, CTLFLAG_RD, 	\
641 	&dep_current[D_ ## type], 0, "");				\
642     SYSCTL_ULONG(_debug_softdep_highuse, OID_AUTO, str, CTLFLAG_RD, 	\
643 	&dep_highuse[D_ ## type], 0, "");				\
644     SYSCTL_ULONG(_debug_softdep_write, OID_AUTO, str, CTLFLAG_RD, 	\
645 	&dep_write[D_ ## type], 0, "");
646 
647 SOFTDEP_TYPE(PAGEDEP, pagedep, "File page dependencies");
648 SOFTDEP_TYPE(INODEDEP, inodedep, "Inode dependencies");
649 SOFTDEP_TYPE(BMSAFEMAP, bmsafemap,
650     "Block or frag allocated from cyl group map");
651 SOFTDEP_TYPE(NEWBLK, newblk, "New block or frag allocation dependency");
652 SOFTDEP_TYPE(ALLOCDIRECT, allocdirect, "Block or frag dependency for an inode");
653 SOFTDEP_TYPE(INDIRDEP, indirdep, "Indirect block dependencies");
654 SOFTDEP_TYPE(ALLOCINDIR, allocindir, "Block dependency for an indirect block");
655 SOFTDEP_TYPE(FREEFRAG, freefrag, "Previously used frag for an inode");
656 SOFTDEP_TYPE(FREEBLKS, freeblks, "Blocks freed from an inode");
657 SOFTDEP_TYPE(FREEFILE, freefile, "Inode deallocated");
658 SOFTDEP_TYPE(DIRADD, diradd, "New directory entry");
659 SOFTDEP_TYPE(MKDIR, mkdir, "New directory");
660 SOFTDEP_TYPE(DIRREM, dirrem, "Directory entry deleted");
661 SOFTDEP_TYPE(NEWDIRBLK, newdirblk, "Unclaimed new directory block");
662 SOFTDEP_TYPE(FREEWORK, freework, "free an inode block");
663 SOFTDEP_TYPE(FREEDEP, freedep, "track a block free");
664 SOFTDEP_TYPE(JADDREF, jaddref, "Journal inode ref add");
665 SOFTDEP_TYPE(JREMREF, jremref, "Journal inode ref remove");
666 SOFTDEP_TYPE(JMVREF, jmvref, "Journal inode ref move");
667 SOFTDEP_TYPE(JNEWBLK, jnewblk, "Journal new block");
668 SOFTDEP_TYPE(JFREEBLK, jfreeblk, "Journal free block");
669 SOFTDEP_TYPE(JFREEFRAG, jfreefrag, "Journal free frag");
670 SOFTDEP_TYPE(JSEG, jseg, "Journal segment");
671 SOFTDEP_TYPE(JSEGDEP, jsegdep, "Journal segment complete");
672 SOFTDEP_TYPE(SBDEP, sbdep, "Superblock write dependency");
673 SOFTDEP_TYPE(JTRUNC, jtrunc, "Journal inode truncation");
674 SOFTDEP_TYPE(JFSYNC, jfsync, "Journal fsync complete");
675 
676 static MALLOC_DEFINE(M_SENTINEL, "sentinel", "Worklist sentinel");
677 
678 static MALLOC_DEFINE(M_SAVEDINO, "savedino", "Saved inodes");
679 static MALLOC_DEFINE(M_JBLOCKS, "jblocks", "Journal block locations");
680 static MALLOC_DEFINE(M_MOUNTDATA, "softdep", "Softdep per-mount data");
681 
682 #define M_SOFTDEP_FLAGS	(M_WAITOK)
683 
684 /*
685  * translate from workitem type to memory type
686  * MUST match the defines above, such that memtype[D_XXX] == M_XXX
687  */
688 static struct malloc_type *memtype[] = {
689 	NULL,
690 	M_PAGEDEP,
691 	M_INODEDEP,
692 	M_BMSAFEMAP,
693 	M_NEWBLK,
694 	M_ALLOCDIRECT,
695 	M_INDIRDEP,
696 	M_ALLOCINDIR,
697 	M_FREEFRAG,
698 	M_FREEBLKS,
699 	M_FREEFILE,
700 	M_DIRADD,
701 	M_MKDIR,
702 	M_DIRREM,
703 	M_NEWDIRBLK,
704 	M_FREEWORK,
705 	M_FREEDEP,
706 	M_JADDREF,
707 	M_JREMREF,
708 	M_JMVREF,
709 	M_JNEWBLK,
710 	M_JFREEBLK,
711 	M_JFREEFRAG,
712 	M_JSEG,
713 	M_JSEGDEP,
714 	M_SBDEP,
715 	M_JTRUNC,
716 	M_JFSYNC,
717 	M_SENTINEL
718 };
719 
720 #define DtoM(type) (memtype[type])
721 
722 /*
723  * Names of malloc types.
724  */
725 #define TYPENAME(type)  \
726 	((unsigned)(type) <= D_LAST && (unsigned)(type) >= D_FIRST ? \
727 	memtype[type]->ks_shortdesc : "???")
728 /*
729  * End system adaptation definitions.
730  */
731 
732 #define	DOTDOT_OFFSET	offsetof(struct dirtemplate, dotdot_ino)
733 #define	DOT_OFFSET	offsetof(struct dirtemplate, dot_ino)
734 
735 /*
736  * Internal function prototypes.
737  */
738 static	void check_clear_deps(struct mount *);
739 static	void softdep_error(char *, int);
740 static	int softdep_process_worklist(struct mount *, int);
741 static	int softdep_waitidle(struct mount *, int);
742 static	void drain_output(struct vnode *);
743 static	struct buf *getdirtybuf(struct buf *, struct rwlock *, int);
744 static	int check_inodedep_free(struct inodedep *);
745 static	void clear_remove(struct mount *);
746 static	void clear_inodedeps(struct mount *);
747 static	void unlinked_inodedep(struct mount *, struct inodedep *);
748 static	void clear_unlinked_inodedep(struct inodedep *);
749 static	struct inodedep *first_unlinked_inodedep(struct ufsmount *);
750 static	int flush_pagedep_deps(struct vnode *, struct mount *,
751 	    struct diraddhd *);
752 static	int free_pagedep(struct pagedep *);
753 static	int flush_newblk_dep(struct vnode *, struct mount *, ufs_lbn_t);
754 static	int flush_inodedep_deps(struct vnode *, struct mount *, ino_t);
755 static	int flush_deplist(struct allocdirectlst *, int, int *);
756 static	int sync_cgs(struct mount *, int);
757 static	int handle_written_filepage(struct pagedep *, struct buf *, int);
758 static	int handle_written_sbdep(struct sbdep *, struct buf *);
759 static	void initiate_write_sbdep(struct sbdep *);
760 static	void diradd_inode_written(struct diradd *, struct inodedep *);
761 static	int handle_written_indirdep(struct indirdep *, struct buf *,
762 	    struct buf**, int);
763 static	int handle_written_inodeblock(struct inodedep *, struct buf *, int);
764 static	int jnewblk_rollforward(struct jnewblk *, struct fs *, struct cg *,
765 	    uint8_t *);
766 static	int handle_written_bmsafemap(struct bmsafemap *, struct buf *, int);
767 static	void handle_written_jaddref(struct jaddref *);
768 static	void handle_written_jremref(struct jremref *);
769 static	void handle_written_jseg(struct jseg *, struct buf *);
770 static	void handle_written_jnewblk(struct jnewblk *);
771 static	void handle_written_jblkdep(struct jblkdep *);
772 static	void handle_written_jfreefrag(struct jfreefrag *);
773 static	void complete_jseg(struct jseg *);
774 static	void complete_jsegs(struct jseg *);
775 static	void jseg_write(struct ufsmount *ump, struct jseg *, uint8_t *);
776 static	void jaddref_write(struct jaddref *, struct jseg *, uint8_t *);
777 static	void jremref_write(struct jremref *, struct jseg *, uint8_t *);
778 static	void jmvref_write(struct jmvref *, struct jseg *, uint8_t *);
779 static	void jtrunc_write(struct jtrunc *, struct jseg *, uint8_t *);
780 static	void jfsync_write(struct jfsync *, struct jseg *, uint8_t *data);
781 static	void jnewblk_write(struct jnewblk *, struct jseg *, uint8_t *);
782 static	void jfreeblk_write(struct jfreeblk *, struct jseg *, uint8_t *);
783 static	void jfreefrag_write(struct jfreefrag *, struct jseg *, uint8_t *);
784 static	inline void inoref_write(struct inoref *, struct jseg *,
785 	    struct jrefrec *);
786 static	void handle_allocdirect_partdone(struct allocdirect *,
787 	    struct workhead *);
788 static	struct jnewblk *cancel_newblk(struct newblk *, struct worklist *,
789 	    struct workhead *);
790 static	void indirdep_complete(struct indirdep *);
791 static	int indirblk_lookup(struct mount *, ufs2_daddr_t);
792 static	void indirblk_insert(struct freework *);
793 static	void indirblk_remove(struct freework *);
794 static	void handle_allocindir_partdone(struct allocindir *);
795 static	void initiate_write_filepage(struct pagedep *, struct buf *);
796 static	void initiate_write_indirdep(struct indirdep*, struct buf *);
797 static	void handle_written_mkdir(struct mkdir *, int);
798 static	int jnewblk_rollback(struct jnewblk *, struct fs *, struct cg *,
799 	    uint8_t *);
800 static	void initiate_write_bmsafemap(struct bmsafemap *, struct buf *);
801 static	void initiate_write_inodeblock_ufs1(struct inodedep *, struct buf *);
802 static	void initiate_write_inodeblock_ufs2(struct inodedep *, struct buf *);
803 static	void handle_workitem_freefile(struct freefile *);
804 static	int handle_workitem_remove(struct dirrem *, int);
805 static	struct dirrem *newdirrem(struct buf *, struct inode *,
806 	    struct inode *, int, struct dirrem **);
807 static	struct indirdep *indirdep_lookup(struct mount *, struct inode *,
808 	    struct buf *);
809 static	void cancel_indirdep(struct indirdep *, struct buf *,
810 	    struct freeblks *);
811 static	void free_indirdep(struct indirdep *);
812 static	void free_diradd(struct diradd *, struct workhead *);
813 static	void merge_diradd(struct inodedep *, struct diradd *);
814 static	void complete_diradd(struct diradd *);
815 static	struct diradd *diradd_lookup(struct pagedep *, int);
816 static	struct jremref *cancel_diradd_dotdot(struct inode *, struct dirrem *,
817 	    struct jremref *);
818 static	struct jremref *cancel_mkdir_dotdot(struct inode *, struct dirrem *,
819 	    struct jremref *);
820 static	void cancel_diradd(struct diradd *, struct dirrem *, struct jremref *,
821 	    struct jremref *, struct jremref *);
822 static	void dirrem_journal(struct dirrem *, struct jremref *, struct jremref *,
823 	    struct jremref *);
824 static	void cancel_allocindir(struct allocindir *, struct buf *bp,
825 	    struct freeblks *, int);
826 static	int setup_trunc_indir(struct freeblks *, struct inode *,
827 	    ufs_lbn_t, ufs_lbn_t, ufs2_daddr_t);
828 static	void complete_trunc_indir(struct freework *);
829 static	void trunc_indirdep(struct indirdep *, struct freeblks *, struct buf *,
830 	    int);
831 static	void complete_mkdir(struct mkdir *);
832 static	void free_newdirblk(struct newdirblk *);
833 static	void free_jremref(struct jremref *);
834 static	void free_jaddref(struct jaddref *);
835 static	void free_jsegdep(struct jsegdep *);
836 static	void free_jsegs(struct jblocks *);
837 static	void rele_jseg(struct jseg *);
838 static	void free_jseg(struct jseg *, struct jblocks *);
839 static	void free_jnewblk(struct jnewblk *);
840 static	void free_jblkdep(struct jblkdep *);
841 static	void free_jfreefrag(struct jfreefrag *);
842 static	void free_freedep(struct freedep *);
843 static	void journal_jremref(struct dirrem *, struct jremref *,
844 	    struct inodedep *);
845 static	void cancel_jnewblk(struct jnewblk *, struct workhead *);
846 static	int cancel_jaddref(struct jaddref *, struct inodedep *,
847 	    struct workhead *);
848 static	void cancel_jfreefrag(struct jfreefrag *);
849 static	inline void setup_freedirect(struct freeblks *, struct inode *,
850 	    int, int);
851 static	inline void setup_freeext(struct freeblks *, struct inode *, int, int);
852 static	inline void setup_freeindir(struct freeblks *, struct inode *, int,
853 	    ufs_lbn_t, int);
854 static	inline struct freeblks *newfreeblks(struct mount *, struct inode *);
855 static	void freeblks_free(struct ufsmount *, struct freeblks *, int);
856 static	void indir_trunc(struct freework *, ufs2_daddr_t, ufs_lbn_t);
857 static	ufs2_daddr_t blkcount(struct fs *, ufs2_daddr_t, off_t);
858 static	int trunc_check_buf(struct buf *, int *, ufs_lbn_t, int, int);
859 static	void trunc_dependencies(struct inode *, struct freeblks *, ufs_lbn_t,
860 	    int, int);
861 static	void trunc_pages(struct inode *, off_t, ufs2_daddr_t, int);
862 static 	int cancel_pagedep(struct pagedep *, struct freeblks *, int);
863 static	int deallocate_dependencies(struct buf *, struct freeblks *, int);
864 static	void newblk_freefrag(struct newblk*);
865 static	void free_newblk(struct newblk *);
866 static	void cancel_allocdirect(struct allocdirectlst *,
867 	    struct allocdirect *, struct freeblks *);
868 static	int check_inode_unwritten(struct inodedep *);
869 static	int free_inodedep(struct inodedep *);
870 static	void freework_freeblock(struct freework *, u_long);
871 static	void freework_enqueue(struct freework *);
872 static	int handle_workitem_freeblocks(struct freeblks *, int);
873 static	int handle_complete_freeblocks(struct freeblks *, int);
874 static	void handle_workitem_indirblk(struct freework *);
875 static	void handle_written_freework(struct freework *);
876 static	void merge_inode_lists(struct allocdirectlst *,struct allocdirectlst *);
877 static	struct worklist *jnewblk_merge(struct worklist *, struct worklist *,
878 	    struct workhead *);
879 static	struct freefrag *setup_allocindir_phase2(struct buf *, struct inode *,
880 	    struct inodedep *, struct allocindir *, ufs_lbn_t);
881 static	struct allocindir *newallocindir(struct inode *, int, ufs2_daddr_t,
882 	    ufs2_daddr_t, ufs_lbn_t);
883 static	void handle_workitem_freefrag(struct freefrag *);
884 static	struct freefrag *newfreefrag(struct inode *, ufs2_daddr_t, long,
885 	    ufs_lbn_t, u_long);
886 static	void allocdirect_merge(struct allocdirectlst *,
887 	    struct allocdirect *, struct allocdirect *);
888 static	struct freefrag *allocindir_merge(struct allocindir *,
889 	    struct allocindir *);
890 static	int bmsafemap_find(struct bmsafemap_hashhead *, int,
891 	    struct bmsafemap **);
892 static	struct bmsafemap *bmsafemap_lookup(struct mount *, struct buf *,
893 	    int cg, struct bmsafemap *);
894 static	int newblk_find(struct newblk_hashhead *, ufs2_daddr_t, int,
895 	    struct newblk **);
896 static	int newblk_lookup(struct mount *, ufs2_daddr_t, int, struct newblk **);
897 static	int inodedep_find(struct inodedep_hashhead *, ino_t,
898 	    struct inodedep **);
899 static	int inodedep_lookup(struct mount *, ino_t, int, struct inodedep **);
900 static	int pagedep_lookup(struct mount *, struct buf *bp, ino_t, ufs_lbn_t,
901 	    int, struct pagedep **);
902 static	int pagedep_find(struct pagedep_hashhead *, ino_t, ufs_lbn_t,
903 	    struct pagedep **);
904 static	void pause_timer(void *);
905 static	int request_cleanup(struct mount *, int);
906 static	int softdep_request_cleanup_flush(struct mount *, struct ufsmount *);
907 static	void schedule_cleanup(struct mount *);
908 static void softdep_ast_cleanup_proc(struct thread *);
909 static struct ufsmount *softdep_bp_to_mp(struct buf *bp);
910 static	int process_worklist_item(struct mount *, int, int);
911 static	void process_removes(struct vnode *);
912 static	void process_truncates(struct vnode *);
913 static	void jwork_move(struct workhead *, struct workhead *);
914 static	void jwork_insert(struct workhead *, struct jsegdep *);
915 static	void add_to_worklist(struct worklist *, int);
916 static	void wake_worklist(struct worklist *);
917 static	void wait_worklist(struct worklist *, char *);
918 static	void remove_from_worklist(struct worklist *);
919 static	void softdep_flush(void *);
920 static	void softdep_flushjournal(struct mount *);
921 static	int softdep_speedup(struct ufsmount *);
922 static	void worklist_speedup(struct mount *);
923 static	int journal_mount(struct mount *, struct fs *, struct ucred *);
924 static	void journal_unmount(struct ufsmount *);
925 static	int journal_space(struct ufsmount *, int);
926 static	void journal_suspend(struct ufsmount *);
927 static	int journal_unsuspend(struct ufsmount *ump);
928 static	void softdep_prelink(struct vnode *, struct vnode *);
929 static	void add_to_journal(struct worklist *);
930 static	void remove_from_journal(struct worklist *);
931 static	bool softdep_excess_items(struct ufsmount *, int);
932 static	void softdep_process_journal(struct mount *, struct worklist *, int);
933 static	struct jremref *newjremref(struct dirrem *, struct inode *,
934 	    struct inode *ip, off_t, nlink_t);
935 static	struct jaddref *newjaddref(struct inode *, ino_t, off_t, int16_t,
936 	    uint16_t);
937 static	inline void newinoref(struct inoref *, ino_t, ino_t, off_t, nlink_t,
938 	    uint16_t);
939 static	inline struct jsegdep *inoref_jseg(struct inoref *);
940 static	struct jmvref *newjmvref(struct inode *, ino_t, off_t, off_t);
941 static	struct jfreeblk *newjfreeblk(struct freeblks *, ufs_lbn_t,
942 	    ufs2_daddr_t, int);
943 static	void adjust_newfreework(struct freeblks *, int);
944 static	struct jtrunc *newjtrunc(struct freeblks *, off_t, int);
945 static	void move_newblock_dep(struct jaddref *, struct inodedep *);
946 static	void cancel_jfreeblk(struct freeblks *, ufs2_daddr_t);
947 static	struct jfreefrag *newjfreefrag(struct freefrag *, struct inode *,
948 	    ufs2_daddr_t, long, ufs_lbn_t);
949 static	struct freework *newfreework(struct ufsmount *, struct freeblks *,
950 	    struct freework *, ufs_lbn_t, ufs2_daddr_t, int, int, int);
951 static	int jwait(struct worklist *, int);
952 static	struct inodedep *inodedep_lookup_ip(struct inode *);
953 static	int bmsafemap_backgroundwrite(struct bmsafemap *, struct buf *);
954 static	struct freefile *handle_bufwait(struct inodedep *, struct workhead *);
955 static	void handle_jwork(struct workhead *);
956 static	struct mkdir *setup_newdir(struct diradd *, ino_t, ino_t, struct buf *,
957 	    struct mkdir **);
958 static	struct jblocks *jblocks_create(void);
959 static	ufs2_daddr_t jblocks_alloc(struct jblocks *, int, int *);
960 static	void jblocks_free(struct jblocks *, struct mount *, int);
961 static	void jblocks_destroy(struct jblocks *);
962 static	void jblocks_add(struct jblocks *, ufs2_daddr_t, int);
963 
964 /*
965  * Exported softdep operations.
966  */
967 static	void softdep_disk_io_initiation(struct buf *);
968 static	void softdep_disk_write_complete(struct buf *);
969 static	void softdep_deallocate_dependencies(struct buf *);
970 static	int softdep_count_dependencies(struct buf *bp, int);
971 
972 /*
973  * Global lock over all of soft updates.
974  */
975 static struct mtx lk;
976 MTX_SYSINIT(softdep_lock, &lk, "global softdep", MTX_DEF);
977 
978 #define ACQUIRE_GBLLOCK(lk)	mtx_lock(lk)
979 #define FREE_GBLLOCK(lk)	mtx_unlock(lk)
980 #define GBLLOCK_OWNED(lk)	mtx_assert((lk), MA_OWNED)
981 
982 /*
983  * Per-filesystem soft-updates locking.
984  */
985 #define LOCK_PTR(ump)		(&(ump)->um_softdep->sd_fslock)
986 #define TRY_ACQUIRE_LOCK(ump)	rw_try_wlock(&(ump)->um_softdep->sd_fslock)
987 #define ACQUIRE_LOCK(ump)	rw_wlock(&(ump)->um_softdep->sd_fslock)
988 #define FREE_LOCK(ump)		rw_wunlock(&(ump)->um_softdep->sd_fslock)
989 #define LOCK_OWNED(ump)		rw_assert(&(ump)->um_softdep->sd_fslock, \
990 				    RA_WLOCKED)
991 
992 #define	BUF_AREC(bp)		lockallowrecurse(&(bp)->b_lock)
993 #define	BUF_NOREC(bp)		lockdisablerecurse(&(bp)->b_lock)
994 
995 /*
996  * Worklist queue management.
997  * These routines require that the lock be held.
998  */
999 #ifndef /* NOT */ INVARIANTS
1000 #define WORKLIST_INSERT(head, item) do {	\
1001 	(item)->wk_state |= ONWORKLIST;		\
1002 	LIST_INSERT_HEAD(head, item, wk_list);	\
1003 } while (0)
1004 #define WORKLIST_REMOVE(item) do {		\
1005 	(item)->wk_state &= ~ONWORKLIST;	\
1006 	LIST_REMOVE(item, wk_list);		\
1007 } while (0)
1008 #define WORKLIST_INSERT_UNLOCKED	WORKLIST_INSERT
1009 #define WORKLIST_REMOVE_UNLOCKED	WORKLIST_REMOVE
1010 
1011 #else /* INVARIANTS */
1012 static	void worklist_insert(struct workhead *, struct worklist *, int,
1013 	const char *, int);
1014 static	void worklist_remove(struct worklist *, int, const char *, int);
1015 
1016 #define WORKLIST_INSERT(head, item) \
1017 	worklist_insert(head, item, 1, __func__, __LINE__)
1018 #define WORKLIST_INSERT_UNLOCKED(head, item)\
1019 	worklist_insert(head, item, 0, __func__, __LINE__)
1020 #define WORKLIST_REMOVE(item)\
1021 	worklist_remove(item, 1, __func__, __LINE__)
1022 #define WORKLIST_REMOVE_UNLOCKED(item)\
1023 	worklist_remove(item, 0, __func__, __LINE__)
1024 
1025 static void
1026 worklist_insert(head, item, locked, func, line)
1027 	struct workhead *head;
1028 	struct worklist *item;
1029 	int locked;
1030 	const char *func;
1031 	int line;
1032 {
1033 
1034 	if (locked)
1035 		LOCK_OWNED(VFSTOUFS(item->wk_mp));
1036 	if (item->wk_state & ONWORKLIST)
1037 		panic("worklist_insert: %p %s(0x%X) already on list, "
1038 		    "added in function %s at line %d",
1039 		    item, TYPENAME(item->wk_type), item->wk_state,
1040 		    item->wk_func, item->wk_line);
1041 	item->wk_state |= ONWORKLIST;
1042 	item->wk_func = func;
1043 	item->wk_line = line;
1044 	LIST_INSERT_HEAD(head, item, wk_list);
1045 }
1046 
1047 static void
1048 worklist_remove(item, locked, func, line)
1049 	struct worklist *item;
1050 	int locked;
1051 	const char *func;
1052 	int line;
1053 {
1054 
1055 	if (locked)
1056 		LOCK_OWNED(VFSTOUFS(item->wk_mp));
1057 	if ((item->wk_state & ONWORKLIST) == 0)
1058 		panic("worklist_remove: %p %s(0x%X) not on list, "
1059 		    "removed in function %s at line %d",
1060 		    item, TYPENAME(item->wk_type), item->wk_state,
1061 		    item->wk_func, item->wk_line);
1062 	item->wk_state &= ~ONWORKLIST;
1063 	item->wk_func = func;
1064 	item->wk_line = line;
1065 	LIST_REMOVE(item, wk_list);
1066 }
1067 #endif /* INVARIANTS */
1068 
1069 /*
1070  * Merge two jsegdeps keeping only the oldest one as newer references
1071  * can't be discarded until after older references.
1072  */
1073 static inline struct jsegdep *
1074 jsegdep_merge(struct jsegdep *one, struct jsegdep *two)
1075 {
1076 	struct jsegdep *swp;
1077 
1078 	if (two == NULL)
1079 		return (one);
1080 
1081 	if (one->jd_seg->js_seq > two->jd_seg->js_seq) {
1082 		swp = one;
1083 		one = two;
1084 		two = swp;
1085 	}
1086 	WORKLIST_REMOVE(&two->jd_list);
1087 	free_jsegdep(two);
1088 
1089 	return (one);
1090 }
1091 
1092 /*
1093  * If two freedeps are compatible free one to reduce list size.
1094  */
1095 static inline struct freedep *
1096 freedep_merge(struct freedep *one, struct freedep *two)
1097 {
1098 	if (two == NULL)
1099 		return (one);
1100 
1101 	if (one->fd_freework == two->fd_freework) {
1102 		WORKLIST_REMOVE(&two->fd_list);
1103 		free_freedep(two);
1104 	}
1105 	return (one);
1106 }
1107 
1108 /*
1109  * Move journal work from one list to another.  Duplicate freedeps and
1110  * jsegdeps are coalesced to keep the lists as small as possible.
1111  */
1112 static void
1113 jwork_move(dst, src)
1114 	struct workhead *dst;
1115 	struct workhead *src;
1116 {
1117 	struct freedep *freedep;
1118 	struct jsegdep *jsegdep;
1119 	struct worklist *wkn;
1120 	struct worklist *wk;
1121 
1122 	KASSERT(dst != src,
1123 	    ("jwork_move: dst == src"));
1124 	freedep = NULL;
1125 	jsegdep = NULL;
1126 	LIST_FOREACH_SAFE(wk, dst, wk_list, wkn) {
1127 		if (wk->wk_type == D_JSEGDEP)
1128 			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1129 		else if (wk->wk_type == D_FREEDEP)
1130 			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1131 	}
1132 
1133 	while ((wk = LIST_FIRST(src)) != NULL) {
1134 		WORKLIST_REMOVE(wk);
1135 		WORKLIST_INSERT(dst, wk);
1136 		if (wk->wk_type == D_JSEGDEP) {
1137 			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1138 			continue;
1139 		}
1140 		if (wk->wk_type == D_FREEDEP)
1141 			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1142 	}
1143 }
1144 
1145 static void
1146 jwork_insert(dst, jsegdep)
1147 	struct workhead *dst;
1148 	struct jsegdep *jsegdep;
1149 {
1150 	struct jsegdep *jsegdepn;
1151 	struct worklist *wk;
1152 
1153 	LIST_FOREACH(wk, dst, wk_list)
1154 		if (wk->wk_type == D_JSEGDEP)
1155 			break;
1156 	if (wk == NULL) {
1157 		WORKLIST_INSERT(dst, &jsegdep->jd_list);
1158 		return;
1159 	}
1160 	jsegdepn = WK_JSEGDEP(wk);
1161 	if (jsegdep->jd_seg->js_seq < jsegdepn->jd_seg->js_seq) {
1162 		WORKLIST_REMOVE(wk);
1163 		free_jsegdep(jsegdepn);
1164 		WORKLIST_INSERT(dst, &jsegdep->jd_list);
1165 	} else
1166 		free_jsegdep(jsegdep);
1167 }
1168 
1169 /*
1170  * Routines for tracking and managing workitems.
1171  */
1172 static	void workitem_free(struct worklist *, int);
1173 static	void workitem_alloc(struct worklist *, int, struct mount *);
1174 static	void workitem_reassign(struct worklist *, int);
1175 
1176 #define	WORKITEM_FREE(item, type) \
1177 	workitem_free((struct worklist *)(item), (type))
1178 #define	WORKITEM_REASSIGN(item, type) \
1179 	workitem_reassign((struct worklist *)(item), (type))
1180 
1181 static void
1182 workitem_free(item, type)
1183 	struct worklist *item;
1184 	int type;
1185 {
1186 	struct ufsmount *ump;
1187 
1188 #ifdef INVARIANTS
1189 	if (item->wk_state & ONWORKLIST)
1190 		panic("workitem_free: %s(0x%X) still on list, "
1191 		    "added in function %s at line %d",
1192 		    TYPENAME(item->wk_type), item->wk_state,
1193 		    item->wk_func, item->wk_line);
1194 	if (item->wk_type != type && type != D_NEWBLK)
1195 		panic("workitem_free: type mismatch %s != %s",
1196 		    TYPENAME(item->wk_type), TYPENAME(type));
1197 #endif
1198 	if (item->wk_state & IOWAITING)
1199 		wakeup(item);
1200 	ump = VFSTOUFS(item->wk_mp);
1201 	LOCK_OWNED(ump);
1202 	KASSERT(ump->softdep_deps > 0,
1203 	    ("workitem_free: %s: softdep_deps going negative",
1204 	    ump->um_fs->fs_fsmnt));
1205 	if (--ump->softdep_deps == 0 && ump->softdep_req)
1206 		wakeup(&ump->softdep_deps);
1207 	KASSERT(dep_current[item->wk_type] > 0,
1208 	    ("workitem_free: %s: dep_current[%s] going negative",
1209 	    ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1210 	KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1211 	    ("workitem_free: %s: softdep_curdeps[%s] going negative",
1212 	    ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1213 	atomic_subtract_long(&dep_current[item->wk_type], 1);
1214 	ump->softdep_curdeps[item->wk_type] -= 1;
1215 #ifdef INVARIANTS
1216 	LIST_REMOVE(item, wk_all);
1217 #endif
1218 	free(item, DtoM(type));
1219 }
1220 
1221 static void
1222 workitem_alloc(item, type, mp)
1223 	struct worklist *item;
1224 	int type;
1225 	struct mount *mp;
1226 {
1227 	struct ufsmount *ump;
1228 
1229 	item->wk_type = type;
1230 	item->wk_mp = mp;
1231 	item->wk_state = 0;
1232 
1233 	ump = VFSTOUFS(mp);
1234 	ACQUIRE_GBLLOCK(&lk);
1235 	dep_current[type]++;
1236 	if (dep_current[type] > dep_highuse[type])
1237 		dep_highuse[type] = dep_current[type];
1238 	dep_total[type]++;
1239 	FREE_GBLLOCK(&lk);
1240 	ACQUIRE_LOCK(ump);
1241 	ump->softdep_curdeps[type] += 1;
1242 	ump->softdep_deps++;
1243 	ump->softdep_accdeps++;
1244 #ifdef INVARIANTS
1245 	LIST_INSERT_HEAD(&ump->softdep_alldeps[type], item, wk_all);
1246 #endif
1247 	FREE_LOCK(ump);
1248 }
1249 
1250 static void
1251 workitem_reassign(item, newtype)
1252 	struct worklist *item;
1253 	int newtype;
1254 {
1255 	struct ufsmount *ump;
1256 
1257 	ump = VFSTOUFS(item->wk_mp);
1258 	LOCK_OWNED(ump);
1259 	KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1260 	    ("workitem_reassign: %s: softdep_curdeps[%s] going negative",
1261 	    VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1262 	ump->softdep_curdeps[item->wk_type] -= 1;
1263 	ump->softdep_curdeps[newtype] += 1;
1264 	KASSERT(dep_current[item->wk_type] > 0,
1265 	    ("workitem_reassign: %s: dep_current[%s] going negative",
1266 	    VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1267 	ACQUIRE_GBLLOCK(&lk);
1268 	dep_current[newtype]++;
1269 	dep_current[item->wk_type]--;
1270 	if (dep_current[newtype] > dep_highuse[newtype])
1271 		dep_highuse[newtype] = dep_current[newtype];
1272 	dep_total[newtype]++;
1273 	FREE_GBLLOCK(&lk);
1274 	item->wk_type = newtype;
1275 }
1276 
1277 /*
1278  * Workitem queue management
1279  */
1280 static int max_softdeps;	/* maximum number of structs before slowdown */
1281 static int tickdelay = 2;	/* number of ticks to pause during slowdown */
1282 static int proc_waiting;	/* tracks whether we have a timeout posted */
1283 static int *stat_countp;	/* statistic to count in proc_waiting timeout */
1284 static struct callout softdep_callout;
1285 static int req_clear_inodedeps;	/* syncer process flush some inodedeps */
1286 static int req_clear_remove;	/* syncer process flush some freeblks */
1287 static int softdep_flushcache = 0; /* Should we do BIO_FLUSH? */
1288 
1289 /*
1290  * runtime statistics
1291  */
1292 static int stat_flush_threads;	/* number of softdep flushing threads */
1293 static int stat_worklist_push;	/* number of worklist cleanups */
1294 static int stat_blk_limit_push;	/* number of times block limit neared */
1295 static int stat_ino_limit_push;	/* number of times inode limit neared */
1296 static int stat_blk_limit_hit;	/* number of times block slowdown imposed */
1297 static int stat_ino_limit_hit;	/* number of times inode slowdown imposed */
1298 static int stat_sync_limit_hit;	/* number of synchronous slowdowns imposed */
1299 static int stat_indir_blk_ptrs;	/* bufs redirtied as indir ptrs not written */
1300 static int stat_inode_bitmap;	/* bufs redirtied as inode bitmap not written */
1301 static int stat_direct_blk_ptrs;/* bufs redirtied as direct ptrs not written */
1302 static int stat_dir_entry;	/* bufs redirtied as dir entry cannot write */
1303 static int stat_jaddref;	/* bufs redirtied as ino bitmap can not write */
1304 static int stat_jnewblk;	/* bufs redirtied as blk bitmap can not write */
1305 static int stat_journal_min;	/* Times hit journal min threshold */
1306 static int stat_journal_low;	/* Times hit journal low threshold */
1307 static int stat_journal_wait;	/* Times blocked in jwait(). */
1308 static int stat_jwait_filepage;	/* Times blocked in jwait() for filepage. */
1309 static int stat_jwait_freeblks;	/* Times blocked in jwait() for freeblks. */
1310 static int stat_jwait_inode;	/* Times blocked in jwait() for inodes. */
1311 static int stat_jwait_newblk;	/* Times blocked in jwait() for newblks. */
1312 static int stat_cleanup_high_delay; /* Maximum cleanup delay (in ticks) */
1313 static int stat_cleanup_blkrequests; /* Number of block cleanup requests */
1314 static int stat_cleanup_inorequests; /* Number of inode cleanup requests */
1315 static int stat_cleanup_retries; /* Number of cleanups that needed to flush */
1316 static int stat_cleanup_failures; /* Number of cleanup requests that failed */
1317 static int stat_emptyjblocks; /* Number of potentially empty journal blocks */
1318 
1319 SYSCTL_INT(_debug_softdep, OID_AUTO, max_softdeps, CTLFLAG_RW,
1320     &max_softdeps, 0, "");
1321 SYSCTL_INT(_debug_softdep, OID_AUTO, tickdelay, CTLFLAG_RW,
1322     &tickdelay, 0, "");
1323 SYSCTL_INT(_debug_softdep, OID_AUTO, flush_threads, CTLFLAG_RD,
1324     &stat_flush_threads, 0, "");
1325 SYSCTL_INT(_debug_softdep, OID_AUTO, worklist_push,
1326     CTLFLAG_RW | CTLFLAG_STATS, &stat_worklist_push, 0,"");
1327 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_push,
1328     CTLFLAG_RW | CTLFLAG_STATS, &stat_blk_limit_push, 0,"");
1329 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_push,
1330     CTLFLAG_RW | CTLFLAG_STATS, &stat_ino_limit_push, 0,"");
1331 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_hit,
1332     CTLFLAG_RW | CTLFLAG_STATS, &stat_blk_limit_hit, 0, "");
1333 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_hit,
1334     CTLFLAG_RW | CTLFLAG_STATS, &stat_ino_limit_hit, 0, "");
1335 SYSCTL_INT(_debug_softdep, OID_AUTO, sync_limit_hit,
1336     CTLFLAG_RW | CTLFLAG_STATS, &stat_sync_limit_hit, 0, "");
1337 SYSCTL_INT(_debug_softdep, OID_AUTO, indir_blk_ptrs,
1338     CTLFLAG_RW | CTLFLAG_STATS, &stat_indir_blk_ptrs, 0, "");
1339 SYSCTL_INT(_debug_softdep, OID_AUTO, inode_bitmap,
1340     CTLFLAG_RW | CTLFLAG_STATS, &stat_inode_bitmap, 0, "");
1341 SYSCTL_INT(_debug_softdep, OID_AUTO, direct_blk_ptrs,
1342     CTLFLAG_RW | CTLFLAG_STATS, &stat_direct_blk_ptrs, 0, "");
1343 SYSCTL_INT(_debug_softdep, OID_AUTO, dir_entry,
1344     CTLFLAG_RW | CTLFLAG_STATS, &stat_dir_entry, 0, "");
1345 SYSCTL_INT(_debug_softdep, OID_AUTO, jaddref_rollback,
1346     CTLFLAG_RW | CTLFLAG_STATS, &stat_jaddref, 0, "");
1347 SYSCTL_INT(_debug_softdep, OID_AUTO, jnewblk_rollback,
1348     CTLFLAG_RW | CTLFLAG_STATS, &stat_jnewblk, 0, "");
1349 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_low,
1350     CTLFLAG_RW | CTLFLAG_STATS, &stat_journal_low, 0, "");
1351 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_min,
1352     CTLFLAG_RW | CTLFLAG_STATS, &stat_journal_min, 0, "");
1353 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_wait,
1354     CTLFLAG_RW | CTLFLAG_STATS, &stat_journal_wait, 0, "");
1355 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_filepage,
1356     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_filepage, 0, "");
1357 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_freeblks,
1358     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_freeblks, 0, "");
1359 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_inode,
1360     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_inode, 0, "");
1361 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_newblk,
1362     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_newblk, 0, "");
1363 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_blkrequests,
1364     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_blkrequests, 0, "");
1365 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_inorequests,
1366     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_inorequests, 0, "");
1367 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_high_delay,
1368     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_high_delay, 0, "");
1369 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_retries,
1370     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_retries, 0, "");
1371 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_failures,
1372     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_failures, 0, "");
1373 
1374 SYSCTL_INT(_debug_softdep, OID_AUTO, flushcache, CTLFLAG_RW,
1375     &softdep_flushcache, 0, "");
1376 SYSCTL_INT(_debug_softdep, OID_AUTO, emptyjblocks, CTLFLAG_RD,
1377     &stat_emptyjblocks, 0, "");
1378 
1379 SYSCTL_DECL(_vfs_ffs);
1380 
1381 /* Whether to recompute the summary at mount time */
1382 static int compute_summary_at_mount = 0;
1383 SYSCTL_INT(_vfs_ffs, OID_AUTO, compute_summary_at_mount, CTLFLAG_RW,
1384 	   &compute_summary_at_mount, 0, "Recompute summary at mount");
1385 static int print_threads = 0;
1386 SYSCTL_INT(_debug_softdep, OID_AUTO, print_threads, CTLFLAG_RW,
1387     &print_threads, 0, "Notify flusher thread start/stop");
1388 
1389 /* List of all filesystems mounted with soft updates */
1390 static TAILQ_HEAD(, mount_softdeps) softdepmounts;
1391 
1392 /*
1393  * This function cleans the worklist for a filesystem.
1394  * Each filesystem running with soft dependencies gets its own
1395  * thread to run in this function. The thread is started up in
1396  * softdep_mount and shutdown in softdep_unmount. They show up
1397  * as part of the kernel "bufdaemon" process whose process
1398  * entry is available in bufdaemonproc.
1399  */
1400 static int searchfailed;
1401 extern struct proc *bufdaemonproc;
1402 static void
1403 softdep_flush(addr)
1404 	void *addr;
1405 {
1406 	struct mount *mp;
1407 	struct thread *td;
1408 	struct ufsmount *ump;
1409 
1410 	td = curthread;
1411 	td->td_pflags |= TDP_NORUNNINGBUF;
1412 	mp = (struct mount *)addr;
1413 	ump = VFSTOUFS(mp);
1414 	atomic_add_int(&stat_flush_threads, 1);
1415 	ACQUIRE_LOCK(ump);
1416 	ump->softdep_flags &= ~FLUSH_STARTING;
1417 	wakeup(&ump->softdep_flushtd);
1418 	FREE_LOCK(ump);
1419 	if (print_threads) {
1420 		if (stat_flush_threads == 1)
1421 			printf("Running %s at pid %d\n", bufdaemonproc->p_comm,
1422 			    bufdaemonproc->p_pid);
1423 		printf("Start thread %s\n", td->td_name);
1424 	}
1425 	for (;;) {
1426 		while (softdep_process_worklist(mp, 0) > 0 ||
1427 		    (MOUNTEDSUJ(mp) &&
1428 		    VFSTOUFS(mp)->softdep_jblocks->jb_suspended))
1429 			kthread_suspend_check();
1430 		ACQUIRE_LOCK(ump);
1431 		if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1432 			msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM,
1433 			    "sdflush", hz / 2);
1434 		ump->softdep_flags &= ~FLUSH_CLEANUP;
1435 		/*
1436 		 * Check to see if we are done and need to exit.
1437 		 */
1438 		if ((ump->softdep_flags & FLUSH_EXIT) == 0) {
1439 			FREE_LOCK(ump);
1440 			continue;
1441 		}
1442 		ump->softdep_flags &= ~FLUSH_EXIT;
1443 		FREE_LOCK(ump);
1444 		wakeup(&ump->softdep_flags);
1445 		if (print_threads)
1446 			printf("Stop thread %s: searchfailed %d, did cleanups %d\n", td->td_name, searchfailed, ump->um_softdep->sd_cleanups);
1447 		atomic_subtract_int(&stat_flush_threads, 1);
1448 		kthread_exit();
1449 		panic("kthread_exit failed\n");
1450 	}
1451 }
1452 
1453 static void
1454 worklist_speedup(mp)
1455 	struct mount *mp;
1456 {
1457 	struct ufsmount *ump;
1458 
1459 	ump = VFSTOUFS(mp);
1460 	LOCK_OWNED(ump);
1461 	if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1462 		ump->softdep_flags |= FLUSH_CLEANUP;
1463 	wakeup(&ump->softdep_flushtd);
1464 }
1465 
1466 static void
1467 softdep_send_speedup(struct ufsmount *ump, size_t shortage, u_int flags)
1468 {
1469 	struct buf *bp;
1470 
1471 	if ((ump->um_flags & UM_CANSPEEDUP) == 0)
1472 		return;
1473 
1474 	bp = malloc(sizeof(*bp), M_TRIM, M_WAITOK | M_ZERO);
1475 	bp->b_iocmd = BIO_SPEEDUP;
1476 	bp->b_ioflags = flags;
1477 	bp->b_bcount = shortage;
1478 	g_vfs_strategy(ump->um_bo, bp);
1479 	bufwait(bp);
1480 	free(bp, M_TRIM);
1481 }
1482 
1483 static int
1484 softdep_speedup(ump)
1485 	struct ufsmount *ump;
1486 {
1487 	struct ufsmount *altump;
1488 	struct mount_softdeps *sdp;
1489 
1490 	LOCK_OWNED(ump);
1491 	worklist_speedup(ump->um_mountp);
1492 	bd_speedup();
1493 	/*
1494 	 * If we have global shortages, then we need other
1495 	 * filesystems to help with the cleanup. Here we wakeup a
1496 	 * flusher thread for a filesystem that is over its fair
1497 	 * share of resources.
1498 	 */
1499 	if (req_clear_inodedeps || req_clear_remove) {
1500 		ACQUIRE_GBLLOCK(&lk);
1501 		TAILQ_FOREACH(sdp, &softdepmounts, sd_next) {
1502 			if ((altump = sdp->sd_ump) == ump)
1503 				continue;
1504 			if (((req_clear_inodedeps &&
1505 			    altump->softdep_curdeps[D_INODEDEP] >
1506 			    max_softdeps / stat_flush_threads) ||
1507 			    (req_clear_remove &&
1508 			    altump->softdep_curdeps[D_DIRREM] >
1509 			    (max_softdeps / 2) / stat_flush_threads)) &&
1510 			    TRY_ACQUIRE_LOCK(altump))
1511 				break;
1512 		}
1513 		if (sdp == NULL) {
1514 			searchfailed++;
1515 			FREE_GBLLOCK(&lk);
1516 		} else {
1517 			/*
1518 			 * Move to the end of the list so we pick a
1519 			 * different one on out next try.
1520 			 */
1521 			TAILQ_REMOVE(&softdepmounts, sdp, sd_next);
1522 			TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
1523 			FREE_GBLLOCK(&lk);
1524 			if ((altump->softdep_flags &
1525 			    (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1526 				altump->softdep_flags |= FLUSH_CLEANUP;
1527 			altump->um_softdep->sd_cleanups++;
1528 			wakeup(&altump->softdep_flushtd);
1529 			FREE_LOCK(altump);
1530 		}
1531 	}
1532 	return (speedup_syncer());
1533 }
1534 
1535 /*
1536  * Add an item to the end of the work queue.
1537  * This routine requires that the lock be held.
1538  * This is the only routine that adds items to the list.
1539  * The following routine is the only one that removes items
1540  * and does so in order from first to last.
1541  */
1542 
1543 #define	WK_HEAD		0x0001	/* Add to HEAD. */
1544 #define	WK_NODELAY	0x0002	/* Process immediately. */
1545 
1546 static void
1547 add_to_worklist(wk, flags)
1548 	struct worklist *wk;
1549 	int flags;
1550 {
1551 	struct ufsmount *ump;
1552 
1553 	ump = VFSTOUFS(wk->wk_mp);
1554 	LOCK_OWNED(ump);
1555 	if (wk->wk_state & ONWORKLIST)
1556 		panic("add_to_worklist: %s(0x%X) already on list",
1557 		    TYPENAME(wk->wk_type), wk->wk_state);
1558 	wk->wk_state |= ONWORKLIST;
1559 	if (ump->softdep_on_worklist == 0) {
1560 		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1561 		ump->softdep_worklist_tail = wk;
1562 	} else if (flags & WK_HEAD) {
1563 		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1564 	} else {
1565 		LIST_INSERT_AFTER(ump->softdep_worklist_tail, wk, wk_list);
1566 		ump->softdep_worklist_tail = wk;
1567 	}
1568 	ump->softdep_on_worklist += 1;
1569 	if (flags & WK_NODELAY)
1570 		worklist_speedup(wk->wk_mp);
1571 }
1572 
1573 /*
1574  * Remove the item to be processed. If we are removing the last
1575  * item on the list, we need to recalculate the tail pointer.
1576  */
1577 static void
1578 remove_from_worklist(wk)
1579 	struct worklist *wk;
1580 {
1581 	struct ufsmount *ump;
1582 
1583 	ump = VFSTOUFS(wk->wk_mp);
1584 	if (ump->softdep_worklist_tail == wk)
1585 		ump->softdep_worklist_tail =
1586 		    (struct worklist *)wk->wk_list.le_prev;
1587 	WORKLIST_REMOVE(wk);
1588 	ump->softdep_on_worklist -= 1;
1589 }
1590 
1591 static void
1592 wake_worklist(wk)
1593 	struct worklist *wk;
1594 {
1595 	if (wk->wk_state & IOWAITING) {
1596 		wk->wk_state &= ~IOWAITING;
1597 		wakeup(wk);
1598 	}
1599 }
1600 
1601 static void
1602 wait_worklist(wk, wmesg)
1603 	struct worklist *wk;
1604 	char *wmesg;
1605 {
1606 	struct ufsmount *ump;
1607 
1608 	ump = VFSTOUFS(wk->wk_mp);
1609 	wk->wk_state |= IOWAITING;
1610 	msleep(wk, LOCK_PTR(ump), PVM, wmesg, 0);
1611 }
1612 
1613 /*
1614  * Process that runs once per second to handle items in the background queue.
1615  *
1616  * Note that we ensure that everything is done in the order in which they
1617  * appear in the queue. The code below depends on this property to ensure
1618  * that blocks of a file are freed before the inode itself is freed. This
1619  * ordering ensures that no new <vfsid, inum, lbn> triples will be generated
1620  * until all the old ones have been purged from the dependency lists.
1621  */
1622 static int
1623 softdep_process_worklist(mp, full)
1624 	struct mount *mp;
1625 	int full;
1626 {
1627 	int cnt, matchcnt;
1628 	struct ufsmount *ump;
1629 	long starttime;
1630 
1631 	KASSERT(mp != NULL, ("softdep_process_worklist: NULL mp"));
1632 	if (MOUNTEDSOFTDEP(mp) == 0)
1633 		return (0);
1634 	matchcnt = 0;
1635 	ump = VFSTOUFS(mp);
1636 	ACQUIRE_LOCK(ump);
1637 	starttime = time_second;
1638 	softdep_process_journal(mp, NULL, full ? MNT_WAIT : 0);
1639 	check_clear_deps(mp);
1640 	while (ump->softdep_on_worklist > 0) {
1641 		if ((cnt = process_worklist_item(mp, 10, LK_NOWAIT)) == 0)
1642 			break;
1643 		else
1644 			matchcnt += cnt;
1645 		check_clear_deps(mp);
1646 		/*
1647 		 * We do not generally want to stop for buffer space, but if
1648 		 * we are really being a buffer hog, we will stop and wait.
1649 		 */
1650 		if (should_yield()) {
1651 			FREE_LOCK(ump);
1652 			kern_yield(PRI_USER);
1653 			bwillwrite();
1654 			ACQUIRE_LOCK(ump);
1655 		}
1656 		/*
1657 		 * Never allow processing to run for more than one
1658 		 * second. This gives the syncer thread the opportunity
1659 		 * to pause if appropriate.
1660 		 */
1661 		if (!full && starttime != time_second)
1662 			break;
1663 	}
1664 	if (full == 0)
1665 		journal_unsuspend(ump);
1666 	FREE_LOCK(ump);
1667 	return (matchcnt);
1668 }
1669 
1670 /*
1671  * Process all removes associated with a vnode if we are running out of
1672  * journal space.  Any other process which attempts to flush these will
1673  * be unable as we have the vnodes locked.
1674  */
1675 static void
1676 process_removes(vp)
1677 	struct vnode *vp;
1678 {
1679 	struct inodedep *inodedep;
1680 	struct dirrem *dirrem;
1681 	struct ufsmount *ump;
1682 	struct mount *mp;
1683 	ino_t inum;
1684 
1685 	mp = vp->v_mount;
1686 	ump = VFSTOUFS(mp);
1687 	LOCK_OWNED(ump);
1688 	inum = VTOI(vp)->i_number;
1689 	for (;;) {
1690 top:
1691 		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1692 			return;
1693 		LIST_FOREACH(dirrem, &inodedep->id_dirremhd, dm_inonext) {
1694 			/*
1695 			 * If another thread is trying to lock this vnode
1696 			 * it will fail but we must wait for it to do so
1697 			 * before we can proceed.
1698 			 */
1699 			if (dirrem->dm_state & INPROGRESS) {
1700 				wait_worklist(&dirrem->dm_list, "pwrwait");
1701 				goto top;
1702 			}
1703 			if ((dirrem->dm_state & (COMPLETE | ONWORKLIST)) ==
1704 			    (COMPLETE | ONWORKLIST))
1705 				break;
1706 		}
1707 		if (dirrem == NULL)
1708 			return;
1709 		remove_from_worklist(&dirrem->dm_list);
1710 		FREE_LOCK(ump);
1711 		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1712 			panic("process_removes: suspended filesystem");
1713 		handle_workitem_remove(dirrem, 0);
1714 		vn_finished_secondary_write(mp);
1715 		ACQUIRE_LOCK(ump);
1716 	}
1717 }
1718 
1719 /*
1720  * Process all truncations associated with a vnode if we are running out
1721  * of journal space.  This is called when the vnode lock is already held
1722  * and no other process can clear the truncation.  This function returns
1723  * a value greater than zero if it did any work.
1724  */
1725 static void
1726 process_truncates(vp)
1727 	struct vnode *vp;
1728 {
1729 	struct inodedep *inodedep;
1730 	struct freeblks *freeblks;
1731 	struct ufsmount *ump;
1732 	struct mount *mp;
1733 	ino_t inum;
1734 	int cgwait;
1735 
1736 	mp = vp->v_mount;
1737 	ump = VFSTOUFS(mp);
1738 	LOCK_OWNED(ump);
1739 	inum = VTOI(vp)->i_number;
1740 	for (;;) {
1741 		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1742 			return;
1743 		cgwait = 0;
1744 		TAILQ_FOREACH(freeblks, &inodedep->id_freeblklst, fb_next) {
1745 			/* Journal entries not yet written.  */
1746 			if (!LIST_EMPTY(&freeblks->fb_jblkdephd)) {
1747 				jwait(&LIST_FIRST(
1748 				    &freeblks->fb_jblkdephd)->jb_list,
1749 				    MNT_WAIT);
1750 				break;
1751 			}
1752 			/* Another thread is executing this item. */
1753 			if (freeblks->fb_state & INPROGRESS) {
1754 				wait_worklist(&freeblks->fb_list, "ptrwait");
1755 				break;
1756 			}
1757 			/* Freeblks is waiting on a inode write. */
1758 			if ((freeblks->fb_state & COMPLETE) == 0) {
1759 				FREE_LOCK(ump);
1760 				ffs_update(vp, 1);
1761 				ACQUIRE_LOCK(ump);
1762 				break;
1763 			}
1764 			if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST)) ==
1765 			    (ALLCOMPLETE | ONWORKLIST)) {
1766 				remove_from_worklist(&freeblks->fb_list);
1767 				freeblks->fb_state |= INPROGRESS;
1768 				FREE_LOCK(ump);
1769 				if (vn_start_secondary_write(NULL, &mp,
1770 				    V_NOWAIT))
1771 					panic("process_truncates: "
1772 					    "suspended filesystem");
1773 				handle_workitem_freeblocks(freeblks, 0);
1774 				vn_finished_secondary_write(mp);
1775 				ACQUIRE_LOCK(ump);
1776 				break;
1777 			}
1778 			if (freeblks->fb_cgwait)
1779 				cgwait++;
1780 		}
1781 		if (cgwait) {
1782 			FREE_LOCK(ump);
1783 			sync_cgs(mp, MNT_WAIT);
1784 			ffs_sync_snap(mp, MNT_WAIT);
1785 			ACQUIRE_LOCK(ump);
1786 			continue;
1787 		}
1788 		if (freeblks == NULL)
1789 			break;
1790 	}
1791 	return;
1792 }
1793 
1794 /*
1795  * Process one item on the worklist.
1796  */
1797 static int
1798 process_worklist_item(mp, target, flags)
1799 	struct mount *mp;
1800 	int target;
1801 	int flags;
1802 {
1803 	struct worklist sentinel;
1804 	struct worklist *wk;
1805 	struct ufsmount *ump;
1806 	int matchcnt;
1807 	int error;
1808 
1809 	KASSERT(mp != NULL, ("process_worklist_item: NULL mp"));
1810 	/*
1811 	 * If we are being called because of a process doing a
1812 	 * copy-on-write, then it is not safe to write as we may
1813 	 * recurse into the copy-on-write routine.
1814 	 */
1815 	if (curthread->td_pflags & TDP_COWINPROGRESS)
1816 		return (-1);
1817 	PHOLD(curproc);	/* Don't let the stack go away. */
1818 	ump = VFSTOUFS(mp);
1819 	LOCK_OWNED(ump);
1820 	matchcnt = 0;
1821 	sentinel.wk_mp = NULL;
1822 	sentinel.wk_type = D_SENTINEL;
1823 	LIST_INSERT_HEAD(&ump->softdep_workitem_pending, &sentinel, wk_list);
1824 	for (wk = LIST_NEXT(&sentinel, wk_list); wk != NULL;
1825 	    wk = LIST_NEXT(&sentinel, wk_list)) {
1826 		if (wk->wk_type == D_SENTINEL) {
1827 			LIST_REMOVE(&sentinel, wk_list);
1828 			LIST_INSERT_AFTER(wk, &sentinel, wk_list);
1829 			continue;
1830 		}
1831 		if (wk->wk_state & INPROGRESS)
1832 			panic("process_worklist_item: %p already in progress.",
1833 			    wk);
1834 		wk->wk_state |= INPROGRESS;
1835 		remove_from_worklist(wk);
1836 		FREE_LOCK(ump);
1837 		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1838 			panic("process_worklist_item: suspended filesystem");
1839 		switch (wk->wk_type) {
1840 		case D_DIRREM:
1841 			/* removal of a directory entry */
1842 			error = handle_workitem_remove(WK_DIRREM(wk), flags);
1843 			break;
1844 
1845 		case D_FREEBLKS:
1846 			/* releasing blocks and/or fragments from a file */
1847 			error = handle_workitem_freeblocks(WK_FREEBLKS(wk),
1848 			    flags);
1849 			break;
1850 
1851 		case D_FREEFRAG:
1852 			/* releasing a fragment when replaced as a file grows */
1853 			handle_workitem_freefrag(WK_FREEFRAG(wk));
1854 			error = 0;
1855 			break;
1856 
1857 		case D_FREEFILE:
1858 			/* releasing an inode when its link count drops to 0 */
1859 			handle_workitem_freefile(WK_FREEFILE(wk));
1860 			error = 0;
1861 			break;
1862 
1863 		default:
1864 			panic("%s_process_worklist: Unknown type %s",
1865 			    "softdep", TYPENAME(wk->wk_type));
1866 			/* NOTREACHED */
1867 		}
1868 		vn_finished_secondary_write(mp);
1869 		ACQUIRE_LOCK(ump);
1870 		if (error == 0) {
1871 			if (++matchcnt == target)
1872 				break;
1873 			continue;
1874 		}
1875 		/*
1876 		 * We have to retry the worklist item later.  Wake up any
1877 		 * waiters who may be able to complete it immediately and
1878 		 * add the item back to the head so we don't try to execute
1879 		 * it again.
1880 		 */
1881 		wk->wk_state &= ~INPROGRESS;
1882 		wake_worklist(wk);
1883 		add_to_worklist(wk, WK_HEAD);
1884 	}
1885 	/* Sentinal could've become the tail from remove_from_worklist. */
1886 	if (ump->softdep_worklist_tail == &sentinel)
1887 		ump->softdep_worklist_tail =
1888 		    (struct worklist *)sentinel.wk_list.le_prev;
1889 	LIST_REMOVE(&sentinel, wk_list);
1890 	PRELE(curproc);
1891 	return (matchcnt);
1892 }
1893 
1894 /*
1895  * Move dependencies from one buffer to another.
1896  */
1897 int
1898 softdep_move_dependencies(oldbp, newbp)
1899 	struct buf *oldbp;
1900 	struct buf *newbp;
1901 {
1902 	struct worklist *wk, *wktail;
1903 	struct ufsmount *ump;
1904 	int dirty;
1905 
1906 	if ((wk = LIST_FIRST(&oldbp->b_dep)) == NULL)
1907 		return (0);
1908 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
1909 	    ("softdep_move_dependencies called on non-softdep filesystem"));
1910 	dirty = 0;
1911 	wktail = NULL;
1912 	ump = VFSTOUFS(wk->wk_mp);
1913 	ACQUIRE_LOCK(ump);
1914 	while ((wk = LIST_FIRST(&oldbp->b_dep)) != NULL) {
1915 		LIST_REMOVE(wk, wk_list);
1916 		if (wk->wk_type == D_BMSAFEMAP &&
1917 		    bmsafemap_backgroundwrite(WK_BMSAFEMAP(wk), newbp))
1918 			dirty = 1;
1919 		if (wktail == NULL)
1920 			LIST_INSERT_HEAD(&newbp->b_dep, wk, wk_list);
1921 		else
1922 			LIST_INSERT_AFTER(wktail, wk, wk_list);
1923 		wktail = wk;
1924 	}
1925 	FREE_LOCK(ump);
1926 
1927 	return (dirty);
1928 }
1929 
1930 /*
1931  * Purge the work list of all items associated with a particular mount point.
1932  */
1933 int
1934 softdep_flushworklist(oldmnt, countp, td)
1935 	struct mount *oldmnt;
1936 	int *countp;
1937 	struct thread *td;
1938 {
1939 	struct vnode *devvp;
1940 	struct ufsmount *ump;
1941 	int count, error;
1942 
1943 	/*
1944 	 * Alternately flush the block device associated with the mount
1945 	 * point and process any dependencies that the flushing
1946 	 * creates. We continue until no more worklist dependencies
1947 	 * are found.
1948 	 */
1949 	*countp = 0;
1950 	error = 0;
1951 	ump = VFSTOUFS(oldmnt);
1952 	devvp = ump->um_devvp;
1953 	while ((count = softdep_process_worklist(oldmnt, 1)) > 0) {
1954 		*countp += count;
1955 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1956 		error = VOP_FSYNC(devvp, MNT_WAIT, td);
1957 		VOP_UNLOCK(devvp);
1958 		if (error != 0)
1959 			break;
1960 	}
1961 	return (error);
1962 }
1963 
1964 #define	SU_WAITIDLE_RETRIES	20
1965 static int
1966 softdep_waitidle(struct mount *mp, int flags __unused)
1967 {
1968 	struct ufsmount *ump;
1969 	struct vnode *devvp;
1970 	struct thread *td;
1971 	int error, i;
1972 
1973 	ump = VFSTOUFS(mp);
1974 	devvp = ump->um_devvp;
1975 	td = curthread;
1976 	error = 0;
1977 	ACQUIRE_LOCK(ump);
1978 	for (i = 0; i < SU_WAITIDLE_RETRIES && ump->softdep_deps != 0; i++) {
1979 		ump->softdep_req = 1;
1980 		KASSERT((flags & FORCECLOSE) == 0 ||
1981 		    ump->softdep_on_worklist == 0,
1982 		    ("softdep_waitidle: work added after flush"));
1983 		msleep(&ump->softdep_deps, LOCK_PTR(ump), PVM | PDROP,
1984 		    "softdeps", 10 * hz);
1985 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1986 		error = VOP_FSYNC(devvp, MNT_WAIT, td);
1987 		VOP_UNLOCK(devvp);
1988 		ACQUIRE_LOCK(ump);
1989 		if (error != 0)
1990 			break;
1991 	}
1992 	ump->softdep_req = 0;
1993 	if (i == SU_WAITIDLE_RETRIES && error == 0 && ump->softdep_deps != 0) {
1994 		error = EBUSY;
1995 		printf("softdep_waitidle: Failed to flush worklist for %p\n",
1996 		    mp);
1997 	}
1998 	FREE_LOCK(ump);
1999 	return (error);
2000 }
2001 
2002 /*
2003  * Flush all vnodes and worklist items associated with a specified mount point.
2004  */
2005 int
2006 softdep_flushfiles(oldmnt, flags, td)
2007 	struct mount *oldmnt;
2008 	int flags;
2009 	struct thread *td;
2010 {
2011 #ifdef QUOTA
2012 	struct ufsmount *ump;
2013 	int i;
2014 #endif
2015 	int error, early, depcount, loopcnt, retry_flush_count, retry;
2016 	int morework;
2017 
2018 	KASSERT(MOUNTEDSOFTDEP(oldmnt) != 0,
2019 	    ("softdep_flushfiles called on non-softdep filesystem"));
2020 	loopcnt = 10;
2021 	retry_flush_count = 3;
2022 retry_flush:
2023 	error = 0;
2024 
2025 	/*
2026 	 * Alternately flush the vnodes associated with the mount
2027 	 * point and process any dependencies that the flushing
2028 	 * creates. In theory, this loop can happen at most twice,
2029 	 * but we give it a few extra just to be sure.
2030 	 */
2031 	for (; loopcnt > 0; loopcnt--) {
2032 		/*
2033 		 * Do another flush in case any vnodes were brought in
2034 		 * as part of the cleanup operations.
2035 		 */
2036 		early = retry_flush_count == 1 || (oldmnt->mnt_kern_flag &
2037 		    MNTK_UNMOUNT) == 0 ? 0 : EARLYFLUSH;
2038 		if ((error = ffs_flushfiles(oldmnt, flags | early, td)) != 0)
2039 			break;
2040 		if ((error = softdep_flushworklist(oldmnt, &depcount, td)) != 0 ||
2041 		    depcount == 0)
2042 			break;
2043 	}
2044 	/*
2045 	 * If we are unmounting then it is an error to fail. If we
2046 	 * are simply trying to downgrade to read-only, then filesystem
2047 	 * activity can keep us busy forever, so we just fail with EBUSY.
2048 	 */
2049 	if (loopcnt == 0) {
2050 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT)
2051 			panic("softdep_flushfiles: looping");
2052 		error = EBUSY;
2053 	}
2054 	if (!error)
2055 		error = softdep_waitidle(oldmnt, flags);
2056 	if (!error) {
2057 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT) {
2058 			retry = 0;
2059 			MNT_ILOCK(oldmnt);
2060 			morework = oldmnt->mnt_nvnodelistsize > 0;
2061 #ifdef QUOTA
2062 			ump = VFSTOUFS(oldmnt);
2063 			UFS_LOCK(ump);
2064 			for (i = 0; i < MAXQUOTAS; i++) {
2065 				if (ump->um_quotas[i] != NULLVP)
2066 					morework = 1;
2067 			}
2068 			UFS_UNLOCK(ump);
2069 #endif
2070 			if (morework) {
2071 				if (--retry_flush_count > 0) {
2072 					retry = 1;
2073 					loopcnt = 3;
2074 				} else
2075 					error = EBUSY;
2076 			}
2077 			MNT_IUNLOCK(oldmnt);
2078 			if (retry)
2079 				goto retry_flush;
2080 		}
2081 	}
2082 	return (error);
2083 }
2084 
2085 /*
2086  * Structure hashing.
2087  *
2088  * There are four types of structures that can be looked up:
2089  *	1) pagedep structures identified by mount point, inode number,
2090  *	   and logical block.
2091  *	2) inodedep structures identified by mount point and inode number.
2092  *	3) newblk structures identified by mount point and
2093  *	   physical block number.
2094  *	4) bmsafemap structures identified by mount point and
2095  *	   cylinder group number.
2096  *
2097  * The "pagedep" and "inodedep" dependency structures are hashed
2098  * separately from the file blocks and inodes to which they correspond.
2099  * This separation helps when the in-memory copy of an inode or
2100  * file block must be replaced. It also obviates the need to access
2101  * an inode or file page when simply updating (or de-allocating)
2102  * dependency structures. Lookup of newblk structures is needed to
2103  * find newly allocated blocks when trying to associate them with
2104  * their allocdirect or allocindir structure.
2105  *
2106  * The lookup routines optionally create and hash a new instance when
2107  * an existing entry is not found. The bmsafemap lookup routine always
2108  * allocates a new structure if an existing one is not found.
2109  */
2110 #define DEPALLOC	0x0001	/* allocate structure if lookup fails */
2111 
2112 /*
2113  * Structures and routines associated with pagedep caching.
2114  */
2115 #define	PAGEDEP_HASH(ump, inum, lbn) \
2116 	(&(ump)->pagedep_hashtbl[((inum) + (lbn)) & (ump)->pagedep_hash_size])
2117 
2118 static int
2119 pagedep_find(pagedephd, ino, lbn, pagedeppp)
2120 	struct pagedep_hashhead *pagedephd;
2121 	ino_t ino;
2122 	ufs_lbn_t lbn;
2123 	struct pagedep **pagedeppp;
2124 {
2125 	struct pagedep *pagedep;
2126 
2127 	LIST_FOREACH(pagedep, pagedephd, pd_hash) {
2128 		if (ino == pagedep->pd_ino && lbn == pagedep->pd_lbn) {
2129 			*pagedeppp = pagedep;
2130 			return (1);
2131 		}
2132 	}
2133 	*pagedeppp = NULL;
2134 	return (0);
2135 }
2136 /*
2137  * Look up a pagedep. Return 1 if found, 0 otherwise.
2138  * If not found, allocate if DEPALLOC flag is passed.
2139  * Found or allocated entry is returned in pagedeppp.
2140  */
2141 static int
2142 pagedep_lookup(mp, bp, ino, lbn, flags, pagedeppp)
2143 	struct mount *mp;
2144 	struct buf *bp;
2145 	ino_t ino;
2146 	ufs_lbn_t lbn;
2147 	int flags;
2148 	struct pagedep **pagedeppp;
2149 {
2150 	struct pagedep *pagedep;
2151 	struct pagedep_hashhead *pagedephd;
2152 	struct worklist *wk;
2153 	struct ufsmount *ump;
2154 	int ret;
2155 	int i;
2156 
2157 	ump = VFSTOUFS(mp);
2158 	LOCK_OWNED(ump);
2159 	if (bp) {
2160 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
2161 			if (wk->wk_type == D_PAGEDEP) {
2162 				*pagedeppp = WK_PAGEDEP(wk);
2163 				return (1);
2164 			}
2165 		}
2166 	}
2167 	pagedephd = PAGEDEP_HASH(ump, ino, lbn);
2168 	ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2169 	if (ret) {
2170 		if (((*pagedeppp)->pd_state & ONWORKLIST) == 0 && bp)
2171 			WORKLIST_INSERT(&bp->b_dep, &(*pagedeppp)->pd_list);
2172 		return (1);
2173 	}
2174 	if ((flags & DEPALLOC) == 0)
2175 		return (0);
2176 	FREE_LOCK(ump);
2177 	pagedep = malloc(sizeof(struct pagedep),
2178 	    M_PAGEDEP, M_SOFTDEP_FLAGS|M_ZERO);
2179 	workitem_alloc(&pagedep->pd_list, D_PAGEDEP, mp);
2180 	ACQUIRE_LOCK(ump);
2181 	ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2182 	if (*pagedeppp) {
2183 		/*
2184 		 * This should never happen since we only create pagedeps
2185 		 * with the vnode lock held.  Could be an assert.
2186 		 */
2187 		WORKITEM_FREE(pagedep, D_PAGEDEP);
2188 		return (ret);
2189 	}
2190 	pagedep->pd_ino = ino;
2191 	pagedep->pd_lbn = lbn;
2192 	LIST_INIT(&pagedep->pd_dirremhd);
2193 	LIST_INIT(&pagedep->pd_pendinghd);
2194 	for (i = 0; i < DAHASHSZ; i++)
2195 		LIST_INIT(&pagedep->pd_diraddhd[i]);
2196 	LIST_INSERT_HEAD(pagedephd, pagedep, pd_hash);
2197 	WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
2198 	*pagedeppp = pagedep;
2199 	return (0);
2200 }
2201 
2202 /*
2203  * Structures and routines associated with inodedep caching.
2204  */
2205 #define	INODEDEP_HASH(ump, inum) \
2206       (&(ump)->inodedep_hashtbl[(inum) & (ump)->inodedep_hash_size])
2207 
2208 static int
2209 inodedep_find(inodedephd, inum, inodedeppp)
2210 	struct inodedep_hashhead *inodedephd;
2211 	ino_t inum;
2212 	struct inodedep **inodedeppp;
2213 {
2214 	struct inodedep *inodedep;
2215 
2216 	LIST_FOREACH(inodedep, inodedephd, id_hash)
2217 		if (inum == inodedep->id_ino)
2218 			break;
2219 	if (inodedep) {
2220 		*inodedeppp = inodedep;
2221 		return (1);
2222 	}
2223 	*inodedeppp = NULL;
2224 
2225 	return (0);
2226 }
2227 /*
2228  * Look up an inodedep. Return 1 if found, 0 if not found.
2229  * If not found, allocate if DEPALLOC flag is passed.
2230  * Found or allocated entry is returned in inodedeppp.
2231  */
2232 static int
2233 inodedep_lookup(mp, inum, flags, inodedeppp)
2234 	struct mount *mp;
2235 	ino_t inum;
2236 	int flags;
2237 	struct inodedep **inodedeppp;
2238 {
2239 	struct inodedep *inodedep;
2240 	struct inodedep_hashhead *inodedephd;
2241 	struct ufsmount *ump;
2242 	struct fs *fs;
2243 
2244 	ump = VFSTOUFS(mp);
2245 	LOCK_OWNED(ump);
2246 	fs = ump->um_fs;
2247 	inodedephd = INODEDEP_HASH(ump, inum);
2248 
2249 	if (inodedep_find(inodedephd, inum, inodedeppp))
2250 		return (1);
2251 	if ((flags & DEPALLOC) == 0)
2252 		return (0);
2253 	/*
2254 	 * If the system is over its limit and our filesystem is
2255 	 * responsible for more than our share of that usage and
2256 	 * we are not in a rush, request some inodedep cleanup.
2257 	 */
2258 	if (softdep_excess_items(ump, D_INODEDEP))
2259 		schedule_cleanup(mp);
2260 	else
2261 		FREE_LOCK(ump);
2262 	inodedep = malloc(sizeof(struct inodedep),
2263 		M_INODEDEP, M_SOFTDEP_FLAGS);
2264 	workitem_alloc(&inodedep->id_list, D_INODEDEP, mp);
2265 	ACQUIRE_LOCK(ump);
2266 	if (inodedep_find(inodedephd, inum, inodedeppp)) {
2267 		WORKITEM_FREE(inodedep, D_INODEDEP);
2268 		return (1);
2269 	}
2270 	inodedep->id_fs = fs;
2271 	inodedep->id_ino = inum;
2272 	inodedep->id_state = ALLCOMPLETE;
2273 	inodedep->id_nlinkdelta = 0;
2274 	inodedep->id_savedino1 = NULL;
2275 	inodedep->id_savedsize = -1;
2276 	inodedep->id_savedextsize = -1;
2277 	inodedep->id_savednlink = -1;
2278 	inodedep->id_bmsafemap = NULL;
2279 	inodedep->id_mkdiradd = NULL;
2280 	LIST_INIT(&inodedep->id_dirremhd);
2281 	LIST_INIT(&inodedep->id_pendinghd);
2282 	LIST_INIT(&inodedep->id_inowait);
2283 	LIST_INIT(&inodedep->id_bufwait);
2284 	TAILQ_INIT(&inodedep->id_inoreflst);
2285 	TAILQ_INIT(&inodedep->id_inoupdt);
2286 	TAILQ_INIT(&inodedep->id_newinoupdt);
2287 	TAILQ_INIT(&inodedep->id_extupdt);
2288 	TAILQ_INIT(&inodedep->id_newextupdt);
2289 	TAILQ_INIT(&inodedep->id_freeblklst);
2290 	LIST_INSERT_HEAD(inodedephd, inodedep, id_hash);
2291 	*inodedeppp = inodedep;
2292 	return (0);
2293 }
2294 
2295 /*
2296  * Structures and routines associated with newblk caching.
2297  */
2298 #define	NEWBLK_HASH(ump, inum) \
2299 	(&(ump)->newblk_hashtbl[(inum) & (ump)->newblk_hash_size])
2300 
2301 static int
2302 newblk_find(newblkhd, newblkno, flags, newblkpp)
2303 	struct newblk_hashhead *newblkhd;
2304 	ufs2_daddr_t newblkno;
2305 	int flags;
2306 	struct newblk **newblkpp;
2307 {
2308 	struct newblk *newblk;
2309 
2310 	LIST_FOREACH(newblk, newblkhd, nb_hash) {
2311 		if (newblkno != newblk->nb_newblkno)
2312 			continue;
2313 		/*
2314 		 * If we're creating a new dependency don't match those that
2315 		 * have already been converted to allocdirects.  This is for
2316 		 * a frag extend.
2317 		 */
2318 		if ((flags & DEPALLOC) && newblk->nb_list.wk_type != D_NEWBLK)
2319 			continue;
2320 		break;
2321 	}
2322 	if (newblk) {
2323 		*newblkpp = newblk;
2324 		return (1);
2325 	}
2326 	*newblkpp = NULL;
2327 	return (0);
2328 }
2329 
2330 /*
2331  * Look up a newblk. Return 1 if found, 0 if not found.
2332  * If not found, allocate if DEPALLOC flag is passed.
2333  * Found or allocated entry is returned in newblkpp.
2334  */
2335 static int
2336 newblk_lookup(mp, newblkno, flags, newblkpp)
2337 	struct mount *mp;
2338 	ufs2_daddr_t newblkno;
2339 	int flags;
2340 	struct newblk **newblkpp;
2341 {
2342 	struct newblk *newblk;
2343 	struct newblk_hashhead *newblkhd;
2344 	struct ufsmount *ump;
2345 
2346 	ump = VFSTOUFS(mp);
2347 	LOCK_OWNED(ump);
2348 	newblkhd = NEWBLK_HASH(ump, newblkno);
2349 	if (newblk_find(newblkhd, newblkno, flags, newblkpp))
2350 		return (1);
2351 	if ((flags & DEPALLOC) == 0)
2352 		return (0);
2353 	if (softdep_excess_items(ump, D_NEWBLK) ||
2354 	    softdep_excess_items(ump, D_ALLOCDIRECT) ||
2355 	    softdep_excess_items(ump, D_ALLOCINDIR))
2356 		schedule_cleanup(mp);
2357 	else
2358 		FREE_LOCK(ump);
2359 	newblk = malloc(sizeof(union allblk), M_NEWBLK,
2360 	    M_SOFTDEP_FLAGS | M_ZERO);
2361 	workitem_alloc(&newblk->nb_list, D_NEWBLK, mp);
2362 	ACQUIRE_LOCK(ump);
2363 	if (newblk_find(newblkhd, newblkno, flags, newblkpp)) {
2364 		WORKITEM_FREE(newblk, D_NEWBLK);
2365 		return (1);
2366 	}
2367 	newblk->nb_freefrag = NULL;
2368 	LIST_INIT(&newblk->nb_indirdeps);
2369 	LIST_INIT(&newblk->nb_newdirblk);
2370 	LIST_INIT(&newblk->nb_jwork);
2371 	newblk->nb_state = ATTACHED;
2372 	newblk->nb_newblkno = newblkno;
2373 	LIST_INSERT_HEAD(newblkhd, newblk, nb_hash);
2374 	*newblkpp = newblk;
2375 	return (0);
2376 }
2377 
2378 /*
2379  * Structures and routines associated with freed indirect block caching.
2380  */
2381 #define	INDIR_HASH(ump, blkno) \
2382 	(&(ump)->indir_hashtbl[(blkno) & (ump)->indir_hash_size])
2383 
2384 /*
2385  * Lookup an indirect block in the indir hash table.  The freework is
2386  * removed and potentially freed.  The caller must do a blocking journal
2387  * write before writing to the blkno.
2388  */
2389 static int
2390 indirblk_lookup(mp, blkno)
2391 	struct mount *mp;
2392 	ufs2_daddr_t blkno;
2393 {
2394 	struct freework *freework;
2395 	struct indir_hashhead *wkhd;
2396 	struct ufsmount *ump;
2397 
2398 	ump = VFSTOUFS(mp);
2399 	wkhd = INDIR_HASH(ump, blkno);
2400 	TAILQ_FOREACH(freework, wkhd, fw_next) {
2401 		if (freework->fw_blkno != blkno)
2402 			continue;
2403 		indirblk_remove(freework);
2404 		return (1);
2405 	}
2406 	return (0);
2407 }
2408 
2409 /*
2410  * Insert an indirect block represented by freework into the indirblk
2411  * hash table so that it may prevent the block from being re-used prior
2412  * to the journal being written.
2413  */
2414 static void
2415 indirblk_insert(freework)
2416 	struct freework *freework;
2417 {
2418 	struct jblocks *jblocks;
2419 	struct jseg *jseg;
2420 	struct ufsmount *ump;
2421 
2422 	ump = VFSTOUFS(freework->fw_list.wk_mp);
2423 	jblocks = ump->softdep_jblocks;
2424 	jseg = TAILQ_LAST(&jblocks->jb_segs, jseglst);
2425 	if (jseg == NULL)
2426 		return;
2427 
2428 	LIST_INSERT_HEAD(&jseg->js_indirs, freework, fw_segs);
2429 	TAILQ_INSERT_HEAD(INDIR_HASH(ump, freework->fw_blkno), freework,
2430 	    fw_next);
2431 	freework->fw_state &= ~DEPCOMPLETE;
2432 }
2433 
2434 static void
2435 indirblk_remove(freework)
2436 	struct freework *freework;
2437 {
2438 	struct ufsmount *ump;
2439 
2440 	ump = VFSTOUFS(freework->fw_list.wk_mp);
2441 	LIST_REMOVE(freework, fw_segs);
2442 	TAILQ_REMOVE(INDIR_HASH(ump, freework->fw_blkno), freework, fw_next);
2443 	freework->fw_state |= DEPCOMPLETE;
2444 	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
2445 		WORKITEM_FREE(freework, D_FREEWORK);
2446 }
2447 
2448 /*
2449  * Executed during filesystem system initialization before
2450  * mounting any filesystems.
2451  */
2452 void
2453 softdep_initialize()
2454 {
2455 
2456 	TAILQ_INIT(&softdepmounts);
2457 #ifdef __LP64__
2458 	max_softdeps = desiredvnodes * 4;
2459 #else
2460 	max_softdeps = desiredvnodes * 2;
2461 #endif
2462 
2463 	/* initialise bioops hack */
2464 	bioops.io_start = softdep_disk_io_initiation;
2465 	bioops.io_complete = softdep_disk_write_complete;
2466 	bioops.io_deallocate = softdep_deallocate_dependencies;
2467 	bioops.io_countdeps = softdep_count_dependencies;
2468 	softdep_ast_cleanup = softdep_ast_cleanup_proc;
2469 
2470 	/* Initialize the callout with an mtx. */
2471 	callout_init_mtx(&softdep_callout, &lk, 0);
2472 }
2473 
2474 /*
2475  * Executed after all filesystems have been unmounted during
2476  * filesystem module unload.
2477  */
2478 void
2479 softdep_uninitialize()
2480 {
2481 
2482 	/* clear bioops hack */
2483 	bioops.io_start = NULL;
2484 	bioops.io_complete = NULL;
2485 	bioops.io_deallocate = NULL;
2486 	bioops.io_countdeps = NULL;
2487 	softdep_ast_cleanup = NULL;
2488 
2489 	callout_drain(&softdep_callout);
2490 }
2491 
2492 /*
2493  * Called at mount time to notify the dependency code that a
2494  * filesystem wishes to use it.
2495  */
2496 int
2497 softdep_mount(devvp, mp, fs, cred)
2498 	struct vnode *devvp;
2499 	struct mount *mp;
2500 	struct fs *fs;
2501 	struct ucred *cred;
2502 {
2503 	struct csum_total cstotal;
2504 	struct mount_softdeps *sdp;
2505 	struct ufsmount *ump;
2506 	struct cg *cgp;
2507 	struct buf *bp;
2508 	u_int cyl, i;
2509 	int error;
2510 
2511 	sdp = malloc(sizeof(struct mount_softdeps), M_MOUNTDATA,
2512 	    M_WAITOK | M_ZERO);
2513 	MNT_ILOCK(mp);
2514 	mp->mnt_flag = (mp->mnt_flag & ~MNT_ASYNC) | MNT_SOFTDEP;
2515 	if ((mp->mnt_kern_flag & MNTK_SOFTDEP) == 0) {
2516 		mp->mnt_kern_flag = (mp->mnt_kern_flag & ~MNTK_ASYNC) |
2517 			MNTK_SOFTDEP | MNTK_NOASYNC;
2518 	}
2519 	ump = VFSTOUFS(mp);
2520 	ump->um_softdep = sdp;
2521 	MNT_IUNLOCK(mp);
2522 	rw_init(LOCK_PTR(ump), "per-fs softdep");
2523 	sdp->sd_ump = ump;
2524 	LIST_INIT(&ump->softdep_workitem_pending);
2525 	LIST_INIT(&ump->softdep_journal_pending);
2526 	TAILQ_INIT(&ump->softdep_unlinked);
2527 	LIST_INIT(&ump->softdep_dirtycg);
2528 	ump->softdep_worklist_tail = NULL;
2529 	ump->softdep_on_worklist = 0;
2530 	ump->softdep_deps = 0;
2531 	LIST_INIT(&ump->softdep_mkdirlisthd);
2532 	ump->pagedep_hashtbl = hashinit(desiredvnodes / 5, M_PAGEDEP,
2533 	    &ump->pagedep_hash_size);
2534 	ump->pagedep_nextclean = 0;
2535 	ump->inodedep_hashtbl = hashinit(desiredvnodes, M_INODEDEP,
2536 	    &ump->inodedep_hash_size);
2537 	ump->inodedep_nextclean = 0;
2538 	ump->newblk_hashtbl = hashinit(max_softdeps / 2,  M_NEWBLK,
2539 	    &ump->newblk_hash_size);
2540 	ump->bmsafemap_hashtbl = hashinit(1024, M_BMSAFEMAP,
2541 	    &ump->bmsafemap_hash_size);
2542 	i = 1 << (ffs(desiredvnodes / 10) - 1);
2543 	ump->indir_hashtbl = malloc(i * sizeof(struct indir_hashhead),
2544 	    M_FREEWORK, M_WAITOK);
2545 	ump->indir_hash_size = i - 1;
2546 	for (i = 0; i <= ump->indir_hash_size; i++)
2547 		TAILQ_INIT(&ump->indir_hashtbl[i]);
2548 #ifdef INVARIANTS
2549 	for (i = 0; i <= D_LAST; i++)
2550 		LIST_INIT(&ump->softdep_alldeps[i]);
2551 #endif
2552 	ACQUIRE_GBLLOCK(&lk);
2553 	TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
2554 	FREE_GBLLOCK(&lk);
2555 	if ((fs->fs_flags & FS_SUJ) &&
2556 	    (error = journal_mount(mp, fs, cred)) != 0) {
2557 		printf("Failed to start journal: %d\n", error);
2558 		softdep_unmount(mp);
2559 		return (error);
2560 	}
2561 	/*
2562 	 * Start our flushing thread in the bufdaemon process.
2563 	 */
2564 	ACQUIRE_LOCK(ump);
2565 	ump->softdep_flags |= FLUSH_STARTING;
2566 	FREE_LOCK(ump);
2567 	kproc_kthread_add(&softdep_flush, mp, &bufdaemonproc,
2568 	    &ump->softdep_flushtd, 0, 0, "softdepflush", "%s worker",
2569 	    mp->mnt_stat.f_mntonname);
2570 	ACQUIRE_LOCK(ump);
2571 	while ((ump->softdep_flags & FLUSH_STARTING) != 0) {
2572 		msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM, "sdstart",
2573 		    hz / 2);
2574 	}
2575 	FREE_LOCK(ump);
2576 	/*
2577 	 * When doing soft updates, the counters in the
2578 	 * superblock may have gotten out of sync. Recomputation
2579 	 * can take a long time and can be deferred for background
2580 	 * fsck.  However, the old behavior of scanning the cylinder
2581 	 * groups and recalculating them at mount time is available
2582 	 * by setting vfs.ffs.compute_summary_at_mount to one.
2583 	 */
2584 	if (compute_summary_at_mount == 0 || fs->fs_clean != 0)
2585 		return (0);
2586 	bzero(&cstotal, sizeof cstotal);
2587 	for (cyl = 0; cyl < fs->fs_ncg; cyl++) {
2588 		if ((error = bread(devvp, fsbtodb(fs, cgtod(fs, cyl)),
2589 		    fs->fs_cgsize, cred, &bp)) != 0) {
2590 			brelse(bp);
2591 			softdep_unmount(mp);
2592 			return (error);
2593 		}
2594 		cgp = (struct cg *)bp->b_data;
2595 		cstotal.cs_nffree += cgp->cg_cs.cs_nffree;
2596 		cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree;
2597 		cstotal.cs_nifree += cgp->cg_cs.cs_nifree;
2598 		cstotal.cs_ndir += cgp->cg_cs.cs_ndir;
2599 		fs->fs_cs(fs, cyl) = cgp->cg_cs;
2600 		brelse(bp);
2601 	}
2602 #ifdef INVARIANTS
2603 	if (bcmp(&cstotal, &fs->fs_cstotal, sizeof cstotal))
2604 		printf("%s: superblock summary recomputed\n", fs->fs_fsmnt);
2605 #endif
2606 	bcopy(&cstotal, &fs->fs_cstotal, sizeof cstotal);
2607 	return (0);
2608 }
2609 
2610 void
2611 softdep_unmount(mp)
2612 	struct mount *mp;
2613 {
2614 	struct ufsmount *ump;
2615 #ifdef INVARIANTS
2616 	int i;
2617 #endif
2618 
2619 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
2620 	    ("softdep_unmount called on non-softdep filesystem"));
2621 	ump = VFSTOUFS(mp);
2622 	MNT_ILOCK(mp);
2623 	mp->mnt_flag &= ~MNT_SOFTDEP;
2624 	if (MOUNTEDSUJ(mp) == 0) {
2625 		MNT_IUNLOCK(mp);
2626 	} else {
2627 		mp->mnt_flag &= ~MNT_SUJ;
2628 		MNT_IUNLOCK(mp);
2629 		journal_unmount(ump);
2630 	}
2631 	/*
2632 	 * Shut down our flushing thread. Check for NULL is if
2633 	 * softdep_mount errors out before the thread has been created.
2634 	 */
2635 	if (ump->softdep_flushtd != NULL) {
2636 		ACQUIRE_LOCK(ump);
2637 		ump->softdep_flags |= FLUSH_EXIT;
2638 		wakeup(&ump->softdep_flushtd);
2639 		msleep(&ump->softdep_flags, LOCK_PTR(ump), PVM | PDROP,
2640 		    "sdwait", 0);
2641 		KASSERT((ump->softdep_flags & FLUSH_EXIT) == 0,
2642 		    ("Thread shutdown failed"));
2643 	}
2644 	/*
2645 	 * Free up our resources.
2646 	 */
2647 	ACQUIRE_GBLLOCK(&lk);
2648 	TAILQ_REMOVE(&softdepmounts, ump->um_softdep, sd_next);
2649 	FREE_GBLLOCK(&lk);
2650 	rw_destroy(LOCK_PTR(ump));
2651 	hashdestroy(ump->pagedep_hashtbl, M_PAGEDEP, ump->pagedep_hash_size);
2652 	hashdestroy(ump->inodedep_hashtbl, M_INODEDEP, ump->inodedep_hash_size);
2653 	hashdestroy(ump->newblk_hashtbl, M_NEWBLK, ump->newblk_hash_size);
2654 	hashdestroy(ump->bmsafemap_hashtbl, M_BMSAFEMAP,
2655 	    ump->bmsafemap_hash_size);
2656 	free(ump->indir_hashtbl, M_FREEWORK);
2657 #ifdef INVARIANTS
2658 	for (i = 0; i <= D_LAST; i++) {
2659 		KASSERT(ump->softdep_curdeps[i] == 0,
2660 		    ("Unmount %s: Dep type %s != 0 (%ld)", ump->um_fs->fs_fsmnt,
2661 		    TYPENAME(i), ump->softdep_curdeps[i]));
2662 		KASSERT(LIST_EMPTY(&ump->softdep_alldeps[i]),
2663 		    ("Unmount %s: Dep type %s not empty (%p)", ump->um_fs->fs_fsmnt,
2664 		    TYPENAME(i), LIST_FIRST(&ump->softdep_alldeps[i])));
2665 	}
2666 #endif
2667 	free(ump->um_softdep, M_MOUNTDATA);
2668 }
2669 
2670 static struct jblocks *
2671 jblocks_create(void)
2672 {
2673 	struct jblocks *jblocks;
2674 
2675 	jblocks = malloc(sizeof(*jblocks), M_JBLOCKS, M_WAITOK | M_ZERO);
2676 	TAILQ_INIT(&jblocks->jb_segs);
2677 	jblocks->jb_avail = 10;
2678 	jblocks->jb_extent = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2679 	    M_JBLOCKS, M_WAITOK | M_ZERO);
2680 
2681 	return (jblocks);
2682 }
2683 
2684 static ufs2_daddr_t
2685 jblocks_alloc(jblocks, bytes, actual)
2686 	struct jblocks *jblocks;
2687 	int bytes;
2688 	int *actual;
2689 {
2690 	ufs2_daddr_t daddr;
2691 	struct jextent *jext;
2692 	int freecnt;
2693 	int blocks;
2694 
2695 	blocks = bytes / DEV_BSIZE;
2696 	jext = &jblocks->jb_extent[jblocks->jb_head];
2697 	freecnt = jext->je_blocks - jblocks->jb_off;
2698 	if (freecnt == 0) {
2699 		jblocks->jb_off = 0;
2700 		if (++jblocks->jb_head > jblocks->jb_used)
2701 			jblocks->jb_head = 0;
2702 		jext = &jblocks->jb_extent[jblocks->jb_head];
2703 		freecnt = jext->je_blocks;
2704 	}
2705 	if (freecnt > blocks)
2706 		freecnt = blocks;
2707 	*actual = freecnt * DEV_BSIZE;
2708 	daddr = jext->je_daddr + jblocks->jb_off;
2709 	jblocks->jb_off += freecnt;
2710 	jblocks->jb_free -= freecnt;
2711 
2712 	return (daddr);
2713 }
2714 
2715 static void
2716 jblocks_free(jblocks, mp, bytes)
2717 	struct jblocks *jblocks;
2718 	struct mount *mp;
2719 	int bytes;
2720 {
2721 
2722 	LOCK_OWNED(VFSTOUFS(mp));
2723 	jblocks->jb_free += bytes / DEV_BSIZE;
2724 	if (jblocks->jb_suspended)
2725 		worklist_speedup(mp);
2726 	wakeup(jblocks);
2727 }
2728 
2729 static void
2730 jblocks_destroy(jblocks)
2731 	struct jblocks *jblocks;
2732 {
2733 
2734 	if (jblocks->jb_extent)
2735 		free(jblocks->jb_extent, M_JBLOCKS);
2736 	free(jblocks, M_JBLOCKS);
2737 }
2738 
2739 static void
2740 jblocks_add(jblocks, daddr, blocks)
2741 	struct jblocks *jblocks;
2742 	ufs2_daddr_t daddr;
2743 	int blocks;
2744 {
2745 	struct jextent *jext;
2746 
2747 	jblocks->jb_blocks += blocks;
2748 	jblocks->jb_free += blocks;
2749 	jext = &jblocks->jb_extent[jblocks->jb_used];
2750 	/* Adding the first block. */
2751 	if (jext->je_daddr == 0) {
2752 		jext->je_daddr = daddr;
2753 		jext->je_blocks = blocks;
2754 		return;
2755 	}
2756 	/* Extending the last extent. */
2757 	if (jext->je_daddr + jext->je_blocks == daddr) {
2758 		jext->je_blocks += blocks;
2759 		return;
2760 	}
2761 	/* Adding a new extent. */
2762 	if (++jblocks->jb_used == jblocks->jb_avail) {
2763 		jblocks->jb_avail *= 2;
2764 		jext = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2765 		    M_JBLOCKS, M_WAITOK | M_ZERO);
2766 		memcpy(jext, jblocks->jb_extent,
2767 		    sizeof(struct jextent) * jblocks->jb_used);
2768 		free(jblocks->jb_extent, M_JBLOCKS);
2769 		jblocks->jb_extent = jext;
2770 	}
2771 	jext = &jblocks->jb_extent[jblocks->jb_used];
2772 	jext->je_daddr = daddr;
2773 	jext->je_blocks = blocks;
2774 	return;
2775 }
2776 
2777 int
2778 softdep_journal_lookup(mp, vpp)
2779 	struct mount *mp;
2780 	struct vnode **vpp;
2781 {
2782 	struct componentname cnp;
2783 	struct vnode *dvp;
2784 	ino_t sujournal;
2785 	int error;
2786 
2787 	error = VFS_VGET(mp, UFS_ROOTINO, LK_EXCLUSIVE, &dvp);
2788 	if (error)
2789 		return (error);
2790 	bzero(&cnp, sizeof(cnp));
2791 	cnp.cn_nameiop = LOOKUP;
2792 	cnp.cn_flags = ISLASTCN;
2793 	cnp.cn_thread = curthread;
2794 	cnp.cn_cred = curthread->td_ucred;
2795 	cnp.cn_pnbuf = SUJ_FILE;
2796 	cnp.cn_nameptr = SUJ_FILE;
2797 	cnp.cn_namelen = strlen(SUJ_FILE);
2798 	error = ufs_lookup_ino(dvp, NULL, &cnp, &sujournal);
2799 	vput(dvp);
2800 	if (error != 0)
2801 		return (error);
2802 	error = VFS_VGET(mp, sujournal, LK_EXCLUSIVE, vpp);
2803 	return (error);
2804 }
2805 
2806 /*
2807  * Open and verify the journal file.
2808  */
2809 static int
2810 journal_mount(mp, fs, cred)
2811 	struct mount *mp;
2812 	struct fs *fs;
2813 	struct ucred *cred;
2814 {
2815 	struct jblocks *jblocks;
2816 	struct ufsmount *ump;
2817 	struct vnode *vp;
2818 	struct inode *ip;
2819 	ufs2_daddr_t blkno;
2820 	int bcount;
2821 	int error;
2822 	int i;
2823 
2824 	ump = VFSTOUFS(mp);
2825 	ump->softdep_journal_tail = NULL;
2826 	ump->softdep_on_journal = 0;
2827 	ump->softdep_accdeps = 0;
2828 	ump->softdep_req = 0;
2829 	ump->softdep_jblocks = NULL;
2830 	error = softdep_journal_lookup(mp, &vp);
2831 	if (error != 0) {
2832 		printf("Failed to find journal.  Use tunefs to create one\n");
2833 		return (error);
2834 	}
2835 	ip = VTOI(vp);
2836 	if (ip->i_size < SUJ_MIN) {
2837 		error = ENOSPC;
2838 		goto out;
2839 	}
2840 	bcount = lblkno(fs, ip->i_size);	/* Only use whole blocks. */
2841 	jblocks = jblocks_create();
2842 	for (i = 0; i < bcount; i++) {
2843 		error = ufs_bmaparray(vp, i, &blkno, NULL, NULL, NULL);
2844 		if (error)
2845 			break;
2846 		jblocks_add(jblocks, blkno, fsbtodb(fs, fs->fs_frag));
2847 	}
2848 	if (error) {
2849 		jblocks_destroy(jblocks);
2850 		goto out;
2851 	}
2852 	jblocks->jb_low = jblocks->jb_free / 3;	/* Reserve 33%. */
2853 	jblocks->jb_min = jblocks->jb_free / 10; /* Suspend at 10%. */
2854 	ump->softdep_jblocks = jblocks;
2855 out:
2856 	if (error == 0) {
2857 		MNT_ILOCK(mp);
2858 		mp->mnt_flag |= MNT_SUJ;
2859 		mp->mnt_flag &= ~MNT_SOFTDEP;
2860 		MNT_IUNLOCK(mp);
2861 		/*
2862 		 * Only validate the journal contents if the
2863 		 * filesystem is clean, otherwise we write the logs
2864 		 * but they'll never be used.  If the filesystem was
2865 		 * still dirty when we mounted it the journal is
2866 		 * invalid and a new journal can only be valid if it
2867 		 * starts from a clean mount.
2868 		 */
2869 		if (fs->fs_clean) {
2870 			DIP_SET(ip, i_modrev, fs->fs_mtime);
2871 			ip->i_flags |= IN_MODIFIED;
2872 			ffs_update(vp, 1);
2873 		}
2874 	}
2875 	vput(vp);
2876 	return (error);
2877 }
2878 
2879 static void
2880 journal_unmount(ump)
2881 	struct ufsmount *ump;
2882 {
2883 
2884 	if (ump->softdep_jblocks)
2885 		jblocks_destroy(ump->softdep_jblocks);
2886 	ump->softdep_jblocks = NULL;
2887 }
2888 
2889 /*
2890  * Called when a journal record is ready to be written.  Space is allocated
2891  * and the journal entry is created when the journal is flushed to stable
2892  * store.
2893  */
2894 static void
2895 add_to_journal(wk)
2896 	struct worklist *wk;
2897 {
2898 	struct ufsmount *ump;
2899 
2900 	ump = VFSTOUFS(wk->wk_mp);
2901 	LOCK_OWNED(ump);
2902 	if (wk->wk_state & ONWORKLIST)
2903 		panic("add_to_journal: %s(0x%X) already on list",
2904 		    TYPENAME(wk->wk_type), wk->wk_state);
2905 	wk->wk_state |= ONWORKLIST | DEPCOMPLETE;
2906 	if (LIST_EMPTY(&ump->softdep_journal_pending)) {
2907 		ump->softdep_jblocks->jb_age = ticks;
2908 		LIST_INSERT_HEAD(&ump->softdep_journal_pending, wk, wk_list);
2909 	} else
2910 		LIST_INSERT_AFTER(ump->softdep_journal_tail, wk, wk_list);
2911 	ump->softdep_journal_tail = wk;
2912 	ump->softdep_on_journal += 1;
2913 }
2914 
2915 /*
2916  * Remove an arbitrary item for the journal worklist maintain the tail
2917  * pointer.  This happens when a new operation obviates the need to
2918  * journal an old operation.
2919  */
2920 static void
2921 remove_from_journal(wk)
2922 	struct worklist *wk;
2923 {
2924 	struct ufsmount *ump;
2925 
2926 	ump = VFSTOUFS(wk->wk_mp);
2927 	LOCK_OWNED(ump);
2928 #ifdef INVARIANTS
2929 	{
2930 		struct worklist *wkn;
2931 
2932 		LIST_FOREACH(wkn, &ump->softdep_journal_pending, wk_list)
2933 			if (wkn == wk)
2934 				break;
2935 		if (wkn == NULL)
2936 			panic("remove_from_journal: %p is not in journal", wk);
2937 	}
2938 #endif
2939 	/*
2940 	 * We emulate a TAILQ to save space in most structures which do not
2941 	 * require TAILQ semantics.  Here we must update the tail position
2942 	 * when removing the tail which is not the final entry. This works
2943 	 * only if the worklist linkage are at the beginning of the structure.
2944 	 */
2945 	if (ump->softdep_journal_tail == wk)
2946 		ump->softdep_journal_tail =
2947 		    (struct worklist *)wk->wk_list.le_prev;
2948 	WORKLIST_REMOVE(wk);
2949 	ump->softdep_on_journal -= 1;
2950 }
2951 
2952 /*
2953  * Check for journal space as well as dependency limits so the prelink
2954  * code can throttle both journaled and non-journaled filesystems.
2955  * Threshold is 0 for low and 1 for min.
2956  */
2957 static int
2958 journal_space(ump, thresh)
2959 	struct ufsmount *ump;
2960 	int thresh;
2961 {
2962 	struct jblocks *jblocks;
2963 	int limit, avail;
2964 
2965 	jblocks = ump->softdep_jblocks;
2966 	if (jblocks == NULL)
2967 		return (1);
2968 	/*
2969 	 * We use a tighter restriction here to prevent request_cleanup()
2970 	 * running in threads from running into locks we currently hold.
2971 	 * We have to be over the limit and our filesystem has to be
2972 	 * responsible for more than our share of that usage.
2973 	 */
2974 	limit = (max_softdeps / 10) * 9;
2975 	if (dep_current[D_INODEDEP] > limit &&
2976 	    ump->softdep_curdeps[D_INODEDEP] > limit / stat_flush_threads)
2977 		return (0);
2978 	if (thresh)
2979 		thresh = jblocks->jb_min;
2980 	else
2981 		thresh = jblocks->jb_low;
2982 	avail = (ump->softdep_on_journal * JREC_SIZE) / DEV_BSIZE;
2983 	avail = jblocks->jb_free - avail;
2984 
2985 	return (avail > thresh);
2986 }
2987 
2988 static void
2989 journal_suspend(ump)
2990 	struct ufsmount *ump;
2991 {
2992 	struct jblocks *jblocks;
2993 	struct mount *mp;
2994 	bool set;
2995 
2996 	mp = UFSTOVFS(ump);
2997 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0)
2998 		return;
2999 
3000 	jblocks = ump->softdep_jblocks;
3001 	vfs_op_enter(mp);
3002 	set = false;
3003 	MNT_ILOCK(mp);
3004 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
3005 		stat_journal_min++;
3006 		mp->mnt_kern_flag |= MNTK_SUSPEND;
3007 		mp->mnt_susp_owner = ump->softdep_flushtd;
3008 		set = true;
3009 	}
3010 	jblocks->jb_suspended = 1;
3011 	MNT_IUNLOCK(mp);
3012 	if (!set)
3013 		vfs_op_exit(mp);
3014 }
3015 
3016 static int
3017 journal_unsuspend(struct ufsmount *ump)
3018 {
3019 	struct jblocks *jblocks;
3020 	struct mount *mp;
3021 
3022 	mp = UFSTOVFS(ump);
3023 	jblocks = ump->softdep_jblocks;
3024 
3025 	if (jblocks != NULL && jblocks->jb_suspended &&
3026 	    journal_space(ump, jblocks->jb_min)) {
3027 		jblocks->jb_suspended = 0;
3028 		FREE_LOCK(ump);
3029 		mp->mnt_susp_owner = curthread;
3030 		vfs_write_resume(mp, 0);
3031 		ACQUIRE_LOCK(ump);
3032 		return (1);
3033 	}
3034 	return (0);
3035 }
3036 
3037 /*
3038  * Called before any allocation function to be certain that there is
3039  * sufficient space in the journal prior to creating any new records.
3040  * Since in the case of block allocation we may have multiple locked
3041  * buffers at the time of the actual allocation we can not block
3042  * when the journal records are created.  Doing so would create a deadlock
3043  * if any of these buffers needed to be flushed to reclaim space.  Instead
3044  * we require a sufficiently large amount of available space such that
3045  * each thread in the system could have passed this allocation check and
3046  * still have sufficient free space.  With 20% of a minimum journal size
3047  * of 1MB we have 6553 records available.
3048  */
3049 int
3050 softdep_prealloc(vp, waitok)
3051 	struct vnode *vp;
3052 	int waitok;
3053 {
3054 	struct ufsmount *ump;
3055 
3056 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
3057 	    ("softdep_prealloc called on non-softdep filesystem"));
3058 	/*
3059 	 * Nothing to do if we are not running journaled soft updates.
3060 	 * If we currently hold the snapshot lock, we must avoid
3061 	 * handling other resources that could cause deadlock.  Do not
3062 	 * touch quotas vnode since it is typically recursed with
3063 	 * other vnode locks held.
3064 	 */
3065 	if (DOINGSUJ(vp) == 0 || IS_SNAPSHOT(VTOI(vp)) ||
3066 	    (vp->v_vflag & VV_SYSTEM) != 0)
3067 		return (0);
3068 	ump = VFSTOUFS(vp->v_mount);
3069 	ACQUIRE_LOCK(ump);
3070 	if (journal_space(ump, 0)) {
3071 		FREE_LOCK(ump);
3072 		return (0);
3073 	}
3074 	stat_journal_low++;
3075 	FREE_LOCK(ump);
3076 	if (waitok == MNT_NOWAIT)
3077 		return (ENOSPC);
3078 	/*
3079 	 * Attempt to sync this vnode once to flush any journal
3080 	 * work attached to it.
3081 	 */
3082 	if ((curthread->td_pflags & TDP_COWINPROGRESS) == 0)
3083 		ffs_syncvnode(vp, waitok, 0);
3084 	ACQUIRE_LOCK(ump);
3085 	process_removes(vp);
3086 	process_truncates(vp);
3087 	if (journal_space(ump, 0) == 0) {
3088 		softdep_speedup(ump);
3089 		if (journal_space(ump, 1) == 0)
3090 			journal_suspend(ump);
3091 	}
3092 	FREE_LOCK(ump);
3093 
3094 	return (0);
3095 }
3096 
3097 /*
3098  * Before adjusting a link count on a vnode verify that we have sufficient
3099  * journal space.  If not, process operations that depend on the currently
3100  * locked pair of vnodes to try to flush space as the syncer, buf daemon,
3101  * and softdep flush threads can not acquire these locks to reclaim space.
3102  */
3103 static void
3104 softdep_prelink(dvp, vp)
3105 	struct vnode *dvp;
3106 	struct vnode *vp;
3107 {
3108 	struct ufsmount *ump;
3109 
3110 	ump = VFSTOUFS(dvp->v_mount);
3111 	LOCK_OWNED(ump);
3112 	/*
3113 	 * Nothing to do if we have sufficient journal space.
3114 	 * If we currently hold the snapshot lock, we must avoid
3115 	 * handling other resources that could cause deadlock.
3116 	 */
3117 	if (journal_space(ump, 0) || (vp && IS_SNAPSHOT(VTOI(vp))))
3118 		return;
3119 	stat_journal_low++;
3120 	FREE_LOCK(ump);
3121 	if (vp)
3122 		ffs_syncvnode(vp, MNT_NOWAIT, 0);
3123 	ffs_syncvnode(dvp, MNT_WAIT, 0);
3124 	ACQUIRE_LOCK(ump);
3125 	/* Process vp before dvp as it may create .. removes. */
3126 	if (vp) {
3127 		process_removes(vp);
3128 		process_truncates(vp);
3129 	}
3130 	process_removes(dvp);
3131 	process_truncates(dvp);
3132 	softdep_speedup(ump);
3133 	process_worklist_item(UFSTOVFS(ump), 2, LK_NOWAIT);
3134 	if (journal_space(ump, 0) == 0) {
3135 		softdep_speedup(ump);
3136 		if (journal_space(ump, 1) == 0)
3137 			journal_suspend(ump);
3138 	}
3139 }
3140 
3141 static void
3142 jseg_write(ump, jseg, data)
3143 	struct ufsmount *ump;
3144 	struct jseg *jseg;
3145 	uint8_t *data;
3146 {
3147 	struct jsegrec *rec;
3148 
3149 	rec = (struct jsegrec *)data;
3150 	rec->jsr_seq = jseg->js_seq;
3151 	rec->jsr_oldest = jseg->js_oldseq;
3152 	rec->jsr_cnt = jseg->js_cnt;
3153 	rec->jsr_blocks = jseg->js_size / ump->um_devvp->v_bufobj.bo_bsize;
3154 	rec->jsr_crc = 0;
3155 	rec->jsr_time = ump->um_fs->fs_mtime;
3156 }
3157 
3158 static inline void
3159 inoref_write(inoref, jseg, rec)
3160 	struct inoref *inoref;
3161 	struct jseg *jseg;
3162 	struct jrefrec *rec;
3163 {
3164 
3165 	inoref->if_jsegdep->jd_seg = jseg;
3166 	rec->jr_ino = inoref->if_ino;
3167 	rec->jr_parent = inoref->if_parent;
3168 	rec->jr_nlink = inoref->if_nlink;
3169 	rec->jr_mode = inoref->if_mode;
3170 	rec->jr_diroff = inoref->if_diroff;
3171 }
3172 
3173 static void
3174 jaddref_write(jaddref, jseg, data)
3175 	struct jaddref *jaddref;
3176 	struct jseg *jseg;
3177 	uint8_t *data;
3178 {
3179 	struct jrefrec *rec;
3180 
3181 	rec = (struct jrefrec *)data;
3182 	rec->jr_op = JOP_ADDREF;
3183 	inoref_write(&jaddref->ja_ref, jseg, rec);
3184 }
3185 
3186 static void
3187 jremref_write(jremref, jseg, data)
3188 	struct jremref *jremref;
3189 	struct jseg *jseg;
3190 	uint8_t *data;
3191 {
3192 	struct jrefrec *rec;
3193 
3194 	rec = (struct jrefrec *)data;
3195 	rec->jr_op = JOP_REMREF;
3196 	inoref_write(&jremref->jr_ref, jseg, rec);
3197 }
3198 
3199 static void
3200 jmvref_write(jmvref, jseg, data)
3201 	struct jmvref *jmvref;
3202 	struct jseg *jseg;
3203 	uint8_t *data;
3204 {
3205 	struct jmvrec *rec;
3206 
3207 	rec = (struct jmvrec *)data;
3208 	rec->jm_op = JOP_MVREF;
3209 	rec->jm_ino = jmvref->jm_ino;
3210 	rec->jm_parent = jmvref->jm_parent;
3211 	rec->jm_oldoff = jmvref->jm_oldoff;
3212 	rec->jm_newoff = jmvref->jm_newoff;
3213 }
3214 
3215 static void
3216 jnewblk_write(jnewblk, jseg, data)
3217 	struct jnewblk *jnewblk;
3218 	struct jseg *jseg;
3219 	uint8_t *data;
3220 {
3221 	struct jblkrec *rec;
3222 
3223 	jnewblk->jn_jsegdep->jd_seg = jseg;
3224 	rec = (struct jblkrec *)data;
3225 	rec->jb_op = JOP_NEWBLK;
3226 	rec->jb_ino = jnewblk->jn_ino;
3227 	rec->jb_blkno = jnewblk->jn_blkno;
3228 	rec->jb_lbn = jnewblk->jn_lbn;
3229 	rec->jb_frags = jnewblk->jn_frags;
3230 	rec->jb_oldfrags = jnewblk->jn_oldfrags;
3231 }
3232 
3233 static void
3234 jfreeblk_write(jfreeblk, jseg, data)
3235 	struct jfreeblk *jfreeblk;
3236 	struct jseg *jseg;
3237 	uint8_t *data;
3238 {
3239 	struct jblkrec *rec;
3240 
3241 	jfreeblk->jf_dep.jb_jsegdep->jd_seg = jseg;
3242 	rec = (struct jblkrec *)data;
3243 	rec->jb_op = JOP_FREEBLK;
3244 	rec->jb_ino = jfreeblk->jf_ino;
3245 	rec->jb_blkno = jfreeblk->jf_blkno;
3246 	rec->jb_lbn = jfreeblk->jf_lbn;
3247 	rec->jb_frags = jfreeblk->jf_frags;
3248 	rec->jb_oldfrags = 0;
3249 }
3250 
3251 static void
3252 jfreefrag_write(jfreefrag, jseg, data)
3253 	struct jfreefrag *jfreefrag;
3254 	struct jseg *jseg;
3255 	uint8_t *data;
3256 {
3257 	struct jblkrec *rec;
3258 
3259 	jfreefrag->fr_jsegdep->jd_seg = jseg;
3260 	rec = (struct jblkrec *)data;
3261 	rec->jb_op = JOP_FREEBLK;
3262 	rec->jb_ino = jfreefrag->fr_ino;
3263 	rec->jb_blkno = jfreefrag->fr_blkno;
3264 	rec->jb_lbn = jfreefrag->fr_lbn;
3265 	rec->jb_frags = jfreefrag->fr_frags;
3266 	rec->jb_oldfrags = 0;
3267 }
3268 
3269 static void
3270 jtrunc_write(jtrunc, jseg, data)
3271 	struct jtrunc *jtrunc;
3272 	struct jseg *jseg;
3273 	uint8_t *data;
3274 {
3275 	struct jtrncrec *rec;
3276 
3277 	jtrunc->jt_dep.jb_jsegdep->jd_seg = jseg;
3278 	rec = (struct jtrncrec *)data;
3279 	rec->jt_op = JOP_TRUNC;
3280 	rec->jt_ino = jtrunc->jt_ino;
3281 	rec->jt_size = jtrunc->jt_size;
3282 	rec->jt_extsize = jtrunc->jt_extsize;
3283 }
3284 
3285 static void
3286 jfsync_write(jfsync, jseg, data)
3287 	struct jfsync *jfsync;
3288 	struct jseg *jseg;
3289 	uint8_t *data;
3290 {
3291 	struct jtrncrec *rec;
3292 
3293 	rec = (struct jtrncrec *)data;
3294 	rec->jt_op = JOP_SYNC;
3295 	rec->jt_ino = jfsync->jfs_ino;
3296 	rec->jt_size = jfsync->jfs_size;
3297 	rec->jt_extsize = jfsync->jfs_extsize;
3298 }
3299 
3300 static void
3301 softdep_flushjournal(mp)
3302 	struct mount *mp;
3303 {
3304 	struct jblocks *jblocks;
3305 	struct ufsmount *ump;
3306 
3307 	if (MOUNTEDSUJ(mp) == 0)
3308 		return;
3309 	ump = VFSTOUFS(mp);
3310 	jblocks = ump->softdep_jblocks;
3311 	ACQUIRE_LOCK(ump);
3312 	while (ump->softdep_on_journal) {
3313 		jblocks->jb_needseg = 1;
3314 		softdep_process_journal(mp, NULL, MNT_WAIT);
3315 	}
3316 	FREE_LOCK(ump);
3317 }
3318 
3319 static void softdep_synchronize_completed(struct bio *);
3320 static void softdep_synchronize(struct bio *, struct ufsmount *, void *);
3321 
3322 static void
3323 softdep_synchronize_completed(bp)
3324         struct bio *bp;
3325 {
3326 	struct jseg *oldest;
3327 	struct jseg *jseg;
3328 	struct ufsmount *ump;
3329 
3330 	/*
3331 	 * caller1 marks the last segment written before we issued the
3332 	 * synchronize cache.
3333 	 */
3334 	jseg = bp->bio_caller1;
3335 	if (jseg == NULL) {
3336 		g_destroy_bio(bp);
3337 		return;
3338 	}
3339 	ump = VFSTOUFS(jseg->js_list.wk_mp);
3340 	ACQUIRE_LOCK(ump);
3341 	oldest = NULL;
3342 	/*
3343 	 * Mark all the journal entries waiting on the synchronize cache
3344 	 * as completed so they may continue on.
3345 	 */
3346 	while (jseg != NULL && (jseg->js_state & COMPLETE) == 0) {
3347 		jseg->js_state |= COMPLETE;
3348 		oldest = jseg;
3349 		jseg = TAILQ_PREV(jseg, jseglst, js_next);
3350 	}
3351 	/*
3352 	 * Restart deferred journal entry processing from the oldest
3353 	 * completed jseg.
3354 	 */
3355 	if (oldest)
3356 		complete_jsegs(oldest);
3357 
3358 	FREE_LOCK(ump);
3359 	g_destroy_bio(bp);
3360 }
3361 
3362 /*
3363  * Send BIO_FLUSH/SYNCHRONIZE CACHE to the device to enforce write ordering
3364  * barriers.  The journal must be written prior to any blocks that depend
3365  * on it and the journal can not be released until the blocks have be
3366  * written.  This code handles both barriers simultaneously.
3367  */
3368 static void
3369 softdep_synchronize(bp, ump, caller1)
3370 	struct bio *bp;
3371 	struct ufsmount *ump;
3372 	void *caller1;
3373 {
3374 
3375 	bp->bio_cmd = BIO_FLUSH;
3376 	bp->bio_flags |= BIO_ORDERED;
3377 	bp->bio_data = NULL;
3378 	bp->bio_offset = ump->um_cp->provider->mediasize;
3379 	bp->bio_length = 0;
3380 	bp->bio_done = softdep_synchronize_completed;
3381 	bp->bio_caller1 = caller1;
3382 	g_io_request(bp, ump->um_cp);
3383 }
3384 
3385 /*
3386  * Flush some journal records to disk.
3387  */
3388 static void
3389 softdep_process_journal(mp, needwk, flags)
3390 	struct mount *mp;
3391 	struct worklist *needwk;
3392 	int flags;
3393 {
3394 	struct jblocks *jblocks;
3395 	struct ufsmount *ump;
3396 	struct worklist *wk;
3397 	struct jseg *jseg;
3398 	struct buf *bp;
3399 	struct bio *bio;
3400 	uint8_t *data;
3401 	struct fs *fs;
3402 	int shouldflush;
3403 	int segwritten;
3404 	int jrecmin;	/* Minimum records per block. */
3405 	int jrecmax;	/* Maximum records per block. */
3406 	int size;
3407 	int cnt;
3408 	int off;
3409 	int devbsize;
3410 
3411 	if (MOUNTEDSUJ(mp) == 0)
3412 		return;
3413 	shouldflush = softdep_flushcache;
3414 	bio = NULL;
3415 	jseg = NULL;
3416 	ump = VFSTOUFS(mp);
3417 	LOCK_OWNED(ump);
3418 	fs = ump->um_fs;
3419 	jblocks = ump->softdep_jblocks;
3420 	devbsize = ump->um_devvp->v_bufobj.bo_bsize;
3421 	/*
3422 	 * We write anywhere between a disk block and fs block.  The upper
3423 	 * bound is picked to prevent buffer cache fragmentation and limit
3424 	 * processing time per I/O.
3425 	 */
3426 	jrecmin = (devbsize / JREC_SIZE) - 1; /* -1 for seg header */
3427 	jrecmax = (fs->fs_bsize / devbsize) * jrecmin;
3428 	segwritten = 0;
3429 	for (;;) {
3430 		cnt = ump->softdep_on_journal;
3431 		/*
3432 		 * Criteria for writing a segment:
3433 		 * 1) We have a full block.
3434 		 * 2) We're called from jwait() and haven't found the
3435 		 *    journal item yet.
3436 		 * 3) Always write if needseg is set.
3437 		 * 4) If we are called from process_worklist and have
3438 		 *    not yet written anything we write a partial block
3439 		 *    to enforce a 1 second maximum latency on journal
3440 		 *    entries.
3441 		 */
3442 		if (cnt < (jrecmax - 1) && needwk == NULL &&
3443 		    jblocks->jb_needseg == 0 && (segwritten || cnt == 0))
3444 			break;
3445 		cnt++;
3446 		/*
3447 		 * Verify some free journal space.  softdep_prealloc() should
3448 		 * guarantee that we don't run out so this is indicative of
3449 		 * a problem with the flow control.  Try to recover
3450 		 * gracefully in any event.
3451 		 */
3452 		while (jblocks->jb_free == 0) {
3453 			if (flags != MNT_WAIT)
3454 				break;
3455 			printf("softdep: Out of journal space!\n");
3456 			softdep_speedup(ump);
3457 			msleep(jblocks, LOCK_PTR(ump), PRIBIO, "jblocks", hz);
3458 		}
3459 		FREE_LOCK(ump);
3460 		jseg = malloc(sizeof(*jseg), M_JSEG, M_SOFTDEP_FLAGS);
3461 		workitem_alloc(&jseg->js_list, D_JSEG, mp);
3462 		LIST_INIT(&jseg->js_entries);
3463 		LIST_INIT(&jseg->js_indirs);
3464 		jseg->js_state = ATTACHED;
3465 		if (shouldflush == 0)
3466 			jseg->js_state |= COMPLETE;
3467 		else if (bio == NULL)
3468 			bio = g_alloc_bio();
3469 		jseg->js_jblocks = jblocks;
3470 		bp = geteblk(fs->fs_bsize, 0);
3471 		ACQUIRE_LOCK(ump);
3472 		/*
3473 		 * If there was a race while we were allocating the block
3474 		 * and jseg the entry we care about was likely written.
3475 		 * We bail out in both the WAIT and NOWAIT case and assume
3476 		 * the caller will loop if the entry it cares about is
3477 		 * not written.
3478 		 */
3479 		cnt = ump->softdep_on_journal;
3480 		if (cnt + jblocks->jb_needseg == 0 || jblocks->jb_free == 0) {
3481 			bp->b_flags |= B_INVAL | B_NOCACHE;
3482 			WORKITEM_FREE(jseg, D_JSEG);
3483 			FREE_LOCK(ump);
3484 			brelse(bp);
3485 			ACQUIRE_LOCK(ump);
3486 			break;
3487 		}
3488 		/*
3489 		 * Calculate the disk block size required for the available
3490 		 * records rounded to the min size.
3491 		 */
3492 		if (cnt == 0)
3493 			size = devbsize;
3494 		else if (cnt < jrecmax)
3495 			size = howmany(cnt, jrecmin) * devbsize;
3496 		else
3497 			size = fs->fs_bsize;
3498 		/*
3499 		 * Allocate a disk block for this journal data and account
3500 		 * for truncation of the requested size if enough contiguous
3501 		 * space was not available.
3502 		 */
3503 		bp->b_blkno = jblocks_alloc(jblocks, size, &size);
3504 		bp->b_lblkno = bp->b_blkno;
3505 		bp->b_offset = bp->b_blkno * DEV_BSIZE;
3506 		bp->b_bcount = size;
3507 		bp->b_flags &= ~B_INVAL;
3508 		bp->b_flags |= B_VALIDSUSPWRT | B_NOCOPY;
3509 		/*
3510 		 * Initialize our jseg with cnt records.  Assign the next
3511 		 * sequence number to it and link it in-order.
3512 		 */
3513 		cnt = MIN(cnt, (size / devbsize) * jrecmin);
3514 		jseg->js_buf = bp;
3515 		jseg->js_cnt = cnt;
3516 		jseg->js_refs = cnt + 1;	/* Self ref. */
3517 		jseg->js_size = size;
3518 		jseg->js_seq = jblocks->jb_nextseq++;
3519 		if (jblocks->jb_oldestseg == NULL)
3520 			jblocks->jb_oldestseg = jseg;
3521 		jseg->js_oldseq = jblocks->jb_oldestseg->js_seq;
3522 		TAILQ_INSERT_TAIL(&jblocks->jb_segs, jseg, js_next);
3523 		if (jblocks->jb_writeseg == NULL)
3524 			jblocks->jb_writeseg = jseg;
3525 		/*
3526 		 * Start filling in records from the pending list.
3527 		 */
3528 		data = bp->b_data;
3529 		off = 0;
3530 
3531 		/*
3532 		 * Always put a header on the first block.
3533 		 * XXX As with below, there might not be a chance to get
3534 		 * into the loop.  Ensure that something valid is written.
3535 		 */
3536 		jseg_write(ump, jseg, data);
3537 		off += JREC_SIZE;
3538 		data = bp->b_data + off;
3539 
3540 		/*
3541 		 * XXX Something is wrong here.  There's no work to do,
3542 		 * but we need to perform and I/O and allow it to complete
3543 		 * anyways.
3544 		 */
3545 		if (LIST_EMPTY(&ump->softdep_journal_pending))
3546 			stat_emptyjblocks++;
3547 
3548 		while ((wk = LIST_FIRST(&ump->softdep_journal_pending))
3549 		    != NULL) {
3550 			if (cnt == 0)
3551 				break;
3552 			/* Place a segment header on every device block. */
3553 			if ((off % devbsize) == 0) {
3554 				jseg_write(ump, jseg, data);
3555 				off += JREC_SIZE;
3556 				data = bp->b_data + off;
3557 			}
3558 			if (wk == needwk)
3559 				needwk = NULL;
3560 			remove_from_journal(wk);
3561 			wk->wk_state |= INPROGRESS;
3562 			WORKLIST_INSERT(&jseg->js_entries, wk);
3563 			switch (wk->wk_type) {
3564 			case D_JADDREF:
3565 				jaddref_write(WK_JADDREF(wk), jseg, data);
3566 				break;
3567 			case D_JREMREF:
3568 				jremref_write(WK_JREMREF(wk), jseg, data);
3569 				break;
3570 			case D_JMVREF:
3571 				jmvref_write(WK_JMVREF(wk), jseg, data);
3572 				break;
3573 			case D_JNEWBLK:
3574 				jnewblk_write(WK_JNEWBLK(wk), jseg, data);
3575 				break;
3576 			case D_JFREEBLK:
3577 				jfreeblk_write(WK_JFREEBLK(wk), jseg, data);
3578 				break;
3579 			case D_JFREEFRAG:
3580 				jfreefrag_write(WK_JFREEFRAG(wk), jseg, data);
3581 				break;
3582 			case D_JTRUNC:
3583 				jtrunc_write(WK_JTRUNC(wk), jseg, data);
3584 				break;
3585 			case D_JFSYNC:
3586 				jfsync_write(WK_JFSYNC(wk), jseg, data);
3587 				break;
3588 			default:
3589 				panic("process_journal: Unknown type %s",
3590 				    TYPENAME(wk->wk_type));
3591 				/* NOTREACHED */
3592 			}
3593 			off += JREC_SIZE;
3594 			data = bp->b_data + off;
3595 			cnt--;
3596 		}
3597 
3598 		/* Clear any remaining space so we don't leak kernel data */
3599 		if (size > off)
3600 			bzero(data, size - off);
3601 
3602 		/*
3603 		 * Write this one buffer and continue.
3604 		 */
3605 		segwritten = 1;
3606 		jblocks->jb_needseg = 0;
3607 		WORKLIST_INSERT(&bp->b_dep, &jseg->js_list);
3608 		FREE_LOCK(ump);
3609 		pbgetvp(ump->um_devvp, bp);
3610 		/*
3611 		 * We only do the blocking wait once we find the journal
3612 		 * entry we're looking for.
3613 		 */
3614 		if (needwk == NULL && flags == MNT_WAIT)
3615 			bwrite(bp);
3616 		else
3617 			bawrite(bp);
3618 		ACQUIRE_LOCK(ump);
3619 	}
3620 	/*
3621 	 * If we wrote a segment issue a synchronize cache so the journal
3622 	 * is reflected on disk before the data is written.  Since reclaiming
3623 	 * journal space also requires writing a journal record this
3624 	 * process also enforces a barrier before reclamation.
3625 	 */
3626 	if (segwritten && shouldflush) {
3627 		softdep_synchronize(bio, ump,
3628 		    TAILQ_LAST(&jblocks->jb_segs, jseglst));
3629 	} else if (bio)
3630 		g_destroy_bio(bio);
3631 	/*
3632 	 * If we've suspended the filesystem because we ran out of journal
3633 	 * space either try to sync it here to make some progress or
3634 	 * unsuspend it if we already have.
3635 	 */
3636 	if (flags == 0 && jblocks->jb_suspended) {
3637 		if (journal_unsuspend(ump))
3638 			return;
3639 		FREE_LOCK(ump);
3640 		VFS_SYNC(mp, MNT_NOWAIT);
3641 		ffs_sbupdate(ump, MNT_WAIT, 0);
3642 		ACQUIRE_LOCK(ump);
3643 	}
3644 }
3645 
3646 /*
3647  * Complete a jseg, allowing all dependencies awaiting journal writes
3648  * to proceed.  Each journal dependency also attaches a jsegdep to dependent
3649  * structures so that the journal segment can be freed to reclaim space.
3650  */
3651 static void
3652 complete_jseg(jseg)
3653 	struct jseg *jseg;
3654 {
3655 	struct worklist *wk;
3656 	struct jmvref *jmvref;
3657 #ifdef INVARIANTS
3658 	int i = 0;
3659 #endif
3660 
3661 	while ((wk = LIST_FIRST(&jseg->js_entries)) != NULL) {
3662 		WORKLIST_REMOVE(wk);
3663 		wk->wk_state &= ~INPROGRESS;
3664 		wk->wk_state |= COMPLETE;
3665 		KASSERT(i++ < jseg->js_cnt,
3666 		    ("handle_written_jseg: overflow %d >= %d",
3667 		    i - 1, jseg->js_cnt));
3668 		switch (wk->wk_type) {
3669 		case D_JADDREF:
3670 			handle_written_jaddref(WK_JADDREF(wk));
3671 			break;
3672 		case D_JREMREF:
3673 			handle_written_jremref(WK_JREMREF(wk));
3674 			break;
3675 		case D_JMVREF:
3676 			rele_jseg(jseg);	/* No jsegdep. */
3677 			jmvref = WK_JMVREF(wk);
3678 			LIST_REMOVE(jmvref, jm_deps);
3679 			if ((jmvref->jm_pagedep->pd_state & ONWORKLIST) == 0)
3680 				free_pagedep(jmvref->jm_pagedep);
3681 			WORKITEM_FREE(jmvref, D_JMVREF);
3682 			break;
3683 		case D_JNEWBLK:
3684 			handle_written_jnewblk(WK_JNEWBLK(wk));
3685 			break;
3686 		case D_JFREEBLK:
3687 			handle_written_jblkdep(&WK_JFREEBLK(wk)->jf_dep);
3688 			break;
3689 		case D_JTRUNC:
3690 			handle_written_jblkdep(&WK_JTRUNC(wk)->jt_dep);
3691 			break;
3692 		case D_JFSYNC:
3693 			rele_jseg(jseg);	/* No jsegdep. */
3694 			WORKITEM_FREE(wk, D_JFSYNC);
3695 			break;
3696 		case D_JFREEFRAG:
3697 			handle_written_jfreefrag(WK_JFREEFRAG(wk));
3698 			break;
3699 		default:
3700 			panic("handle_written_jseg: Unknown type %s",
3701 			    TYPENAME(wk->wk_type));
3702 			/* NOTREACHED */
3703 		}
3704 	}
3705 	/* Release the self reference so the structure may be freed. */
3706 	rele_jseg(jseg);
3707 }
3708 
3709 /*
3710  * Determine which jsegs are ready for completion processing.  Waits for
3711  * synchronize cache to complete as well as forcing in-order completion
3712  * of journal entries.
3713  */
3714 static void
3715 complete_jsegs(jseg)
3716 	struct jseg *jseg;
3717 {
3718 	struct jblocks *jblocks;
3719 	struct jseg *jsegn;
3720 
3721 	jblocks = jseg->js_jblocks;
3722 	/*
3723 	 * Don't allow out of order completions.  If this isn't the first
3724 	 * block wait for it to write before we're done.
3725 	 */
3726 	if (jseg != jblocks->jb_writeseg)
3727 		return;
3728 	/* Iterate through available jsegs processing their entries. */
3729 	while (jseg && (jseg->js_state & ALLCOMPLETE) == ALLCOMPLETE) {
3730 		jblocks->jb_oldestwrseq = jseg->js_oldseq;
3731 		jsegn = TAILQ_NEXT(jseg, js_next);
3732 		complete_jseg(jseg);
3733 		jseg = jsegn;
3734 	}
3735 	jblocks->jb_writeseg = jseg;
3736 	/*
3737 	 * Attempt to free jsegs now that oldestwrseq may have advanced.
3738 	 */
3739 	free_jsegs(jblocks);
3740 }
3741 
3742 /*
3743  * Mark a jseg as DEPCOMPLETE and throw away the buffer.  Attempt to handle
3744  * the final completions.
3745  */
3746 static void
3747 handle_written_jseg(jseg, bp)
3748 	struct jseg *jseg;
3749 	struct buf *bp;
3750 {
3751 
3752 	if (jseg->js_refs == 0)
3753 		panic("handle_written_jseg: No self-reference on %p", jseg);
3754 	jseg->js_state |= DEPCOMPLETE;
3755 	/*
3756 	 * We'll never need this buffer again, set flags so it will be
3757 	 * discarded.
3758 	 */
3759 	bp->b_flags |= B_INVAL | B_NOCACHE;
3760 	pbrelvp(bp);
3761 	complete_jsegs(jseg);
3762 }
3763 
3764 static inline struct jsegdep *
3765 inoref_jseg(inoref)
3766 	struct inoref *inoref;
3767 {
3768 	struct jsegdep *jsegdep;
3769 
3770 	jsegdep = inoref->if_jsegdep;
3771 	inoref->if_jsegdep = NULL;
3772 
3773 	return (jsegdep);
3774 }
3775 
3776 /*
3777  * Called once a jremref has made it to stable store.  The jremref is marked
3778  * complete and we attempt to free it.  Any pagedeps writes sleeping waiting
3779  * for the jremref to complete will be awoken by free_jremref.
3780  */
3781 static void
3782 handle_written_jremref(jremref)
3783 	struct jremref *jremref;
3784 {
3785 	struct inodedep *inodedep;
3786 	struct jsegdep *jsegdep;
3787 	struct dirrem *dirrem;
3788 
3789 	/* Grab the jsegdep. */
3790 	jsegdep = inoref_jseg(&jremref->jr_ref);
3791 	/*
3792 	 * Remove us from the inoref list.
3793 	 */
3794 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino,
3795 	    0, &inodedep) == 0)
3796 		panic("handle_written_jremref: Lost inodedep");
3797 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
3798 	/*
3799 	 * Complete the dirrem.
3800 	 */
3801 	dirrem = jremref->jr_dirrem;
3802 	jremref->jr_dirrem = NULL;
3803 	LIST_REMOVE(jremref, jr_deps);
3804 	jsegdep->jd_state |= jremref->jr_state & MKDIR_PARENT;
3805 	jwork_insert(&dirrem->dm_jwork, jsegdep);
3806 	if (LIST_EMPTY(&dirrem->dm_jremrefhd) &&
3807 	    (dirrem->dm_state & COMPLETE) != 0)
3808 		add_to_worklist(&dirrem->dm_list, 0);
3809 	free_jremref(jremref);
3810 }
3811 
3812 /*
3813  * Called once a jaddref has made it to stable store.  The dependency is
3814  * marked complete and any dependent structures are added to the inode
3815  * bufwait list to be completed as soon as it is written.  If a bitmap write
3816  * depends on this entry we move the inode into the inodedephd of the
3817  * bmsafemap dependency and attempt to remove the jaddref from the bmsafemap.
3818  */
3819 static void
3820 handle_written_jaddref(jaddref)
3821 	struct jaddref *jaddref;
3822 {
3823 	struct jsegdep *jsegdep;
3824 	struct inodedep *inodedep;
3825 	struct diradd *diradd;
3826 	struct mkdir *mkdir;
3827 
3828 	/* Grab the jsegdep. */
3829 	jsegdep = inoref_jseg(&jaddref->ja_ref);
3830 	mkdir = NULL;
3831 	diradd = NULL;
3832 	if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
3833 	    0, &inodedep) == 0)
3834 		panic("handle_written_jaddref: Lost inodedep.");
3835 	if (jaddref->ja_diradd == NULL)
3836 		panic("handle_written_jaddref: No dependency");
3837 	if (jaddref->ja_diradd->da_list.wk_type == D_DIRADD) {
3838 		diradd = jaddref->ja_diradd;
3839 		WORKLIST_INSERT(&inodedep->id_bufwait, &diradd->da_list);
3840 	} else if (jaddref->ja_state & MKDIR_PARENT) {
3841 		mkdir = jaddref->ja_mkdir;
3842 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir->md_list);
3843 	} else if (jaddref->ja_state & MKDIR_BODY)
3844 		mkdir = jaddref->ja_mkdir;
3845 	else
3846 		panic("handle_written_jaddref: Unknown dependency %p",
3847 		    jaddref->ja_diradd);
3848 	jaddref->ja_diradd = NULL;	/* also clears ja_mkdir */
3849 	/*
3850 	 * Remove us from the inode list.
3851 	 */
3852 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref, if_deps);
3853 	/*
3854 	 * The mkdir may be waiting on the jaddref to clear before freeing.
3855 	 */
3856 	if (mkdir) {
3857 		KASSERT(mkdir->md_list.wk_type == D_MKDIR,
3858 		    ("handle_written_jaddref: Incorrect type for mkdir %s",
3859 		    TYPENAME(mkdir->md_list.wk_type)));
3860 		mkdir->md_jaddref = NULL;
3861 		diradd = mkdir->md_diradd;
3862 		mkdir->md_state |= DEPCOMPLETE;
3863 		complete_mkdir(mkdir);
3864 	}
3865 	jwork_insert(&diradd->da_jwork, jsegdep);
3866 	if (jaddref->ja_state & NEWBLOCK) {
3867 		inodedep->id_state |= ONDEPLIST;
3868 		LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_inodedephd,
3869 		    inodedep, id_deps);
3870 	}
3871 	free_jaddref(jaddref);
3872 }
3873 
3874 /*
3875  * Called once a jnewblk journal is written.  The allocdirect or allocindir
3876  * is placed in the bmsafemap to await notification of a written bitmap.  If
3877  * the operation was canceled we add the segdep to the appropriate
3878  * dependency to free the journal space once the canceling operation
3879  * completes.
3880  */
3881 static void
3882 handle_written_jnewblk(jnewblk)
3883 	struct jnewblk *jnewblk;
3884 {
3885 	struct bmsafemap *bmsafemap;
3886 	struct freefrag *freefrag;
3887 	struct freework *freework;
3888 	struct jsegdep *jsegdep;
3889 	struct newblk *newblk;
3890 
3891 	/* Grab the jsegdep. */
3892 	jsegdep = jnewblk->jn_jsegdep;
3893 	jnewblk->jn_jsegdep = NULL;
3894 	if (jnewblk->jn_dep == NULL)
3895 		panic("handle_written_jnewblk: No dependency for the segdep.");
3896 	switch (jnewblk->jn_dep->wk_type) {
3897 	case D_NEWBLK:
3898 	case D_ALLOCDIRECT:
3899 	case D_ALLOCINDIR:
3900 		/*
3901 		 * Add the written block to the bmsafemap so it can
3902 		 * be notified when the bitmap is on disk.
3903 		 */
3904 		newblk = WK_NEWBLK(jnewblk->jn_dep);
3905 		newblk->nb_jnewblk = NULL;
3906 		if ((newblk->nb_state & GOINGAWAY) == 0) {
3907 			bmsafemap = newblk->nb_bmsafemap;
3908 			newblk->nb_state |= ONDEPLIST;
3909 			LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk,
3910 			    nb_deps);
3911 		}
3912 		jwork_insert(&newblk->nb_jwork, jsegdep);
3913 		break;
3914 	case D_FREEFRAG:
3915 		/*
3916 		 * A newblock being removed by a freefrag when replaced by
3917 		 * frag extension.
3918 		 */
3919 		freefrag = WK_FREEFRAG(jnewblk->jn_dep);
3920 		freefrag->ff_jdep = NULL;
3921 		jwork_insert(&freefrag->ff_jwork, jsegdep);
3922 		break;
3923 	case D_FREEWORK:
3924 		/*
3925 		 * A direct block was removed by truncate.
3926 		 */
3927 		freework = WK_FREEWORK(jnewblk->jn_dep);
3928 		freework->fw_jnewblk = NULL;
3929 		jwork_insert(&freework->fw_freeblks->fb_jwork, jsegdep);
3930 		break;
3931 	default:
3932 		panic("handle_written_jnewblk: Unknown type %d.",
3933 		    jnewblk->jn_dep->wk_type);
3934 	}
3935 	jnewblk->jn_dep = NULL;
3936 	free_jnewblk(jnewblk);
3937 }
3938 
3939 /*
3940  * Cancel a jfreefrag that won't be needed, probably due to colliding with
3941  * an in-flight allocation that has not yet been committed.  Divorce us
3942  * from the freefrag and mark it DEPCOMPLETE so that it may be added
3943  * to the worklist.
3944  */
3945 static void
3946 cancel_jfreefrag(jfreefrag)
3947 	struct jfreefrag *jfreefrag;
3948 {
3949 	struct freefrag *freefrag;
3950 
3951 	if (jfreefrag->fr_jsegdep) {
3952 		free_jsegdep(jfreefrag->fr_jsegdep);
3953 		jfreefrag->fr_jsegdep = NULL;
3954 	}
3955 	freefrag = jfreefrag->fr_freefrag;
3956 	jfreefrag->fr_freefrag = NULL;
3957 	free_jfreefrag(jfreefrag);
3958 	freefrag->ff_state |= DEPCOMPLETE;
3959 	CTR1(KTR_SUJ, "cancel_jfreefrag: blkno %jd", freefrag->ff_blkno);
3960 }
3961 
3962 /*
3963  * Free a jfreefrag when the parent freefrag is rendered obsolete.
3964  */
3965 static void
3966 free_jfreefrag(jfreefrag)
3967 	struct jfreefrag *jfreefrag;
3968 {
3969 
3970 	if (jfreefrag->fr_state & INPROGRESS)
3971 		WORKLIST_REMOVE(&jfreefrag->fr_list);
3972 	else if (jfreefrag->fr_state & ONWORKLIST)
3973 		remove_from_journal(&jfreefrag->fr_list);
3974 	if (jfreefrag->fr_freefrag != NULL)
3975 		panic("free_jfreefrag:  Still attached to a freefrag.");
3976 	WORKITEM_FREE(jfreefrag, D_JFREEFRAG);
3977 }
3978 
3979 /*
3980  * Called when the journal write for a jfreefrag completes.  The parent
3981  * freefrag is added to the worklist if this completes its dependencies.
3982  */
3983 static void
3984 handle_written_jfreefrag(jfreefrag)
3985 	struct jfreefrag *jfreefrag;
3986 {
3987 	struct jsegdep *jsegdep;
3988 	struct freefrag *freefrag;
3989 
3990 	/* Grab the jsegdep. */
3991 	jsegdep = jfreefrag->fr_jsegdep;
3992 	jfreefrag->fr_jsegdep = NULL;
3993 	freefrag = jfreefrag->fr_freefrag;
3994 	if (freefrag == NULL)
3995 		panic("handle_written_jfreefrag: No freefrag.");
3996 	freefrag->ff_state |= DEPCOMPLETE;
3997 	freefrag->ff_jdep = NULL;
3998 	jwork_insert(&freefrag->ff_jwork, jsegdep);
3999 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
4000 		add_to_worklist(&freefrag->ff_list, 0);
4001 	jfreefrag->fr_freefrag = NULL;
4002 	free_jfreefrag(jfreefrag);
4003 }
4004 
4005 /*
4006  * Called when the journal write for a jfreeblk completes.  The jfreeblk
4007  * is removed from the freeblks list of pending journal writes and the
4008  * jsegdep is moved to the freeblks jwork to be completed when all blocks
4009  * have been reclaimed.
4010  */
4011 static void
4012 handle_written_jblkdep(jblkdep)
4013 	struct jblkdep *jblkdep;
4014 {
4015 	struct freeblks *freeblks;
4016 	struct jsegdep *jsegdep;
4017 
4018 	/* Grab the jsegdep. */
4019 	jsegdep = jblkdep->jb_jsegdep;
4020 	jblkdep->jb_jsegdep = NULL;
4021 	freeblks = jblkdep->jb_freeblks;
4022 	LIST_REMOVE(jblkdep, jb_deps);
4023 	jwork_insert(&freeblks->fb_jwork, jsegdep);
4024 	/*
4025 	 * If the freeblks is all journaled, we can add it to the worklist.
4026 	 */
4027 	if (LIST_EMPTY(&freeblks->fb_jblkdephd) &&
4028 	    (freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
4029 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
4030 
4031 	free_jblkdep(jblkdep);
4032 }
4033 
4034 static struct jsegdep *
4035 newjsegdep(struct worklist *wk)
4036 {
4037 	struct jsegdep *jsegdep;
4038 
4039 	jsegdep = malloc(sizeof(*jsegdep), M_JSEGDEP, M_SOFTDEP_FLAGS);
4040 	workitem_alloc(&jsegdep->jd_list, D_JSEGDEP, wk->wk_mp);
4041 	jsegdep->jd_seg = NULL;
4042 
4043 	return (jsegdep);
4044 }
4045 
4046 static struct jmvref *
4047 newjmvref(dp, ino, oldoff, newoff)
4048 	struct inode *dp;
4049 	ino_t ino;
4050 	off_t oldoff;
4051 	off_t newoff;
4052 {
4053 	struct jmvref *jmvref;
4054 
4055 	jmvref = malloc(sizeof(*jmvref), M_JMVREF, M_SOFTDEP_FLAGS);
4056 	workitem_alloc(&jmvref->jm_list, D_JMVREF, ITOVFS(dp));
4057 	jmvref->jm_list.wk_state = ATTACHED | DEPCOMPLETE;
4058 	jmvref->jm_parent = dp->i_number;
4059 	jmvref->jm_ino = ino;
4060 	jmvref->jm_oldoff = oldoff;
4061 	jmvref->jm_newoff = newoff;
4062 
4063 	return (jmvref);
4064 }
4065 
4066 /*
4067  * Allocate a new jremref that tracks the removal of ip from dp with the
4068  * directory entry offset of diroff.  Mark the entry as ATTACHED and
4069  * DEPCOMPLETE as we have all the information required for the journal write
4070  * and the directory has already been removed from the buffer.  The caller
4071  * is responsible for linking the jremref into the pagedep and adding it
4072  * to the journal to write.  The MKDIR_PARENT flag is set if we're doing
4073  * a DOTDOT addition so handle_workitem_remove() can properly assign
4074  * the jsegdep when we're done.
4075  */
4076 static struct jremref *
4077 newjremref(struct dirrem *dirrem, struct inode *dp, struct inode *ip,
4078     off_t diroff, nlink_t nlink)
4079 {
4080 	struct jremref *jremref;
4081 
4082 	jremref = malloc(sizeof(*jremref), M_JREMREF, M_SOFTDEP_FLAGS);
4083 	workitem_alloc(&jremref->jr_list, D_JREMREF, ITOVFS(dp));
4084 	jremref->jr_state = ATTACHED;
4085 	newinoref(&jremref->jr_ref, ip->i_number, dp->i_number, diroff,
4086 	   nlink, ip->i_mode);
4087 	jremref->jr_dirrem = dirrem;
4088 
4089 	return (jremref);
4090 }
4091 
4092 static inline void
4093 newinoref(struct inoref *inoref, ino_t ino, ino_t parent, off_t diroff,
4094     nlink_t nlink, uint16_t mode)
4095 {
4096 
4097 	inoref->if_jsegdep = newjsegdep(&inoref->if_list);
4098 	inoref->if_diroff = diroff;
4099 	inoref->if_ino = ino;
4100 	inoref->if_parent = parent;
4101 	inoref->if_nlink = nlink;
4102 	inoref->if_mode = mode;
4103 }
4104 
4105 /*
4106  * Allocate a new jaddref to track the addition of ino to dp at diroff.  The
4107  * directory offset may not be known until later.  The caller is responsible
4108  * adding the entry to the journal when this information is available.  nlink
4109  * should be the link count prior to the addition and mode is only required
4110  * to have the correct FMT.
4111  */
4112 static struct jaddref *
4113 newjaddref(struct inode *dp, ino_t ino, off_t diroff, int16_t nlink,
4114     uint16_t mode)
4115 {
4116 	struct jaddref *jaddref;
4117 
4118 	jaddref = malloc(sizeof(*jaddref), M_JADDREF, M_SOFTDEP_FLAGS);
4119 	workitem_alloc(&jaddref->ja_list, D_JADDREF, ITOVFS(dp));
4120 	jaddref->ja_state = ATTACHED;
4121 	jaddref->ja_mkdir = NULL;
4122 	newinoref(&jaddref->ja_ref, ino, dp->i_number, diroff, nlink, mode);
4123 
4124 	return (jaddref);
4125 }
4126 
4127 /*
4128  * Create a new free dependency for a freework.  The caller is responsible
4129  * for adjusting the reference count when it has the lock held.  The freedep
4130  * will track an outstanding bitmap write that will ultimately clear the
4131  * freework to continue.
4132  */
4133 static struct freedep *
4134 newfreedep(struct freework *freework)
4135 {
4136 	struct freedep *freedep;
4137 
4138 	freedep = malloc(sizeof(*freedep), M_FREEDEP, M_SOFTDEP_FLAGS);
4139 	workitem_alloc(&freedep->fd_list, D_FREEDEP, freework->fw_list.wk_mp);
4140 	freedep->fd_freework = freework;
4141 
4142 	return (freedep);
4143 }
4144 
4145 /*
4146  * Free a freedep structure once the buffer it is linked to is written.  If
4147  * this is the last reference to the freework schedule it for completion.
4148  */
4149 static void
4150 free_freedep(freedep)
4151 	struct freedep *freedep;
4152 {
4153 	struct freework *freework;
4154 
4155 	freework = freedep->fd_freework;
4156 	freework->fw_freeblks->fb_cgwait--;
4157 	if (--freework->fw_ref == 0)
4158 		freework_enqueue(freework);
4159 	WORKITEM_FREE(freedep, D_FREEDEP);
4160 }
4161 
4162 /*
4163  * Allocate a new freework structure that may be a level in an indirect
4164  * when parent is not NULL or a top level block when it is.  The top level
4165  * freework structures are allocated without the per-filesystem lock held
4166  * and before the freeblks is visible outside of softdep_setup_freeblocks().
4167  */
4168 static struct freework *
4169 newfreework(ump, freeblks, parent, lbn, nb, frags, off, journal)
4170 	struct ufsmount *ump;
4171 	struct freeblks *freeblks;
4172 	struct freework *parent;
4173 	ufs_lbn_t lbn;
4174 	ufs2_daddr_t nb;
4175 	int frags;
4176 	int off;
4177 	int journal;
4178 {
4179 	struct freework *freework;
4180 
4181 	freework = malloc(sizeof(*freework), M_FREEWORK, M_SOFTDEP_FLAGS);
4182 	workitem_alloc(&freework->fw_list, D_FREEWORK, freeblks->fb_list.wk_mp);
4183 	freework->fw_state = ATTACHED;
4184 	freework->fw_jnewblk = NULL;
4185 	freework->fw_freeblks = freeblks;
4186 	freework->fw_parent = parent;
4187 	freework->fw_lbn = lbn;
4188 	freework->fw_blkno = nb;
4189 	freework->fw_frags = frags;
4190 	freework->fw_indir = NULL;
4191 	freework->fw_ref = (MOUNTEDSUJ(UFSTOVFS(ump)) == 0 ||
4192 	    lbn >= -UFS_NXADDR) ? 0 : NINDIR(ump->um_fs) + 1;
4193 	freework->fw_start = freework->fw_off = off;
4194 	if (journal)
4195 		newjfreeblk(freeblks, lbn, nb, frags);
4196 	if (parent == NULL) {
4197 		ACQUIRE_LOCK(ump);
4198 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
4199 		freeblks->fb_ref++;
4200 		FREE_LOCK(ump);
4201 	}
4202 
4203 	return (freework);
4204 }
4205 
4206 /*
4207  * Eliminate a jfreeblk for a block that does not need journaling.
4208  */
4209 static void
4210 cancel_jfreeblk(freeblks, blkno)
4211 	struct freeblks *freeblks;
4212 	ufs2_daddr_t blkno;
4213 {
4214 	struct jfreeblk *jfreeblk;
4215 	struct jblkdep *jblkdep;
4216 
4217 	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps) {
4218 		if (jblkdep->jb_list.wk_type != D_JFREEBLK)
4219 			continue;
4220 		jfreeblk = WK_JFREEBLK(&jblkdep->jb_list);
4221 		if (jfreeblk->jf_blkno == blkno)
4222 			break;
4223 	}
4224 	if (jblkdep == NULL)
4225 		return;
4226 	CTR1(KTR_SUJ, "cancel_jfreeblk: blkno %jd", blkno);
4227 	free_jsegdep(jblkdep->jb_jsegdep);
4228 	LIST_REMOVE(jblkdep, jb_deps);
4229 	WORKITEM_FREE(jfreeblk, D_JFREEBLK);
4230 }
4231 
4232 /*
4233  * Allocate a new jfreeblk to journal top level block pointer when truncating
4234  * a file.  The caller must add this to the worklist when the per-filesystem
4235  * lock is held.
4236  */
4237 static struct jfreeblk *
4238 newjfreeblk(freeblks, lbn, blkno, frags)
4239 	struct freeblks *freeblks;
4240 	ufs_lbn_t lbn;
4241 	ufs2_daddr_t blkno;
4242 	int frags;
4243 {
4244 	struct jfreeblk *jfreeblk;
4245 
4246 	jfreeblk = malloc(sizeof(*jfreeblk), M_JFREEBLK, M_SOFTDEP_FLAGS);
4247 	workitem_alloc(&jfreeblk->jf_dep.jb_list, D_JFREEBLK,
4248 	    freeblks->fb_list.wk_mp);
4249 	jfreeblk->jf_dep.jb_jsegdep = newjsegdep(&jfreeblk->jf_dep.jb_list);
4250 	jfreeblk->jf_dep.jb_freeblks = freeblks;
4251 	jfreeblk->jf_ino = freeblks->fb_inum;
4252 	jfreeblk->jf_lbn = lbn;
4253 	jfreeblk->jf_blkno = blkno;
4254 	jfreeblk->jf_frags = frags;
4255 	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jfreeblk->jf_dep, jb_deps);
4256 
4257 	return (jfreeblk);
4258 }
4259 
4260 /*
4261  * The journal is only prepared to handle full-size block numbers, so we
4262  * have to adjust the record to reflect the change to a full-size block.
4263  * For example, suppose we have a block made up of fragments 8-15 and
4264  * want to free its last two fragments. We are given a request that says:
4265  *     FREEBLK ino=5, blkno=14, lbn=0, frags=2, oldfrags=0
4266  * where frags are the number of fragments to free and oldfrags are the
4267  * number of fragments to keep. To block align it, we have to change it to
4268  * have a valid full-size blkno, so it becomes:
4269  *     FREEBLK ino=5, blkno=8, lbn=0, frags=2, oldfrags=6
4270  */
4271 static void
4272 adjust_newfreework(freeblks, frag_offset)
4273 	struct freeblks *freeblks;
4274 	int frag_offset;
4275 {
4276 	struct jfreeblk *jfreeblk;
4277 
4278 	KASSERT((LIST_FIRST(&freeblks->fb_jblkdephd) != NULL &&
4279 	    LIST_FIRST(&freeblks->fb_jblkdephd)->jb_list.wk_type == D_JFREEBLK),
4280 	    ("adjust_newfreework: Missing freeblks dependency"));
4281 
4282 	jfreeblk = WK_JFREEBLK(LIST_FIRST(&freeblks->fb_jblkdephd));
4283 	jfreeblk->jf_blkno -= frag_offset;
4284 	jfreeblk->jf_frags += frag_offset;
4285 }
4286 
4287 /*
4288  * Allocate a new jtrunc to track a partial truncation.
4289  */
4290 static struct jtrunc *
4291 newjtrunc(freeblks, size, extsize)
4292 	struct freeblks *freeblks;
4293 	off_t size;
4294 	int extsize;
4295 {
4296 	struct jtrunc *jtrunc;
4297 
4298 	jtrunc = malloc(sizeof(*jtrunc), M_JTRUNC, M_SOFTDEP_FLAGS);
4299 	workitem_alloc(&jtrunc->jt_dep.jb_list, D_JTRUNC,
4300 	    freeblks->fb_list.wk_mp);
4301 	jtrunc->jt_dep.jb_jsegdep = newjsegdep(&jtrunc->jt_dep.jb_list);
4302 	jtrunc->jt_dep.jb_freeblks = freeblks;
4303 	jtrunc->jt_ino = freeblks->fb_inum;
4304 	jtrunc->jt_size = size;
4305 	jtrunc->jt_extsize = extsize;
4306 	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jtrunc->jt_dep, jb_deps);
4307 
4308 	return (jtrunc);
4309 }
4310 
4311 /*
4312  * If we're canceling a new bitmap we have to search for another ref
4313  * to move into the bmsafemap dep.  This might be better expressed
4314  * with another structure.
4315  */
4316 static void
4317 move_newblock_dep(jaddref, inodedep)
4318 	struct jaddref *jaddref;
4319 	struct inodedep *inodedep;
4320 {
4321 	struct inoref *inoref;
4322 	struct jaddref *jaddrefn;
4323 
4324 	jaddrefn = NULL;
4325 	for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4326 	    inoref = TAILQ_NEXT(inoref, if_deps)) {
4327 		if ((jaddref->ja_state & NEWBLOCK) &&
4328 		    inoref->if_list.wk_type == D_JADDREF) {
4329 			jaddrefn = (struct jaddref *)inoref;
4330 			break;
4331 		}
4332 	}
4333 	if (jaddrefn == NULL)
4334 		return;
4335 	jaddrefn->ja_state &= ~(ATTACHED | UNDONE);
4336 	jaddrefn->ja_state |= jaddref->ja_state &
4337 	    (ATTACHED | UNDONE | NEWBLOCK);
4338 	jaddref->ja_state &= ~(ATTACHED | UNDONE | NEWBLOCK);
4339 	jaddref->ja_state |= ATTACHED;
4340 	LIST_REMOVE(jaddref, ja_bmdeps);
4341 	LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_jaddrefhd, jaddrefn,
4342 	    ja_bmdeps);
4343 }
4344 
4345 /*
4346  * Cancel a jaddref either before it has been written or while it is being
4347  * written.  This happens when a link is removed before the add reaches
4348  * the disk.  The jaddref dependency is kept linked into the bmsafemap
4349  * and inode to prevent the link count or bitmap from reaching the disk
4350  * until handle_workitem_remove() re-adjusts the counts and bitmaps as
4351  * required.
4352  *
4353  * Returns 1 if the canceled addref requires journaling of the remove and
4354  * 0 otherwise.
4355  */
4356 static int
4357 cancel_jaddref(jaddref, inodedep, wkhd)
4358 	struct jaddref *jaddref;
4359 	struct inodedep *inodedep;
4360 	struct workhead *wkhd;
4361 {
4362 	struct inoref *inoref;
4363 	struct jsegdep *jsegdep;
4364 	int needsj;
4365 
4366 	KASSERT((jaddref->ja_state & COMPLETE) == 0,
4367 	    ("cancel_jaddref: Canceling complete jaddref"));
4368 	if (jaddref->ja_state & (INPROGRESS | COMPLETE))
4369 		needsj = 1;
4370 	else
4371 		needsj = 0;
4372 	if (inodedep == NULL)
4373 		if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
4374 		    0, &inodedep) == 0)
4375 			panic("cancel_jaddref: Lost inodedep");
4376 	/*
4377 	 * We must adjust the nlink of any reference operation that follows
4378 	 * us so that it is consistent with the in-memory reference.  This
4379 	 * ensures that inode nlink rollbacks always have the correct link.
4380 	 */
4381 	if (needsj == 0) {
4382 		for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4383 		    inoref = TAILQ_NEXT(inoref, if_deps)) {
4384 			if (inoref->if_state & GOINGAWAY)
4385 				break;
4386 			inoref->if_nlink--;
4387 		}
4388 	}
4389 	jsegdep = inoref_jseg(&jaddref->ja_ref);
4390 	if (jaddref->ja_state & NEWBLOCK)
4391 		move_newblock_dep(jaddref, inodedep);
4392 	wake_worklist(&jaddref->ja_list);
4393 	jaddref->ja_mkdir = NULL;
4394 	if (jaddref->ja_state & INPROGRESS) {
4395 		jaddref->ja_state &= ~INPROGRESS;
4396 		WORKLIST_REMOVE(&jaddref->ja_list);
4397 		jwork_insert(wkhd, jsegdep);
4398 	} else {
4399 		free_jsegdep(jsegdep);
4400 		if (jaddref->ja_state & DEPCOMPLETE)
4401 			remove_from_journal(&jaddref->ja_list);
4402 	}
4403 	jaddref->ja_state |= (GOINGAWAY | DEPCOMPLETE);
4404 	/*
4405 	 * Leave NEWBLOCK jaddrefs on the inodedep so handle_workitem_remove
4406 	 * can arrange for them to be freed with the bitmap.  Otherwise we
4407 	 * no longer need this addref attached to the inoreflst and it
4408 	 * will incorrectly adjust nlink if we leave it.
4409 	 */
4410 	if ((jaddref->ja_state & NEWBLOCK) == 0) {
4411 		TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
4412 		    if_deps);
4413 		jaddref->ja_state |= COMPLETE;
4414 		free_jaddref(jaddref);
4415 		return (needsj);
4416 	}
4417 	/*
4418 	 * Leave the head of the list for jsegdeps for fast merging.
4419 	 */
4420 	if (LIST_FIRST(wkhd) != NULL) {
4421 		jaddref->ja_state |= ONWORKLIST;
4422 		LIST_INSERT_AFTER(LIST_FIRST(wkhd), &jaddref->ja_list, wk_list);
4423 	} else
4424 		WORKLIST_INSERT(wkhd, &jaddref->ja_list);
4425 
4426 	return (needsj);
4427 }
4428 
4429 /*
4430  * Attempt to free a jaddref structure when some work completes.  This
4431  * should only succeed once the entry is written and all dependencies have
4432  * been notified.
4433  */
4434 static void
4435 free_jaddref(jaddref)
4436 	struct jaddref *jaddref;
4437 {
4438 
4439 	if ((jaddref->ja_state & ALLCOMPLETE) != ALLCOMPLETE)
4440 		return;
4441 	if (jaddref->ja_ref.if_jsegdep)
4442 		panic("free_jaddref: segdep attached to jaddref %p(0x%X)\n",
4443 		    jaddref, jaddref->ja_state);
4444 	if (jaddref->ja_state & NEWBLOCK)
4445 		LIST_REMOVE(jaddref, ja_bmdeps);
4446 	if (jaddref->ja_state & (INPROGRESS | ONWORKLIST))
4447 		panic("free_jaddref: Bad state %p(0x%X)",
4448 		    jaddref, jaddref->ja_state);
4449 	if (jaddref->ja_mkdir != NULL)
4450 		panic("free_jaddref: Work pending, 0x%X\n", jaddref->ja_state);
4451 	WORKITEM_FREE(jaddref, D_JADDREF);
4452 }
4453 
4454 /*
4455  * Free a jremref structure once it has been written or discarded.
4456  */
4457 static void
4458 free_jremref(jremref)
4459 	struct jremref *jremref;
4460 {
4461 
4462 	if (jremref->jr_ref.if_jsegdep)
4463 		free_jsegdep(jremref->jr_ref.if_jsegdep);
4464 	if (jremref->jr_state & INPROGRESS)
4465 		panic("free_jremref: IO still pending");
4466 	WORKITEM_FREE(jremref, D_JREMREF);
4467 }
4468 
4469 /*
4470  * Free a jnewblk structure.
4471  */
4472 static void
4473 free_jnewblk(jnewblk)
4474 	struct jnewblk *jnewblk;
4475 {
4476 
4477 	if ((jnewblk->jn_state & ALLCOMPLETE) != ALLCOMPLETE)
4478 		return;
4479 	LIST_REMOVE(jnewblk, jn_deps);
4480 	if (jnewblk->jn_dep != NULL)
4481 		panic("free_jnewblk: Dependency still attached.");
4482 	WORKITEM_FREE(jnewblk, D_JNEWBLK);
4483 }
4484 
4485 /*
4486  * Cancel a jnewblk which has been been made redundant by frag extension.
4487  */
4488 static void
4489 cancel_jnewblk(jnewblk, wkhd)
4490 	struct jnewblk *jnewblk;
4491 	struct workhead *wkhd;
4492 {
4493 	struct jsegdep *jsegdep;
4494 
4495 	CTR1(KTR_SUJ, "cancel_jnewblk: blkno %jd", jnewblk->jn_blkno);
4496 	jsegdep = jnewblk->jn_jsegdep;
4497 	if (jnewblk->jn_jsegdep == NULL || jnewblk->jn_dep == NULL)
4498 		panic("cancel_jnewblk: Invalid state");
4499 	jnewblk->jn_jsegdep  = NULL;
4500 	jnewblk->jn_dep = NULL;
4501 	jnewblk->jn_state |= GOINGAWAY;
4502 	if (jnewblk->jn_state & INPROGRESS) {
4503 		jnewblk->jn_state &= ~INPROGRESS;
4504 		WORKLIST_REMOVE(&jnewblk->jn_list);
4505 		jwork_insert(wkhd, jsegdep);
4506 	} else {
4507 		free_jsegdep(jsegdep);
4508 		remove_from_journal(&jnewblk->jn_list);
4509 	}
4510 	wake_worklist(&jnewblk->jn_list);
4511 	WORKLIST_INSERT(wkhd, &jnewblk->jn_list);
4512 }
4513 
4514 static void
4515 free_jblkdep(jblkdep)
4516 	struct jblkdep *jblkdep;
4517 {
4518 
4519 	if (jblkdep->jb_list.wk_type == D_JFREEBLK)
4520 		WORKITEM_FREE(jblkdep, D_JFREEBLK);
4521 	else if (jblkdep->jb_list.wk_type == D_JTRUNC)
4522 		WORKITEM_FREE(jblkdep, D_JTRUNC);
4523 	else
4524 		panic("free_jblkdep: Unexpected type %s",
4525 		    TYPENAME(jblkdep->jb_list.wk_type));
4526 }
4527 
4528 /*
4529  * Free a single jseg once it is no longer referenced in memory or on
4530  * disk.  Reclaim journal blocks and dependencies waiting for the segment
4531  * to disappear.
4532  */
4533 static void
4534 free_jseg(jseg, jblocks)
4535 	struct jseg *jseg;
4536 	struct jblocks *jblocks;
4537 {
4538 	struct freework *freework;
4539 
4540 	/*
4541 	 * Free freework structures that were lingering to indicate freed
4542 	 * indirect blocks that forced journal write ordering on reallocate.
4543 	 */
4544 	while ((freework = LIST_FIRST(&jseg->js_indirs)) != NULL)
4545 		indirblk_remove(freework);
4546 	if (jblocks->jb_oldestseg == jseg)
4547 		jblocks->jb_oldestseg = TAILQ_NEXT(jseg, js_next);
4548 	TAILQ_REMOVE(&jblocks->jb_segs, jseg, js_next);
4549 	jblocks_free(jblocks, jseg->js_list.wk_mp, jseg->js_size);
4550 	KASSERT(LIST_EMPTY(&jseg->js_entries),
4551 	    ("free_jseg: Freed jseg has valid entries."));
4552 	WORKITEM_FREE(jseg, D_JSEG);
4553 }
4554 
4555 /*
4556  * Free all jsegs that meet the criteria for being reclaimed and update
4557  * oldestseg.
4558  */
4559 static void
4560 free_jsegs(jblocks)
4561 	struct jblocks *jblocks;
4562 {
4563 	struct jseg *jseg;
4564 
4565 	/*
4566 	 * Free only those jsegs which have none allocated before them to
4567 	 * preserve the journal space ordering.
4568 	 */
4569 	while ((jseg = TAILQ_FIRST(&jblocks->jb_segs)) != NULL) {
4570 		/*
4571 		 * Only reclaim space when nothing depends on this journal
4572 		 * set and another set has written that it is no longer
4573 		 * valid.
4574 		 */
4575 		if (jseg->js_refs != 0) {
4576 			jblocks->jb_oldestseg = jseg;
4577 			return;
4578 		}
4579 		if ((jseg->js_state & ALLCOMPLETE) != ALLCOMPLETE)
4580 			break;
4581 		if (jseg->js_seq > jblocks->jb_oldestwrseq)
4582 			break;
4583 		/*
4584 		 * We can free jsegs that didn't write entries when
4585 		 * oldestwrseq == js_seq.
4586 		 */
4587 		if (jseg->js_seq == jblocks->jb_oldestwrseq &&
4588 		    jseg->js_cnt != 0)
4589 			break;
4590 		free_jseg(jseg, jblocks);
4591 	}
4592 	/*
4593 	 * If we exited the loop above we still must discover the
4594 	 * oldest valid segment.
4595 	 */
4596 	if (jseg)
4597 		for (jseg = jblocks->jb_oldestseg; jseg != NULL;
4598 		     jseg = TAILQ_NEXT(jseg, js_next))
4599 			if (jseg->js_refs != 0)
4600 				break;
4601 	jblocks->jb_oldestseg = jseg;
4602 	/*
4603 	 * The journal has no valid records but some jsegs may still be
4604 	 * waiting on oldestwrseq to advance.  We force a small record
4605 	 * out to permit these lingering records to be reclaimed.
4606 	 */
4607 	if (jblocks->jb_oldestseg == NULL && !TAILQ_EMPTY(&jblocks->jb_segs))
4608 		jblocks->jb_needseg = 1;
4609 }
4610 
4611 /*
4612  * Release one reference to a jseg and free it if the count reaches 0.  This
4613  * should eventually reclaim journal space as well.
4614  */
4615 static void
4616 rele_jseg(jseg)
4617 	struct jseg *jseg;
4618 {
4619 
4620 	KASSERT(jseg->js_refs > 0,
4621 	    ("free_jseg: Invalid refcnt %d", jseg->js_refs));
4622 	if (--jseg->js_refs != 0)
4623 		return;
4624 	free_jsegs(jseg->js_jblocks);
4625 }
4626 
4627 /*
4628  * Release a jsegdep and decrement the jseg count.
4629  */
4630 static void
4631 free_jsegdep(jsegdep)
4632 	struct jsegdep *jsegdep;
4633 {
4634 
4635 	if (jsegdep->jd_seg)
4636 		rele_jseg(jsegdep->jd_seg);
4637 	WORKITEM_FREE(jsegdep, D_JSEGDEP);
4638 }
4639 
4640 /*
4641  * Wait for a journal item to make it to disk.  Initiate journal processing
4642  * if required.
4643  */
4644 static int
4645 jwait(wk, waitfor)
4646 	struct worklist *wk;
4647 	int waitfor;
4648 {
4649 
4650 	LOCK_OWNED(VFSTOUFS(wk->wk_mp));
4651 	/*
4652 	 * Blocking journal waits cause slow synchronous behavior.  Record
4653 	 * stats on the frequency of these blocking operations.
4654 	 */
4655 	if (waitfor == MNT_WAIT) {
4656 		stat_journal_wait++;
4657 		switch (wk->wk_type) {
4658 		case D_JREMREF:
4659 		case D_JMVREF:
4660 			stat_jwait_filepage++;
4661 			break;
4662 		case D_JTRUNC:
4663 		case D_JFREEBLK:
4664 			stat_jwait_freeblks++;
4665 			break;
4666 		case D_JNEWBLK:
4667 			stat_jwait_newblk++;
4668 			break;
4669 		case D_JADDREF:
4670 			stat_jwait_inode++;
4671 			break;
4672 		default:
4673 			break;
4674 		}
4675 	}
4676 	/*
4677 	 * If IO has not started we process the journal.  We can't mark the
4678 	 * worklist item as IOWAITING because we drop the lock while
4679 	 * processing the journal and the worklist entry may be freed after
4680 	 * this point.  The caller may call back in and re-issue the request.
4681 	 */
4682 	if ((wk->wk_state & INPROGRESS) == 0) {
4683 		softdep_process_journal(wk->wk_mp, wk, waitfor);
4684 		if (waitfor != MNT_WAIT)
4685 			return (EBUSY);
4686 		return (0);
4687 	}
4688 	if (waitfor != MNT_WAIT)
4689 		return (EBUSY);
4690 	wait_worklist(wk, "jwait");
4691 	return (0);
4692 }
4693 
4694 /*
4695  * Lookup an inodedep based on an inode pointer and set the nlinkdelta as
4696  * appropriate.  This is a convenience function to reduce duplicate code
4697  * for the setup and revert functions below.
4698  */
4699 static struct inodedep *
4700 inodedep_lookup_ip(ip)
4701 	struct inode *ip;
4702 {
4703 	struct inodedep *inodedep;
4704 
4705 	KASSERT(ip->i_nlink >= ip->i_effnlink,
4706 	    ("inodedep_lookup_ip: bad delta"));
4707 	(void) inodedep_lookup(ITOVFS(ip), ip->i_number, DEPALLOC,
4708 	    &inodedep);
4709 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
4710 	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
4711 
4712 	return (inodedep);
4713 }
4714 
4715 /*
4716  * Called prior to creating a new inode and linking it to a directory.  The
4717  * jaddref structure must already be allocated by softdep_setup_inomapdep
4718  * and it is discovered here so we can initialize the mode and update
4719  * nlinkdelta.
4720  */
4721 void
4722 softdep_setup_create(dp, ip)
4723 	struct inode *dp;
4724 	struct inode *ip;
4725 {
4726 	struct inodedep *inodedep;
4727 	struct jaddref *jaddref;
4728 	struct vnode *dvp;
4729 
4730 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4731 	    ("softdep_setup_create called on non-softdep filesystem"));
4732 	KASSERT(ip->i_nlink == 1,
4733 	    ("softdep_setup_create: Invalid link count."));
4734 	dvp = ITOV(dp);
4735 	ACQUIRE_LOCK(ITOUMP(dp));
4736 	inodedep = inodedep_lookup_ip(ip);
4737 	if (DOINGSUJ(dvp)) {
4738 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4739 		    inoreflst);
4740 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
4741 		    ("softdep_setup_create: No addref structure present."));
4742 	}
4743 	softdep_prelink(dvp, NULL);
4744 	FREE_LOCK(ITOUMP(dp));
4745 }
4746 
4747 /*
4748  * Create a jaddref structure to track the addition of a DOTDOT link when
4749  * we are reparenting an inode as part of a rename.  This jaddref will be
4750  * found by softdep_setup_directory_change.  Adjusts nlinkdelta for
4751  * non-journaling softdep.
4752  */
4753 void
4754 softdep_setup_dotdot_link(dp, ip)
4755 	struct inode *dp;
4756 	struct inode *ip;
4757 {
4758 	struct inodedep *inodedep;
4759 	struct jaddref *jaddref;
4760 	struct vnode *dvp;
4761 
4762 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4763 	    ("softdep_setup_dotdot_link called on non-softdep filesystem"));
4764 	dvp = ITOV(dp);
4765 	jaddref = NULL;
4766 	/*
4767 	 * We don't set MKDIR_PARENT as this is not tied to a mkdir and
4768 	 * is used as a normal link would be.
4769 	 */
4770 	if (DOINGSUJ(dvp))
4771 		jaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4772 		    dp->i_effnlink - 1, dp->i_mode);
4773 	ACQUIRE_LOCK(ITOUMP(dp));
4774 	inodedep = inodedep_lookup_ip(dp);
4775 	if (jaddref)
4776 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4777 		    if_deps);
4778 	softdep_prelink(dvp, ITOV(ip));
4779 	FREE_LOCK(ITOUMP(dp));
4780 }
4781 
4782 /*
4783  * Create a jaddref structure to track a new link to an inode.  The directory
4784  * offset is not known until softdep_setup_directory_add or
4785  * softdep_setup_directory_change.  Adjusts nlinkdelta for non-journaling
4786  * softdep.
4787  */
4788 void
4789 softdep_setup_link(dp, ip)
4790 	struct inode *dp;
4791 	struct inode *ip;
4792 {
4793 	struct inodedep *inodedep;
4794 	struct jaddref *jaddref;
4795 	struct vnode *dvp;
4796 
4797 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4798 	    ("softdep_setup_link called on non-softdep filesystem"));
4799 	dvp = ITOV(dp);
4800 	jaddref = NULL;
4801 	if (DOINGSUJ(dvp))
4802 		jaddref = newjaddref(dp, ip->i_number, 0, ip->i_effnlink - 1,
4803 		    ip->i_mode);
4804 	ACQUIRE_LOCK(ITOUMP(dp));
4805 	inodedep = inodedep_lookup_ip(ip);
4806 	if (jaddref)
4807 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4808 		    if_deps);
4809 	softdep_prelink(dvp, ITOV(ip));
4810 	FREE_LOCK(ITOUMP(dp));
4811 }
4812 
4813 /*
4814  * Called to create the jaddref structures to track . and .. references as
4815  * well as lookup and further initialize the incomplete jaddref created
4816  * by softdep_setup_inomapdep when the inode was allocated.  Adjusts
4817  * nlinkdelta for non-journaling softdep.
4818  */
4819 void
4820 softdep_setup_mkdir(dp, ip)
4821 	struct inode *dp;
4822 	struct inode *ip;
4823 {
4824 	struct inodedep *inodedep;
4825 	struct jaddref *dotdotaddref;
4826 	struct jaddref *dotaddref;
4827 	struct jaddref *jaddref;
4828 	struct vnode *dvp;
4829 
4830 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4831 	    ("softdep_setup_mkdir called on non-softdep filesystem"));
4832 	dvp = ITOV(dp);
4833 	dotaddref = dotdotaddref = NULL;
4834 	if (DOINGSUJ(dvp)) {
4835 		dotaddref = newjaddref(ip, ip->i_number, DOT_OFFSET, 1,
4836 		    ip->i_mode);
4837 		dotaddref->ja_state |= MKDIR_BODY;
4838 		dotdotaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4839 		    dp->i_effnlink - 1, dp->i_mode);
4840 		dotdotaddref->ja_state |= MKDIR_PARENT;
4841 	}
4842 	ACQUIRE_LOCK(ITOUMP(dp));
4843 	inodedep = inodedep_lookup_ip(ip);
4844 	if (DOINGSUJ(dvp)) {
4845 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4846 		    inoreflst);
4847 		KASSERT(jaddref != NULL,
4848 		    ("softdep_setup_mkdir: No addref structure present."));
4849 		KASSERT(jaddref->ja_parent == dp->i_number,
4850 		    ("softdep_setup_mkdir: bad parent %ju",
4851 		    (uintmax_t)jaddref->ja_parent));
4852 		TAILQ_INSERT_BEFORE(&jaddref->ja_ref, &dotaddref->ja_ref,
4853 		    if_deps);
4854 	}
4855 	inodedep = inodedep_lookup_ip(dp);
4856 	if (DOINGSUJ(dvp))
4857 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst,
4858 		    &dotdotaddref->ja_ref, if_deps);
4859 	softdep_prelink(ITOV(dp), NULL);
4860 	FREE_LOCK(ITOUMP(dp));
4861 }
4862 
4863 /*
4864  * Called to track nlinkdelta of the inode and parent directories prior to
4865  * unlinking a directory.
4866  */
4867 void
4868 softdep_setup_rmdir(dp, ip)
4869 	struct inode *dp;
4870 	struct inode *ip;
4871 {
4872 	struct vnode *dvp;
4873 
4874 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4875 	    ("softdep_setup_rmdir called on non-softdep filesystem"));
4876 	dvp = ITOV(dp);
4877 	ACQUIRE_LOCK(ITOUMP(dp));
4878 	(void) inodedep_lookup_ip(ip);
4879 	(void) inodedep_lookup_ip(dp);
4880 	softdep_prelink(dvp, ITOV(ip));
4881 	FREE_LOCK(ITOUMP(dp));
4882 }
4883 
4884 /*
4885  * Called to track nlinkdelta of the inode and parent directories prior to
4886  * unlink.
4887  */
4888 void
4889 softdep_setup_unlink(dp, ip)
4890 	struct inode *dp;
4891 	struct inode *ip;
4892 {
4893 	struct vnode *dvp;
4894 
4895 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4896 	    ("softdep_setup_unlink called on non-softdep filesystem"));
4897 	dvp = ITOV(dp);
4898 	ACQUIRE_LOCK(ITOUMP(dp));
4899 	(void) inodedep_lookup_ip(ip);
4900 	(void) inodedep_lookup_ip(dp);
4901 	softdep_prelink(dvp, ITOV(ip));
4902 	FREE_LOCK(ITOUMP(dp));
4903 }
4904 
4905 /*
4906  * Called to release the journal structures created by a failed non-directory
4907  * creation.  Adjusts nlinkdelta for non-journaling softdep.
4908  */
4909 void
4910 softdep_revert_create(dp, ip)
4911 	struct inode *dp;
4912 	struct inode *ip;
4913 {
4914 	struct inodedep *inodedep;
4915 	struct jaddref *jaddref;
4916 	struct vnode *dvp;
4917 
4918 	KASSERT(MOUNTEDSOFTDEP(ITOVFS((dp))) != 0,
4919 	    ("softdep_revert_create called on non-softdep filesystem"));
4920 	dvp = ITOV(dp);
4921 	ACQUIRE_LOCK(ITOUMP(dp));
4922 	inodedep = inodedep_lookup_ip(ip);
4923 	if (DOINGSUJ(dvp)) {
4924 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4925 		    inoreflst);
4926 		KASSERT(jaddref->ja_parent == dp->i_number,
4927 		    ("softdep_revert_create: addref parent mismatch"));
4928 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4929 	}
4930 	FREE_LOCK(ITOUMP(dp));
4931 }
4932 
4933 /*
4934  * Called to release the journal structures created by a failed link
4935  * addition.  Adjusts nlinkdelta for non-journaling softdep.
4936  */
4937 void
4938 softdep_revert_link(dp, ip)
4939 	struct inode *dp;
4940 	struct inode *ip;
4941 {
4942 	struct inodedep *inodedep;
4943 	struct jaddref *jaddref;
4944 	struct vnode *dvp;
4945 
4946 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4947 	    ("softdep_revert_link called on non-softdep filesystem"));
4948 	dvp = ITOV(dp);
4949 	ACQUIRE_LOCK(ITOUMP(dp));
4950 	inodedep = inodedep_lookup_ip(ip);
4951 	if (DOINGSUJ(dvp)) {
4952 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4953 		    inoreflst);
4954 		KASSERT(jaddref->ja_parent == dp->i_number,
4955 		    ("softdep_revert_link: addref parent mismatch"));
4956 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4957 	}
4958 	FREE_LOCK(ITOUMP(dp));
4959 }
4960 
4961 /*
4962  * Called to release the journal structures created by a failed mkdir
4963  * attempt.  Adjusts nlinkdelta for non-journaling softdep.
4964  */
4965 void
4966 softdep_revert_mkdir(dp, ip)
4967 	struct inode *dp;
4968 	struct inode *ip;
4969 {
4970 	struct inodedep *inodedep;
4971 	struct jaddref *jaddref;
4972 	struct jaddref *dotaddref;
4973 	struct vnode *dvp;
4974 
4975 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4976 	    ("softdep_revert_mkdir called on non-softdep filesystem"));
4977 	dvp = ITOV(dp);
4978 
4979 	ACQUIRE_LOCK(ITOUMP(dp));
4980 	inodedep = inodedep_lookup_ip(dp);
4981 	if (DOINGSUJ(dvp)) {
4982 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4983 		    inoreflst);
4984 		KASSERT(jaddref->ja_parent == ip->i_number,
4985 		    ("softdep_revert_mkdir: dotdot addref parent mismatch"));
4986 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4987 	}
4988 	inodedep = inodedep_lookup_ip(ip);
4989 	if (DOINGSUJ(dvp)) {
4990 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4991 		    inoreflst);
4992 		KASSERT(jaddref->ja_parent == dp->i_number,
4993 		    ("softdep_revert_mkdir: addref parent mismatch"));
4994 		dotaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
4995 		    inoreflst, if_deps);
4996 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4997 		KASSERT(dotaddref->ja_parent == ip->i_number,
4998 		    ("softdep_revert_mkdir: dot addref parent mismatch"));
4999 		cancel_jaddref(dotaddref, inodedep, &inodedep->id_inowait);
5000 	}
5001 	FREE_LOCK(ITOUMP(dp));
5002 }
5003 
5004 /*
5005  * Called to correct nlinkdelta after a failed rmdir.
5006  */
5007 void
5008 softdep_revert_rmdir(dp, ip)
5009 	struct inode *dp;
5010 	struct inode *ip;
5011 {
5012 
5013 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5014 	    ("softdep_revert_rmdir called on non-softdep filesystem"));
5015 	ACQUIRE_LOCK(ITOUMP(dp));
5016 	(void) inodedep_lookup_ip(ip);
5017 	(void) inodedep_lookup_ip(dp);
5018 	FREE_LOCK(ITOUMP(dp));
5019 }
5020 
5021 /*
5022  * Protecting the freemaps (or bitmaps).
5023  *
5024  * To eliminate the need to execute fsck before mounting a filesystem
5025  * after a power failure, one must (conservatively) guarantee that the
5026  * on-disk copy of the bitmaps never indicate that a live inode or block is
5027  * free.  So, when a block or inode is allocated, the bitmap should be
5028  * updated (on disk) before any new pointers.  When a block or inode is
5029  * freed, the bitmap should not be updated until all pointers have been
5030  * reset.  The latter dependency is handled by the delayed de-allocation
5031  * approach described below for block and inode de-allocation.  The former
5032  * dependency is handled by calling the following procedure when a block or
5033  * inode is allocated. When an inode is allocated an "inodedep" is created
5034  * with its DEPCOMPLETE flag cleared until its bitmap is written to disk.
5035  * Each "inodedep" is also inserted into the hash indexing structure so
5036  * that any additional link additions can be made dependent on the inode
5037  * allocation.
5038  *
5039  * The ufs filesystem maintains a number of free block counts (e.g., per
5040  * cylinder group, per cylinder and per <cylinder, rotational position> pair)
5041  * in addition to the bitmaps.  These counts are used to improve efficiency
5042  * during allocation and therefore must be consistent with the bitmaps.
5043  * There is no convenient way to guarantee post-crash consistency of these
5044  * counts with simple update ordering, for two main reasons: (1) The counts
5045  * and bitmaps for a single cylinder group block are not in the same disk
5046  * sector.  If a disk write is interrupted (e.g., by power failure), one may
5047  * be written and the other not.  (2) Some of the counts are located in the
5048  * superblock rather than the cylinder group block. So, we focus our soft
5049  * updates implementation on protecting the bitmaps. When mounting a
5050  * filesystem, we recompute the auxiliary counts from the bitmaps.
5051  */
5052 
5053 /*
5054  * Called just after updating the cylinder group block to allocate an inode.
5055  */
5056 void
5057 softdep_setup_inomapdep(bp, ip, newinum, mode)
5058 	struct buf *bp;		/* buffer for cylgroup block with inode map */
5059 	struct inode *ip;	/* inode related to allocation */
5060 	ino_t newinum;		/* new inode number being allocated */
5061 	int mode;
5062 {
5063 	struct inodedep *inodedep;
5064 	struct bmsafemap *bmsafemap;
5065 	struct jaddref *jaddref;
5066 	struct mount *mp;
5067 	struct fs *fs;
5068 
5069 	mp = ITOVFS(ip);
5070 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5071 	    ("softdep_setup_inomapdep called on non-softdep filesystem"));
5072 	fs = VFSTOUFS(mp)->um_fs;
5073 	jaddref = NULL;
5074 
5075 	/*
5076 	 * Allocate the journal reference add structure so that the bitmap
5077 	 * can be dependent on it.
5078 	 */
5079 	if (MOUNTEDSUJ(mp)) {
5080 		jaddref = newjaddref(ip, newinum, 0, 0, mode);
5081 		jaddref->ja_state |= NEWBLOCK;
5082 	}
5083 
5084 	/*
5085 	 * Create a dependency for the newly allocated inode.
5086 	 * Panic if it already exists as something is seriously wrong.
5087 	 * Otherwise add it to the dependency list for the buffer holding
5088 	 * the cylinder group map from which it was allocated.
5089 	 *
5090 	 * We have to preallocate a bmsafemap entry in case it is needed
5091 	 * in bmsafemap_lookup since once we allocate the inodedep, we
5092 	 * have to finish initializing it before we can FREE_LOCK().
5093 	 * By preallocating, we avoid FREE_LOCK() while doing a malloc
5094 	 * in bmsafemap_lookup. We cannot call bmsafemap_lookup before
5095 	 * creating the inodedep as it can be freed during the time
5096 	 * that we FREE_LOCK() while allocating the inodedep. We must
5097 	 * call workitem_alloc() before entering the locked section as
5098 	 * it also acquires the lock and we must avoid trying doing so
5099 	 * recursively.
5100 	 */
5101 	bmsafemap = malloc(sizeof(struct bmsafemap),
5102 	    M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5103 	workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5104 	ACQUIRE_LOCK(ITOUMP(ip));
5105 	if ((inodedep_lookup(mp, newinum, DEPALLOC, &inodedep)))
5106 		panic("softdep_setup_inomapdep: dependency %p for new"
5107 		    "inode already exists", inodedep);
5108 	bmsafemap = bmsafemap_lookup(mp, bp, ino_to_cg(fs, newinum), bmsafemap);
5109 	if (jaddref) {
5110 		LIST_INSERT_HEAD(&bmsafemap->sm_jaddrefhd, jaddref, ja_bmdeps);
5111 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
5112 		    if_deps);
5113 	} else {
5114 		inodedep->id_state |= ONDEPLIST;
5115 		LIST_INSERT_HEAD(&bmsafemap->sm_inodedephd, inodedep, id_deps);
5116 	}
5117 	inodedep->id_bmsafemap = bmsafemap;
5118 	inodedep->id_state &= ~DEPCOMPLETE;
5119 	FREE_LOCK(ITOUMP(ip));
5120 }
5121 
5122 /*
5123  * Called just after updating the cylinder group block to
5124  * allocate block or fragment.
5125  */
5126 void
5127 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
5128 	struct buf *bp;		/* buffer for cylgroup block with block map */
5129 	struct mount *mp;	/* filesystem doing allocation */
5130 	ufs2_daddr_t newblkno;	/* number of newly allocated block */
5131 	int frags;		/* Number of fragments. */
5132 	int oldfrags;		/* Previous number of fragments for extend. */
5133 {
5134 	struct newblk *newblk;
5135 	struct bmsafemap *bmsafemap;
5136 	struct jnewblk *jnewblk;
5137 	struct ufsmount *ump;
5138 	struct fs *fs;
5139 
5140 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5141 	    ("softdep_setup_blkmapdep called on non-softdep filesystem"));
5142 	ump = VFSTOUFS(mp);
5143 	fs = ump->um_fs;
5144 	jnewblk = NULL;
5145 	/*
5146 	 * Create a dependency for the newly allocated block.
5147 	 * Add it to the dependency list for the buffer holding
5148 	 * the cylinder group map from which it was allocated.
5149 	 */
5150 	if (MOUNTEDSUJ(mp)) {
5151 		jnewblk = malloc(sizeof(*jnewblk), M_JNEWBLK, M_SOFTDEP_FLAGS);
5152 		workitem_alloc(&jnewblk->jn_list, D_JNEWBLK, mp);
5153 		jnewblk->jn_jsegdep = newjsegdep(&jnewblk->jn_list);
5154 		jnewblk->jn_state = ATTACHED;
5155 		jnewblk->jn_blkno = newblkno;
5156 		jnewblk->jn_frags = frags;
5157 		jnewblk->jn_oldfrags = oldfrags;
5158 #ifdef INVARIANTS
5159 		{
5160 			struct cg *cgp;
5161 			uint8_t *blksfree;
5162 			long bno;
5163 			int i;
5164 
5165 			cgp = (struct cg *)bp->b_data;
5166 			blksfree = cg_blksfree(cgp);
5167 			bno = dtogd(fs, jnewblk->jn_blkno);
5168 			for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags;
5169 			    i++) {
5170 				if (isset(blksfree, bno + i))
5171 					panic("softdep_setup_blkmapdep: "
5172 					    "free fragment %d from %d-%d "
5173 					    "state 0x%X dep %p", i,
5174 					    jnewblk->jn_oldfrags,
5175 					    jnewblk->jn_frags,
5176 					    jnewblk->jn_state,
5177 					    jnewblk->jn_dep);
5178 			}
5179 		}
5180 #endif
5181 	}
5182 
5183 	CTR3(KTR_SUJ,
5184 	    "softdep_setup_blkmapdep: blkno %jd frags %d oldfrags %d",
5185 	    newblkno, frags, oldfrags);
5186 	ACQUIRE_LOCK(ump);
5187 	if (newblk_lookup(mp, newblkno, DEPALLOC, &newblk) != 0)
5188 		panic("softdep_setup_blkmapdep: found block");
5189 	newblk->nb_bmsafemap = bmsafemap = bmsafemap_lookup(mp, bp,
5190 	    dtog(fs, newblkno), NULL);
5191 	if (jnewblk) {
5192 		jnewblk->jn_dep = (struct worklist *)newblk;
5193 		LIST_INSERT_HEAD(&bmsafemap->sm_jnewblkhd, jnewblk, jn_deps);
5194 	} else {
5195 		newblk->nb_state |= ONDEPLIST;
5196 		LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
5197 	}
5198 	newblk->nb_bmsafemap = bmsafemap;
5199 	newblk->nb_jnewblk = jnewblk;
5200 	FREE_LOCK(ump);
5201 }
5202 
5203 #define	BMSAFEMAP_HASH(ump, cg) \
5204       (&(ump)->bmsafemap_hashtbl[(cg) & (ump)->bmsafemap_hash_size])
5205 
5206 static int
5207 bmsafemap_find(bmsafemaphd, cg, bmsafemapp)
5208 	struct bmsafemap_hashhead *bmsafemaphd;
5209 	int cg;
5210 	struct bmsafemap **bmsafemapp;
5211 {
5212 	struct bmsafemap *bmsafemap;
5213 
5214 	LIST_FOREACH(bmsafemap, bmsafemaphd, sm_hash)
5215 		if (bmsafemap->sm_cg == cg)
5216 			break;
5217 	if (bmsafemap) {
5218 		*bmsafemapp = bmsafemap;
5219 		return (1);
5220 	}
5221 	*bmsafemapp = NULL;
5222 
5223 	return (0);
5224 }
5225 
5226 /*
5227  * Find the bmsafemap associated with a cylinder group buffer.
5228  * If none exists, create one. The buffer must be locked when
5229  * this routine is called and this routine must be called with
5230  * the softdep lock held. To avoid giving up the lock while
5231  * allocating a new bmsafemap, a preallocated bmsafemap may be
5232  * provided. If it is provided but not needed, it is freed.
5233  */
5234 static struct bmsafemap *
5235 bmsafemap_lookup(mp, bp, cg, newbmsafemap)
5236 	struct mount *mp;
5237 	struct buf *bp;
5238 	int cg;
5239 	struct bmsafemap *newbmsafemap;
5240 {
5241 	struct bmsafemap_hashhead *bmsafemaphd;
5242 	struct bmsafemap *bmsafemap, *collision;
5243 	struct worklist *wk;
5244 	struct ufsmount *ump;
5245 
5246 	ump = VFSTOUFS(mp);
5247 	LOCK_OWNED(ump);
5248 	KASSERT(bp != NULL, ("bmsafemap_lookup: missing buffer"));
5249 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5250 		if (wk->wk_type == D_BMSAFEMAP) {
5251 			if (newbmsafemap)
5252 				WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5253 			return (WK_BMSAFEMAP(wk));
5254 		}
5255 	}
5256 	bmsafemaphd = BMSAFEMAP_HASH(ump, cg);
5257 	if (bmsafemap_find(bmsafemaphd, cg, &bmsafemap) == 1) {
5258 		if (newbmsafemap)
5259 			WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5260 		return (bmsafemap);
5261 	}
5262 	if (newbmsafemap) {
5263 		bmsafemap = newbmsafemap;
5264 	} else {
5265 		FREE_LOCK(ump);
5266 		bmsafemap = malloc(sizeof(struct bmsafemap),
5267 			M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5268 		workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5269 		ACQUIRE_LOCK(ump);
5270 	}
5271 	bmsafemap->sm_buf = bp;
5272 	LIST_INIT(&bmsafemap->sm_inodedephd);
5273 	LIST_INIT(&bmsafemap->sm_inodedepwr);
5274 	LIST_INIT(&bmsafemap->sm_newblkhd);
5275 	LIST_INIT(&bmsafemap->sm_newblkwr);
5276 	LIST_INIT(&bmsafemap->sm_jaddrefhd);
5277 	LIST_INIT(&bmsafemap->sm_jnewblkhd);
5278 	LIST_INIT(&bmsafemap->sm_freehd);
5279 	LIST_INIT(&bmsafemap->sm_freewr);
5280 	if (bmsafemap_find(bmsafemaphd, cg, &collision) == 1) {
5281 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
5282 		return (collision);
5283 	}
5284 	bmsafemap->sm_cg = cg;
5285 	LIST_INSERT_HEAD(bmsafemaphd, bmsafemap, sm_hash);
5286 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
5287 	WORKLIST_INSERT(&bp->b_dep, &bmsafemap->sm_list);
5288 	return (bmsafemap);
5289 }
5290 
5291 /*
5292  * Direct block allocation dependencies.
5293  *
5294  * When a new block is allocated, the corresponding disk locations must be
5295  * initialized (with zeros or new data) before the on-disk inode points to
5296  * them.  Also, the freemap from which the block was allocated must be
5297  * updated (on disk) before the inode's pointer. These two dependencies are
5298  * independent of each other and are needed for all file blocks and indirect
5299  * blocks that are pointed to directly by the inode.  Just before the
5300  * "in-core" version of the inode is updated with a newly allocated block
5301  * number, a procedure (below) is called to setup allocation dependency
5302  * structures.  These structures are removed when the corresponding
5303  * dependencies are satisfied or when the block allocation becomes obsolete
5304  * (i.e., the file is deleted, the block is de-allocated, or the block is a
5305  * fragment that gets upgraded).  All of these cases are handled in
5306  * procedures described later.
5307  *
5308  * When a file extension causes a fragment to be upgraded, either to a larger
5309  * fragment or to a full block, the on-disk location may change (if the
5310  * previous fragment could not simply be extended). In this case, the old
5311  * fragment must be de-allocated, but not until after the inode's pointer has
5312  * been updated. In most cases, this is handled by later procedures, which
5313  * will construct a "freefrag" structure to be added to the workitem queue
5314  * when the inode update is complete (or obsolete).  The main exception to
5315  * this is when an allocation occurs while a pending allocation dependency
5316  * (for the same block pointer) remains.  This case is handled in the main
5317  * allocation dependency setup procedure by immediately freeing the
5318  * unreferenced fragments.
5319  */
5320 void
5321 softdep_setup_allocdirect(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5322 	struct inode *ip;	/* inode to which block is being added */
5323 	ufs_lbn_t off;		/* block pointer within inode */
5324 	ufs2_daddr_t newblkno;	/* disk block number being added */
5325 	ufs2_daddr_t oldblkno;	/* previous block number, 0 unless frag */
5326 	long newsize;		/* size of new block */
5327 	long oldsize;		/* size of new block */
5328 	struct buf *bp;		/* bp for allocated block */
5329 {
5330 	struct allocdirect *adp, *oldadp;
5331 	struct allocdirectlst *adphead;
5332 	struct freefrag *freefrag;
5333 	struct inodedep *inodedep;
5334 	struct pagedep *pagedep;
5335 	struct jnewblk *jnewblk;
5336 	struct newblk *newblk;
5337 	struct mount *mp;
5338 	ufs_lbn_t lbn;
5339 
5340 	lbn = bp->b_lblkno;
5341 	mp = ITOVFS(ip);
5342 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5343 	    ("softdep_setup_allocdirect called on non-softdep filesystem"));
5344 	if (oldblkno && oldblkno != newblkno)
5345 		/*
5346 		 * The usual case is that a smaller fragment that
5347 		 * was just allocated has been replaced with a bigger
5348 		 * fragment or a full-size block. If it is marked as
5349 		 * B_DELWRI, the current contents have not been written
5350 		 * to disk. It is possible that the block was written
5351 		 * earlier, but very uncommon. If the block has never
5352 		 * been written, there is no need to send a BIO_DELETE
5353 		 * for it when it is freed. The gain from avoiding the
5354 		 * TRIMs for the common case of unwritten blocks far
5355 		 * exceeds the cost of the write amplification for the
5356 		 * uncommon case of failing to send a TRIM for a block
5357 		 * that had been written.
5358 		 */
5359 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn,
5360 		    (bp->b_flags & B_DELWRI) != 0 ? NOTRIM_KEY : SINGLETON_KEY);
5361 	else
5362 		freefrag = NULL;
5363 
5364 	CTR6(KTR_SUJ,
5365 	    "softdep_setup_allocdirect: ino %d blkno %jd oldblkno %jd "
5366 	    "off %jd newsize %ld oldsize %d",
5367 	    ip->i_number, newblkno, oldblkno, off, newsize, oldsize);
5368 	ACQUIRE_LOCK(ITOUMP(ip));
5369 	if (off >= UFS_NDADDR) {
5370 		if (lbn > 0)
5371 			panic("softdep_setup_allocdirect: bad lbn %jd, off %jd",
5372 			    lbn, off);
5373 		/* allocating an indirect block */
5374 		if (oldblkno != 0)
5375 			panic("softdep_setup_allocdirect: non-zero indir");
5376 	} else {
5377 		if (off != lbn)
5378 			panic("softdep_setup_allocdirect: lbn %jd != off %jd",
5379 			    lbn, off);
5380 		/*
5381 		 * Allocating a direct block.
5382 		 *
5383 		 * If we are allocating a directory block, then we must
5384 		 * allocate an associated pagedep to track additions and
5385 		 * deletions.
5386 		 */
5387 		if ((ip->i_mode & IFMT) == IFDIR)
5388 			pagedep_lookup(mp, bp, ip->i_number, off, DEPALLOC,
5389 			    &pagedep);
5390 	}
5391 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5392 		panic("softdep_setup_allocdirect: lost block");
5393 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5394 	    ("softdep_setup_allocdirect: newblk already initialized"));
5395 	/*
5396 	 * Convert the newblk to an allocdirect.
5397 	 */
5398 	WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5399 	adp = (struct allocdirect *)newblk;
5400 	newblk->nb_freefrag = freefrag;
5401 	adp->ad_offset = off;
5402 	adp->ad_oldblkno = oldblkno;
5403 	adp->ad_newsize = newsize;
5404 	adp->ad_oldsize = oldsize;
5405 
5406 	/*
5407 	 * Finish initializing the journal.
5408 	 */
5409 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5410 		jnewblk->jn_ino = ip->i_number;
5411 		jnewblk->jn_lbn = lbn;
5412 		add_to_journal(&jnewblk->jn_list);
5413 	}
5414 	if (freefrag && freefrag->ff_jdep != NULL &&
5415 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5416 		add_to_journal(freefrag->ff_jdep);
5417 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5418 	adp->ad_inodedep = inodedep;
5419 
5420 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5421 	/*
5422 	 * The list of allocdirects must be kept in sorted and ascending
5423 	 * order so that the rollback routines can quickly determine the
5424 	 * first uncommitted block (the size of the file stored on disk
5425 	 * ends at the end of the lowest committed fragment, or if there
5426 	 * are no fragments, at the end of the highest committed block).
5427 	 * Since files generally grow, the typical case is that the new
5428 	 * block is to be added at the end of the list. We speed this
5429 	 * special case by checking against the last allocdirect in the
5430 	 * list before laboriously traversing the list looking for the
5431 	 * insertion point.
5432 	 */
5433 	adphead = &inodedep->id_newinoupdt;
5434 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
5435 	if (oldadp == NULL || oldadp->ad_offset <= off) {
5436 		/* insert at end of list */
5437 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5438 		if (oldadp != NULL && oldadp->ad_offset == off)
5439 			allocdirect_merge(adphead, adp, oldadp);
5440 		FREE_LOCK(ITOUMP(ip));
5441 		return;
5442 	}
5443 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
5444 		if (oldadp->ad_offset >= off)
5445 			break;
5446 	}
5447 	if (oldadp == NULL)
5448 		panic("softdep_setup_allocdirect: lost entry");
5449 	/* insert in middle of list */
5450 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5451 	if (oldadp->ad_offset == off)
5452 		allocdirect_merge(adphead, adp, oldadp);
5453 
5454 	FREE_LOCK(ITOUMP(ip));
5455 }
5456 
5457 /*
5458  * Merge a newer and older journal record to be stored either in a
5459  * newblock or freefrag.  This handles aggregating journal records for
5460  * fragment allocation into a second record as well as replacing a
5461  * journal free with an aborted journal allocation.  A segment for the
5462  * oldest record will be placed on wkhd if it has been written.  If not
5463  * the segment for the newer record will suffice.
5464  */
5465 static struct worklist *
5466 jnewblk_merge(new, old, wkhd)
5467 	struct worklist *new;
5468 	struct worklist *old;
5469 	struct workhead *wkhd;
5470 {
5471 	struct jnewblk *njnewblk;
5472 	struct jnewblk *jnewblk;
5473 
5474 	/* Handle NULLs to simplify callers. */
5475 	if (new == NULL)
5476 		return (old);
5477 	if (old == NULL)
5478 		return (new);
5479 	/* Replace a jfreefrag with a jnewblk. */
5480 	if (new->wk_type == D_JFREEFRAG) {
5481 		if (WK_JNEWBLK(old)->jn_blkno != WK_JFREEFRAG(new)->fr_blkno)
5482 			panic("jnewblk_merge: blkno mismatch: %p, %p",
5483 			    old, new);
5484 		cancel_jfreefrag(WK_JFREEFRAG(new));
5485 		return (old);
5486 	}
5487 	if (old->wk_type != D_JNEWBLK || new->wk_type != D_JNEWBLK)
5488 		panic("jnewblk_merge: Bad type: old %d new %d\n",
5489 		    old->wk_type, new->wk_type);
5490 	/*
5491 	 * Handle merging of two jnewblk records that describe
5492 	 * different sets of fragments in the same block.
5493 	 */
5494 	jnewblk = WK_JNEWBLK(old);
5495 	njnewblk = WK_JNEWBLK(new);
5496 	if (jnewblk->jn_blkno != njnewblk->jn_blkno)
5497 		panic("jnewblk_merge: Merging disparate blocks.");
5498 	/*
5499 	 * The record may be rolled back in the cg.
5500 	 */
5501 	if (jnewblk->jn_state & UNDONE) {
5502 		jnewblk->jn_state &= ~UNDONE;
5503 		njnewblk->jn_state |= UNDONE;
5504 		njnewblk->jn_state &= ~ATTACHED;
5505 	}
5506 	/*
5507 	 * We modify the newer addref and free the older so that if neither
5508 	 * has been written the most up-to-date copy will be on disk.  If
5509 	 * both have been written but rolled back we only temporarily need
5510 	 * one of them to fix the bits when the cg write completes.
5511 	 */
5512 	jnewblk->jn_state |= ATTACHED | COMPLETE;
5513 	njnewblk->jn_oldfrags = jnewblk->jn_oldfrags;
5514 	cancel_jnewblk(jnewblk, wkhd);
5515 	WORKLIST_REMOVE(&jnewblk->jn_list);
5516 	free_jnewblk(jnewblk);
5517 	return (new);
5518 }
5519 
5520 /*
5521  * Replace an old allocdirect dependency with a newer one.
5522  */
5523 static void
5524 allocdirect_merge(adphead, newadp, oldadp)
5525 	struct allocdirectlst *adphead;	/* head of list holding allocdirects */
5526 	struct allocdirect *newadp;	/* allocdirect being added */
5527 	struct allocdirect *oldadp;	/* existing allocdirect being checked */
5528 {
5529 	struct worklist *wk;
5530 	struct freefrag *freefrag;
5531 
5532 	freefrag = NULL;
5533 	LOCK_OWNED(VFSTOUFS(newadp->ad_list.wk_mp));
5534 	if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
5535 	    newadp->ad_oldsize != oldadp->ad_newsize ||
5536 	    newadp->ad_offset >= UFS_NDADDR)
5537 		panic("%s %jd != new %jd || old size %ld != new %ld",
5538 		    "allocdirect_merge: old blkno",
5539 		    (intmax_t)newadp->ad_oldblkno,
5540 		    (intmax_t)oldadp->ad_newblkno,
5541 		    newadp->ad_oldsize, oldadp->ad_newsize);
5542 	newadp->ad_oldblkno = oldadp->ad_oldblkno;
5543 	newadp->ad_oldsize = oldadp->ad_oldsize;
5544 	/*
5545 	 * If the old dependency had a fragment to free or had never
5546 	 * previously had a block allocated, then the new dependency
5547 	 * can immediately post its freefrag and adopt the old freefrag.
5548 	 * This action is done by swapping the freefrag dependencies.
5549 	 * The new dependency gains the old one's freefrag, and the
5550 	 * old one gets the new one and then immediately puts it on
5551 	 * the worklist when it is freed by free_newblk. It is
5552 	 * not possible to do this swap when the old dependency had a
5553 	 * non-zero size but no previous fragment to free. This condition
5554 	 * arises when the new block is an extension of the old block.
5555 	 * Here, the first part of the fragment allocated to the new
5556 	 * dependency is part of the block currently claimed on disk by
5557 	 * the old dependency, so cannot legitimately be freed until the
5558 	 * conditions for the new dependency are fulfilled.
5559 	 */
5560 	freefrag = newadp->ad_freefrag;
5561 	if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
5562 		newadp->ad_freefrag = oldadp->ad_freefrag;
5563 		oldadp->ad_freefrag = freefrag;
5564 	}
5565 	/*
5566 	 * If we are tracking a new directory-block allocation,
5567 	 * move it from the old allocdirect to the new allocdirect.
5568 	 */
5569 	if ((wk = LIST_FIRST(&oldadp->ad_newdirblk)) != NULL) {
5570 		WORKLIST_REMOVE(wk);
5571 		if (!LIST_EMPTY(&oldadp->ad_newdirblk))
5572 			panic("allocdirect_merge: extra newdirblk");
5573 		WORKLIST_INSERT(&newadp->ad_newdirblk, wk);
5574 	}
5575 	TAILQ_REMOVE(adphead, oldadp, ad_next);
5576 	/*
5577 	 * We need to move any journal dependencies over to the freefrag
5578 	 * that releases this block if it exists.  Otherwise we are
5579 	 * extending an existing block and we'll wait until that is
5580 	 * complete to release the journal space and extend the
5581 	 * new journal to cover this old space as well.
5582 	 */
5583 	if (freefrag == NULL) {
5584 		if (oldadp->ad_newblkno != newadp->ad_newblkno)
5585 			panic("allocdirect_merge: %jd != %jd",
5586 			    oldadp->ad_newblkno, newadp->ad_newblkno);
5587 		newadp->ad_block.nb_jnewblk = (struct jnewblk *)
5588 		    jnewblk_merge(&newadp->ad_block.nb_jnewblk->jn_list,
5589 		    &oldadp->ad_block.nb_jnewblk->jn_list,
5590 		    &newadp->ad_block.nb_jwork);
5591 		oldadp->ad_block.nb_jnewblk = NULL;
5592 		cancel_newblk(&oldadp->ad_block, NULL,
5593 		    &newadp->ad_block.nb_jwork);
5594 	} else {
5595 		wk = (struct worklist *) cancel_newblk(&oldadp->ad_block,
5596 		    &freefrag->ff_list, &freefrag->ff_jwork);
5597 		freefrag->ff_jdep = jnewblk_merge(freefrag->ff_jdep, wk,
5598 		    &freefrag->ff_jwork);
5599 	}
5600 	free_newblk(&oldadp->ad_block);
5601 }
5602 
5603 /*
5604  * Allocate a jfreefrag structure to journal a single block free.
5605  */
5606 static struct jfreefrag *
5607 newjfreefrag(freefrag, ip, blkno, size, lbn)
5608 	struct freefrag *freefrag;
5609 	struct inode *ip;
5610 	ufs2_daddr_t blkno;
5611 	long size;
5612 	ufs_lbn_t lbn;
5613 {
5614 	struct jfreefrag *jfreefrag;
5615 	struct fs *fs;
5616 
5617 	fs = ITOFS(ip);
5618 	jfreefrag = malloc(sizeof(struct jfreefrag), M_JFREEFRAG,
5619 	    M_SOFTDEP_FLAGS);
5620 	workitem_alloc(&jfreefrag->fr_list, D_JFREEFRAG, ITOVFS(ip));
5621 	jfreefrag->fr_jsegdep = newjsegdep(&jfreefrag->fr_list);
5622 	jfreefrag->fr_state = ATTACHED | DEPCOMPLETE;
5623 	jfreefrag->fr_ino = ip->i_number;
5624 	jfreefrag->fr_lbn = lbn;
5625 	jfreefrag->fr_blkno = blkno;
5626 	jfreefrag->fr_frags = numfrags(fs, size);
5627 	jfreefrag->fr_freefrag = freefrag;
5628 
5629 	return (jfreefrag);
5630 }
5631 
5632 /*
5633  * Allocate a new freefrag structure.
5634  */
5635 static struct freefrag *
5636 newfreefrag(ip, blkno, size, lbn, key)
5637 	struct inode *ip;
5638 	ufs2_daddr_t blkno;
5639 	long size;
5640 	ufs_lbn_t lbn;
5641 	u_long key;
5642 {
5643 	struct freefrag *freefrag;
5644 	struct ufsmount *ump;
5645 	struct fs *fs;
5646 
5647 	CTR4(KTR_SUJ, "newfreefrag: ino %d blkno %jd size %ld lbn %jd",
5648 	    ip->i_number, blkno, size, lbn);
5649 	ump = ITOUMP(ip);
5650 	fs = ump->um_fs;
5651 	if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
5652 		panic("newfreefrag: frag size");
5653 	freefrag = malloc(sizeof(struct freefrag),
5654 	    M_FREEFRAG, M_SOFTDEP_FLAGS);
5655 	workitem_alloc(&freefrag->ff_list, D_FREEFRAG, UFSTOVFS(ump));
5656 	freefrag->ff_state = ATTACHED;
5657 	LIST_INIT(&freefrag->ff_jwork);
5658 	freefrag->ff_inum = ip->i_number;
5659 	freefrag->ff_vtype = ITOV(ip)->v_type;
5660 	freefrag->ff_blkno = blkno;
5661 	freefrag->ff_fragsize = size;
5662 	freefrag->ff_key = key;
5663 
5664 	if (MOUNTEDSUJ(UFSTOVFS(ump))) {
5665 		freefrag->ff_jdep = (struct worklist *)
5666 		    newjfreefrag(freefrag, ip, blkno, size, lbn);
5667 	} else {
5668 		freefrag->ff_state |= DEPCOMPLETE;
5669 		freefrag->ff_jdep = NULL;
5670 	}
5671 
5672 	return (freefrag);
5673 }
5674 
5675 /*
5676  * This workitem de-allocates fragments that were replaced during
5677  * file block allocation.
5678  */
5679 static void
5680 handle_workitem_freefrag(freefrag)
5681 	struct freefrag *freefrag;
5682 {
5683 	struct ufsmount *ump = VFSTOUFS(freefrag->ff_list.wk_mp);
5684 	struct workhead wkhd;
5685 
5686 	CTR3(KTR_SUJ,
5687 	    "handle_workitem_freefrag: ino %d blkno %jd size %ld",
5688 	    freefrag->ff_inum, freefrag->ff_blkno, freefrag->ff_fragsize);
5689 	/*
5690 	 * It would be illegal to add new completion items to the
5691 	 * freefrag after it was schedule to be done so it must be
5692 	 * safe to modify the list head here.
5693 	 */
5694 	LIST_INIT(&wkhd);
5695 	ACQUIRE_LOCK(ump);
5696 	LIST_SWAP(&freefrag->ff_jwork, &wkhd, worklist, wk_list);
5697 	/*
5698 	 * If the journal has not been written we must cancel it here.
5699 	 */
5700 	if (freefrag->ff_jdep) {
5701 		if (freefrag->ff_jdep->wk_type != D_JNEWBLK)
5702 			panic("handle_workitem_freefrag: Unexpected type %d\n",
5703 			    freefrag->ff_jdep->wk_type);
5704 		cancel_jnewblk(WK_JNEWBLK(freefrag->ff_jdep), &wkhd);
5705 	}
5706 	FREE_LOCK(ump);
5707 	ffs_blkfree(ump, ump->um_fs, ump->um_devvp, freefrag->ff_blkno,
5708 	   freefrag->ff_fragsize, freefrag->ff_inum, freefrag->ff_vtype,
5709 	   &wkhd, freefrag->ff_key);
5710 	ACQUIRE_LOCK(ump);
5711 	WORKITEM_FREE(freefrag, D_FREEFRAG);
5712 	FREE_LOCK(ump);
5713 }
5714 
5715 /*
5716  * Set up a dependency structure for an external attributes data block.
5717  * This routine follows much of the structure of softdep_setup_allocdirect.
5718  * See the description of softdep_setup_allocdirect above for details.
5719  */
5720 void
5721 softdep_setup_allocext(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5722 	struct inode *ip;
5723 	ufs_lbn_t off;
5724 	ufs2_daddr_t newblkno;
5725 	ufs2_daddr_t oldblkno;
5726 	long newsize;
5727 	long oldsize;
5728 	struct buf *bp;
5729 {
5730 	struct allocdirect *adp, *oldadp;
5731 	struct allocdirectlst *adphead;
5732 	struct freefrag *freefrag;
5733 	struct inodedep *inodedep;
5734 	struct jnewblk *jnewblk;
5735 	struct newblk *newblk;
5736 	struct mount *mp;
5737 	struct ufsmount *ump;
5738 	ufs_lbn_t lbn;
5739 
5740 	mp = ITOVFS(ip);
5741 	ump = VFSTOUFS(mp);
5742 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5743 	    ("softdep_setup_allocext called on non-softdep filesystem"));
5744 	KASSERT(off < UFS_NXADDR,
5745 	    ("softdep_setup_allocext: lbn %lld > UFS_NXADDR", (long long)off));
5746 
5747 	lbn = bp->b_lblkno;
5748 	if (oldblkno && oldblkno != newblkno)
5749 		/*
5750 		 * The usual case is that a smaller fragment that
5751 		 * was just allocated has been replaced with a bigger
5752 		 * fragment or a full-size block. If it is marked as
5753 		 * B_DELWRI, the current contents have not been written
5754 		 * to disk. It is possible that the block was written
5755 		 * earlier, but very uncommon. If the block has never
5756 		 * been written, there is no need to send a BIO_DELETE
5757 		 * for it when it is freed. The gain from avoiding the
5758 		 * TRIMs for the common case of unwritten blocks far
5759 		 * exceeds the cost of the write amplification for the
5760 		 * uncommon case of failing to send a TRIM for a block
5761 		 * that had been written.
5762 		 */
5763 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn,
5764 		    (bp->b_flags & B_DELWRI) != 0 ? NOTRIM_KEY : SINGLETON_KEY);
5765 	else
5766 		freefrag = NULL;
5767 
5768 	ACQUIRE_LOCK(ump);
5769 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5770 		panic("softdep_setup_allocext: lost block");
5771 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5772 	    ("softdep_setup_allocext: newblk already initialized"));
5773 	/*
5774 	 * Convert the newblk to an allocdirect.
5775 	 */
5776 	WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5777 	adp = (struct allocdirect *)newblk;
5778 	newblk->nb_freefrag = freefrag;
5779 	adp->ad_offset = off;
5780 	adp->ad_oldblkno = oldblkno;
5781 	adp->ad_newsize = newsize;
5782 	adp->ad_oldsize = oldsize;
5783 	adp->ad_state |=  EXTDATA;
5784 
5785 	/*
5786 	 * Finish initializing the journal.
5787 	 */
5788 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5789 		jnewblk->jn_ino = ip->i_number;
5790 		jnewblk->jn_lbn = lbn;
5791 		add_to_journal(&jnewblk->jn_list);
5792 	}
5793 	if (freefrag && freefrag->ff_jdep != NULL &&
5794 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5795 		add_to_journal(freefrag->ff_jdep);
5796 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5797 	adp->ad_inodedep = inodedep;
5798 
5799 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5800 	/*
5801 	 * The list of allocdirects must be kept in sorted and ascending
5802 	 * order so that the rollback routines can quickly determine the
5803 	 * first uncommitted block (the size of the file stored on disk
5804 	 * ends at the end of the lowest committed fragment, or if there
5805 	 * are no fragments, at the end of the highest committed block).
5806 	 * Since files generally grow, the typical case is that the new
5807 	 * block is to be added at the end of the list. We speed this
5808 	 * special case by checking against the last allocdirect in the
5809 	 * list before laboriously traversing the list looking for the
5810 	 * insertion point.
5811 	 */
5812 	adphead = &inodedep->id_newextupdt;
5813 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
5814 	if (oldadp == NULL || oldadp->ad_offset <= off) {
5815 		/* insert at end of list */
5816 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5817 		if (oldadp != NULL && oldadp->ad_offset == off)
5818 			allocdirect_merge(adphead, adp, oldadp);
5819 		FREE_LOCK(ump);
5820 		return;
5821 	}
5822 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
5823 		if (oldadp->ad_offset >= off)
5824 			break;
5825 	}
5826 	if (oldadp == NULL)
5827 		panic("softdep_setup_allocext: lost entry");
5828 	/* insert in middle of list */
5829 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5830 	if (oldadp->ad_offset == off)
5831 		allocdirect_merge(adphead, adp, oldadp);
5832 	FREE_LOCK(ump);
5833 }
5834 
5835 /*
5836  * Indirect block allocation dependencies.
5837  *
5838  * The same dependencies that exist for a direct block also exist when
5839  * a new block is allocated and pointed to by an entry in a block of
5840  * indirect pointers. The undo/redo states described above are also
5841  * used here. Because an indirect block contains many pointers that
5842  * may have dependencies, a second copy of the entire in-memory indirect
5843  * block is kept. The buffer cache copy is always completely up-to-date.
5844  * The second copy, which is used only as a source for disk writes,
5845  * contains only the safe pointers (i.e., those that have no remaining
5846  * update dependencies). The second copy is freed when all pointers
5847  * are safe. The cache is not allowed to replace indirect blocks with
5848  * pending update dependencies. If a buffer containing an indirect
5849  * block with dependencies is written, these routines will mark it
5850  * dirty again. It can only be successfully written once all the
5851  * dependencies are removed. The ffs_fsync routine in conjunction with
5852  * softdep_sync_metadata work together to get all the dependencies
5853  * removed so that a file can be successfully written to disk. Three
5854  * procedures are used when setting up indirect block pointer
5855  * dependencies. The division is necessary because of the organization
5856  * of the "balloc" routine and because of the distinction between file
5857  * pages and file metadata blocks.
5858  */
5859 
5860 /*
5861  * Allocate a new allocindir structure.
5862  */
5863 static struct allocindir *
5864 newallocindir(ip, ptrno, newblkno, oldblkno, lbn)
5865 	struct inode *ip;	/* inode for file being extended */
5866 	int ptrno;		/* offset of pointer in indirect block */
5867 	ufs2_daddr_t newblkno;	/* disk block number being added */
5868 	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
5869 	ufs_lbn_t lbn;
5870 {
5871 	struct newblk *newblk;
5872 	struct allocindir *aip;
5873 	struct freefrag *freefrag;
5874 	struct jnewblk *jnewblk;
5875 
5876 	if (oldblkno)
5877 		freefrag = newfreefrag(ip, oldblkno, ITOFS(ip)->fs_bsize, lbn,
5878 		    SINGLETON_KEY);
5879 	else
5880 		freefrag = NULL;
5881 	ACQUIRE_LOCK(ITOUMP(ip));
5882 	if (newblk_lookup(ITOVFS(ip), newblkno, 0, &newblk) == 0)
5883 		panic("new_allocindir: lost block");
5884 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5885 	    ("newallocindir: newblk already initialized"));
5886 	WORKITEM_REASSIGN(newblk, D_ALLOCINDIR);
5887 	newblk->nb_freefrag = freefrag;
5888 	aip = (struct allocindir *)newblk;
5889 	aip->ai_offset = ptrno;
5890 	aip->ai_oldblkno = oldblkno;
5891 	aip->ai_lbn = lbn;
5892 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5893 		jnewblk->jn_ino = ip->i_number;
5894 		jnewblk->jn_lbn = lbn;
5895 		add_to_journal(&jnewblk->jn_list);
5896 	}
5897 	if (freefrag && freefrag->ff_jdep != NULL &&
5898 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5899 		add_to_journal(freefrag->ff_jdep);
5900 	return (aip);
5901 }
5902 
5903 /*
5904  * Called just before setting an indirect block pointer
5905  * to a newly allocated file page.
5906  */
5907 void
5908 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
5909 	struct inode *ip;	/* inode for file being extended */
5910 	ufs_lbn_t lbn;		/* allocated block number within file */
5911 	struct buf *bp;		/* buffer with indirect blk referencing page */
5912 	int ptrno;		/* offset of pointer in indirect block */
5913 	ufs2_daddr_t newblkno;	/* disk block number being added */
5914 	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
5915 	struct buf *nbp;	/* buffer holding allocated page */
5916 {
5917 	struct inodedep *inodedep;
5918 	struct freefrag *freefrag;
5919 	struct allocindir *aip;
5920 	struct pagedep *pagedep;
5921 	struct mount *mp;
5922 	struct ufsmount *ump;
5923 
5924 	mp = ITOVFS(ip);
5925 	ump = VFSTOUFS(mp);
5926 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5927 	    ("softdep_setup_allocindir_page called on non-softdep filesystem"));
5928 	KASSERT(lbn == nbp->b_lblkno,
5929 	    ("softdep_setup_allocindir_page: lbn %jd != lblkno %jd",
5930 	    lbn, bp->b_lblkno));
5931 	CTR4(KTR_SUJ,
5932 	    "softdep_setup_allocindir_page: ino %d blkno %jd oldblkno %jd "
5933 	    "lbn %jd", ip->i_number, newblkno, oldblkno, lbn);
5934 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_page");
5935 	aip = newallocindir(ip, ptrno, newblkno, oldblkno, lbn);
5936 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5937 	/*
5938 	 * If we are allocating a directory page, then we must
5939 	 * allocate an associated pagedep to track additions and
5940 	 * deletions.
5941 	 */
5942 	if ((ip->i_mode & IFMT) == IFDIR)
5943 		pagedep_lookup(mp, nbp, ip->i_number, lbn, DEPALLOC, &pagedep);
5944 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5945 	freefrag = setup_allocindir_phase2(bp, ip, inodedep, aip, lbn);
5946 	FREE_LOCK(ump);
5947 	if (freefrag)
5948 		handle_workitem_freefrag(freefrag);
5949 }
5950 
5951 /*
5952  * Called just before setting an indirect block pointer to a
5953  * newly allocated indirect block.
5954  */
5955 void
5956 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
5957 	struct buf *nbp;	/* newly allocated indirect block */
5958 	struct inode *ip;	/* inode for file being extended */
5959 	struct buf *bp;		/* indirect block referencing allocated block */
5960 	int ptrno;		/* offset of pointer in indirect block */
5961 	ufs2_daddr_t newblkno;	/* disk block number being added */
5962 {
5963 	struct inodedep *inodedep;
5964 	struct allocindir *aip;
5965 	struct ufsmount *ump;
5966 	ufs_lbn_t lbn;
5967 
5968 	ump = ITOUMP(ip);
5969 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
5970 	    ("softdep_setup_allocindir_meta called on non-softdep filesystem"));
5971 	CTR3(KTR_SUJ,
5972 	    "softdep_setup_allocindir_meta: ino %d blkno %jd ptrno %d",
5973 	    ip->i_number, newblkno, ptrno);
5974 	lbn = nbp->b_lblkno;
5975 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_meta");
5976 	aip = newallocindir(ip, ptrno, newblkno, 0, lbn);
5977 	inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
5978 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5979 	if (setup_allocindir_phase2(bp, ip, inodedep, aip, lbn))
5980 		panic("softdep_setup_allocindir_meta: Block already existed");
5981 	FREE_LOCK(ump);
5982 }
5983 
5984 static void
5985 indirdep_complete(indirdep)
5986 	struct indirdep *indirdep;
5987 {
5988 	struct allocindir *aip;
5989 
5990 	LIST_REMOVE(indirdep, ir_next);
5991 	indirdep->ir_state |= DEPCOMPLETE;
5992 
5993 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL) {
5994 		LIST_REMOVE(aip, ai_next);
5995 		free_newblk(&aip->ai_block);
5996 	}
5997 	/*
5998 	 * If this indirdep is not attached to a buf it was simply waiting
5999 	 * on completion to clear completehd.  free_indirdep() asserts
6000 	 * that nothing is dangling.
6001 	 */
6002 	if ((indirdep->ir_state & ONWORKLIST) == 0)
6003 		free_indirdep(indirdep);
6004 }
6005 
6006 static struct indirdep *
6007 indirdep_lookup(mp, ip, bp)
6008 	struct mount *mp;
6009 	struct inode *ip;
6010 	struct buf *bp;
6011 {
6012 	struct indirdep *indirdep, *newindirdep;
6013 	struct newblk *newblk;
6014 	struct ufsmount *ump;
6015 	struct worklist *wk;
6016 	struct fs *fs;
6017 	ufs2_daddr_t blkno;
6018 
6019 	ump = VFSTOUFS(mp);
6020 	LOCK_OWNED(ump);
6021 	indirdep = NULL;
6022 	newindirdep = NULL;
6023 	fs = ump->um_fs;
6024 	for (;;) {
6025 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
6026 			if (wk->wk_type != D_INDIRDEP)
6027 				continue;
6028 			indirdep = WK_INDIRDEP(wk);
6029 			break;
6030 		}
6031 		/* Found on the buffer worklist, no new structure to free. */
6032 		if (indirdep != NULL && newindirdep == NULL)
6033 			return (indirdep);
6034 		if (indirdep != NULL && newindirdep != NULL)
6035 			panic("indirdep_lookup: simultaneous create");
6036 		/* None found on the buffer and a new structure is ready. */
6037 		if (indirdep == NULL && newindirdep != NULL)
6038 			break;
6039 		/* None found and no new structure available. */
6040 		FREE_LOCK(ump);
6041 		newindirdep = malloc(sizeof(struct indirdep),
6042 		    M_INDIRDEP, M_SOFTDEP_FLAGS);
6043 		workitem_alloc(&newindirdep->ir_list, D_INDIRDEP, mp);
6044 		newindirdep->ir_state = ATTACHED;
6045 		if (I_IS_UFS1(ip))
6046 			newindirdep->ir_state |= UFS1FMT;
6047 		TAILQ_INIT(&newindirdep->ir_trunc);
6048 		newindirdep->ir_saveddata = NULL;
6049 		LIST_INIT(&newindirdep->ir_deplisthd);
6050 		LIST_INIT(&newindirdep->ir_donehd);
6051 		LIST_INIT(&newindirdep->ir_writehd);
6052 		LIST_INIT(&newindirdep->ir_completehd);
6053 		if (bp->b_blkno == bp->b_lblkno) {
6054 			ufs_bmaparray(bp->b_vp, bp->b_lblkno, &blkno, bp,
6055 			    NULL, NULL);
6056 			bp->b_blkno = blkno;
6057 		}
6058 		newindirdep->ir_freeblks = NULL;
6059 		newindirdep->ir_savebp =
6060 		    getblk(ump->um_devvp, bp->b_blkno, bp->b_bcount, 0, 0, 0);
6061 		newindirdep->ir_bp = bp;
6062 		BUF_KERNPROC(newindirdep->ir_savebp);
6063 		bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
6064 		ACQUIRE_LOCK(ump);
6065 	}
6066 	indirdep = newindirdep;
6067 	WORKLIST_INSERT(&bp->b_dep, &indirdep->ir_list);
6068 	/*
6069 	 * If the block is not yet allocated we don't set DEPCOMPLETE so
6070 	 * that we don't free dependencies until the pointers are valid.
6071 	 * This could search b_dep for D_ALLOCDIRECT/D_ALLOCINDIR rather
6072 	 * than using the hash.
6073 	 */
6074 	if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk))
6075 		LIST_INSERT_HEAD(&newblk->nb_indirdeps, indirdep, ir_next);
6076 	else
6077 		indirdep->ir_state |= DEPCOMPLETE;
6078 	return (indirdep);
6079 }
6080 
6081 /*
6082  * Called to finish the allocation of the "aip" allocated
6083  * by one of the two routines above.
6084  */
6085 static struct freefrag *
6086 setup_allocindir_phase2(bp, ip, inodedep, aip, lbn)
6087 	struct buf *bp;		/* in-memory copy of the indirect block */
6088 	struct inode *ip;	/* inode for file being extended */
6089 	struct inodedep *inodedep; /* Inodedep for ip */
6090 	struct allocindir *aip;	/* allocindir allocated by the above routines */
6091 	ufs_lbn_t lbn;		/* Logical block number for this block. */
6092 {
6093 	struct fs *fs;
6094 	struct indirdep *indirdep;
6095 	struct allocindir *oldaip;
6096 	struct freefrag *freefrag;
6097 	struct mount *mp;
6098 	struct ufsmount *ump;
6099 
6100 	mp = ITOVFS(ip);
6101 	ump = VFSTOUFS(mp);
6102 	LOCK_OWNED(ump);
6103 	fs = ump->um_fs;
6104 	if (bp->b_lblkno >= 0)
6105 		panic("setup_allocindir_phase2: not indir blk");
6106 	KASSERT(aip->ai_offset >= 0 && aip->ai_offset < NINDIR(fs),
6107 	    ("setup_allocindir_phase2: Bad offset %d", aip->ai_offset));
6108 	indirdep = indirdep_lookup(mp, ip, bp);
6109 	KASSERT(indirdep->ir_savebp != NULL,
6110 	    ("setup_allocindir_phase2 NULL ir_savebp"));
6111 	aip->ai_indirdep = indirdep;
6112 	/*
6113 	 * Check for an unwritten dependency for this indirect offset.  If
6114 	 * there is, merge the old dependency into the new one.  This happens
6115 	 * as a result of reallocblk only.
6116 	 */
6117 	freefrag = NULL;
6118 	if (aip->ai_oldblkno != 0) {
6119 		LIST_FOREACH(oldaip, &indirdep->ir_deplisthd, ai_next) {
6120 			if (oldaip->ai_offset == aip->ai_offset) {
6121 				freefrag = allocindir_merge(aip, oldaip);
6122 				goto done;
6123 			}
6124 		}
6125 		LIST_FOREACH(oldaip, &indirdep->ir_donehd, ai_next) {
6126 			if (oldaip->ai_offset == aip->ai_offset) {
6127 				freefrag = allocindir_merge(aip, oldaip);
6128 				goto done;
6129 			}
6130 		}
6131 	}
6132 done:
6133 	LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
6134 	return (freefrag);
6135 }
6136 
6137 /*
6138  * Merge two allocindirs which refer to the same block.  Move newblock
6139  * dependencies and setup the freefrags appropriately.
6140  */
6141 static struct freefrag *
6142 allocindir_merge(aip, oldaip)
6143 	struct allocindir *aip;
6144 	struct allocindir *oldaip;
6145 {
6146 	struct freefrag *freefrag;
6147 	struct worklist *wk;
6148 
6149 	if (oldaip->ai_newblkno != aip->ai_oldblkno)
6150 		panic("allocindir_merge: blkno");
6151 	aip->ai_oldblkno = oldaip->ai_oldblkno;
6152 	freefrag = aip->ai_freefrag;
6153 	aip->ai_freefrag = oldaip->ai_freefrag;
6154 	oldaip->ai_freefrag = NULL;
6155 	KASSERT(freefrag != NULL, ("setup_allocindir_phase2: No freefrag"));
6156 	/*
6157 	 * If we are tracking a new directory-block allocation,
6158 	 * move it from the old allocindir to the new allocindir.
6159 	 */
6160 	if ((wk = LIST_FIRST(&oldaip->ai_newdirblk)) != NULL) {
6161 		WORKLIST_REMOVE(wk);
6162 		if (!LIST_EMPTY(&oldaip->ai_newdirblk))
6163 			panic("allocindir_merge: extra newdirblk");
6164 		WORKLIST_INSERT(&aip->ai_newdirblk, wk);
6165 	}
6166 	/*
6167 	 * We can skip journaling for this freefrag and just complete
6168 	 * any pending journal work for the allocindir that is being
6169 	 * removed after the freefrag completes.
6170 	 */
6171 	if (freefrag->ff_jdep)
6172 		cancel_jfreefrag(WK_JFREEFRAG(freefrag->ff_jdep));
6173 	LIST_REMOVE(oldaip, ai_next);
6174 	freefrag->ff_jdep = (struct worklist *)cancel_newblk(&oldaip->ai_block,
6175 	    &freefrag->ff_list, &freefrag->ff_jwork);
6176 	free_newblk(&oldaip->ai_block);
6177 
6178 	return (freefrag);
6179 }
6180 
6181 static inline void
6182 setup_freedirect(freeblks, ip, i, needj)
6183 	struct freeblks *freeblks;
6184 	struct inode *ip;
6185 	int i;
6186 	int needj;
6187 {
6188 	struct ufsmount *ump;
6189 	ufs2_daddr_t blkno;
6190 	int frags;
6191 
6192 	blkno = DIP(ip, i_db[i]);
6193 	if (blkno == 0)
6194 		return;
6195 	DIP_SET(ip, i_db[i], 0);
6196 	ump = ITOUMP(ip);
6197 	frags = sblksize(ump->um_fs, ip->i_size, i);
6198 	frags = numfrags(ump->um_fs, frags);
6199 	newfreework(ump, freeblks, NULL, i, blkno, frags, 0, needj);
6200 }
6201 
6202 static inline void
6203 setup_freeext(freeblks, ip, i, needj)
6204 	struct freeblks *freeblks;
6205 	struct inode *ip;
6206 	int i;
6207 	int needj;
6208 {
6209 	struct ufsmount *ump;
6210 	ufs2_daddr_t blkno;
6211 	int frags;
6212 
6213 	blkno = ip->i_din2->di_extb[i];
6214 	if (blkno == 0)
6215 		return;
6216 	ip->i_din2->di_extb[i] = 0;
6217 	ump = ITOUMP(ip);
6218 	frags = sblksize(ump->um_fs, ip->i_din2->di_extsize, i);
6219 	frags = numfrags(ump->um_fs, frags);
6220 	newfreework(ump, freeblks, NULL, -1 - i, blkno, frags, 0, needj);
6221 }
6222 
6223 static inline void
6224 setup_freeindir(freeblks, ip, i, lbn, needj)
6225 	struct freeblks *freeblks;
6226 	struct inode *ip;
6227 	int i;
6228 	ufs_lbn_t lbn;
6229 	int needj;
6230 {
6231 	struct ufsmount *ump;
6232 	ufs2_daddr_t blkno;
6233 
6234 	blkno = DIP(ip, i_ib[i]);
6235 	if (blkno == 0)
6236 		return;
6237 	DIP_SET(ip, i_ib[i], 0);
6238 	ump = ITOUMP(ip);
6239 	newfreework(ump, freeblks, NULL, lbn, blkno, ump->um_fs->fs_frag,
6240 	    0, needj);
6241 }
6242 
6243 static inline struct freeblks *
6244 newfreeblks(mp, ip)
6245 	struct mount *mp;
6246 	struct inode *ip;
6247 {
6248 	struct freeblks *freeblks;
6249 
6250 	freeblks = malloc(sizeof(struct freeblks),
6251 		M_FREEBLKS, M_SOFTDEP_FLAGS|M_ZERO);
6252 	workitem_alloc(&freeblks->fb_list, D_FREEBLKS, mp);
6253 	LIST_INIT(&freeblks->fb_jblkdephd);
6254 	LIST_INIT(&freeblks->fb_jwork);
6255 	freeblks->fb_ref = 0;
6256 	freeblks->fb_cgwait = 0;
6257 	freeblks->fb_state = ATTACHED;
6258 	freeblks->fb_uid = ip->i_uid;
6259 	freeblks->fb_inum = ip->i_number;
6260 	freeblks->fb_vtype = ITOV(ip)->v_type;
6261 	freeblks->fb_modrev = DIP(ip, i_modrev);
6262 	freeblks->fb_devvp = ITODEVVP(ip);
6263 	freeblks->fb_chkcnt = 0;
6264 	freeblks->fb_len = 0;
6265 
6266 	return (freeblks);
6267 }
6268 
6269 static void
6270 trunc_indirdep(indirdep, freeblks, bp, off)
6271 	struct indirdep *indirdep;
6272 	struct freeblks *freeblks;
6273 	struct buf *bp;
6274 	int off;
6275 {
6276 	struct allocindir *aip, *aipn;
6277 
6278 	/*
6279 	 * The first set of allocindirs won't be in savedbp.
6280 	 */
6281 	LIST_FOREACH_SAFE(aip, &indirdep->ir_deplisthd, ai_next, aipn)
6282 		if (aip->ai_offset > off)
6283 			cancel_allocindir(aip, bp, freeblks, 1);
6284 	LIST_FOREACH_SAFE(aip, &indirdep->ir_donehd, ai_next, aipn)
6285 		if (aip->ai_offset > off)
6286 			cancel_allocindir(aip, bp, freeblks, 1);
6287 	/*
6288 	 * These will exist in savedbp.
6289 	 */
6290 	LIST_FOREACH_SAFE(aip, &indirdep->ir_writehd, ai_next, aipn)
6291 		if (aip->ai_offset > off)
6292 			cancel_allocindir(aip, NULL, freeblks, 0);
6293 	LIST_FOREACH_SAFE(aip, &indirdep->ir_completehd, ai_next, aipn)
6294 		if (aip->ai_offset > off)
6295 			cancel_allocindir(aip, NULL, freeblks, 0);
6296 }
6297 
6298 /*
6299  * Follow the chain of indirects down to lastlbn creating a freework
6300  * structure for each.  This will be used to start indir_trunc() at
6301  * the right offset and create the journal records for the parrtial
6302  * truncation.  A second step will handle the truncated dependencies.
6303  */
6304 static int
6305 setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno)
6306 	struct freeblks *freeblks;
6307 	struct inode *ip;
6308 	ufs_lbn_t lbn;
6309 	ufs_lbn_t lastlbn;
6310 	ufs2_daddr_t blkno;
6311 {
6312 	struct indirdep *indirdep;
6313 	struct indirdep *indirn;
6314 	struct freework *freework;
6315 	struct newblk *newblk;
6316 	struct mount *mp;
6317 	struct ufsmount *ump;
6318 	struct buf *bp;
6319 	uint8_t *start;
6320 	uint8_t *end;
6321 	ufs_lbn_t lbnadd;
6322 	int level;
6323 	int error;
6324 	int off;
6325 
6326 
6327 	freework = NULL;
6328 	if (blkno == 0)
6329 		return (0);
6330 	mp = freeblks->fb_list.wk_mp;
6331 	ump = VFSTOUFS(mp);
6332 	/*
6333 	 * Here, calls to VOP_BMAP() will fail.  However, we already have
6334 	 * the on-disk address, so we just pass it to bread() instead of
6335 	 * having bread() attempt to calculate it using VOP_BMAP().
6336 	 */
6337 	error = breadn_flags(ITOV(ip), lbn, blkptrtodb(ump, blkno),
6338 	    (int)mp->mnt_stat.f_iosize, NULL, NULL, 0, NOCRED, 0, NULL, &bp);
6339 	if (error)
6340 		return (error);
6341 	level = lbn_level(lbn);
6342 	lbnadd = lbn_offset(ump->um_fs, level);
6343 	/*
6344 	 * Compute the offset of the last block we want to keep.  Store
6345 	 * in the freework the first block we want to completely free.
6346 	 */
6347 	off = (lastlbn - -(lbn + level)) / lbnadd;
6348 	if (off + 1 == NINDIR(ump->um_fs))
6349 		goto nowork;
6350 	freework = newfreework(ump, freeblks, NULL, lbn, blkno, 0, off + 1, 0);
6351 	/*
6352 	 * Link the freework into the indirdep.  This will prevent any new
6353 	 * allocations from proceeding until we are finished with the
6354 	 * truncate and the block is written.
6355 	 */
6356 	ACQUIRE_LOCK(ump);
6357 	indirdep = indirdep_lookup(mp, ip, bp);
6358 	if (indirdep->ir_freeblks)
6359 		panic("setup_trunc_indir: indirdep already truncated.");
6360 	TAILQ_INSERT_TAIL(&indirdep->ir_trunc, freework, fw_next);
6361 	freework->fw_indir = indirdep;
6362 	/*
6363 	 * Cancel any allocindirs that will not make it to disk.
6364 	 * We have to do this for all copies of the indirdep that
6365 	 * live on this newblk.
6366 	 */
6367 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
6368 		if (newblk_lookup(mp, dbtofsb(ump->um_fs, bp->b_blkno), 0,
6369 		    &newblk) == 0)
6370 			panic("setup_trunc_indir: lost block");
6371 		LIST_FOREACH(indirn, &newblk->nb_indirdeps, ir_next)
6372 			trunc_indirdep(indirn, freeblks, bp, off);
6373 	} else
6374 		trunc_indirdep(indirdep, freeblks, bp, off);
6375 	FREE_LOCK(ump);
6376 	/*
6377 	 * Creation is protected by the buf lock. The saveddata is only
6378 	 * needed if a full truncation follows a partial truncation but it
6379 	 * is difficult to allocate in that case so we fetch it anyway.
6380 	 */
6381 	if (indirdep->ir_saveddata == NULL)
6382 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
6383 		    M_SOFTDEP_FLAGS);
6384 nowork:
6385 	/* Fetch the blkno of the child and the zero start offset. */
6386 	if (I_IS_UFS1(ip)) {
6387 		blkno = ((ufs1_daddr_t *)bp->b_data)[off];
6388 		start = (uint8_t *)&((ufs1_daddr_t *)bp->b_data)[off+1];
6389 	} else {
6390 		blkno = ((ufs2_daddr_t *)bp->b_data)[off];
6391 		start = (uint8_t *)&((ufs2_daddr_t *)bp->b_data)[off+1];
6392 	}
6393 	if (freework) {
6394 		/* Zero the truncated pointers. */
6395 		end = bp->b_data + bp->b_bcount;
6396 		bzero(start, end - start);
6397 		bdwrite(bp);
6398 	} else
6399 		bqrelse(bp);
6400 	if (level == 0)
6401 		return (0);
6402 	lbn++; /* adjust level */
6403 	lbn -= (off * lbnadd);
6404 	return setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno);
6405 }
6406 
6407 /*
6408  * Complete the partial truncation of an indirect block setup by
6409  * setup_trunc_indir().  This zeros the truncated pointers in the saved
6410  * copy and writes them to disk before the freeblks is allowed to complete.
6411  */
6412 static void
6413 complete_trunc_indir(freework)
6414 	struct freework *freework;
6415 {
6416 	struct freework *fwn;
6417 	struct indirdep *indirdep;
6418 	struct ufsmount *ump;
6419 	struct buf *bp;
6420 	uintptr_t start;
6421 	int count;
6422 
6423 	ump = VFSTOUFS(freework->fw_list.wk_mp);
6424 	LOCK_OWNED(ump);
6425 	indirdep = freework->fw_indir;
6426 	for (;;) {
6427 		bp = indirdep->ir_bp;
6428 		/* See if the block was discarded. */
6429 		if (bp == NULL)
6430 			break;
6431 		/* Inline part of getdirtybuf().  We dont want bremfree. */
6432 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) == 0)
6433 			break;
6434 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
6435 		    LOCK_PTR(ump)) == 0)
6436 			BUF_UNLOCK(bp);
6437 		ACQUIRE_LOCK(ump);
6438 	}
6439 	freework->fw_state |= DEPCOMPLETE;
6440 	TAILQ_REMOVE(&indirdep->ir_trunc, freework, fw_next);
6441 	/*
6442 	 * Zero the pointers in the saved copy.
6443 	 */
6444 	if (indirdep->ir_state & UFS1FMT)
6445 		start = sizeof(ufs1_daddr_t);
6446 	else
6447 		start = sizeof(ufs2_daddr_t);
6448 	start *= freework->fw_start;
6449 	count = indirdep->ir_savebp->b_bcount - start;
6450 	start += (uintptr_t)indirdep->ir_savebp->b_data;
6451 	bzero((char *)start, count);
6452 	/*
6453 	 * We need to start the next truncation in the list if it has not
6454 	 * been started yet.
6455 	 */
6456 	fwn = TAILQ_FIRST(&indirdep->ir_trunc);
6457 	if (fwn != NULL) {
6458 		if (fwn->fw_freeblks == indirdep->ir_freeblks)
6459 			TAILQ_REMOVE(&indirdep->ir_trunc, fwn, fw_next);
6460 		if ((fwn->fw_state & ONWORKLIST) == 0)
6461 			freework_enqueue(fwn);
6462 	}
6463 	/*
6464 	 * If bp is NULL the block was fully truncated, restore
6465 	 * the saved block list otherwise free it if it is no
6466 	 * longer needed.
6467 	 */
6468 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
6469 		if (bp == NULL)
6470 			bcopy(indirdep->ir_saveddata,
6471 			    indirdep->ir_savebp->b_data,
6472 			    indirdep->ir_savebp->b_bcount);
6473 		free(indirdep->ir_saveddata, M_INDIRDEP);
6474 		indirdep->ir_saveddata = NULL;
6475 	}
6476 	/*
6477 	 * When bp is NULL there is a full truncation pending.  We
6478 	 * must wait for this full truncation to be journaled before
6479 	 * we can release this freework because the disk pointers will
6480 	 * never be written as zero.
6481 	 */
6482 	if (bp == NULL)  {
6483 		if (LIST_EMPTY(&indirdep->ir_freeblks->fb_jblkdephd))
6484 			handle_written_freework(freework);
6485 		else
6486 			WORKLIST_INSERT(&indirdep->ir_freeblks->fb_freeworkhd,
6487 			   &freework->fw_list);
6488 	} else {
6489 		/* Complete when the real copy is written. */
6490 		WORKLIST_INSERT(&bp->b_dep, &freework->fw_list);
6491 		BUF_UNLOCK(bp);
6492 	}
6493 }
6494 
6495 /*
6496  * Calculate the number of blocks we are going to release where datablocks
6497  * is the current total and length is the new file size.
6498  */
6499 static ufs2_daddr_t
6500 blkcount(fs, datablocks, length)
6501 	struct fs *fs;
6502 	ufs2_daddr_t datablocks;
6503 	off_t length;
6504 {
6505 	off_t totblks, numblks;
6506 
6507 	totblks = 0;
6508 	numblks = howmany(length, fs->fs_bsize);
6509 	if (numblks <= UFS_NDADDR) {
6510 		totblks = howmany(length, fs->fs_fsize);
6511 		goto out;
6512 	}
6513         totblks = blkstofrags(fs, numblks);
6514 	numblks -= UFS_NDADDR;
6515 	/*
6516 	 * Count all single, then double, then triple indirects required.
6517 	 * Subtracting one indirects worth of blocks for each pass
6518 	 * acknowledges one of each pointed to by the inode.
6519 	 */
6520 	for (;;) {
6521 		totblks += blkstofrags(fs, howmany(numblks, NINDIR(fs)));
6522 		numblks -= NINDIR(fs);
6523 		if (numblks <= 0)
6524 			break;
6525 		numblks = howmany(numblks, NINDIR(fs));
6526 	}
6527 out:
6528 	totblks = fsbtodb(fs, totblks);
6529 	/*
6530 	 * Handle sparse files.  We can't reclaim more blocks than the inode
6531 	 * references.  We will correct it later in handle_complete_freeblks()
6532 	 * when we know the real count.
6533 	 */
6534 	if (totblks > datablocks)
6535 		return (0);
6536 	return (datablocks - totblks);
6537 }
6538 
6539 /*
6540  * Handle freeblocks for journaled softupdate filesystems.
6541  *
6542  * Contrary to normal softupdates, we must preserve the block pointers in
6543  * indirects until their subordinates are free.  This is to avoid journaling
6544  * every block that is freed which may consume more space than the journal
6545  * itself.  The recovery program will see the free block journals at the
6546  * base of the truncated area and traverse them to reclaim space.  The
6547  * pointers in the inode may be cleared immediately after the journal
6548  * records are written because each direct and indirect pointer in the
6549  * inode is recorded in a journal.  This permits full truncation to proceed
6550  * asynchronously.  The write order is journal -> inode -> cgs -> indirects.
6551  *
6552  * The algorithm is as follows:
6553  * 1) Traverse the in-memory state and create journal entries to release
6554  *    the relevant blocks and full indirect trees.
6555  * 2) Traverse the indirect block chain adding partial truncation freework
6556  *    records to indirects in the path to lastlbn.  The freework will
6557  *    prevent new allocation dependencies from being satisfied in this
6558  *    indirect until the truncation completes.
6559  * 3) Read and lock the inode block, performing an update with the new size
6560  *    and pointers.  This prevents truncated data from becoming valid on
6561  *    disk through step 4.
6562  * 4) Reap unsatisfied dependencies that are beyond the truncated area,
6563  *    eliminate journal work for those records that do not require it.
6564  * 5) Schedule the journal records to be written followed by the inode block.
6565  * 6) Allocate any necessary frags for the end of file.
6566  * 7) Zero any partially truncated blocks.
6567  *
6568  * From this truncation proceeds asynchronously using the freework and
6569  * indir_trunc machinery.  The file will not be extended again into a
6570  * partially truncated indirect block until all work is completed but
6571  * the normal dependency mechanism ensures that it is rolled back/forward
6572  * as appropriate.  Further truncation may occur without delay and is
6573  * serialized in indir_trunc().
6574  */
6575 void
6576 softdep_journal_freeblocks(ip, cred, length, flags)
6577 	struct inode *ip;	/* The inode whose length is to be reduced */
6578 	struct ucred *cred;
6579 	off_t length;		/* The new length for the file */
6580 	int flags;		/* IO_EXT and/or IO_NORMAL */
6581 {
6582 	struct freeblks *freeblks, *fbn;
6583 	struct worklist *wk, *wkn;
6584 	struct inodedep *inodedep;
6585 	struct jblkdep *jblkdep;
6586 	struct allocdirect *adp, *adpn;
6587 	struct ufsmount *ump;
6588 	struct fs *fs;
6589 	struct buf *bp;
6590 	struct vnode *vp;
6591 	struct mount *mp;
6592 	ufs2_daddr_t extblocks, datablocks;
6593 	ufs_lbn_t tmpval, lbn, lastlbn;
6594 	int frags, lastoff, iboff, allocblock, needj, error, i;
6595 
6596 	ump = ITOUMP(ip);
6597 	mp = UFSTOVFS(ump);
6598 	fs = ump->um_fs;
6599 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6600 	    ("softdep_journal_freeblocks called on non-softdep filesystem"));
6601 	vp = ITOV(ip);
6602 	needj = 1;
6603 	iboff = -1;
6604 	allocblock = 0;
6605 	extblocks = 0;
6606 	datablocks = 0;
6607 	frags = 0;
6608 	freeblks = newfreeblks(mp, ip);
6609 	ACQUIRE_LOCK(ump);
6610 	/*
6611 	 * If we're truncating a removed file that will never be written
6612 	 * we don't need to journal the block frees.  The canceled journals
6613 	 * for the allocations will suffice.
6614 	 */
6615 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6616 	if ((inodedep->id_state & (UNLINKED | DEPCOMPLETE)) == UNLINKED &&
6617 	    length == 0)
6618 		needj = 0;
6619 	CTR3(KTR_SUJ, "softdep_journal_freeblks: ip %d length %ld needj %d",
6620 	    ip->i_number, length, needj);
6621 	FREE_LOCK(ump);
6622 	/*
6623 	 * Calculate the lbn that we are truncating to.  This results in -1
6624 	 * if we're truncating the 0 bytes.  So it is the last lbn we want
6625 	 * to keep, not the first lbn we want to truncate.
6626 	 */
6627 	lastlbn = lblkno(fs, length + fs->fs_bsize - 1) - 1;
6628 	lastoff = blkoff(fs, length);
6629 	/*
6630 	 * Compute frags we are keeping in lastlbn.  0 means all.
6631 	 */
6632 	if (lastlbn >= 0 && lastlbn < UFS_NDADDR) {
6633 		frags = fragroundup(fs, lastoff);
6634 		/* adp offset of last valid allocdirect. */
6635 		iboff = lastlbn;
6636 	} else if (lastlbn > 0)
6637 		iboff = UFS_NDADDR;
6638 	if (fs->fs_magic == FS_UFS2_MAGIC)
6639 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6640 	/*
6641 	 * Handle normal data blocks and indirects.  This section saves
6642 	 * values used after the inode update to complete frag and indirect
6643 	 * truncation.
6644 	 */
6645 	if ((flags & IO_NORMAL) != 0) {
6646 		/*
6647 		 * Handle truncation of whole direct and indirect blocks.
6648 		 */
6649 		for (i = iboff + 1; i < UFS_NDADDR; i++)
6650 			setup_freedirect(freeblks, ip, i, needj);
6651 		for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
6652 		    i < UFS_NIADDR;
6653 		    i++, lbn += tmpval, tmpval *= NINDIR(fs)) {
6654 			/* Release a whole indirect tree. */
6655 			if (lbn > lastlbn) {
6656 				setup_freeindir(freeblks, ip, i, -lbn -i,
6657 				    needj);
6658 				continue;
6659 			}
6660 			iboff = i + UFS_NDADDR;
6661 			/*
6662 			 * Traverse partially truncated indirect tree.
6663 			 */
6664 			if (lbn <= lastlbn && lbn + tmpval - 1 > lastlbn)
6665 				setup_trunc_indir(freeblks, ip, -lbn - i,
6666 				    lastlbn, DIP(ip, i_ib[i]));
6667 		}
6668 		/*
6669 		 * Handle partial truncation to a frag boundary.
6670 		 */
6671 		if (frags) {
6672 			ufs2_daddr_t blkno;
6673 			long oldfrags;
6674 
6675 			oldfrags = blksize(fs, ip, lastlbn);
6676 			blkno = DIP(ip, i_db[lastlbn]);
6677 			if (blkno && oldfrags != frags) {
6678 				oldfrags -= frags;
6679 				oldfrags = numfrags(fs, oldfrags);
6680 				blkno += numfrags(fs, frags);
6681 				newfreework(ump, freeblks, NULL, lastlbn,
6682 				    blkno, oldfrags, 0, needj);
6683 				if (needj)
6684 					adjust_newfreework(freeblks,
6685 					    numfrags(fs, frags));
6686 			} else if (blkno == 0)
6687 				allocblock = 1;
6688 		}
6689 		/*
6690 		 * Add a journal record for partial truncate if we are
6691 		 * handling indirect blocks.  Non-indirects need no extra
6692 		 * journaling.
6693 		 */
6694 		if (length != 0 && lastlbn >= UFS_NDADDR) {
6695 			UFS_INODE_SET_FLAG(ip, IN_TRUNCATED);
6696 			newjtrunc(freeblks, length, 0);
6697 		}
6698 		ip->i_size = length;
6699 		DIP_SET(ip, i_size, ip->i_size);
6700 		datablocks = DIP(ip, i_blocks) - extblocks;
6701 		if (length != 0)
6702 			datablocks = blkcount(fs, datablocks, length);
6703 		freeblks->fb_len = length;
6704 	}
6705 	if ((flags & IO_EXT) != 0) {
6706 		for (i = 0; i < UFS_NXADDR; i++)
6707 			setup_freeext(freeblks, ip, i, needj);
6708 		ip->i_din2->di_extsize = 0;
6709 		datablocks += extblocks;
6710 	}
6711 #ifdef QUOTA
6712 	/* Reference the quotas in case the block count is wrong in the end. */
6713 	quotaref(vp, freeblks->fb_quota);
6714 	(void) chkdq(ip, -datablocks, NOCRED, FORCE);
6715 #endif
6716 	freeblks->fb_chkcnt = -datablocks;
6717 	UFS_LOCK(ump);
6718 	fs->fs_pendingblocks += datablocks;
6719 	UFS_UNLOCK(ump);
6720 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6721 	/*
6722 	 * Handle truncation of incomplete alloc direct dependencies.  We
6723 	 * hold the inode block locked to prevent incomplete dependencies
6724 	 * from reaching the disk while we are eliminating those that
6725 	 * have been truncated.  This is a partially inlined ffs_update().
6726 	 */
6727 	ufs_itimes(vp);
6728 	ip->i_flag &= ~(IN_LAZYACCESS | IN_LAZYMOD | IN_MODIFIED);
6729 	error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6730 	    (int)fs->fs_bsize, cred, &bp);
6731 	if (error) {
6732 		softdep_error("softdep_journal_freeblocks", error);
6733 		return;
6734 	}
6735 	if (bp->b_bufsize == fs->fs_bsize)
6736 		bp->b_flags |= B_CLUSTEROK;
6737 	softdep_update_inodeblock(ip, bp, 0);
6738 	if (ump->um_fstype == UFS1) {
6739 		*((struct ufs1_dinode *)bp->b_data +
6740 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din1;
6741 	} else {
6742 		ffs_update_dinode_ckhash(fs, ip->i_din2);
6743 		*((struct ufs2_dinode *)bp->b_data +
6744 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din2;
6745 	}
6746 	ACQUIRE_LOCK(ump);
6747 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6748 	if ((inodedep->id_state & IOSTARTED) != 0)
6749 		panic("softdep_setup_freeblocks: inode busy");
6750 	/*
6751 	 * Add the freeblks structure to the list of operations that
6752 	 * must await the zero'ed inode being written to disk. If we
6753 	 * still have a bitmap dependency (needj), then the inode
6754 	 * has never been written to disk, so we can process the
6755 	 * freeblks below once we have deleted the dependencies.
6756 	 */
6757 	if (needj)
6758 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6759 	else
6760 		freeblks->fb_state |= COMPLETE;
6761 	if ((flags & IO_NORMAL) != 0) {
6762 		TAILQ_FOREACH_SAFE(adp, &inodedep->id_inoupdt, ad_next, adpn) {
6763 			if (adp->ad_offset > iboff)
6764 				cancel_allocdirect(&inodedep->id_inoupdt, adp,
6765 				    freeblks);
6766 			/*
6767 			 * Truncate the allocdirect.  We could eliminate
6768 			 * or modify journal records as well.
6769 			 */
6770 			else if (adp->ad_offset == iboff && frags)
6771 				adp->ad_newsize = frags;
6772 		}
6773 	}
6774 	if ((flags & IO_EXT) != 0)
6775 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
6776 			cancel_allocdirect(&inodedep->id_extupdt, adp,
6777 			    freeblks);
6778 	/*
6779 	 * Scan the bufwait list for newblock dependencies that will never
6780 	 * make it to disk.
6781 	 */
6782 	LIST_FOREACH_SAFE(wk, &inodedep->id_bufwait, wk_list, wkn) {
6783 		if (wk->wk_type != D_ALLOCDIRECT)
6784 			continue;
6785 		adp = WK_ALLOCDIRECT(wk);
6786 		if (((flags & IO_NORMAL) != 0 && (adp->ad_offset > iboff)) ||
6787 		    ((flags & IO_EXT) != 0 && (adp->ad_state & EXTDATA))) {
6788 			cancel_jfreeblk(freeblks, adp->ad_newblkno);
6789 			cancel_newblk(WK_NEWBLK(wk), NULL, &freeblks->fb_jwork);
6790 			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
6791 		}
6792 	}
6793 	/*
6794 	 * Add journal work.
6795 	 */
6796 	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps)
6797 		add_to_journal(&jblkdep->jb_list);
6798 	FREE_LOCK(ump);
6799 	bdwrite(bp);
6800 	/*
6801 	 * Truncate dependency structures beyond length.
6802 	 */
6803 	trunc_dependencies(ip, freeblks, lastlbn, frags, flags);
6804 	/*
6805 	 * This is only set when we need to allocate a fragment because
6806 	 * none existed at the end of a frag-sized file.  It handles only
6807 	 * allocating a new, zero filled block.
6808 	 */
6809 	if (allocblock) {
6810 		ip->i_size = length - lastoff;
6811 		DIP_SET(ip, i_size, ip->i_size);
6812 		error = UFS_BALLOC(vp, length - 1, 1, cred, BA_CLRBUF, &bp);
6813 		if (error != 0) {
6814 			softdep_error("softdep_journal_freeblks", error);
6815 			return;
6816 		}
6817 		ip->i_size = length;
6818 		DIP_SET(ip, i_size, length);
6819 		UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_UPDATE);
6820 		allocbuf(bp, frags);
6821 		ffs_update(vp, 0);
6822 		bawrite(bp);
6823 	} else if (lastoff != 0 && vp->v_type != VDIR) {
6824 		int size;
6825 
6826 		/*
6827 		 * Zero the end of a truncated frag or block.
6828 		 */
6829 		size = sblksize(fs, length, lastlbn);
6830 		error = bread(vp, lastlbn, size, cred, &bp);
6831 		if (error) {
6832 			softdep_error("softdep_journal_freeblks", error);
6833 			return;
6834 		}
6835 		bzero((char *)bp->b_data + lastoff, size - lastoff);
6836 		bawrite(bp);
6837 
6838 	}
6839 	ACQUIRE_LOCK(ump);
6840 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6841 	TAILQ_INSERT_TAIL(&inodedep->id_freeblklst, freeblks, fb_next);
6842 	freeblks->fb_state |= DEPCOMPLETE | ONDEPLIST;
6843 	/*
6844 	 * We zero earlier truncations so they don't erroneously
6845 	 * update i_blocks.
6846 	 */
6847 	if (freeblks->fb_len == 0 && (flags & IO_NORMAL) != 0)
6848 		TAILQ_FOREACH(fbn, &inodedep->id_freeblklst, fb_next)
6849 			fbn->fb_len = 0;
6850 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE &&
6851 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
6852 		freeblks->fb_state |= INPROGRESS;
6853 	else
6854 		freeblks = NULL;
6855 	FREE_LOCK(ump);
6856 	if (freeblks)
6857 		handle_workitem_freeblocks(freeblks, 0);
6858 	trunc_pages(ip, length, extblocks, flags);
6859 
6860 }
6861 
6862 /*
6863  * Flush a JOP_SYNC to the journal.
6864  */
6865 void
6866 softdep_journal_fsync(ip)
6867 	struct inode *ip;
6868 {
6869 	struct jfsync *jfsync;
6870 	struct ufsmount *ump;
6871 
6872 	ump = ITOUMP(ip);
6873 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
6874 	    ("softdep_journal_fsync called on non-softdep filesystem"));
6875 	if ((ip->i_flag & IN_TRUNCATED) == 0)
6876 		return;
6877 	ip->i_flag &= ~IN_TRUNCATED;
6878 	jfsync = malloc(sizeof(*jfsync), M_JFSYNC, M_SOFTDEP_FLAGS | M_ZERO);
6879 	workitem_alloc(&jfsync->jfs_list, D_JFSYNC, UFSTOVFS(ump));
6880 	jfsync->jfs_size = ip->i_size;
6881 	jfsync->jfs_ino = ip->i_number;
6882 	ACQUIRE_LOCK(ump);
6883 	add_to_journal(&jfsync->jfs_list);
6884 	jwait(&jfsync->jfs_list, MNT_WAIT);
6885 	FREE_LOCK(ump);
6886 }
6887 
6888 /*
6889  * Block de-allocation dependencies.
6890  *
6891  * When blocks are de-allocated, the on-disk pointers must be nullified before
6892  * the blocks are made available for use by other files.  (The true
6893  * requirement is that old pointers must be nullified before new on-disk
6894  * pointers are set.  We chose this slightly more stringent requirement to
6895  * reduce complexity.) Our implementation handles this dependency by updating
6896  * the inode (or indirect block) appropriately but delaying the actual block
6897  * de-allocation (i.e., freemap and free space count manipulation) until
6898  * after the updated versions reach stable storage.  After the disk is
6899  * updated, the blocks can be safely de-allocated whenever it is convenient.
6900  * This implementation handles only the common case of reducing a file's
6901  * length to zero. Other cases are handled by the conventional synchronous
6902  * write approach.
6903  *
6904  * The ffs implementation with which we worked double-checks
6905  * the state of the block pointers and file size as it reduces
6906  * a file's length.  Some of this code is replicated here in our
6907  * soft updates implementation.  The freeblks->fb_chkcnt field is
6908  * used to transfer a part of this information to the procedure
6909  * that eventually de-allocates the blocks.
6910  *
6911  * This routine should be called from the routine that shortens
6912  * a file's length, before the inode's size or block pointers
6913  * are modified. It will save the block pointer information for
6914  * later release and zero the inode so that the calling routine
6915  * can release it.
6916  */
6917 void
6918 softdep_setup_freeblocks(ip, length, flags)
6919 	struct inode *ip;	/* The inode whose length is to be reduced */
6920 	off_t length;		/* The new length for the file */
6921 	int flags;		/* IO_EXT and/or IO_NORMAL */
6922 {
6923 	struct ufs1_dinode *dp1;
6924 	struct ufs2_dinode *dp2;
6925 	struct freeblks *freeblks;
6926 	struct inodedep *inodedep;
6927 	struct allocdirect *adp;
6928 	struct ufsmount *ump;
6929 	struct buf *bp;
6930 	struct fs *fs;
6931 	ufs2_daddr_t extblocks, datablocks;
6932 	struct mount *mp;
6933 	int i, delay, error;
6934 	ufs_lbn_t tmpval;
6935 	ufs_lbn_t lbn;
6936 
6937 	ump = ITOUMP(ip);
6938 	mp = UFSTOVFS(ump);
6939 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6940 	    ("softdep_setup_freeblocks called on non-softdep filesystem"));
6941 	CTR2(KTR_SUJ, "softdep_setup_freeblks: ip %d length %ld",
6942 	    ip->i_number, length);
6943 	KASSERT(length == 0, ("softdep_setup_freeblocks: non-zero length"));
6944 	fs = ump->um_fs;
6945 	if ((error = bread(ump->um_devvp,
6946 	    fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6947 	    (int)fs->fs_bsize, NOCRED, &bp)) != 0) {
6948 		brelse(bp);
6949 		softdep_error("softdep_setup_freeblocks", error);
6950 		return;
6951 	}
6952 	freeblks = newfreeblks(mp, ip);
6953 	extblocks = 0;
6954 	datablocks = 0;
6955 	if (fs->fs_magic == FS_UFS2_MAGIC)
6956 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6957 	if ((flags & IO_NORMAL) != 0) {
6958 		for (i = 0; i < UFS_NDADDR; i++)
6959 			setup_freedirect(freeblks, ip, i, 0);
6960 		for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
6961 		    i < UFS_NIADDR;
6962 		    i++, lbn += tmpval, tmpval *= NINDIR(fs))
6963 			setup_freeindir(freeblks, ip, i, -lbn -i, 0);
6964 		ip->i_size = 0;
6965 		DIP_SET(ip, i_size, 0);
6966 		datablocks = DIP(ip, i_blocks) - extblocks;
6967 	}
6968 	if ((flags & IO_EXT) != 0) {
6969 		for (i = 0; i < UFS_NXADDR; i++)
6970 			setup_freeext(freeblks, ip, i, 0);
6971 		ip->i_din2->di_extsize = 0;
6972 		datablocks += extblocks;
6973 	}
6974 #ifdef QUOTA
6975 	/* Reference the quotas in case the block count is wrong in the end. */
6976 	quotaref(ITOV(ip), freeblks->fb_quota);
6977 	(void) chkdq(ip, -datablocks, NOCRED, FORCE);
6978 #endif
6979 	freeblks->fb_chkcnt = -datablocks;
6980 	UFS_LOCK(ump);
6981 	fs->fs_pendingblocks += datablocks;
6982 	UFS_UNLOCK(ump);
6983 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6984 	/*
6985 	 * Push the zero'ed inode to its disk buffer so that we are free
6986 	 * to delete its dependencies below. Once the dependencies are gone
6987 	 * the buffer can be safely released.
6988 	 */
6989 	if (ump->um_fstype == UFS1) {
6990 		dp1 = ((struct ufs1_dinode *)bp->b_data +
6991 		    ino_to_fsbo(fs, ip->i_number));
6992 		ip->i_din1->di_freelink = dp1->di_freelink;
6993 		*dp1 = *ip->i_din1;
6994 	} else {
6995 		dp2 = ((struct ufs2_dinode *)bp->b_data +
6996 		    ino_to_fsbo(fs, ip->i_number));
6997 		ip->i_din2->di_freelink = dp2->di_freelink;
6998 		ffs_update_dinode_ckhash(fs, ip->i_din2);
6999 		*dp2 = *ip->i_din2;
7000 	}
7001 	/*
7002 	 * Find and eliminate any inode dependencies.
7003 	 */
7004 	ACQUIRE_LOCK(ump);
7005 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
7006 	if ((inodedep->id_state & IOSTARTED) != 0)
7007 		panic("softdep_setup_freeblocks: inode busy");
7008 	/*
7009 	 * Add the freeblks structure to the list of operations that
7010 	 * must await the zero'ed inode being written to disk. If we
7011 	 * still have a bitmap dependency (delay == 0), then the inode
7012 	 * has never been written to disk, so we can process the
7013 	 * freeblks below once we have deleted the dependencies.
7014 	 */
7015 	delay = (inodedep->id_state & DEPCOMPLETE);
7016 	if (delay)
7017 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
7018 	else
7019 		freeblks->fb_state |= COMPLETE;
7020 	/*
7021 	 * Because the file length has been truncated to zero, any
7022 	 * pending block allocation dependency structures associated
7023 	 * with this inode are obsolete and can simply be de-allocated.
7024 	 * We must first merge the two dependency lists to get rid of
7025 	 * any duplicate freefrag structures, then purge the merged list.
7026 	 * If we still have a bitmap dependency, then the inode has never
7027 	 * been written to disk, so we can free any fragments without delay.
7028 	 */
7029 	if (flags & IO_NORMAL) {
7030 		merge_inode_lists(&inodedep->id_newinoupdt,
7031 		    &inodedep->id_inoupdt);
7032 		while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
7033 			cancel_allocdirect(&inodedep->id_inoupdt, adp,
7034 			    freeblks);
7035 	}
7036 	if (flags & IO_EXT) {
7037 		merge_inode_lists(&inodedep->id_newextupdt,
7038 		    &inodedep->id_extupdt);
7039 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
7040 			cancel_allocdirect(&inodedep->id_extupdt, adp,
7041 			    freeblks);
7042 	}
7043 	FREE_LOCK(ump);
7044 	bdwrite(bp);
7045 	trunc_dependencies(ip, freeblks, -1, 0, flags);
7046 	ACQUIRE_LOCK(ump);
7047 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
7048 		(void) free_inodedep(inodedep);
7049 	freeblks->fb_state |= DEPCOMPLETE;
7050 	/*
7051 	 * If the inode with zeroed block pointers is now on disk
7052 	 * we can start freeing blocks.
7053 	 */
7054 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
7055 		freeblks->fb_state |= INPROGRESS;
7056 	else
7057 		freeblks = NULL;
7058 	FREE_LOCK(ump);
7059 	if (freeblks)
7060 		handle_workitem_freeblocks(freeblks, 0);
7061 	trunc_pages(ip, length, extblocks, flags);
7062 }
7063 
7064 /*
7065  * Eliminate pages from the page cache that back parts of this inode and
7066  * adjust the vnode pager's idea of our size.  This prevents stale data
7067  * from hanging around in the page cache.
7068  */
7069 static void
7070 trunc_pages(ip, length, extblocks, flags)
7071 	struct inode *ip;
7072 	off_t length;
7073 	ufs2_daddr_t extblocks;
7074 	int flags;
7075 {
7076 	struct vnode *vp;
7077 	struct fs *fs;
7078 	ufs_lbn_t lbn;
7079 	off_t end, extend;
7080 
7081 	vp = ITOV(ip);
7082 	fs = ITOFS(ip);
7083 	extend = OFF_TO_IDX(lblktosize(fs, -extblocks));
7084 	if ((flags & IO_EXT) != 0)
7085 		vn_pages_remove(vp, extend, 0);
7086 	if ((flags & IO_NORMAL) == 0)
7087 		return;
7088 	BO_LOCK(&vp->v_bufobj);
7089 	drain_output(vp);
7090 	BO_UNLOCK(&vp->v_bufobj);
7091 	/*
7092 	 * The vnode pager eliminates file pages we eliminate indirects
7093 	 * below.
7094 	 */
7095 	vnode_pager_setsize(vp, length);
7096 	/*
7097 	 * Calculate the end based on the last indirect we want to keep.  If
7098 	 * the block extends into indirects we can just use the negative of
7099 	 * its lbn.  Doubles and triples exist at lower numbers so we must
7100 	 * be careful not to remove those, if they exist.  double and triple
7101 	 * indirect lbns do not overlap with others so it is not important
7102 	 * to verify how many levels are required.
7103 	 */
7104 	lbn = lblkno(fs, length);
7105 	if (lbn >= UFS_NDADDR) {
7106 		/* Calculate the virtual lbn of the triple indirect. */
7107 		lbn = -lbn - (UFS_NIADDR - 1);
7108 		end = OFF_TO_IDX(lblktosize(fs, lbn));
7109 	} else
7110 		end = extend;
7111 	vn_pages_remove(vp, OFF_TO_IDX(OFF_MAX), end);
7112 }
7113 
7114 /*
7115  * See if the buf bp is in the range eliminated by truncation.
7116  */
7117 static int
7118 trunc_check_buf(bp, blkoffp, lastlbn, lastoff, flags)
7119 	struct buf *bp;
7120 	int *blkoffp;
7121 	ufs_lbn_t lastlbn;
7122 	int lastoff;
7123 	int flags;
7124 {
7125 	ufs_lbn_t lbn;
7126 
7127 	*blkoffp = 0;
7128 	/* Only match ext/normal blocks as appropriate. */
7129 	if (((flags & IO_EXT) == 0 && (bp->b_xflags & BX_ALTDATA)) ||
7130 	    ((flags & IO_NORMAL) == 0 && (bp->b_xflags & BX_ALTDATA) == 0))
7131 		return (0);
7132 	/* ALTDATA is always a full truncation. */
7133 	if ((bp->b_xflags & BX_ALTDATA) != 0)
7134 		return (1);
7135 	/* -1 is full truncation. */
7136 	if (lastlbn == -1)
7137 		return (1);
7138 	/*
7139 	 * If this is a partial truncate we only want those
7140 	 * blocks and indirect blocks that cover the range
7141 	 * we're after.
7142 	 */
7143 	lbn = bp->b_lblkno;
7144 	if (lbn < 0)
7145 		lbn = -(lbn + lbn_level(lbn));
7146 	if (lbn < lastlbn)
7147 		return (0);
7148 	/* Here we only truncate lblkno if it's partial. */
7149 	if (lbn == lastlbn) {
7150 		if (lastoff == 0)
7151 			return (0);
7152 		*blkoffp = lastoff;
7153 	}
7154 	return (1);
7155 }
7156 
7157 /*
7158  * Eliminate any dependencies that exist in memory beyond lblkno:off
7159  */
7160 static void
7161 trunc_dependencies(ip, freeblks, lastlbn, lastoff, flags)
7162 	struct inode *ip;
7163 	struct freeblks *freeblks;
7164 	ufs_lbn_t lastlbn;
7165 	int lastoff;
7166 	int flags;
7167 {
7168 	struct bufobj *bo;
7169 	struct vnode *vp;
7170 	struct buf *bp;
7171 	int blkoff;
7172 
7173 	/*
7174 	 * We must wait for any I/O in progress to finish so that
7175 	 * all potential buffers on the dirty list will be visible.
7176 	 * Once they are all there, walk the list and get rid of
7177 	 * any dependencies.
7178 	 */
7179 	vp = ITOV(ip);
7180 	bo = &vp->v_bufobj;
7181 	BO_LOCK(bo);
7182 	drain_output(vp);
7183 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs)
7184 		bp->b_vflags &= ~BV_SCANNED;
7185 restart:
7186 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) {
7187 		if (bp->b_vflags & BV_SCANNED)
7188 			continue;
7189 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7190 			bp->b_vflags |= BV_SCANNED;
7191 			continue;
7192 		}
7193 		KASSERT(bp->b_bufobj == bo, ("Wrong object in buffer"));
7194 		if ((bp = getdirtybuf(bp, BO_LOCKPTR(bo), MNT_WAIT)) == NULL)
7195 			goto restart;
7196 		BO_UNLOCK(bo);
7197 		if (deallocate_dependencies(bp, freeblks, blkoff))
7198 			bqrelse(bp);
7199 		else
7200 			brelse(bp);
7201 		BO_LOCK(bo);
7202 		goto restart;
7203 	}
7204 	/*
7205 	 * Now do the work of vtruncbuf while also matching indirect blocks.
7206 	 */
7207 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs)
7208 		bp->b_vflags &= ~BV_SCANNED;
7209 cleanrestart:
7210 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs) {
7211 		if (bp->b_vflags & BV_SCANNED)
7212 			continue;
7213 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7214 			bp->b_vflags |= BV_SCANNED;
7215 			continue;
7216 		}
7217 		if (BUF_LOCK(bp,
7218 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
7219 		    BO_LOCKPTR(bo)) == ENOLCK) {
7220 			BO_LOCK(bo);
7221 			goto cleanrestart;
7222 		}
7223 		bp->b_vflags |= BV_SCANNED;
7224 		bremfree(bp);
7225 		if (blkoff != 0) {
7226 			allocbuf(bp, blkoff);
7227 			bqrelse(bp);
7228 		} else {
7229 			bp->b_flags |= B_INVAL | B_NOCACHE | B_RELBUF;
7230 			brelse(bp);
7231 		}
7232 		BO_LOCK(bo);
7233 		goto cleanrestart;
7234 	}
7235 	drain_output(vp);
7236 	BO_UNLOCK(bo);
7237 }
7238 
7239 static int
7240 cancel_pagedep(pagedep, freeblks, blkoff)
7241 	struct pagedep *pagedep;
7242 	struct freeblks *freeblks;
7243 	int blkoff;
7244 {
7245 	struct jremref *jremref;
7246 	struct jmvref *jmvref;
7247 	struct dirrem *dirrem, *tmp;
7248 	int i;
7249 
7250 	/*
7251 	 * Copy any directory remove dependencies to the list
7252 	 * to be processed after the freeblks proceeds.  If
7253 	 * directory entry never made it to disk they
7254 	 * can be dumped directly onto the work list.
7255 	 */
7256 	LIST_FOREACH_SAFE(dirrem, &pagedep->pd_dirremhd, dm_next, tmp) {
7257 		/* Skip this directory removal if it is intended to remain. */
7258 		if (dirrem->dm_offset < blkoff)
7259 			continue;
7260 		/*
7261 		 * If there are any dirrems we wait for the journal write
7262 		 * to complete and then restart the buf scan as the lock
7263 		 * has been dropped.
7264 		 */
7265 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL) {
7266 			jwait(&jremref->jr_list, MNT_WAIT);
7267 			return (ERESTART);
7268 		}
7269 		LIST_REMOVE(dirrem, dm_next);
7270 		dirrem->dm_dirinum = pagedep->pd_ino;
7271 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &dirrem->dm_list);
7272 	}
7273 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL) {
7274 		jwait(&jmvref->jm_list, MNT_WAIT);
7275 		return (ERESTART);
7276 	}
7277 	/*
7278 	 * When we're partially truncating a pagedep we just want to flush
7279 	 * journal entries and return.  There can not be any adds in the
7280 	 * truncated portion of the directory and newblk must remain if
7281 	 * part of the block remains.
7282 	 */
7283 	if (blkoff != 0) {
7284 		struct diradd *dap;
7285 
7286 		LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
7287 			if (dap->da_offset > blkoff)
7288 				panic("cancel_pagedep: diradd %p off %d > %d",
7289 				    dap, dap->da_offset, blkoff);
7290 		for (i = 0; i < DAHASHSZ; i++)
7291 			LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist)
7292 				if (dap->da_offset > blkoff)
7293 					panic("cancel_pagedep: diradd %p off %d > %d",
7294 					    dap, dap->da_offset, blkoff);
7295 		return (0);
7296 	}
7297 	/*
7298 	 * There should be no directory add dependencies present
7299 	 * as the directory could not be truncated until all
7300 	 * children were removed.
7301 	 */
7302 	KASSERT(LIST_FIRST(&pagedep->pd_pendinghd) == NULL,
7303 	    ("deallocate_dependencies: pendinghd != NULL"));
7304 	for (i = 0; i < DAHASHSZ; i++)
7305 		KASSERT(LIST_FIRST(&pagedep->pd_diraddhd[i]) == NULL,
7306 		    ("deallocate_dependencies: diraddhd != NULL"));
7307 	if ((pagedep->pd_state & NEWBLOCK) != 0)
7308 		free_newdirblk(pagedep->pd_newdirblk);
7309 	if (free_pagedep(pagedep) == 0)
7310 		panic("Failed to free pagedep %p", pagedep);
7311 	return (0);
7312 }
7313 
7314 /*
7315  * Reclaim any dependency structures from a buffer that is about to
7316  * be reallocated to a new vnode. The buffer must be locked, thus,
7317  * no I/O completion operations can occur while we are manipulating
7318  * its associated dependencies. The mutex is held so that other I/O's
7319  * associated with related dependencies do not occur.
7320  */
7321 static int
7322 deallocate_dependencies(bp, freeblks, off)
7323 	struct buf *bp;
7324 	struct freeblks *freeblks;
7325 	int off;
7326 {
7327 	struct indirdep *indirdep;
7328 	struct pagedep *pagedep;
7329 	struct worklist *wk, *wkn;
7330 	struct ufsmount *ump;
7331 
7332 	ump = softdep_bp_to_mp(bp);
7333 	if (ump == NULL)
7334 		goto done;
7335 	ACQUIRE_LOCK(ump);
7336 	LIST_FOREACH_SAFE(wk, &bp->b_dep, wk_list, wkn) {
7337 		switch (wk->wk_type) {
7338 		case D_INDIRDEP:
7339 			indirdep = WK_INDIRDEP(wk);
7340 			if (bp->b_lblkno >= 0 ||
7341 			    bp->b_blkno != indirdep->ir_savebp->b_lblkno)
7342 				panic("deallocate_dependencies: not indir");
7343 			cancel_indirdep(indirdep, bp, freeblks);
7344 			continue;
7345 
7346 		case D_PAGEDEP:
7347 			pagedep = WK_PAGEDEP(wk);
7348 			if (cancel_pagedep(pagedep, freeblks, off)) {
7349 				FREE_LOCK(ump);
7350 				return (ERESTART);
7351 			}
7352 			continue;
7353 
7354 		case D_ALLOCINDIR:
7355 			/*
7356 			 * Simply remove the allocindir, we'll find it via
7357 			 * the indirdep where we can clear pointers if
7358 			 * needed.
7359 			 */
7360 			WORKLIST_REMOVE(wk);
7361 			continue;
7362 
7363 		case D_FREEWORK:
7364 			/*
7365 			 * A truncation is waiting for the zero'd pointers
7366 			 * to be written.  It can be freed when the freeblks
7367 			 * is journaled.
7368 			 */
7369 			WORKLIST_REMOVE(wk);
7370 			wk->wk_state |= ONDEPLIST;
7371 			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
7372 			break;
7373 
7374 		case D_ALLOCDIRECT:
7375 			if (off != 0)
7376 				continue;
7377 			/* FALLTHROUGH */
7378 		default:
7379 			panic("deallocate_dependencies: Unexpected type %s",
7380 			    TYPENAME(wk->wk_type));
7381 			/* NOTREACHED */
7382 		}
7383 	}
7384 	FREE_LOCK(ump);
7385 done:
7386 	/*
7387 	 * Don't throw away this buf, we were partially truncating and
7388 	 * some deps may always remain.
7389 	 */
7390 	if (off) {
7391 		allocbuf(bp, off);
7392 		bp->b_vflags |= BV_SCANNED;
7393 		return (EBUSY);
7394 	}
7395 	bp->b_flags |= B_INVAL | B_NOCACHE;
7396 
7397 	return (0);
7398 }
7399 
7400 /*
7401  * An allocdirect is being canceled due to a truncate.  We must make sure
7402  * the journal entry is released in concert with the blkfree that releases
7403  * the storage.  Completed journal entries must not be released until the
7404  * space is no longer pointed to by the inode or in the bitmap.
7405  */
7406 static void
7407 cancel_allocdirect(adphead, adp, freeblks)
7408 	struct allocdirectlst *adphead;
7409 	struct allocdirect *adp;
7410 	struct freeblks *freeblks;
7411 {
7412 	struct freework *freework;
7413 	struct newblk *newblk;
7414 	struct worklist *wk;
7415 
7416 	TAILQ_REMOVE(adphead, adp, ad_next);
7417 	newblk = (struct newblk *)adp;
7418 	freework = NULL;
7419 	/*
7420 	 * Find the correct freework structure.
7421 	 */
7422 	LIST_FOREACH(wk, &freeblks->fb_freeworkhd, wk_list) {
7423 		if (wk->wk_type != D_FREEWORK)
7424 			continue;
7425 		freework = WK_FREEWORK(wk);
7426 		if (freework->fw_blkno == newblk->nb_newblkno)
7427 			break;
7428 	}
7429 	if (freework == NULL)
7430 		panic("cancel_allocdirect: Freework not found");
7431 	/*
7432 	 * If a newblk exists at all we still have the journal entry that
7433 	 * initiated the allocation so we do not need to journal the free.
7434 	 */
7435 	cancel_jfreeblk(freeblks, freework->fw_blkno);
7436 	/*
7437 	 * If the journal hasn't been written the jnewblk must be passed
7438 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
7439 	 * this by linking the journal dependency into the freework to be
7440 	 * freed when freework_freeblock() is called.  If the journal has
7441 	 * been written we can simply reclaim the journal space when the
7442 	 * freeblks work is complete.
7443 	 */
7444 	freework->fw_jnewblk = cancel_newblk(newblk, &freework->fw_list,
7445 	    &freeblks->fb_jwork);
7446 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
7447 }
7448 
7449 
7450 /*
7451  * Cancel a new block allocation.  May be an indirect or direct block.  We
7452  * remove it from various lists and return any journal record that needs to
7453  * be resolved by the caller.
7454  *
7455  * A special consideration is made for indirects which were never pointed
7456  * at on disk and will never be found once this block is released.
7457  */
7458 static struct jnewblk *
7459 cancel_newblk(newblk, wk, wkhd)
7460 	struct newblk *newblk;
7461 	struct worklist *wk;
7462 	struct workhead *wkhd;
7463 {
7464 	struct jnewblk *jnewblk;
7465 
7466 	CTR1(KTR_SUJ, "cancel_newblk: blkno %jd", newblk->nb_newblkno);
7467 
7468 	newblk->nb_state |= GOINGAWAY;
7469 	/*
7470 	 * Previously we traversed the completedhd on each indirdep
7471 	 * attached to this newblk to cancel them and gather journal
7472 	 * work.  Since we need only the oldest journal segment and
7473 	 * the lowest point on the tree will always have the oldest
7474 	 * journal segment we are free to release the segments
7475 	 * of any subordinates and may leave the indirdep list to
7476 	 * indirdep_complete() when this newblk is freed.
7477 	 */
7478 	if (newblk->nb_state & ONDEPLIST) {
7479 		newblk->nb_state &= ~ONDEPLIST;
7480 		LIST_REMOVE(newblk, nb_deps);
7481 	}
7482 	if (newblk->nb_state & ONWORKLIST)
7483 		WORKLIST_REMOVE(&newblk->nb_list);
7484 	/*
7485 	 * If the journal entry hasn't been written we save a pointer to
7486 	 * the dependency that frees it until it is written or the
7487 	 * superseding operation completes.
7488 	 */
7489 	jnewblk = newblk->nb_jnewblk;
7490 	if (jnewblk != NULL && wk != NULL) {
7491 		newblk->nb_jnewblk = NULL;
7492 		jnewblk->jn_dep = wk;
7493 	}
7494 	if (!LIST_EMPTY(&newblk->nb_jwork))
7495 		jwork_move(wkhd, &newblk->nb_jwork);
7496 	/*
7497 	 * When truncating we must free the newdirblk early to remove
7498 	 * the pagedep from the hash before returning.
7499 	 */
7500 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7501 		free_newdirblk(WK_NEWDIRBLK(wk));
7502 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7503 		panic("cancel_newblk: extra newdirblk");
7504 
7505 	return (jnewblk);
7506 }
7507 
7508 /*
7509  * Schedule the freefrag associated with a newblk to be released once
7510  * the pointers are written and the previous block is no longer needed.
7511  */
7512 static void
7513 newblk_freefrag(newblk)
7514 	struct newblk *newblk;
7515 {
7516 	struct freefrag *freefrag;
7517 
7518 	if (newblk->nb_freefrag == NULL)
7519 		return;
7520 	freefrag = newblk->nb_freefrag;
7521 	newblk->nb_freefrag = NULL;
7522 	freefrag->ff_state |= COMPLETE;
7523 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
7524 		add_to_worklist(&freefrag->ff_list, 0);
7525 }
7526 
7527 /*
7528  * Free a newblk. Generate a new freefrag work request if appropriate.
7529  * This must be called after the inode pointer and any direct block pointers
7530  * are valid or fully removed via truncate or frag extension.
7531  */
7532 static void
7533 free_newblk(newblk)
7534 	struct newblk *newblk;
7535 {
7536 	struct indirdep *indirdep;
7537 	struct worklist *wk;
7538 
7539 	KASSERT(newblk->nb_jnewblk == NULL,
7540 	    ("free_newblk: jnewblk %p still attached", newblk->nb_jnewblk));
7541 	KASSERT(newblk->nb_list.wk_type != D_NEWBLK,
7542 	    ("free_newblk: unclaimed newblk"));
7543 	LOCK_OWNED(VFSTOUFS(newblk->nb_list.wk_mp));
7544 	newblk_freefrag(newblk);
7545 	if (newblk->nb_state & ONDEPLIST)
7546 		LIST_REMOVE(newblk, nb_deps);
7547 	if (newblk->nb_state & ONWORKLIST)
7548 		WORKLIST_REMOVE(&newblk->nb_list);
7549 	LIST_REMOVE(newblk, nb_hash);
7550 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7551 		free_newdirblk(WK_NEWDIRBLK(wk));
7552 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7553 		panic("free_newblk: extra newdirblk");
7554 	while ((indirdep = LIST_FIRST(&newblk->nb_indirdeps)) != NULL)
7555 		indirdep_complete(indirdep);
7556 	handle_jwork(&newblk->nb_jwork);
7557 	WORKITEM_FREE(newblk, D_NEWBLK);
7558 }
7559 
7560 /*
7561  * Free a newdirblk. Clear the NEWBLOCK flag on its associated pagedep.
7562  */
7563 static void
7564 free_newdirblk(newdirblk)
7565 	struct newdirblk *newdirblk;
7566 {
7567 	struct pagedep *pagedep;
7568 	struct diradd *dap;
7569 	struct worklist *wk;
7570 
7571 	LOCK_OWNED(VFSTOUFS(newdirblk->db_list.wk_mp));
7572 	WORKLIST_REMOVE(&newdirblk->db_list);
7573 	/*
7574 	 * If the pagedep is still linked onto the directory buffer
7575 	 * dependency chain, then some of the entries on the
7576 	 * pd_pendinghd list may not be committed to disk yet. In
7577 	 * this case, we will simply clear the NEWBLOCK flag and
7578 	 * let the pd_pendinghd list be processed when the pagedep
7579 	 * is next written. If the pagedep is no longer on the buffer
7580 	 * dependency chain, then all the entries on the pd_pending
7581 	 * list are committed to disk and we can free them here.
7582 	 */
7583 	pagedep = newdirblk->db_pagedep;
7584 	pagedep->pd_state &= ~NEWBLOCK;
7585 	if ((pagedep->pd_state & ONWORKLIST) == 0) {
7586 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
7587 			free_diradd(dap, NULL);
7588 		/*
7589 		 * If no dependencies remain, the pagedep will be freed.
7590 		 */
7591 		free_pagedep(pagedep);
7592 	}
7593 	/* Should only ever be one item in the list. */
7594 	while ((wk = LIST_FIRST(&newdirblk->db_mkdir)) != NULL) {
7595 		WORKLIST_REMOVE(wk);
7596 		handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
7597 	}
7598 	WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
7599 }
7600 
7601 /*
7602  * Prepare an inode to be freed. The actual free operation is not
7603  * done until the zero'ed inode has been written to disk.
7604  */
7605 void
7606 softdep_freefile(pvp, ino, mode)
7607 	struct vnode *pvp;
7608 	ino_t ino;
7609 	int mode;
7610 {
7611 	struct inode *ip = VTOI(pvp);
7612 	struct inodedep *inodedep;
7613 	struct freefile *freefile;
7614 	struct freeblks *freeblks;
7615 	struct ufsmount *ump;
7616 
7617 	ump = ITOUMP(ip);
7618 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
7619 	    ("softdep_freefile called on non-softdep filesystem"));
7620 	/*
7621 	 * This sets up the inode de-allocation dependency.
7622 	 */
7623 	freefile = malloc(sizeof(struct freefile),
7624 		M_FREEFILE, M_SOFTDEP_FLAGS);
7625 	workitem_alloc(&freefile->fx_list, D_FREEFILE, pvp->v_mount);
7626 	freefile->fx_mode = mode;
7627 	freefile->fx_oldinum = ino;
7628 	freefile->fx_devvp = ump->um_devvp;
7629 	LIST_INIT(&freefile->fx_jwork);
7630 	UFS_LOCK(ump);
7631 	ump->um_fs->fs_pendinginodes += 1;
7632 	UFS_UNLOCK(ump);
7633 
7634 	/*
7635 	 * If the inodedep does not exist, then the zero'ed inode has
7636 	 * been written to disk. If the allocated inode has never been
7637 	 * written to disk, then the on-disk inode is zero'ed. In either
7638 	 * case we can free the file immediately.  If the journal was
7639 	 * canceled before being written the inode will never make it to
7640 	 * disk and we must send the canceled journal entrys to
7641 	 * ffs_freefile() to be cleared in conjunction with the bitmap.
7642 	 * Any blocks waiting on the inode to write can be safely freed
7643 	 * here as it will never been written.
7644 	 */
7645 	ACQUIRE_LOCK(ump);
7646 	inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7647 	if (inodedep) {
7648 		/*
7649 		 * Clear out freeblks that no longer need to reference
7650 		 * this inode.
7651 		 */
7652 		while ((freeblks =
7653 		    TAILQ_FIRST(&inodedep->id_freeblklst)) != NULL) {
7654 			TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks,
7655 			    fb_next);
7656 			freeblks->fb_state &= ~ONDEPLIST;
7657 		}
7658 		/*
7659 		 * Remove this inode from the unlinked list.
7660 		 */
7661 		if (inodedep->id_state & UNLINKED) {
7662 			/*
7663 			 * Save the journal work to be freed with the bitmap
7664 			 * before we clear UNLINKED.  Otherwise it can be lost
7665 			 * if the inode block is written.
7666 			 */
7667 			handle_bufwait(inodedep, &freefile->fx_jwork);
7668 			clear_unlinked_inodedep(inodedep);
7669 			/*
7670 			 * Re-acquire inodedep as we've dropped the
7671 			 * per-filesystem lock in clear_unlinked_inodedep().
7672 			 */
7673 			inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7674 		}
7675 	}
7676 	if (inodedep == NULL || check_inode_unwritten(inodedep)) {
7677 		FREE_LOCK(ump);
7678 		handle_workitem_freefile(freefile);
7679 		return;
7680 	}
7681 	if ((inodedep->id_state & DEPCOMPLETE) == 0)
7682 		inodedep->id_state |= GOINGAWAY;
7683 	WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
7684 	FREE_LOCK(ump);
7685 	if (ip->i_number == ino)
7686 		UFS_INODE_SET_FLAG(ip, IN_MODIFIED);
7687 }
7688 
7689 /*
7690  * Check to see if an inode has never been written to disk. If
7691  * so free the inodedep and return success, otherwise return failure.
7692  *
7693  * If we still have a bitmap dependency, then the inode has never
7694  * been written to disk. Drop the dependency as it is no longer
7695  * necessary since the inode is being deallocated. We set the
7696  * ALLCOMPLETE flags since the bitmap now properly shows that the
7697  * inode is not allocated. Even if the inode is actively being
7698  * written, it has been rolled back to its zero'ed state, so we
7699  * are ensured that a zero inode is what is on the disk. For short
7700  * lived files, this change will usually result in removing all the
7701  * dependencies from the inode so that it can be freed immediately.
7702  */
7703 static int
7704 check_inode_unwritten(inodedep)
7705 	struct inodedep *inodedep;
7706 {
7707 
7708 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7709 
7710 	if ((inodedep->id_state & (DEPCOMPLETE | UNLINKED)) != 0 ||
7711 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
7712 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
7713 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
7714 	    !LIST_EMPTY(&inodedep->id_inowait) ||
7715 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7716 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7717 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7718 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7719 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7720 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7721 	    inodedep->id_mkdiradd != NULL ||
7722 	    inodedep->id_nlinkdelta != 0)
7723 		return (0);
7724 	/*
7725 	 * Another process might be in initiate_write_inodeblock_ufs[12]
7726 	 * trying to allocate memory without holding "Softdep Lock".
7727 	 */
7728 	if ((inodedep->id_state & IOSTARTED) != 0 &&
7729 	    inodedep->id_savedino1 == NULL)
7730 		return (0);
7731 
7732 	if (inodedep->id_state & ONDEPLIST)
7733 		LIST_REMOVE(inodedep, id_deps);
7734 	inodedep->id_state &= ~ONDEPLIST;
7735 	inodedep->id_state |= ALLCOMPLETE;
7736 	inodedep->id_bmsafemap = NULL;
7737 	if (inodedep->id_state & ONWORKLIST)
7738 		WORKLIST_REMOVE(&inodedep->id_list);
7739 	if (inodedep->id_savedino1 != NULL) {
7740 		free(inodedep->id_savedino1, M_SAVEDINO);
7741 		inodedep->id_savedino1 = NULL;
7742 	}
7743 	if (free_inodedep(inodedep) == 0)
7744 		panic("check_inode_unwritten: busy inode");
7745 	return (1);
7746 }
7747 
7748 static int
7749 check_inodedep_free(inodedep)
7750 	struct inodedep *inodedep;
7751 {
7752 
7753 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7754 	if ((inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
7755 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
7756 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
7757 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
7758 	    !LIST_EMPTY(&inodedep->id_inowait) ||
7759 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7760 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7761 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7762 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7763 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7764 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7765 	    inodedep->id_mkdiradd != NULL ||
7766 	    inodedep->id_nlinkdelta != 0 ||
7767 	    inodedep->id_savedino1 != NULL)
7768 		return (0);
7769 	return (1);
7770 }
7771 
7772 /*
7773  * Try to free an inodedep structure. Return 1 if it could be freed.
7774  */
7775 static int
7776 free_inodedep(inodedep)
7777 	struct inodedep *inodedep;
7778 {
7779 
7780 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7781 	if ((inodedep->id_state & (ONWORKLIST | UNLINKED)) != 0 ||
7782 	    !check_inodedep_free(inodedep))
7783 		return (0);
7784 	if (inodedep->id_state & ONDEPLIST)
7785 		LIST_REMOVE(inodedep, id_deps);
7786 	LIST_REMOVE(inodedep, id_hash);
7787 	WORKITEM_FREE(inodedep, D_INODEDEP);
7788 	return (1);
7789 }
7790 
7791 /*
7792  * Free the block referenced by a freework structure.  The parent freeblks
7793  * structure is released and completed when the final cg bitmap reaches
7794  * the disk.  This routine may be freeing a jnewblk which never made it to
7795  * disk in which case we do not have to wait as the operation is undone
7796  * in memory immediately.
7797  */
7798 static void
7799 freework_freeblock(freework, key)
7800 	struct freework *freework;
7801 	u_long key;
7802 {
7803 	struct freeblks *freeblks;
7804 	struct jnewblk *jnewblk;
7805 	struct ufsmount *ump;
7806 	struct workhead wkhd;
7807 	struct fs *fs;
7808 	int bsize;
7809 	int needj;
7810 
7811 	ump = VFSTOUFS(freework->fw_list.wk_mp);
7812 	LOCK_OWNED(ump);
7813 	/*
7814 	 * Handle partial truncate separately.
7815 	 */
7816 	if (freework->fw_indir) {
7817 		complete_trunc_indir(freework);
7818 		return;
7819 	}
7820 	freeblks = freework->fw_freeblks;
7821 	fs = ump->um_fs;
7822 	needj = MOUNTEDSUJ(freeblks->fb_list.wk_mp) != 0;
7823 	bsize = lfragtosize(fs, freework->fw_frags);
7824 	LIST_INIT(&wkhd);
7825 	/*
7826 	 * DEPCOMPLETE is cleared in indirblk_insert() if the block lives
7827 	 * on the indirblk hashtable and prevents premature freeing.
7828 	 */
7829 	freework->fw_state |= DEPCOMPLETE;
7830 	/*
7831 	 * SUJ needs to wait for the segment referencing freed indirect
7832 	 * blocks to expire so that we know the checker will not confuse
7833 	 * a re-allocated indirect block with its old contents.
7834 	 */
7835 	if (needj && freework->fw_lbn <= -UFS_NDADDR)
7836 		indirblk_insert(freework);
7837 	/*
7838 	 * If we are canceling an existing jnewblk pass it to the free
7839 	 * routine, otherwise pass the freeblk which will ultimately
7840 	 * release the freeblks.  If we're not journaling, we can just
7841 	 * free the freeblks immediately.
7842 	 */
7843 	jnewblk = freework->fw_jnewblk;
7844 	if (jnewblk != NULL) {
7845 		cancel_jnewblk(jnewblk, &wkhd);
7846 		needj = 0;
7847 	} else if (needj) {
7848 		freework->fw_state |= DELAYEDFREE;
7849 		freeblks->fb_cgwait++;
7850 		WORKLIST_INSERT(&wkhd, &freework->fw_list);
7851 	}
7852 	FREE_LOCK(ump);
7853 	freeblks_free(ump, freeblks, btodb(bsize));
7854 	CTR4(KTR_SUJ,
7855 	    "freework_freeblock: ino %jd blkno %jd lbn %jd size %d",
7856 	    freeblks->fb_inum, freework->fw_blkno, freework->fw_lbn, bsize);
7857 	ffs_blkfree(ump, fs, freeblks->fb_devvp, freework->fw_blkno, bsize,
7858 	    freeblks->fb_inum, freeblks->fb_vtype, &wkhd, key);
7859 	ACQUIRE_LOCK(ump);
7860 	/*
7861 	 * The jnewblk will be discarded and the bits in the map never
7862 	 * made it to disk.  We can immediately free the freeblk.
7863 	 */
7864 	if (needj == 0)
7865 		handle_written_freework(freework);
7866 }
7867 
7868 /*
7869  * We enqueue freework items that need processing back on the freeblks and
7870  * add the freeblks to the worklist.  This makes it easier to find all work
7871  * required to flush a truncation in process_truncates().
7872  */
7873 static void
7874 freework_enqueue(freework)
7875 	struct freework *freework;
7876 {
7877 	struct freeblks *freeblks;
7878 
7879 	freeblks = freework->fw_freeblks;
7880 	if ((freework->fw_state & INPROGRESS) == 0)
7881 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
7882 	if ((freeblks->fb_state &
7883 	    (ONWORKLIST | INPROGRESS | ALLCOMPLETE)) == ALLCOMPLETE &&
7884 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
7885 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7886 }
7887 
7888 /*
7889  * Start, continue, or finish the process of freeing an indirect block tree.
7890  * The free operation may be paused at any point with fw_off containing the
7891  * offset to restart from.  This enables us to implement some flow control
7892  * for large truncates which may fan out and generate a huge number of
7893  * dependencies.
7894  */
7895 static void
7896 handle_workitem_indirblk(freework)
7897 	struct freework *freework;
7898 {
7899 	struct freeblks *freeblks;
7900 	struct ufsmount *ump;
7901 	struct fs *fs;
7902 
7903 	freeblks = freework->fw_freeblks;
7904 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7905 	fs = ump->um_fs;
7906 	if (freework->fw_state & DEPCOMPLETE) {
7907 		handle_written_freework(freework);
7908 		return;
7909 	}
7910 	if (freework->fw_off == NINDIR(fs)) {
7911 		freework_freeblock(freework, SINGLETON_KEY);
7912 		return;
7913 	}
7914 	freework->fw_state |= INPROGRESS;
7915 	FREE_LOCK(ump);
7916 	indir_trunc(freework, fsbtodb(fs, freework->fw_blkno),
7917 	    freework->fw_lbn);
7918 	ACQUIRE_LOCK(ump);
7919 }
7920 
7921 /*
7922  * Called when a freework structure attached to a cg buf is written.  The
7923  * ref on either the parent or the freeblks structure is released and
7924  * the freeblks is added back to the worklist if there is more work to do.
7925  */
7926 static void
7927 handle_written_freework(freework)
7928 	struct freework *freework;
7929 {
7930 	struct freeblks *freeblks;
7931 	struct freework *parent;
7932 
7933 	freeblks = freework->fw_freeblks;
7934 	parent = freework->fw_parent;
7935 	if (freework->fw_state & DELAYEDFREE)
7936 		freeblks->fb_cgwait--;
7937 	freework->fw_state |= COMPLETE;
7938 	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
7939 		WORKITEM_FREE(freework, D_FREEWORK);
7940 	if (parent) {
7941 		if (--parent->fw_ref == 0)
7942 			freework_enqueue(parent);
7943 		return;
7944 	}
7945 	if (--freeblks->fb_ref != 0)
7946 		return;
7947 	if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST | INPROGRESS)) ==
7948 	    ALLCOMPLETE && LIST_EMPTY(&freeblks->fb_jblkdephd))
7949 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7950 }
7951 
7952 /*
7953  * This workitem routine performs the block de-allocation.
7954  * The workitem is added to the pending list after the updated
7955  * inode block has been written to disk.  As mentioned above,
7956  * checks regarding the number of blocks de-allocated (compared
7957  * to the number of blocks allocated for the file) are also
7958  * performed in this function.
7959  */
7960 static int
7961 handle_workitem_freeblocks(freeblks, flags)
7962 	struct freeblks *freeblks;
7963 	int flags;
7964 {
7965 	struct freework *freework;
7966 	struct newblk *newblk;
7967 	struct allocindir *aip;
7968 	struct ufsmount *ump;
7969 	struct worklist *wk;
7970 	u_long key;
7971 
7972 	KASSERT(LIST_EMPTY(&freeblks->fb_jblkdephd),
7973 	    ("handle_workitem_freeblocks: Journal entries not written."));
7974 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7975 	key = ffs_blkrelease_start(ump, freeblks->fb_devvp, freeblks->fb_inum);
7976 	ACQUIRE_LOCK(ump);
7977 	while ((wk = LIST_FIRST(&freeblks->fb_freeworkhd)) != NULL) {
7978 		WORKLIST_REMOVE(wk);
7979 		switch (wk->wk_type) {
7980 		case D_DIRREM:
7981 			wk->wk_state |= COMPLETE;
7982 			add_to_worklist(wk, 0);
7983 			continue;
7984 
7985 		case D_ALLOCDIRECT:
7986 			free_newblk(WK_NEWBLK(wk));
7987 			continue;
7988 
7989 		case D_ALLOCINDIR:
7990 			aip = WK_ALLOCINDIR(wk);
7991 			freework = NULL;
7992 			if (aip->ai_state & DELAYEDFREE) {
7993 				FREE_LOCK(ump);
7994 				freework = newfreework(ump, freeblks, NULL,
7995 				    aip->ai_lbn, aip->ai_newblkno,
7996 				    ump->um_fs->fs_frag, 0, 0);
7997 				ACQUIRE_LOCK(ump);
7998 			}
7999 			newblk = WK_NEWBLK(wk);
8000 			if (newblk->nb_jnewblk) {
8001 				freework->fw_jnewblk = newblk->nb_jnewblk;
8002 				newblk->nb_jnewblk->jn_dep = &freework->fw_list;
8003 				newblk->nb_jnewblk = NULL;
8004 			}
8005 			free_newblk(newblk);
8006 			continue;
8007 
8008 		case D_FREEWORK:
8009 			freework = WK_FREEWORK(wk);
8010 			if (freework->fw_lbn <= -UFS_NDADDR)
8011 				handle_workitem_indirblk(freework);
8012 			else
8013 				freework_freeblock(freework, key);
8014 			continue;
8015 		default:
8016 			panic("handle_workitem_freeblocks: Unknown type %s",
8017 			    TYPENAME(wk->wk_type));
8018 		}
8019 	}
8020 	if (freeblks->fb_ref != 0) {
8021 		freeblks->fb_state &= ~INPROGRESS;
8022 		wake_worklist(&freeblks->fb_list);
8023 		freeblks = NULL;
8024 	}
8025 	FREE_LOCK(ump);
8026 	ffs_blkrelease_finish(ump, key);
8027 	if (freeblks)
8028 		return handle_complete_freeblocks(freeblks, flags);
8029 	return (0);
8030 }
8031 
8032 /*
8033  * Handle completion of block free via truncate.  This allows fs_pending
8034  * to track the actual free block count more closely than if we only updated
8035  * it at the end.  We must be careful to handle cases where the block count
8036  * on free was incorrect.
8037  */
8038 static void
8039 freeblks_free(ump, freeblks, blocks)
8040 	struct ufsmount *ump;
8041 	struct freeblks *freeblks;
8042 	int blocks;
8043 {
8044 	struct fs *fs;
8045 	ufs2_daddr_t remain;
8046 
8047 	UFS_LOCK(ump);
8048 	remain = -freeblks->fb_chkcnt;
8049 	freeblks->fb_chkcnt += blocks;
8050 	if (remain > 0) {
8051 		if (remain < blocks)
8052 			blocks = remain;
8053 		fs = ump->um_fs;
8054 		fs->fs_pendingblocks -= blocks;
8055 	}
8056 	UFS_UNLOCK(ump);
8057 }
8058 
8059 /*
8060  * Once all of the freework workitems are complete we can retire the
8061  * freeblocks dependency and any journal work awaiting completion.  This
8062  * can not be called until all other dependencies are stable on disk.
8063  */
8064 static int
8065 handle_complete_freeblocks(freeblks, flags)
8066 	struct freeblks *freeblks;
8067 	int flags;
8068 {
8069 	struct inodedep *inodedep;
8070 	struct inode *ip;
8071 	struct vnode *vp;
8072 	struct fs *fs;
8073 	struct ufsmount *ump;
8074 	ufs2_daddr_t spare;
8075 
8076 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8077 	fs = ump->um_fs;
8078 	flags = LK_EXCLUSIVE | flags;
8079 	spare = freeblks->fb_chkcnt;
8080 
8081 	/*
8082 	 * If we did not release the expected number of blocks we may have
8083 	 * to adjust the inode block count here.  Only do so if it wasn't
8084 	 * a truncation to zero and the modrev still matches.
8085 	 */
8086 	if (spare && freeblks->fb_len != 0) {
8087 		if (ffs_vgetf(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8088 		    flags, &vp, FFSV_FORCEINSMQ) != 0)
8089 			return (EBUSY);
8090 		ip = VTOI(vp);
8091 		if (ip->i_mode == 0) {
8092 			vgone(vp);
8093 		} else if (DIP(ip, i_modrev) == freeblks->fb_modrev) {
8094 			DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - spare);
8095 			UFS_INODE_SET_FLAG(ip, IN_CHANGE);
8096 			/*
8097 			 * We must wait so this happens before the
8098 			 * journal is reclaimed.
8099 			 */
8100 			ffs_update(vp, 1);
8101 		}
8102 		vput(vp);
8103 	}
8104 	if (spare < 0) {
8105 		UFS_LOCK(ump);
8106 		fs->fs_pendingblocks += spare;
8107 		UFS_UNLOCK(ump);
8108 	}
8109 #ifdef QUOTA
8110 	/* Handle spare. */
8111 	if (spare)
8112 		quotaadj(freeblks->fb_quota, ump, -spare);
8113 	quotarele(freeblks->fb_quota);
8114 #endif
8115 	ACQUIRE_LOCK(ump);
8116 	if (freeblks->fb_state & ONDEPLIST) {
8117 		inodedep_lookup(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8118 		    0, &inodedep);
8119 		TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks, fb_next);
8120 		freeblks->fb_state &= ~ONDEPLIST;
8121 		if (TAILQ_EMPTY(&inodedep->id_freeblklst))
8122 			free_inodedep(inodedep);
8123 	}
8124 	/*
8125 	 * All of the freeblock deps must be complete prior to this call
8126 	 * so it's now safe to complete earlier outstanding journal entries.
8127 	 */
8128 	handle_jwork(&freeblks->fb_jwork);
8129 	WORKITEM_FREE(freeblks, D_FREEBLKS);
8130 	FREE_LOCK(ump);
8131 	return (0);
8132 }
8133 
8134 /*
8135  * Release blocks associated with the freeblks and stored in the indirect
8136  * block dbn. If level is greater than SINGLE, the block is an indirect block
8137  * and recursive calls to indirtrunc must be used to cleanse other indirect
8138  * blocks.
8139  *
8140  * This handles partial and complete truncation of blocks.  Partial is noted
8141  * with goingaway == 0.  In this case the freework is completed after the
8142  * zero'd indirects are written to disk.  For full truncation the freework
8143  * is completed after the block is freed.
8144  */
8145 static void
8146 indir_trunc(freework, dbn, lbn)
8147 	struct freework *freework;
8148 	ufs2_daddr_t dbn;
8149 	ufs_lbn_t lbn;
8150 {
8151 	struct freework *nfreework;
8152 	struct workhead wkhd;
8153 	struct freeblks *freeblks;
8154 	struct buf *bp;
8155 	struct fs *fs;
8156 	struct indirdep *indirdep;
8157 	struct mount *mp;
8158 	struct ufsmount *ump;
8159 	ufs1_daddr_t *bap1;
8160 	ufs2_daddr_t nb, nnb, *bap2;
8161 	ufs_lbn_t lbnadd, nlbn;
8162 	u_long key;
8163 	int nblocks, ufs1fmt, freedblocks;
8164 	int goingaway, freedeps, needj, level, cnt, i;
8165 
8166 	freeblks = freework->fw_freeblks;
8167 	mp = freeblks->fb_list.wk_mp;
8168 	ump = VFSTOUFS(mp);
8169 	fs = ump->um_fs;
8170 	/*
8171 	 * Get buffer of block pointers to be freed.  There are three cases:
8172 	 *
8173 	 * 1) Partial truncate caches the indirdep pointer in the freework
8174 	 *    which provides us a back copy to the save bp which holds the
8175 	 *    pointers we want to clear.  When this completes the zero
8176 	 *    pointers are written to the real copy.
8177 	 * 2) The indirect is being completely truncated, cancel_indirdep()
8178 	 *    eliminated the real copy and placed the indirdep on the saved
8179 	 *    copy.  The indirdep and buf are discarded when this completes.
8180 	 * 3) The indirect was not in memory, we read a copy off of the disk
8181 	 *    using the devvp and drop and invalidate the buffer when we're
8182 	 *    done.
8183 	 */
8184 	goingaway = 1;
8185 	indirdep = NULL;
8186 	if (freework->fw_indir != NULL) {
8187 		goingaway = 0;
8188 		indirdep = freework->fw_indir;
8189 		bp = indirdep->ir_savebp;
8190 		if (bp == NULL || bp->b_blkno != dbn)
8191 			panic("indir_trunc: Bad saved buf %p blkno %jd",
8192 			    bp, (intmax_t)dbn);
8193 	} else if ((bp = incore(&freeblks->fb_devvp->v_bufobj, dbn)) != NULL) {
8194 		/*
8195 		 * The lock prevents the buf dep list from changing and
8196 	 	 * indirects on devvp should only ever have one dependency.
8197 		 */
8198 		indirdep = WK_INDIRDEP(LIST_FIRST(&bp->b_dep));
8199 		if (indirdep == NULL || (indirdep->ir_state & GOINGAWAY) == 0)
8200 			panic("indir_trunc: Bad indirdep %p from buf %p",
8201 			    indirdep, bp);
8202 	} else if (bread(freeblks->fb_devvp, dbn, (int)fs->fs_bsize,
8203 	    NOCRED, &bp) != 0) {
8204 		brelse(bp);
8205 		return;
8206 	}
8207 	ACQUIRE_LOCK(ump);
8208 	/* Protects against a race with complete_trunc_indir(). */
8209 	freework->fw_state &= ~INPROGRESS;
8210 	/*
8211 	 * If we have an indirdep we need to enforce the truncation order
8212 	 * and discard it when it is complete.
8213 	 */
8214 	if (indirdep) {
8215 		if (freework != TAILQ_FIRST(&indirdep->ir_trunc) &&
8216 		    !TAILQ_EMPTY(&indirdep->ir_trunc)) {
8217 			/*
8218 			 * Add the complete truncate to the list on the
8219 			 * indirdep to enforce in-order processing.
8220 			 */
8221 			if (freework->fw_indir == NULL)
8222 				TAILQ_INSERT_TAIL(&indirdep->ir_trunc,
8223 				    freework, fw_next);
8224 			FREE_LOCK(ump);
8225 			return;
8226 		}
8227 		/*
8228 		 * If we're goingaway, free the indirdep.  Otherwise it will
8229 		 * linger until the write completes.
8230 		 */
8231 		if (goingaway) {
8232 			KASSERT(indirdep->ir_savebp == bp,
8233 			    ("indir_trunc: losing ir_savebp %p",
8234 			    indirdep->ir_savebp));
8235 			indirdep->ir_savebp = NULL;
8236 			free_indirdep(indirdep);
8237 		}
8238 	}
8239 	FREE_LOCK(ump);
8240 	/* Initialize pointers depending on block size. */
8241 	if (ump->um_fstype == UFS1) {
8242 		bap1 = (ufs1_daddr_t *)bp->b_data;
8243 		nb = bap1[freework->fw_off];
8244 		ufs1fmt = 1;
8245 		bap2 = NULL;
8246 	} else {
8247 		bap2 = (ufs2_daddr_t *)bp->b_data;
8248 		nb = bap2[freework->fw_off];
8249 		ufs1fmt = 0;
8250 		bap1 = NULL;
8251 	}
8252 	level = lbn_level(lbn);
8253 	needj = MOUNTEDSUJ(UFSTOVFS(ump)) != 0;
8254 	lbnadd = lbn_offset(fs, level);
8255 	nblocks = btodb(fs->fs_bsize);
8256 	nfreework = freework;
8257 	freedeps = 0;
8258 	cnt = 0;
8259 	/*
8260 	 * Reclaim blocks.  Traverses into nested indirect levels and
8261 	 * arranges for the current level to be freed when subordinates
8262 	 * are free when journaling.
8263 	 */
8264 	key = ffs_blkrelease_start(ump, freeblks->fb_devvp, freeblks->fb_inum);
8265 	for (i = freework->fw_off; i < NINDIR(fs); i++, nb = nnb) {
8266 		if (UFS_CHECK_BLKNO(mp, freeblks->fb_inum, nb,
8267 		    fs->fs_bsize) != 0)
8268 			nb = 0;
8269 		if (i != NINDIR(fs) - 1) {
8270 			if (ufs1fmt)
8271 				nnb = bap1[i+1];
8272 			else
8273 				nnb = bap2[i+1];
8274 		} else
8275 			nnb = 0;
8276 		if (nb == 0)
8277 			continue;
8278 		cnt++;
8279 		if (level != 0) {
8280 			nlbn = (lbn + 1) - (i * lbnadd);
8281 			if (needj != 0) {
8282 				nfreework = newfreework(ump, freeblks, freework,
8283 				    nlbn, nb, fs->fs_frag, 0, 0);
8284 				freedeps++;
8285 			}
8286 			indir_trunc(nfreework, fsbtodb(fs, nb), nlbn);
8287 		} else {
8288 			struct freedep *freedep;
8289 
8290 			/*
8291 			 * Attempt to aggregate freedep dependencies for
8292 			 * all blocks being released to the same CG.
8293 			 */
8294 			LIST_INIT(&wkhd);
8295 			if (needj != 0 &&
8296 			    (nnb == 0 || (dtog(fs, nb) != dtog(fs, nnb)))) {
8297 				freedep = newfreedep(freework);
8298 				WORKLIST_INSERT_UNLOCKED(&wkhd,
8299 				    &freedep->fd_list);
8300 				freedeps++;
8301 			}
8302 			CTR3(KTR_SUJ,
8303 			    "indir_trunc: ino %jd blkno %jd size %d",
8304 			    freeblks->fb_inum, nb, fs->fs_bsize);
8305 			ffs_blkfree(ump, fs, freeblks->fb_devvp, nb,
8306 			    fs->fs_bsize, freeblks->fb_inum,
8307 			    freeblks->fb_vtype, &wkhd, key);
8308 		}
8309 	}
8310 	ffs_blkrelease_finish(ump, key);
8311 	if (goingaway) {
8312 		bp->b_flags |= B_INVAL | B_NOCACHE;
8313 		brelse(bp);
8314 	}
8315 	freedblocks = 0;
8316 	if (level == 0)
8317 		freedblocks = (nblocks * cnt);
8318 	if (needj == 0)
8319 		freedblocks += nblocks;
8320 	freeblks_free(ump, freeblks, freedblocks);
8321 	/*
8322 	 * If we are journaling set up the ref counts and offset so this
8323 	 * indirect can be completed when its children are free.
8324 	 */
8325 	if (needj) {
8326 		ACQUIRE_LOCK(ump);
8327 		freework->fw_off = i;
8328 		freework->fw_ref += freedeps;
8329 		freework->fw_ref -= NINDIR(fs) + 1;
8330 		if (level == 0)
8331 			freeblks->fb_cgwait += freedeps;
8332 		if (freework->fw_ref == 0)
8333 			freework_freeblock(freework, SINGLETON_KEY);
8334 		FREE_LOCK(ump);
8335 		return;
8336 	}
8337 	/*
8338 	 * If we're not journaling we can free the indirect now.
8339 	 */
8340 	dbn = dbtofsb(fs, dbn);
8341 	CTR3(KTR_SUJ,
8342 	    "indir_trunc 2: ino %jd blkno %jd size %d",
8343 	    freeblks->fb_inum, dbn, fs->fs_bsize);
8344 	ffs_blkfree(ump, fs, freeblks->fb_devvp, dbn, fs->fs_bsize,
8345 	    freeblks->fb_inum, freeblks->fb_vtype, NULL, SINGLETON_KEY);
8346 	/* Non SUJ softdep does single-threaded truncations. */
8347 	if (freework->fw_blkno == dbn) {
8348 		freework->fw_state |= ALLCOMPLETE;
8349 		ACQUIRE_LOCK(ump);
8350 		handle_written_freework(freework);
8351 		FREE_LOCK(ump);
8352 	}
8353 	return;
8354 }
8355 
8356 /*
8357  * Cancel an allocindir when it is removed via truncation.  When bp is not
8358  * NULL the indirect never appeared on disk and is scheduled to be freed
8359  * independently of the indir so we can more easily track journal work.
8360  */
8361 static void
8362 cancel_allocindir(aip, bp, freeblks, trunc)
8363 	struct allocindir *aip;
8364 	struct buf *bp;
8365 	struct freeblks *freeblks;
8366 	int trunc;
8367 {
8368 	struct indirdep *indirdep;
8369 	struct freefrag *freefrag;
8370 	struct newblk *newblk;
8371 
8372 	newblk = (struct newblk *)aip;
8373 	LIST_REMOVE(aip, ai_next);
8374 	/*
8375 	 * We must eliminate the pointer in bp if it must be freed on its
8376 	 * own due to partial truncate or pending journal work.
8377 	 */
8378 	if (bp && (trunc || newblk->nb_jnewblk)) {
8379 		/*
8380 		 * Clear the pointer and mark the aip to be freed
8381 		 * directly if it never existed on disk.
8382 		 */
8383 		aip->ai_state |= DELAYEDFREE;
8384 		indirdep = aip->ai_indirdep;
8385 		if (indirdep->ir_state & UFS1FMT)
8386 			((ufs1_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8387 		else
8388 			((ufs2_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8389 	}
8390 	/*
8391 	 * When truncating the previous pointer will be freed via
8392 	 * savedbp.  Eliminate the freefrag which would dup free.
8393 	 */
8394 	if (trunc && (freefrag = newblk->nb_freefrag) != NULL) {
8395 		newblk->nb_freefrag = NULL;
8396 		if (freefrag->ff_jdep)
8397 			cancel_jfreefrag(
8398 			    WK_JFREEFRAG(freefrag->ff_jdep));
8399 		jwork_move(&freeblks->fb_jwork, &freefrag->ff_jwork);
8400 		WORKITEM_FREE(freefrag, D_FREEFRAG);
8401 	}
8402 	/*
8403 	 * If the journal hasn't been written the jnewblk must be passed
8404 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
8405 	 * this by leaving the journal dependency on the newblk to be freed
8406 	 * when a freework is created in handle_workitem_freeblocks().
8407 	 */
8408 	cancel_newblk(newblk, NULL, &freeblks->fb_jwork);
8409 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
8410 }
8411 
8412 /*
8413  * Create the mkdir dependencies for . and .. in a new directory.  Link them
8414  * in to a newdirblk so any subsequent additions are tracked properly.  The
8415  * caller is responsible for adding the mkdir1 dependency to the journal
8416  * and updating id_mkdiradd.  This function returns with the per-filesystem
8417  * lock held.
8418  */
8419 static struct mkdir *
8420 setup_newdir(dap, newinum, dinum, newdirbp, mkdirp)
8421 	struct diradd *dap;
8422 	ino_t newinum;
8423 	ino_t dinum;
8424 	struct buf *newdirbp;
8425 	struct mkdir **mkdirp;
8426 {
8427 	struct newblk *newblk;
8428 	struct pagedep *pagedep;
8429 	struct inodedep *inodedep;
8430 	struct newdirblk *newdirblk;
8431 	struct mkdir *mkdir1, *mkdir2;
8432 	struct worklist *wk;
8433 	struct jaddref *jaddref;
8434 	struct ufsmount *ump;
8435 	struct mount *mp;
8436 
8437 	mp = dap->da_list.wk_mp;
8438 	ump = VFSTOUFS(mp);
8439 	newdirblk = malloc(sizeof(struct newdirblk), M_NEWDIRBLK,
8440 	    M_SOFTDEP_FLAGS);
8441 	workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8442 	LIST_INIT(&newdirblk->db_mkdir);
8443 	mkdir1 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8444 	workitem_alloc(&mkdir1->md_list, D_MKDIR, mp);
8445 	mkdir1->md_state = ATTACHED | MKDIR_BODY;
8446 	mkdir1->md_diradd = dap;
8447 	mkdir1->md_jaddref = NULL;
8448 	mkdir2 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8449 	workitem_alloc(&mkdir2->md_list, D_MKDIR, mp);
8450 	mkdir2->md_state = ATTACHED | MKDIR_PARENT;
8451 	mkdir2->md_diradd = dap;
8452 	mkdir2->md_jaddref = NULL;
8453 	if (MOUNTEDSUJ(mp) == 0) {
8454 		mkdir1->md_state |= DEPCOMPLETE;
8455 		mkdir2->md_state |= DEPCOMPLETE;
8456 	}
8457 	/*
8458 	 * Dependency on "." and ".." being written to disk.
8459 	 */
8460 	mkdir1->md_buf = newdirbp;
8461 	ACQUIRE_LOCK(VFSTOUFS(mp));
8462 	LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir1, md_mkdirs);
8463 	/*
8464 	 * We must link the pagedep, allocdirect, and newdirblk for
8465 	 * the initial file page so the pointer to the new directory
8466 	 * is not written until the directory contents are live and
8467 	 * any subsequent additions are not marked live until the
8468 	 * block is reachable via the inode.
8469 	 */
8470 	if (pagedep_lookup(mp, newdirbp, newinum, 0, 0, &pagedep) == 0)
8471 		panic("setup_newdir: lost pagedep");
8472 	LIST_FOREACH(wk, &newdirbp->b_dep, wk_list)
8473 		if (wk->wk_type == D_ALLOCDIRECT)
8474 			break;
8475 	if (wk == NULL)
8476 		panic("setup_newdir: lost allocdirect");
8477 	if (pagedep->pd_state & NEWBLOCK)
8478 		panic("setup_newdir: NEWBLOCK already set");
8479 	newblk = WK_NEWBLK(wk);
8480 	pagedep->pd_state |= NEWBLOCK;
8481 	pagedep->pd_newdirblk = newdirblk;
8482 	newdirblk->db_pagedep = pagedep;
8483 	WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8484 	WORKLIST_INSERT(&newdirblk->db_mkdir, &mkdir1->md_list);
8485 	/*
8486 	 * Look up the inodedep for the parent directory so that we
8487 	 * can link mkdir2 into the pending dotdot jaddref or
8488 	 * the inode write if there is none.  If the inode is
8489 	 * ALLCOMPLETE and no jaddref is present all dependencies have
8490 	 * been satisfied and mkdir2 can be freed.
8491 	 */
8492 	inodedep_lookup(mp, dinum, 0, &inodedep);
8493 	if (MOUNTEDSUJ(mp)) {
8494 		if (inodedep == NULL)
8495 			panic("setup_newdir: Lost parent.");
8496 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8497 		    inoreflst);
8498 		KASSERT(jaddref != NULL && jaddref->ja_parent == newinum &&
8499 		    (jaddref->ja_state & MKDIR_PARENT),
8500 		    ("setup_newdir: bad dotdot jaddref %p", jaddref));
8501 		LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8502 		mkdir2->md_jaddref = jaddref;
8503 		jaddref->ja_mkdir = mkdir2;
8504 	} else if (inodedep == NULL ||
8505 	    (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
8506 		dap->da_state &= ~MKDIR_PARENT;
8507 		WORKITEM_FREE(mkdir2, D_MKDIR);
8508 		mkdir2 = NULL;
8509 	} else {
8510 		LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8511 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir2->md_list);
8512 	}
8513 	*mkdirp = mkdir2;
8514 
8515 	return (mkdir1);
8516 }
8517 
8518 /*
8519  * Directory entry addition dependencies.
8520  *
8521  * When adding a new directory entry, the inode (with its incremented link
8522  * count) must be written to disk before the directory entry's pointer to it.
8523  * Also, if the inode is newly allocated, the corresponding freemap must be
8524  * updated (on disk) before the directory entry's pointer. These requirements
8525  * are met via undo/redo on the directory entry's pointer, which consists
8526  * simply of the inode number.
8527  *
8528  * As directory entries are added and deleted, the free space within a
8529  * directory block can become fragmented.  The ufs filesystem will compact
8530  * a fragmented directory block to make space for a new entry. When this
8531  * occurs, the offsets of previously added entries change. Any "diradd"
8532  * dependency structures corresponding to these entries must be updated with
8533  * the new offsets.
8534  */
8535 
8536 /*
8537  * This routine is called after the in-memory inode's link
8538  * count has been incremented, but before the directory entry's
8539  * pointer to the inode has been set.
8540  */
8541 int
8542 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
8543 	struct buf *bp;		/* buffer containing directory block */
8544 	struct inode *dp;	/* inode for directory */
8545 	off_t diroffset;	/* offset of new entry in directory */
8546 	ino_t newinum;		/* inode referenced by new directory entry */
8547 	struct buf *newdirbp;	/* non-NULL => contents of new mkdir */
8548 	int isnewblk;		/* entry is in a newly allocated block */
8549 {
8550 	int offset;		/* offset of new entry within directory block */
8551 	ufs_lbn_t lbn;		/* block in directory containing new entry */
8552 	struct fs *fs;
8553 	struct diradd *dap;
8554 	struct newblk *newblk;
8555 	struct pagedep *pagedep;
8556 	struct inodedep *inodedep;
8557 	struct newdirblk *newdirblk;
8558 	struct mkdir *mkdir1, *mkdir2;
8559 	struct jaddref *jaddref;
8560 	struct ufsmount *ump;
8561 	struct mount *mp;
8562 	int isindir;
8563 
8564 	mp = ITOVFS(dp);
8565 	ump = VFSTOUFS(mp);
8566 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8567 	    ("softdep_setup_directory_add called on non-softdep filesystem"));
8568 	/*
8569 	 * Whiteouts have no dependencies.
8570 	 */
8571 	if (newinum == UFS_WINO) {
8572 		if (newdirbp != NULL)
8573 			bdwrite(newdirbp);
8574 		return (0);
8575 	}
8576 	jaddref = NULL;
8577 	mkdir1 = mkdir2 = NULL;
8578 	fs = ump->um_fs;
8579 	lbn = lblkno(fs, diroffset);
8580 	offset = blkoff(fs, diroffset);
8581 	dap = malloc(sizeof(struct diradd), M_DIRADD,
8582 		M_SOFTDEP_FLAGS|M_ZERO);
8583 	workitem_alloc(&dap->da_list, D_DIRADD, mp);
8584 	dap->da_offset = offset;
8585 	dap->da_newinum = newinum;
8586 	dap->da_state = ATTACHED;
8587 	LIST_INIT(&dap->da_jwork);
8588 	isindir = bp->b_lblkno >= UFS_NDADDR;
8589 	newdirblk = NULL;
8590 	if (isnewblk &&
8591 	    (isindir ? blkoff(fs, diroffset) : fragoff(fs, diroffset)) == 0) {
8592 		newdirblk = malloc(sizeof(struct newdirblk),
8593 		    M_NEWDIRBLK, M_SOFTDEP_FLAGS);
8594 		workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8595 		LIST_INIT(&newdirblk->db_mkdir);
8596 	}
8597 	/*
8598 	 * If we're creating a new directory setup the dependencies and set
8599 	 * the dap state to wait for them.  Otherwise it's COMPLETE and
8600 	 * we can move on.
8601 	 */
8602 	if (newdirbp == NULL) {
8603 		dap->da_state |= DEPCOMPLETE;
8604 		ACQUIRE_LOCK(ump);
8605 	} else {
8606 		dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
8607 		mkdir1 = setup_newdir(dap, newinum, dp->i_number, newdirbp,
8608 		    &mkdir2);
8609 	}
8610 	/*
8611 	 * Link into parent directory pagedep to await its being written.
8612 	 */
8613 	pagedep_lookup(mp, bp, dp->i_number, lbn, DEPALLOC, &pagedep);
8614 #ifdef INVARIANTS
8615 	if (diradd_lookup(pagedep, offset) != NULL)
8616 		panic("softdep_setup_directory_add: %p already at off %d\n",
8617 		    diradd_lookup(pagedep, offset), offset);
8618 #endif
8619 	dap->da_pagedep = pagedep;
8620 	LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
8621 	    da_pdlist);
8622 	inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
8623 	/*
8624 	 * If we're journaling, link the diradd into the jaddref so it
8625 	 * may be completed after the journal entry is written.  Otherwise,
8626 	 * link the diradd into its inodedep.  If the inode is not yet
8627 	 * written place it on the bufwait list, otherwise do the post-inode
8628 	 * write processing to put it on the id_pendinghd list.
8629 	 */
8630 	if (MOUNTEDSUJ(mp)) {
8631 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8632 		    inoreflst);
8633 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
8634 		    ("softdep_setup_directory_add: bad jaddref %p", jaddref));
8635 		jaddref->ja_diroff = diroffset;
8636 		jaddref->ja_diradd = dap;
8637 		add_to_journal(&jaddref->ja_list);
8638 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
8639 		diradd_inode_written(dap, inodedep);
8640 	else
8641 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
8642 	/*
8643 	 * Add the journal entries for . and .. links now that the primary
8644 	 * link is written.
8645 	 */
8646 	if (mkdir1 != NULL && MOUNTEDSUJ(mp)) {
8647 		jaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
8648 		    inoreflst, if_deps);
8649 		KASSERT(jaddref != NULL &&
8650 		    jaddref->ja_ino == jaddref->ja_parent &&
8651 		    (jaddref->ja_state & MKDIR_BODY),
8652 		    ("softdep_setup_directory_add: bad dot jaddref %p",
8653 		    jaddref));
8654 		mkdir1->md_jaddref = jaddref;
8655 		jaddref->ja_mkdir = mkdir1;
8656 		/*
8657 		 * It is important that the dotdot journal entry
8658 		 * is added prior to the dot entry since dot writes
8659 		 * both the dot and dotdot links.  These both must
8660 		 * be added after the primary link for the journal
8661 		 * to remain consistent.
8662 		 */
8663 		add_to_journal(&mkdir2->md_jaddref->ja_list);
8664 		add_to_journal(&jaddref->ja_list);
8665 	}
8666 	/*
8667 	 * If we are adding a new directory remember this diradd so that if
8668 	 * we rename it we can keep the dot and dotdot dependencies.  If
8669 	 * we are adding a new name for an inode that has a mkdiradd we
8670 	 * must be in rename and we have to move the dot and dotdot
8671 	 * dependencies to this new name.  The old name is being orphaned
8672 	 * soon.
8673 	 */
8674 	if (mkdir1 != NULL) {
8675 		if (inodedep->id_mkdiradd != NULL)
8676 			panic("softdep_setup_directory_add: Existing mkdir");
8677 		inodedep->id_mkdiradd = dap;
8678 	} else if (inodedep->id_mkdiradd)
8679 		merge_diradd(inodedep, dap);
8680 	if (newdirblk != NULL) {
8681 		/*
8682 		 * There is nothing to do if we are already tracking
8683 		 * this block.
8684 		 */
8685 		if ((pagedep->pd_state & NEWBLOCK) != 0) {
8686 			WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
8687 			FREE_LOCK(ump);
8688 			return (0);
8689 		}
8690 		if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk)
8691 		    == 0)
8692 			panic("softdep_setup_directory_add: lost entry");
8693 		WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8694 		pagedep->pd_state |= NEWBLOCK;
8695 		pagedep->pd_newdirblk = newdirblk;
8696 		newdirblk->db_pagedep = pagedep;
8697 		FREE_LOCK(ump);
8698 		/*
8699 		 * If we extended into an indirect signal direnter to sync.
8700 		 */
8701 		if (isindir)
8702 			return (1);
8703 		return (0);
8704 	}
8705 	FREE_LOCK(ump);
8706 	return (0);
8707 }
8708 
8709 /*
8710  * This procedure is called to change the offset of a directory
8711  * entry when compacting a directory block which must be owned
8712  * exclusively by the caller. Note that the actual entry movement
8713  * must be done in this procedure to ensure that no I/O completions
8714  * occur while the move is in progress.
8715  */
8716 void
8717 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
8718 	struct buf *bp;		/* Buffer holding directory block. */
8719 	struct inode *dp;	/* inode for directory */
8720 	caddr_t base;		/* address of dp->i_offset */
8721 	caddr_t oldloc;		/* address of old directory location */
8722 	caddr_t newloc;		/* address of new directory location */
8723 	int entrysize;		/* size of directory entry */
8724 {
8725 	int offset, oldoffset, newoffset;
8726 	struct pagedep *pagedep;
8727 	struct jmvref *jmvref;
8728 	struct diradd *dap;
8729 	struct direct *de;
8730 	struct mount *mp;
8731 	struct ufsmount *ump;
8732 	ufs_lbn_t lbn;
8733 	int flags;
8734 
8735 	mp = ITOVFS(dp);
8736 	ump = VFSTOUFS(mp);
8737 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8738 	    ("softdep_change_directoryentry_offset called on "
8739 	     "non-softdep filesystem"));
8740 	de = (struct direct *)oldloc;
8741 	jmvref = NULL;
8742 	flags = 0;
8743 	/*
8744 	 * Moves are always journaled as it would be too complex to
8745 	 * determine if any affected adds or removes are present in the
8746 	 * journal.
8747 	 */
8748 	if (MOUNTEDSUJ(mp)) {
8749 		flags = DEPALLOC;
8750 		jmvref = newjmvref(dp, de->d_ino,
8751 		    dp->i_offset + (oldloc - base),
8752 		    dp->i_offset + (newloc - base));
8753 	}
8754 	lbn = lblkno(ump->um_fs, dp->i_offset);
8755 	offset = blkoff(ump->um_fs, dp->i_offset);
8756 	oldoffset = offset + (oldloc - base);
8757 	newoffset = offset + (newloc - base);
8758 	ACQUIRE_LOCK(ump);
8759 	if (pagedep_lookup(mp, bp, dp->i_number, lbn, flags, &pagedep) == 0)
8760 		goto done;
8761 	dap = diradd_lookup(pagedep, oldoffset);
8762 	if (dap) {
8763 		dap->da_offset = newoffset;
8764 		newoffset = DIRADDHASH(newoffset);
8765 		oldoffset = DIRADDHASH(oldoffset);
8766 		if ((dap->da_state & ALLCOMPLETE) != ALLCOMPLETE &&
8767 		    newoffset != oldoffset) {
8768 			LIST_REMOVE(dap, da_pdlist);
8769 			LIST_INSERT_HEAD(&pagedep->pd_diraddhd[newoffset],
8770 			    dap, da_pdlist);
8771 		}
8772 	}
8773 done:
8774 	if (jmvref) {
8775 		jmvref->jm_pagedep = pagedep;
8776 		LIST_INSERT_HEAD(&pagedep->pd_jmvrefhd, jmvref, jm_deps);
8777 		add_to_journal(&jmvref->jm_list);
8778 	}
8779 	bcopy(oldloc, newloc, entrysize);
8780 	FREE_LOCK(ump);
8781 }
8782 
8783 /*
8784  * Move the mkdir dependencies and journal work from one diradd to another
8785  * when renaming a directory.  The new name must depend on the mkdir deps
8786  * completing as the old name did.  Directories can only have one valid link
8787  * at a time so one must be canonical.
8788  */
8789 static void
8790 merge_diradd(inodedep, newdap)
8791 	struct inodedep *inodedep;
8792 	struct diradd *newdap;
8793 {
8794 	struct diradd *olddap;
8795 	struct mkdir *mkdir, *nextmd;
8796 	struct ufsmount *ump;
8797 	short state;
8798 
8799 	olddap = inodedep->id_mkdiradd;
8800 	inodedep->id_mkdiradd = newdap;
8801 	if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8802 		newdap->da_state &= ~DEPCOMPLETE;
8803 		ump = VFSTOUFS(inodedep->id_list.wk_mp);
8804 		for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
8805 		     mkdir = nextmd) {
8806 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
8807 			if (mkdir->md_diradd != olddap)
8808 				continue;
8809 			mkdir->md_diradd = newdap;
8810 			state = mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY);
8811 			newdap->da_state |= state;
8812 			olddap->da_state &= ~state;
8813 			if ((olddap->da_state &
8814 			    (MKDIR_PARENT | MKDIR_BODY)) == 0)
8815 				break;
8816 		}
8817 		if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8818 			panic("merge_diradd: unfound ref");
8819 	}
8820 	/*
8821 	 * Any mkdir related journal items are not safe to be freed until
8822 	 * the new name is stable.
8823 	 */
8824 	jwork_move(&newdap->da_jwork, &olddap->da_jwork);
8825 	olddap->da_state |= DEPCOMPLETE;
8826 	complete_diradd(olddap);
8827 }
8828 
8829 /*
8830  * Move the diradd to the pending list when all diradd dependencies are
8831  * complete.
8832  */
8833 static void
8834 complete_diradd(dap)
8835 	struct diradd *dap;
8836 {
8837 	struct pagedep *pagedep;
8838 
8839 	if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
8840 		if (dap->da_state & DIRCHG)
8841 			pagedep = dap->da_previous->dm_pagedep;
8842 		else
8843 			pagedep = dap->da_pagedep;
8844 		LIST_REMOVE(dap, da_pdlist);
8845 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
8846 	}
8847 }
8848 
8849 /*
8850  * Cancel a diradd when a dirrem overlaps with it.  We must cancel the journal
8851  * add entries and conditonally journal the remove.
8852  */
8853 static void
8854 cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref)
8855 	struct diradd *dap;
8856 	struct dirrem *dirrem;
8857 	struct jremref *jremref;
8858 	struct jremref *dotremref;
8859 	struct jremref *dotdotremref;
8860 {
8861 	struct inodedep *inodedep;
8862 	struct jaddref *jaddref;
8863 	struct inoref *inoref;
8864 	struct ufsmount *ump;
8865 	struct mkdir *mkdir;
8866 
8867 	/*
8868 	 * If no remove references were allocated we're on a non-journaled
8869 	 * filesystem and can skip the cancel step.
8870 	 */
8871 	if (jremref == NULL) {
8872 		free_diradd(dap, NULL);
8873 		return;
8874 	}
8875 	/*
8876 	 * Cancel the primary name an free it if it does not require
8877 	 * journaling.
8878 	 */
8879 	if (inodedep_lookup(dap->da_list.wk_mp, dap->da_newinum,
8880 	    0, &inodedep) != 0) {
8881 		/* Abort the addref that reference this diradd.  */
8882 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
8883 			if (inoref->if_list.wk_type != D_JADDREF)
8884 				continue;
8885 			jaddref = (struct jaddref *)inoref;
8886 			if (jaddref->ja_diradd != dap)
8887 				continue;
8888 			if (cancel_jaddref(jaddref, inodedep,
8889 			    &dirrem->dm_jwork) == 0) {
8890 				free_jremref(jremref);
8891 				jremref = NULL;
8892 			}
8893 			break;
8894 		}
8895 	}
8896 	/*
8897 	 * Cancel subordinate names and free them if they do not require
8898 	 * journaling.
8899 	 */
8900 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8901 		ump = VFSTOUFS(dap->da_list.wk_mp);
8902 		LIST_FOREACH(mkdir, &ump->softdep_mkdirlisthd, md_mkdirs) {
8903 			if (mkdir->md_diradd != dap)
8904 				continue;
8905 			if ((jaddref = mkdir->md_jaddref) == NULL)
8906 				continue;
8907 			mkdir->md_jaddref = NULL;
8908 			if (mkdir->md_state & MKDIR_PARENT) {
8909 				if (cancel_jaddref(jaddref, NULL,
8910 				    &dirrem->dm_jwork) == 0) {
8911 					free_jremref(dotdotremref);
8912 					dotdotremref = NULL;
8913 				}
8914 			} else {
8915 				if (cancel_jaddref(jaddref, inodedep,
8916 				    &dirrem->dm_jwork) == 0) {
8917 					free_jremref(dotremref);
8918 					dotremref = NULL;
8919 				}
8920 			}
8921 		}
8922 	}
8923 
8924 	if (jremref)
8925 		journal_jremref(dirrem, jremref, inodedep);
8926 	if (dotremref)
8927 		journal_jremref(dirrem, dotremref, inodedep);
8928 	if (dotdotremref)
8929 		journal_jremref(dirrem, dotdotremref, NULL);
8930 	jwork_move(&dirrem->dm_jwork, &dap->da_jwork);
8931 	free_diradd(dap, &dirrem->dm_jwork);
8932 }
8933 
8934 /*
8935  * Free a diradd dependency structure.
8936  */
8937 static void
8938 free_diradd(dap, wkhd)
8939 	struct diradd *dap;
8940 	struct workhead *wkhd;
8941 {
8942 	struct dirrem *dirrem;
8943 	struct pagedep *pagedep;
8944 	struct inodedep *inodedep;
8945 	struct mkdir *mkdir, *nextmd;
8946 	struct ufsmount *ump;
8947 
8948 	ump = VFSTOUFS(dap->da_list.wk_mp);
8949 	LOCK_OWNED(ump);
8950 	LIST_REMOVE(dap, da_pdlist);
8951 	if (dap->da_state & ONWORKLIST)
8952 		WORKLIST_REMOVE(&dap->da_list);
8953 	if ((dap->da_state & DIRCHG) == 0) {
8954 		pagedep = dap->da_pagedep;
8955 	} else {
8956 		dirrem = dap->da_previous;
8957 		pagedep = dirrem->dm_pagedep;
8958 		dirrem->dm_dirinum = pagedep->pd_ino;
8959 		dirrem->dm_state |= COMPLETE;
8960 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
8961 			add_to_worklist(&dirrem->dm_list, 0);
8962 	}
8963 	if (inodedep_lookup(pagedep->pd_list.wk_mp, dap->da_newinum,
8964 	    0, &inodedep) != 0)
8965 		if (inodedep->id_mkdiradd == dap)
8966 			inodedep->id_mkdiradd = NULL;
8967 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8968 		for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
8969 		     mkdir = nextmd) {
8970 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
8971 			if (mkdir->md_diradd != dap)
8972 				continue;
8973 			dap->da_state &=
8974 			    ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
8975 			LIST_REMOVE(mkdir, md_mkdirs);
8976 			if (mkdir->md_state & ONWORKLIST)
8977 				WORKLIST_REMOVE(&mkdir->md_list);
8978 			if (mkdir->md_jaddref != NULL)
8979 				panic("free_diradd: Unexpected jaddref");
8980 			WORKITEM_FREE(mkdir, D_MKDIR);
8981 			if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
8982 				break;
8983 		}
8984 		if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8985 			panic("free_diradd: unfound ref");
8986 	}
8987 	if (inodedep)
8988 		free_inodedep(inodedep);
8989 	/*
8990 	 * Free any journal segments waiting for the directory write.
8991 	 */
8992 	handle_jwork(&dap->da_jwork);
8993 	WORKITEM_FREE(dap, D_DIRADD);
8994 }
8995 
8996 /*
8997  * Directory entry removal dependencies.
8998  *
8999  * When removing a directory entry, the entry's inode pointer must be
9000  * zero'ed on disk before the corresponding inode's link count is decremented
9001  * (possibly freeing the inode for re-use). This dependency is handled by
9002  * updating the directory entry but delaying the inode count reduction until
9003  * after the directory block has been written to disk. After this point, the
9004  * inode count can be decremented whenever it is convenient.
9005  */
9006 
9007 /*
9008  * This routine should be called immediately after removing
9009  * a directory entry.  The inode's link count should not be
9010  * decremented by the calling procedure -- the soft updates
9011  * code will do this task when it is safe.
9012  */
9013 void
9014 softdep_setup_remove(bp, dp, ip, isrmdir)
9015 	struct buf *bp;		/* buffer containing directory block */
9016 	struct inode *dp;	/* inode for the directory being modified */
9017 	struct inode *ip;	/* inode for directory entry being removed */
9018 	int isrmdir;		/* indicates if doing RMDIR */
9019 {
9020 	struct dirrem *dirrem, *prevdirrem;
9021 	struct inodedep *inodedep;
9022 	struct ufsmount *ump;
9023 	int direct;
9024 
9025 	ump = ITOUMP(ip);
9026 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9027 	    ("softdep_setup_remove called on non-softdep filesystem"));
9028 	/*
9029 	 * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.  We want
9030 	 * newdirrem() to setup the full directory remove which requires
9031 	 * isrmdir > 1.
9032 	 */
9033 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9034 	/*
9035 	 * Add the dirrem to the inodedep's pending remove list for quick
9036 	 * discovery later.
9037 	 */
9038 	if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0)
9039 		panic("softdep_setup_remove: Lost inodedep.");
9040 	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
9041 	dirrem->dm_state |= ONDEPLIST;
9042 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9043 
9044 	/*
9045 	 * If the COMPLETE flag is clear, then there were no active
9046 	 * entries and we want to roll back to a zeroed entry until
9047 	 * the new inode is committed to disk. If the COMPLETE flag is
9048 	 * set then we have deleted an entry that never made it to
9049 	 * disk. If the entry we deleted resulted from a name change,
9050 	 * then the old name still resides on disk. We cannot delete
9051 	 * its inode (returned to us in prevdirrem) until the zeroed
9052 	 * directory entry gets to disk. The new inode has never been
9053 	 * referenced on the disk, so can be deleted immediately.
9054 	 */
9055 	if ((dirrem->dm_state & COMPLETE) == 0) {
9056 		LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
9057 		    dm_next);
9058 		FREE_LOCK(ump);
9059 	} else {
9060 		if (prevdirrem != NULL)
9061 			LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
9062 			    prevdirrem, dm_next);
9063 		dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
9064 		direct = LIST_EMPTY(&dirrem->dm_jremrefhd);
9065 		FREE_LOCK(ump);
9066 		if (direct)
9067 			handle_workitem_remove(dirrem, 0);
9068 	}
9069 }
9070 
9071 /*
9072  * Check for an entry matching 'offset' on both the pd_dirraddhd list and the
9073  * pd_pendinghd list of a pagedep.
9074  */
9075 static struct diradd *
9076 diradd_lookup(pagedep, offset)
9077 	struct pagedep *pagedep;
9078 	int offset;
9079 {
9080 	struct diradd *dap;
9081 
9082 	LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
9083 		if (dap->da_offset == offset)
9084 			return (dap);
9085 	LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
9086 		if (dap->da_offset == offset)
9087 			return (dap);
9088 	return (NULL);
9089 }
9090 
9091 /*
9092  * Search for a .. diradd dependency in a directory that is being removed.
9093  * If the directory was renamed to a new parent we have a diradd rather
9094  * than a mkdir for the .. entry.  We need to cancel it now before
9095  * it is found in truncate().
9096  */
9097 static struct jremref *
9098 cancel_diradd_dotdot(ip, dirrem, jremref)
9099 	struct inode *ip;
9100 	struct dirrem *dirrem;
9101 	struct jremref *jremref;
9102 {
9103 	struct pagedep *pagedep;
9104 	struct diradd *dap;
9105 	struct worklist *wk;
9106 
9107 	if (pagedep_lookup(ITOVFS(ip), NULL, ip->i_number, 0, 0, &pagedep) == 0)
9108 		return (jremref);
9109 	dap = diradd_lookup(pagedep, DOTDOT_OFFSET);
9110 	if (dap == NULL)
9111 		return (jremref);
9112 	cancel_diradd(dap, dirrem, jremref, NULL, NULL);
9113 	/*
9114 	 * Mark any journal work as belonging to the parent so it is freed
9115 	 * with the .. reference.
9116 	 */
9117 	LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9118 		wk->wk_state |= MKDIR_PARENT;
9119 	return (NULL);
9120 }
9121 
9122 /*
9123  * Cancel the MKDIR_PARENT mkdir component of a diradd when we're going to
9124  * replace it with a dirrem/diradd pair as a result of re-parenting a
9125  * directory.  This ensures that we don't simultaneously have a mkdir and
9126  * a diradd for the same .. entry.
9127  */
9128 static struct jremref *
9129 cancel_mkdir_dotdot(ip, dirrem, jremref)
9130 	struct inode *ip;
9131 	struct dirrem *dirrem;
9132 	struct jremref *jremref;
9133 {
9134 	struct inodedep *inodedep;
9135 	struct jaddref *jaddref;
9136 	struct ufsmount *ump;
9137 	struct mkdir *mkdir;
9138 	struct diradd *dap;
9139 	struct mount *mp;
9140 
9141 	mp = ITOVFS(ip);
9142 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9143 		return (jremref);
9144 	dap = inodedep->id_mkdiradd;
9145 	if (dap == NULL || (dap->da_state & MKDIR_PARENT) == 0)
9146 		return (jremref);
9147 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
9148 	for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
9149 	    mkdir = LIST_NEXT(mkdir, md_mkdirs))
9150 		if (mkdir->md_diradd == dap && mkdir->md_state & MKDIR_PARENT)
9151 			break;
9152 	if (mkdir == NULL)
9153 		panic("cancel_mkdir_dotdot: Unable to find mkdir\n");
9154 	if ((jaddref = mkdir->md_jaddref) != NULL) {
9155 		mkdir->md_jaddref = NULL;
9156 		jaddref->ja_state &= ~MKDIR_PARENT;
9157 		if (inodedep_lookup(mp, jaddref->ja_ino, 0, &inodedep) == 0)
9158 			panic("cancel_mkdir_dotdot: Lost parent inodedep");
9159 		if (cancel_jaddref(jaddref, inodedep, &dirrem->dm_jwork)) {
9160 			journal_jremref(dirrem, jremref, inodedep);
9161 			jremref = NULL;
9162 		}
9163 	}
9164 	if (mkdir->md_state & ONWORKLIST)
9165 		WORKLIST_REMOVE(&mkdir->md_list);
9166 	mkdir->md_state |= ALLCOMPLETE;
9167 	complete_mkdir(mkdir);
9168 	return (jremref);
9169 }
9170 
9171 static void
9172 journal_jremref(dirrem, jremref, inodedep)
9173 	struct dirrem *dirrem;
9174 	struct jremref *jremref;
9175 	struct inodedep *inodedep;
9176 {
9177 
9178 	if (inodedep == NULL)
9179 		if (inodedep_lookup(jremref->jr_list.wk_mp,
9180 		    jremref->jr_ref.if_ino, 0, &inodedep) == 0)
9181 			panic("journal_jremref: Lost inodedep");
9182 	LIST_INSERT_HEAD(&dirrem->dm_jremrefhd, jremref, jr_deps);
9183 	TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
9184 	add_to_journal(&jremref->jr_list);
9185 }
9186 
9187 static void
9188 dirrem_journal(dirrem, jremref, dotremref, dotdotremref)
9189 	struct dirrem *dirrem;
9190 	struct jremref *jremref;
9191 	struct jremref *dotremref;
9192 	struct jremref *dotdotremref;
9193 {
9194 	struct inodedep *inodedep;
9195 
9196 
9197 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino, 0,
9198 	    &inodedep) == 0)
9199 		panic("dirrem_journal: Lost inodedep");
9200 	journal_jremref(dirrem, jremref, inodedep);
9201 	if (dotremref)
9202 		journal_jremref(dirrem, dotremref, inodedep);
9203 	if (dotdotremref)
9204 		journal_jremref(dirrem, dotdotremref, NULL);
9205 }
9206 
9207 /*
9208  * Allocate a new dirrem if appropriate and return it along with
9209  * its associated pagedep. Called without a lock, returns with lock.
9210  */
9211 static struct dirrem *
9212 newdirrem(bp, dp, ip, isrmdir, prevdirremp)
9213 	struct buf *bp;		/* buffer containing directory block */
9214 	struct inode *dp;	/* inode for the directory being modified */
9215 	struct inode *ip;	/* inode for directory entry being removed */
9216 	int isrmdir;		/* indicates if doing RMDIR */
9217 	struct dirrem **prevdirremp; /* previously referenced inode, if any */
9218 {
9219 	int offset;
9220 	ufs_lbn_t lbn;
9221 	struct diradd *dap;
9222 	struct dirrem *dirrem;
9223 	struct pagedep *pagedep;
9224 	struct jremref *jremref;
9225 	struct jremref *dotremref;
9226 	struct jremref *dotdotremref;
9227 	struct vnode *dvp;
9228 	struct ufsmount *ump;
9229 
9230 	/*
9231 	 * Whiteouts have no deletion dependencies.
9232 	 */
9233 	if (ip == NULL)
9234 		panic("newdirrem: whiteout");
9235 	dvp = ITOV(dp);
9236 	ump = ITOUMP(dp);
9237 
9238 	/*
9239 	 * If the system is over its limit and our filesystem is
9240 	 * responsible for more than our share of that usage and
9241 	 * we are not a snapshot, request some inodedep cleanup.
9242 	 * Limiting the number of dirrem structures will also limit
9243 	 * the number of freefile and freeblks structures.
9244 	 */
9245 	ACQUIRE_LOCK(ump);
9246 	if (!IS_SNAPSHOT(ip) && softdep_excess_items(ump, D_DIRREM))
9247 		schedule_cleanup(UFSTOVFS(ump));
9248 	else
9249 		FREE_LOCK(ump);
9250 	dirrem = malloc(sizeof(struct dirrem), M_DIRREM, M_SOFTDEP_FLAGS |
9251 	    M_ZERO);
9252 	workitem_alloc(&dirrem->dm_list, D_DIRREM, dvp->v_mount);
9253 	LIST_INIT(&dirrem->dm_jremrefhd);
9254 	LIST_INIT(&dirrem->dm_jwork);
9255 	dirrem->dm_state = isrmdir ? RMDIR : 0;
9256 	dirrem->dm_oldinum = ip->i_number;
9257 	*prevdirremp = NULL;
9258 	/*
9259 	 * Allocate remove reference structures to track journal write
9260 	 * dependencies.  We will always have one for the link and
9261 	 * when doing directories we will always have one more for dot.
9262 	 * When renaming a directory we skip the dotdot link change so
9263 	 * this is not needed.
9264 	 */
9265 	jremref = dotremref = dotdotremref = NULL;
9266 	if (DOINGSUJ(dvp)) {
9267 		if (isrmdir) {
9268 			jremref = newjremref(dirrem, dp, ip, dp->i_offset,
9269 			    ip->i_effnlink + 2);
9270 			dotremref = newjremref(dirrem, ip, ip, DOT_OFFSET,
9271 			    ip->i_effnlink + 1);
9272 			dotdotremref = newjremref(dirrem, ip, dp, DOTDOT_OFFSET,
9273 			    dp->i_effnlink + 1);
9274 			dotdotremref->jr_state |= MKDIR_PARENT;
9275 		} else
9276 			jremref = newjremref(dirrem, dp, ip, dp->i_offset,
9277 			    ip->i_effnlink + 1);
9278 	}
9279 	ACQUIRE_LOCK(ump);
9280 	lbn = lblkno(ump->um_fs, dp->i_offset);
9281 	offset = blkoff(ump->um_fs, dp->i_offset);
9282 	pagedep_lookup(UFSTOVFS(ump), bp, dp->i_number, lbn, DEPALLOC,
9283 	    &pagedep);
9284 	dirrem->dm_pagedep = pagedep;
9285 	dirrem->dm_offset = offset;
9286 	/*
9287 	 * If we're renaming a .. link to a new directory, cancel any
9288 	 * existing MKDIR_PARENT mkdir.  If it has already been canceled
9289 	 * the jremref is preserved for any potential diradd in this
9290 	 * location.  This can not coincide with a rmdir.
9291 	 */
9292 	if (dp->i_offset == DOTDOT_OFFSET) {
9293 		if (isrmdir)
9294 			panic("newdirrem: .. directory change during remove?");
9295 		jremref = cancel_mkdir_dotdot(dp, dirrem, jremref);
9296 	}
9297 	/*
9298 	 * If we're removing a directory search for the .. dependency now and
9299 	 * cancel it.  Any pending journal work will be added to the dirrem
9300 	 * to be completed when the workitem remove completes.
9301 	 */
9302 	if (isrmdir)
9303 		dotdotremref = cancel_diradd_dotdot(ip, dirrem, dotdotremref);
9304 	/*
9305 	 * Check for a diradd dependency for the same directory entry.
9306 	 * If present, then both dependencies become obsolete and can
9307 	 * be de-allocated.
9308 	 */
9309 	dap = diradd_lookup(pagedep, offset);
9310 	if (dap == NULL) {
9311 		/*
9312 		 * Link the jremref structures into the dirrem so they are
9313 		 * written prior to the pagedep.
9314 		 */
9315 		if (jremref)
9316 			dirrem_journal(dirrem, jremref, dotremref,
9317 			    dotdotremref);
9318 		return (dirrem);
9319 	}
9320 	/*
9321 	 * Must be ATTACHED at this point.
9322 	 */
9323 	if ((dap->da_state & ATTACHED) == 0)
9324 		panic("newdirrem: not ATTACHED");
9325 	if (dap->da_newinum != ip->i_number)
9326 		panic("newdirrem: inum %ju should be %ju",
9327 		    (uintmax_t)ip->i_number, (uintmax_t)dap->da_newinum);
9328 	/*
9329 	 * If we are deleting a changed name that never made it to disk,
9330 	 * then return the dirrem describing the previous inode (which
9331 	 * represents the inode currently referenced from this entry on disk).
9332 	 */
9333 	if ((dap->da_state & DIRCHG) != 0) {
9334 		*prevdirremp = dap->da_previous;
9335 		dap->da_state &= ~DIRCHG;
9336 		dap->da_pagedep = pagedep;
9337 	}
9338 	/*
9339 	 * We are deleting an entry that never made it to disk.
9340 	 * Mark it COMPLETE so we can delete its inode immediately.
9341 	 */
9342 	dirrem->dm_state |= COMPLETE;
9343 	cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref);
9344 #ifdef INVARIANTS
9345 	if (isrmdir == 0) {
9346 		struct worklist *wk;
9347 
9348 		LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9349 			if (wk->wk_state & (MKDIR_BODY | MKDIR_PARENT))
9350 				panic("bad wk %p (0x%X)\n", wk, wk->wk_state);
9351 	}
9352 #endif
9353 
9354 	return (dirrem);
9355 }
9356 
9357 /*
9358  * Directory entry change dependencies.
9359  *
9360  * Changing an existing directory entry requires that an add operation
9361  * be completed first followed by a deletion. The semantics for the addition
9362  * are identical to the description of adding a new entry above except
9363  * that the rollback is to the old inode number rather than zero. Once
9364  * the addition dependency is completed, the removal is done as described
9365  * in the removal routine above.
9366  */
9367 
9368 /*
9369  * This routine should be called immediately after changing
9370  * a directory entry.  The inode's link count should not be
9371  * decremented by the calling procedure -- the soft updates
9372  * code will perform this task when it is safe.
9373  */
9374 void
9375 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
9376 	struct buf *bp;		/* buffer containing directory block */
9377 	struct inode *dp;	/* inode for the directory being modified */
9378 	struct inode *ip;	/* inode for directory entry being removed */
9379 	ino_t newinum;		/* new inode number for changed entry */
9380 	int isrmdir;		/* indicates if doing RMDIR */
9381 {
9382 	int offset;
9383 	struct diradd *dap = NULL;
9384 	struct dirrem *dirrem, *prevdirrem;
9385 	struct pagedep *pagedep;
9386 	struct inodedep *inodedep;
9387 	struct jaddref *jaddref;
9388 	struct mount *mp;
9389 	struct ufsmount *ump;
9390 
9391 	mp = ITOVFS(dp);
9392 	ump = VFSTOUFS(mp);
9393 	offset = blkoff(ump->um_fs, dp->i_offset);
9394 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
9395 	   ("softdep_setup_directory_change called on non-softdep filesystem"));
9396 
9397 	/*
9398 	 * Whiteouts do not need diradd dependencies.
9399 	 */
9400 	if (newinum != UFS_WINO) {
9401 		dap = malloc(sizeof(struct diradd),
9402 		    M_DIRADD, M_SOFTDEP_FLAGS|M_ZERO);
9403 		workitem_alloc(&dap->da_list, D_DIRADD, mp);
9404 		dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
9405 		dap->da_offset = offset;
9406 		dap->da_newinum = newinum;
9407 		LIST_INIT(&dap->da_jwork);
9408 	}
9409 
9410 	/*
9411 	 * Allocate a new dirrem and ACQUIRE_LOCK.
9412 	 */
9413 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9414 	pagedep = dirrem->dm_pagedep;
9415 	/*
9416 	 * The possible values for isrmdir:
9417 	 *	0 - non-directory file rename
9418 	 *	1 - directory rename within same directory
9419 	 *   inum - directory rename to new directory of given inode number
9420 	 * When renaming to a new directory, we are both deleting and
9421 	 * creating a new directory entry, so the link count on the new
9422 	 * directory should not change. Thus we do not need the followup
9423 	 * dirrem which is usually done in handle_workitem_remove. We set
9424 	 * the DIRCHG flag to tell handle_workitem_remove to skip the
9425 	 * followup dirrem.
9426 	 */
9427 	if (isrmdir > 1)
9428 		dirrem->dm_state |= DIRCHG;
9429 
9430 	/*
9431 	 * Whiteouts have no additional dependencies,
9432 	 * so just put the dirrem on the correct list.
9433 	 */
9434 	if (newinum == UFS_WINO) {
9435 		if ((dirrem->dm_state & COMPLETE) == 0) {
9436 			LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
9437 			    dm_next);
9438 		} else {
9439 			dirrem->dm_dirinum = pagedep->pd_ino;
9440 			if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9441 				add_to_worklist(&dirrem->dm_list, 0);
9442 		}
9443 		FREE_LOCK(ump);
9444 		return;
9445 	}
9446 	/*
9447 	 * Add the dirrem to the inodedep's pending remove list for quick
9448 	 * discovery later.  A valid nlinkdelta ensures that this lookup
9449 	 * will not fail.
9450 	 */
9451 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9452 		panic("softdep_setup_directory_change: Lost inodedep.");
9453 	dirrem->dm_state |= ONDEPLIST;
9454 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9455 
9456 	/*
9457 	 * If the COMPLETE flag is clear, then there were no active
9458 	 * entries and we want to roll back to the previous inode until
9459 	 * the new inode is committed to disk. If the COMPLETE flag is
9460 	 * set, then we have deleted an entry that never made it to disk.
9461 	 * If the entry we deleted resulted from a name change, then the old
9462 	 * inode reference still resides on disk. Any rollback that we do
9463 	 * needs to be to that old inode (returned to us in prevdirrem). If
9464 	 * the entry we deleted resulted from a create, then there is
9465 	 * no entry on the disk, so we want to roll back to zero rather
9466 	 * than the uncommitted inode. In either of the COMPLETE cases we
9467 	 * want to immediately free the unwritten and unreferenced inode.
9468 	 */
9469 	if ((dirrem->dm_state & COMPLETE) == 0) {
9470 		dap->da_previous = dirrem;
9471 	} else {
9472 		if (prevdirrem != NULL) {
9473 			dap->da_previous = prevdirrem;
9474 		} else {
9475 			dap->da_state &= ~DIRCHG;
9476 			dap->da_pagedep = pagedep;
9477 		}
9478 		dirrem->dm_dirinum = pagedep->pd_ino;
9479 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9480 			add_to_worklist(&dirrem->dm_list, 0);
9481 	}
9482 	/*
9483 	 * Lookup the jaddref for this journal entry.  We must finish
9484 	 * initializing it and make the diradd write dependent on it.
9485 	 * If we're not journaling, put it on the id_bufwait list if the
9486 	 * inode is not yet written. If it is written, do the post-inode
9487 	 * write processing to put it on the id_pendinghd list.
9488 	 */
9489 	inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
9490 	if (MOUNTEDSUJ(mp)) {
9491 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
9492 		    inoreflst);
9493 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
9494 		    ("softdep_setup_directory_change: bad jaddref %p",
9495 		    jaddref));
9496 		jaddref->ja_diroff = dp->i_offset;
9497 		jaddref->ja_diradd = dap;
9498 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9499 		    dap, da_pdlist);
9500 		add_to_journal(&jaddref->ja_list);
9501 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
9502 		dap->da_state |= COMPLETE;
9503 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
9504 		WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
9505 	} else {
9506 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9507 		    dap, da_pdlist);
9508 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
9509 	}
9510 	/*
9511 	 * If we're making a new name for a directory that has not been
9512 	 * committed when need to move the dot and dotdot references to
9513 	 * this new name.
9514 	 */
9515 	if (inodedep->id_mkdiradd && dp->i_offset != DOTDOT_OFFSET)
9516 		merge_diradd(inodedep, dap);
9517 	FREE_LOCK(ump);
9518 }
9519 
9520 /*
9521  * Called whenever the link count on an inode is changed.
9522  * It creates an inode dependency so that the new reference(s)
9523  * to the inode cannot be committed to disk until the updated
9524  * inode has been written.
9525  */
9526 void
9527 softdep_change_linkcnt(ip)
9528 	struct inode *ip;	/* the inode with the increased link count */
9529 {
9530 	struct inodedep *inodedep;
9531 	struct ufsmount *ump;
9532 
9533 	ump = ITOUMP(ip);
9534 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9535 	    ("softdep_change_linkcnt called on non-softdep filesystem"));
9536 	ACQUIRE_LOCK(ump);
9537 	inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
9538 	if (ip->i_nlink < ip->i_effnlink)
9539 		panic("softdep_change_linkcnt: bad delta");
9540 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9541 	FREE_LOCK(ump);
9542 }
9543 
9544 /*
9545  * Attach a sbdep dependency to the superblock buf so that we can keep
9546  * track of the head of the linked list of referenced but unlinked inodes.
9547  */
9548 void
9549 softdep_setup_sbupdate(ump, fs, bp)
9550 	struct ufsmount *ump;
9551 	struct fs *fs;
9552 	struct buf *bp;
9553 {
9554 	struct sbdep *sbdep;
9555 	struct worklist *wk;
9556 
9557 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9558 	    ("softdep_setup_sbupdate called on non-softdep filesystem"));
9559 	LIST_FOREACH(wk, &bp->b_dep, wk_list)
9560 		if (wk->wk_type == D_SBDEP)
9561 			break;
9562 	if (wk != NULL)
9563 		return;
9564 	sbdep = malloc(sizeof(struct sbdep), M_SBDEP, M_SOFTDEP_FLAGS);
9565 	workitem_alloc(&sbdep->sb_list, D_SBDEP, UFSTOVFS(ump));
9566 	sbdep->sb_fs = fs;
9567 	sbdep->sb_ump = ump;
9568 	ACQUIRE_LOCK(ump);
9569 	WORKLIST_INSERT(&bp->b_dep, &sbdep->sb_list);
9570 	FREE_LOCK(ump);
9571 }
9572 
9573 /*
9574  * Return the first unlinked inodedep which is ready to be the head of the
9575  * list.  The inodedep and all those after it must have valid next pointers.
9576  */
9577 static struct inodedep *
9578 first_unlinked_inodedep(ump)
9579 	struct ufsmount *ump;
9580 {
9581 	struct inodedep *inodedep;
9582 	struct inodedep *idp;
9583 
9584 	LOCK_OWNED(ump);
9585 	for (inodedep = TAILQ_LAST(&ump->softdep_unlinked, inodedeplst);
9586 	    inodedep; inodedep = idp) {
9587 		if ((inodedep->id_state & UNLINKNEXT) == 0)
9588 			return (NULL);
9589 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9590 		if (idp == NULL || (idp->id_state & UNLINKNEXT) == 0)
9591 			break;
9592 		if ((inodedep->id_state & UNLINKPREV) == 0)
9593 			break;
9594 	}
9595 	return (inodedep);
9596 }
9597 
9598 /*
9599  * Set the sujfree unlinked head pointer prior to writing a superblock.
9600  */
9601 static void
9602 initiate_write_sbdep(sbdep)
9603 	struct sbdep *sbdep;
9604 {
9605 	struct inodedep *inodedep;
9606 	struct fs *bpfs;
9607 	struct fs *fs;
9608 
9609 	bpfs = sbdep->sb_fs;
9610 	fs = sbdep->sb_ump->um_fs;
9611 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9612 	if (inodedep) {
9613 		fs->fs_sujfree = inodedep->id_ino;
9614 		inodedep->id_state |= UNLINKPREV;
9615 	} else
9616 		fs->fs_sujfree = 0;
9617 	bpfs->fs_sujfree = fs->fs_sujfree;
9618 	/*
9619 	 * Because we have made changes to the superblock, we need to
9620 	 * recompute its check-hash.
9621 	 */
9622 	bpfs->fs_ckhash = ffs_calc_sbhash(bpfs);
9623 }
9624 
9625 /*
9626  * After a superblock is written determine whether it must be written again
9627  * due to a changing unlinked list head.
9628  */
9629 static int
9630 handle_written_sbdep(sbdep, bp)
9631 	struct sbdep *sbdep;
9632 	struct buf *bp;
9633 {
9634 	struct inodedep *inodedep;
9635 	struct fs *fs;
9636 
9637 	LOCK_OWNED(sbdep->sb_ump);
9638 	fs = sbdep->sb_fs;
9639 	/*
9640 	 * If the superblock doesn't match the in-memory list start over.
9641 	 */
9642 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9643 	if ((inodedep && fs->fs_sujfree != inodedep->id_ino) ||
9644 	    (inodedep == NULL && fs->fs_sujfree != 0)) {
9645 		bdirty(bp);
9646 		return (1);
9647 	}
9648 	WORKITEM_FREE(sbdep, D_SBDEP);
9649 	if (fs->fs_sujfree == 0)
9650 		return (0);
9651 	/*
9652 	 * Now that we have a record of this inode in stable store allow it
9653 	 * to be written to free up pending work.  Inodes may see a lot of
9654 	 * write activity after they are unlinked which we must not hold up.
9655 	 */
9656 	for (; inodedep != NULL; inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
9657 		if ((inodedep->id_state & UNLINKLINKS) != UNLINKLINKS)
9658 			panic("handle_written_sbdep: Bad inodedep %p (0x%X)",
9659 			    inodedep, inodedep->id_state);
9660 		if (inodedep->id_state & UNLINKONLIST)
9661 			break;
9662 		inodedep->id_state |= DEPCOMPLETE | UNLINKONLIST;
9663 	}
9664 
9665 	return (0);
9666 }
9667 
9668 /*
9669  * Mark an inodedep as unlinked and insert it into the in-memory unlinked list.
9670  */
9671 static void
9672 unlinked_inodedep(mp, inodedep)
9673 	struct mount *mp;
9674 	struct inodedep *inodedep;
9675 {
9676 	struct ufsmount *ump;
9677 
9678 	ump = VFSTOUFS(mp);
9679 	LOCK_OWNED(ump);
9680 	if (MOUNTEDSUJ(mp) == 0)
9681 		return;
9682 	ump->um_fs->fs_fmod = 1;
9683 	if (inodedep->id_state & UNLINKED)
9684 		panic("unlinked_inodedep: %p already unlinked\n", inodedep);
9685 	inodedep->id_state |= UNLINKED;
9686 	TAILQ_INSERT_HEAD(&ump->softdep_unlinked, inodedep, id_unlinked);
9687 }
9688 
9689 /*
9690  * Remove an inodedep from the unlinked inodedep list.  This may require
9691  * disk writes if the inode has made it that far.
9692  */
9693 static void
9694 clear_unlinked_inodedep(inodedep)
9695 	struct inodedep *inodedep;
9696 {
9697 	struct ufs2_dinode *dip;
9698 	struct ufsmount *ump;
9699 	struct inodedep *idp;
9700 	struct inodedep *idn;
9701 	struct fs *fs, *bpfs;
9702 	struct buf *bp;
9703 	ino_t ino;
9704 	ino_t nino;
9705 	ino_t pino;
9706 	int error;
9707 
9708 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
9709 	fs = ump->um_fs;
9710 	ino = inodedep->id_ino;
9711 	error = 0;
9712 	for (;;) {
9713 		LOCK_OWNED(ump);
9714 		KASSERT((inodedep->id_state & UNLINKED) != 0,
9715 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
9716 		    inodedep));
9717 		/*
9718 		 * If nothing has yet been written simply remove us from
9719 		 * the in memory list and return.  This is the most common
9720 		 * case where handle_workitem_remove() loses the final
9721 		 * reference.
9722 		 */
9723 		if ((inodedep->id_state & UNLINKLINKS) == 0)
9724 			break;
9725 		/*
9726 		 * If we have a NEXT pointer and no PREV pointer we can simply
9727 		 * clear NEXT's PREV and remove ourselves from the list.  Be
9728 		 * careful not to clear PREV if the superblock points at
9729 		 * next as well.
9730 		 */
9731 		idn = TAILQ_NEXT(inodedep, id_unlinked);
9732 		if ((inodedep->id_state & UNLINKLINKS) == UNLINKNEXT) {
9733 			if (idn && fs->fs_sujfree != idn->id_ino)
9734 				idn->id_state &= ~UNLINKPREV;
9735 			break;
9736 		}
9737 		/*
9738 		 * Here we have an inodedep which is actually linked into
9739 		 * the list.  We must remove it by forcing a write to the
9740 		 * link before us, whether it be the superblock or an inode.
9741 		 * Unfortunately the list may change while we're waiting
9742 		 * on the buf lock for either resource so we must loop until
9743 		 * we lock the right one.  If both the superblock and an
9744 		 * inode point to this inode we must clear the inode first
9745 		 * followed by the superblock.
9746 		 */
9747 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9748 		pino = 0;
9749 		if (idp && (idp->id_state & UNLINKNEXT))
9750 			pino = idp->id_ino;
9751 		FREE_LOCK(ump);
9752 		if (pino == 0) {
9753 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9754 			    (int)fs->fs_sbsize, 0, 0, 0);
9755 		} else {
9756 			error = bread(ump->um_devvp,
9757 			    fsbtodb(fs, ino_to_fsba(fs, pino)),
9758 			    (int)fs->fs_bsize, NOCRED, &bp);
9759 			if (error)
9760 				brelse(bp);
9761 		}
9762 		ACQUIRE_LOCK(ump);
9763 		if (error)
9764 			break;
9765 		/* If the list has changed restart the loop. */
9766 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9767 		nino = 0;
9768 		if (idp && (idp->id_state & UNLINKNEXT))
9769 			nino = idp->id_ino;
9770 		if (nino != pino ||
9771 		    (inodedep->id_state & UNLINKPREV) != UNLINKPREV) {
9772 			FREE_LOCK(ump);
9773 			brelse(bp);
9774 			ACQUIRE_LOCK(ump);
9775 			continue;
9776 		}
9777 		nino = 0;
9778 		idn = TAILQ_NEXT(inodedep, id_unlinked);
9779 		if (idn)
9780 			nino = idn->id_ino;
9781 		/*
9782 		 * Remove us from the in memory list.  After this we cannot
9783 		 * access the inodedep.
9784 		 */
9785 		KASSERT((inodedep->id_state & UNLINKED) != 0,
9786 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
9787 		    inodedep));
9788 		inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9789 		TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9790 		FREE_LOCK(ump);
9791 		/*
9792 		 * The predecessor's next pointer is manually updated here
9793 		 * so that the NEXT flag is never cleared for an element
9794 		 * that is in the list.
9795 		 */
9796 		if (pino == 0) {
9797 			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9798 			bpfs = (struct fs *)bp->b_data;
9799 			ffs_oldfscompat_write(bpfs, ump);
9800 			softdep_setup_sbupdate(ump, bpfs, bp);
9801 			/*
9802 			 * Because we may have made changes to the superblock,
9803 			 * we need to recompute its check-hash.
9804 			 */
9805 			bpfs->fs_ckhash = ffs_calc_sbhash(bpfs);
9806 		} else if (fs->fs_magic == FS_UFS1_MAGIC) {
9807 			((struct ufs1_dinode *)bp->b_data +
9808 			    ino_to_fsbo(fs, pino))->di_freelink = nino;
9809 		} else {
9810 			dip = (struct ufs2_dinode *)bp->b_data +
9811 			    ino_to_fsbo(fs, pino);
9812 			dip->di_freelink = nino;
9813 			ffs_update_dinode_ckhash(fs, dip);
9814 		}
9815 		/*
9816 		 * If the bwrite fails we have no recourse to recover.  The
9817 		 * filesystem is corrupted already.
9818 		 */
9819 		bwrite(bp);
9820 		ACQUIRE_LOCK(ump);
9821 		/*
9822 		 * If the superblock pointer still needs to be cleared force
9823 		 * a write here.
9824 		 */
9825 		if (fs->fs_sujfree == ino) {
9826 			FREE_LOCK(ump);
9827 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9828 			    (int)fs->fs_sbsize, 0, 0, 0);
9829 			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9830 			bpfs = (struct fs *)bp->b_data;
9831 			ffs_oldfscompat_write(bpfs, ump);
9832 			softdep_setup_sbupdate(ump, bpfs, bp);
9833 			/*
9834 			 * Because we may have made changes to the superblock,
9835 			 * we need to recompute its check-hash.
9836 			 */
9837 			bpfs->fs_ckhash = ffs_calc_sbhash(bpfs);
9838 			bwrite(bp);
9839 			ACQUIRE_LOCK(ump);
9840 		}
9841 
9842 		if (fs->fs_sujfree != ino)
9843 			return;
9844 		panic("clear_unlinked_inodedep: Failed to clear free head");
9845 	}
9846 	if (inodedep->id_ino == fs->fs_sujfree)
9847 		panic("clear_unlinked_inodedep: Freeing head of free list");
9848 	inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9849 	TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9850 	return;
9851 }
9852 
9853 /*
9854  * This workitem decrements the inode's link count.
9855  * If the link count reaches zero, the file is removed.
9856  */
9857 static int
9858 handle_workitem_remove(dirrem, flags)
9859 	struct dirrem *dirrem;
9860 	int flags;
9861 {
9862 	struct inodedep *inodedep;
9863 	struct workhead dotdotwk;
9864 	struct worklist *wk;
9865 	struct ufsmount *ump;
9866 	struct mount *mp;
9867 	struct vnode *vp;
9868 	struct inode *ip;
9869 	ino_t oldinum;
9870 
9871 	if (dirrem->dm_state & ONWORKLIST)
9872 		panic("handle_workitem_remove: dirrem %p still on worklist",
9873 		    dirrem);
9874 	oldinum = dirrem->dm_oldinum;
9875 	mp = dirrem->dm_list.wk_mp;
9876 	ump = VFSTOUFS(mp);
9877 	flags |= LK_EXCLUSIVE;
9878 	if (ffs_vgetf(mp, oldinum, flags, &vp, FFSV_FORCEINSMQ) != 0)
9879 		return (EBUSY);
9880 	ip = VTOI(vp);
9881 	MPASS(ip->i_mode != 0);
9882 	ACQUIRE_LOCK(ump);
9883 	if ((inodedep_lookup(mp, oldinum, 0, &inodedep)) == 0)
9884 		panic("handle_workitem_remove: lost inodedep");
9885 	if (dirrem->dm_state & ONDEPLIST)
9886 		LIST_REMOVE(dirrem, dm_inonext);
9887 	KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
9888 	    ("handle_workitem_remove:  Journal entries not written."));
9889 
9890 	/*
9891 	 * Move all dependencies waiting on the remove to complete
9892 	 * from the dirrem to the inode inowait list to be completed
9893 	 * after the inode has been updated and written to disk.
9894 	 *
9895 	 * Any marked MKDIR_PARENT are saved to be completed when the
9896 	 * dotdot ref is removed unless DIRCHG is specified.  For
9897 	 * directory change operations there will be no further
9898 	 * directory writes and the jsegdeps need to be moved along
9899 	 * with the rest to be completed when the inode is free or
9900 	 * stable in the inode free list.
9901 	 */
9902 	LIST_INIT(&dotdotwk);
9903 	while ((wk = LIST_FIRST(&dirrem->dm_jwork)) != NULL) {
9904 		WORKLIST_REMOVE(wk);
9905 		if ((dirrem->dm_state & DIRCHG) == 0 &&
9906 		    wk->wk_state & MKDIR_PARENT) {
9907 			wk->wk_state &= ~MKDIR_PARENT;
9908 			WORKLIST_INSERT(&dotdotwk, wk);
9909 			continue;
9910 		}
9911 		WORKLIST_INSERT(&inodedep->id_inowait, wk);
9912 	}
9913 	LIST_SWAP(&dirrem->dm_jwork, &dotdotwk, worklist, wk_list);
9914 	/*
9915 	 * Normal file deletion.
9916 	 */
9917 	if ((dirrem->dm_state & RMDIR) == 0) {
9918 		ip->i_nlink--;
9919 		KASSERT(ip->i_nlink >= 0, ("handle_workitem_remove: file ino "
9920 		    "%ju negative i_nlink %d", (intmax_t)ip->i_number,
9921 		    ip->i_nlink));
9922 		DIP_SET(ip, i_nlink, ip->i_nlink);
9923 		UFS_INODE_SET_FLAG(ip, IN_CHANGE);
9924 		if (ip->i_nlink < ip->i_effnlink)
9925 			panic("handle_workitem_remove: bad file delta");
9926 		if (ip->i_nlink == 0)
9927 			unlinked_inodedep(mp, inodedep);
9928 		inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9929 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9930 		    ("handle_workitem_remove: worklist not empty. %s",
9931 		    TYPENAME(LIST_FIRST(&dirrem->dm_jwork)->wk_type)));
9932 		WORKITEM_FREE(dirrem, D_DIRREM);
9933 		FREE_LOCK(ump);
9934 		goto out;
9935 	}
9936 	/*
9937 	 * Directory deletion. Decrement reference count for both the
9938 	 * just deleted parent directory entry and the reference for ".".
9939 	 * Arrange to have the reference count on the parent decremented
9940 	 * to account for the loss of "..".
9941 	 */
9942 	ip->i_nlink -= 2;
9943 	KASSERT(ip->i_nlink >= 0, ("handle_workitem_remove: directory ino "
9944 	    "%ju negative i_nlink %d", (intmax_t)ip->i_number, ip->i_nlink));
9945 	DIP_SET(ip, i_nlink, ip->i_nlink);
9946 	UFS_INODE_SET_FLAG(ip, IN_CHANGE);
9947 	if (ip->i_nlink < ip->i_effnlink)
9948 		panic("handle_workitem_remove: bad dir delta");
9949 	if (ip->i_nlink == 0)
9950 		unlinked_inodedep(mp, inodedep);
9951 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9952 	/*
9953 	 * Rename a directory to a new parent. Since, we are both deleting
9954 	 * and creating a new directory entry, the link count on the new
9955 	 * directory should not change. Thus we skip the followup dirrem.
9956 	 */
9957 	if (dirrem->dm_state & DIRCHG) {
9958 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9959 		    ("handle_workitem_remove: DIRCHG and worklist not empty."));
9960 		WORKITEM_FREE(dirrem, D_DIRREM);
9961 		FREE_LOCK(ump);
9962 		goto out;
9963 	}
9964 	dirrem->dm_state = ONDEPLIST;
9965 	dirrem->dm_oldinum = dirrem->dm_dirinum;
9966 	/*
9967 	 * Place the dirrem on the parent's diremhd list.
9968 	 */
9969 	if (inodedep_lookup(mp, dirrem->dm_oldinum, 0, &inodedep) == 0)
9970 		panic("handle_workitem_remove: lost dir inodedep");
9971 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9972 	/*
9973 	 * If the allocated inode has never been written to disk, then
9974 	 * the on-disk inode is zero'ed and we can remove the file
9975 	 * immediately.  When journaling if the inode has been marked
9976 	 * unlinked and not DEPCOMPLETE we know it can never be written.
9977 	 */
9978 	inodedep_lookup(mp, oldinum, 0, &inodedep);
9979 	if (inodedep == NULL ||
9980 	    (inodedep->id_state & (DEPCOMPLETE | UNLINKED)) == UNLINKED ||
9981 	    check_inode_unwritten(inodedep)) {
9982 		FREE_LOCK(ump);
9983 		vput(vp);
9984 		return handle_workitem_remove(dirrem, flags);
9985 	}
9986 	WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
9987 	FREE_LOCK(ump);
9988 	UFS_INODE_SET_FLAG(ip, IN_CHANGE);
9989 out:
9990 	ffs_update(vp, 0);
9991 	vput(vp);
9992 	return (0);
9993 }
9994 
9995 /*
9996  * Inode de-allocation dependencies.
9997  *
9998  * When an inode's link count is reduced to zero, it can be de-allocated. We
9999  * found it convenient to postpone de-allocation until after the inode is
10000  * written to disk with its new link count (zero).  At this point, all of the
10001  * on-disk inode's block pointers are nullified and, with careful dependency
10002  * list ordering, all dependencies related to the inode will be satisfied and
10003  * the corresponding dependency structures de-allocated.  So, if/when the
10004  * inode is reused, there will be no mixing of old dependencies with new
10005  * ones.  This artificial dependency is set up by the block de-allocation
10006  * procedure above (softdep_setup_freeblocks) and completed by the
10007  * following procedure.
10008  */
10009 static void
10010 handle_workitem_freefile(freefile)
10011 	struct freefile *freefile;
10012 {
10013 	struct workhead wkhd;
10014 	struct fs *fs;
10015 	struct ufsmount *ump;
10016 	int error;
10017 #ifdef INVARIANTS
10018 	struct inodedep *idp;
10019 #endif
10020 
10021 	ump = VFSTOUFS(freefile->fx_list.wk_mp);
10022 	fs = ump->um_fs;
10023 #ifdef INVARIANTS
10024 	ACQUIRE_LOCK(ump);
10025 	error = inodedep_lookup(UFSTOVFS(ump), freefile->fx_oldinum, 0, &idp);
10026 	FREE_LOCK(ump);
10027 	if (error)
10028 		panic("handle_workitem_freefile: inodedep %p survived", idp);
10029 #endif
10030 	UFS_LOCK(ump);
10031 	fs->fs_pendinginodes -= 1;
10032 	UFS_UNLOCK(ump);
10033 	LIST_INIT(&wkhd);
10034 	LIST_SWAP(&freefile->fx_jwork, &wkhd, worklist, wk_list);
10035 	if ((error = ffs_freefile(ump, fs, freefile->fx_devvp,
10036 	    freefile->fx_oldinum, freefile->fx_mode, &wkhd)) != 0)
10037 		softdep_error("handle_workitem_freefile", error);
10038 	ACQUIRE_LOCK(ump);
10039 	WORKITEM_FREE(freefile, D_FREEFILE);
10040 	FREE_LOCK(ump);
10041 }
10042 
10043 
10044 /*
10045  * Helper function which unlinks marker element from work list and returns
10046  * the next element on the list.
10047  */
10048 static __inline struct worklist *
10049 markernext(struct worklist *marker)
10050 {
10051 	struct worklist *next;
10052 
10053 	next = LIST_NEXT(marker, wk_list);
10054 	LIST_REMOVE(marker, wk_list);
10055 	return next;
10056 }
10057 
10058 /*
10059  * Disk writes.
10060  *
10061  * The dependency structures constructed above are most actively used when file
10062  * system blocks are written to disk.  No constraints are placed on when a
10063  * block can be written, but unsatisfied update dependencies are made safe by
10064  * modifying (or replacing) the source memory for the duration of the disk
10065  * write.  When the disk write completes, the memory block is again brought
10066  * up-to-date.
10067  *
10068  * In-core inode structure reclamation.
10069  *
10070  * Because there are a finite number of "in-core" inode structures, they are
10071  * reused regularly.  By transferring all inode-related dependencies to the
10072  * in-memory inode block and indexing them separately (via "inodedep"s), we
10073  * can allow "in-core" inode structures to be reused at any time and avoid
10074  * any increase in contention.
10075  *
10076  * Called just before entering the device driver to initiate a new disk I/O.
10077  * The buffer must be locked, thus, no I/O completion operations can occur
10078  * while we are manipulating its associated dependencies.
10079  */
10080 static void
10081 softdep_disk_io_initiation(bp)
10082 	struct buf *bp;		/* structure describing disk write to occur */
10083 {
10084 	struct worklist *wk;
10085 	struct worklist marker;
10086 	struct inodedep *inodedep;
10087 	struct freeblks *freeblks;
10088 	struct jblkdep *jblkdep;
10089 	struct newblk *newblk;
10090 	struct ufsmount *ump;
10091 
10092 	/*
10093 	 * We only care about write operations. There should never
10094 	 * be dependencies for reads.
10095 	 */
10096 	if (bp->b_iocmd != BIO_WRITE)
10097 		panic("softdep_disk_io_initiation: not write");
10098 
10099 	if (bp->b_vflags & BV_BKGRDINPROG)
10100 		panic("softdep_disk_io_initiation: Writing buffer with "
10101 		    "background write in progress: %p", bp);
10102 
10103 	ump = softdep_bp_to_mp(bp);
10104 	if (ump == NULL)
10105 		return;
10106 
10107 	marker.wk_type = D_LAST + 1;	/* Not a normal workitem */
10108 	PHOLD(curproc);			/* Don't swap out kernel stack */
10109 	ACQUIRE_LOCK(ump);
10110 	/*
10111 	 * Do any necessary pre-I/O processing.
10112 	 */
10113 	for (wk = LIST_FIRST(&bp->b_dep); wk != NULL;
10114 	     wk = markernext(&marker)) {
10115 		LIST_INSERT_AFTER(wk, &marker, wk_list);
10116 		switch (wk->wk_type) {
10117 
10118 		case D_PAGEDEP:
10119 			initiate_write_filepage(WK_PAGEDEP(wk), bp);
10120 			continue;
10121 
10122 		case D_INODEDEP:
10123 			inodedep = WK_INODEDEP(wk);
10124 			if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC)
10125 				initiate_write_inodeblock_ufs1(inodedep, bp);
10126 			else
10127 				initiate_write_inodeblock_ufs2(inodedep, bp);
10128 			continue;
10129 
10130 		case D_INDIRDEP:
10131 			initiate_write_indirdep(WK_INDIRDEP(wk), bp);
10132 			continue;
10133 
10134 		case D_BMSAFEMAP:
10135 			initiate_write_bmsafemap(WK_BMSAFEMAP(wk), bp);
10136 			continue;
10137 
10138 		case D_JSEG:
10139 			WK_JSEG(wk)->js_buf = NULL;
10140 			continue;
10141 
10142 		case D_FREEBLKS:
10143 			freeblks = WK_FREEBLKS(wk);
10144 			jblkdep = LIST_FIRST(&freeblks->fb_jblkdephd);
10145 			/*
10146 			 * We have to wait for the freeblks to be journaled
10147 			 * before we can write an inodeblock with updated
10148 			 * pointers.  Be careful to arrange the marker so
10149 			 * we revisit the freeblks if it's not removed by
10150 			 * the first jwait().
10151 			 */
10152 			if (jblkdep != NULL) {
10153 				LIST_REMOVE(&marker, wk_list);
10154 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
10155 				jwait(&jblkdep->jb_list, MNT_WAIT);
10156 			}
10157 			continue;
10158 		case D_ALLOCDIRECT:
10159 		case D_ALLOCINDIR:
10160 			/*
10161 			 * We have to wait for the jnewblk to be journaled
10162 			 * before we can write to a block if the contents
10163 			 * may be confused with an earlier file's indirect
10164 			 * at recovery time.  Handle the marker as described
10165 			 * above.
10166 			 */
10167 			newblk = WK_NEWBLK(wk);
10168 			if (newblk->nb_jnewblk != NULL &&
10169 			    indirblk_lookup(newblk->nb_list.wk_mp,
10170 			    newblk->nb_newblkno)) {
10171 				LIST_REMOVE(&marker, wk_list);
10172 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
10173 				jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
10174 			}
10175 			continue;
10176 
10177 		case D_SBDEP:
10178 			initiate_write_sbdep(WK_SBDEP(wk));
10179 			continue;
10180 
10181 		case D_MKDIR:
10182 		case D_FREEWORK:
10183 		case D_FREEDEP:
10184 		case D_JSEGDEP:
10185 			continue;
10186 
10187 		default:
10188 			panic("handle_disk_io_initiation: Unexpected type %s",
10189 			    TYPENAME(wk->wk_type));
10190 			/* NOTREACHED */
10191 		}
10192 	}
10193 	FREE_LOCK(ump);
10194 	PRELE(curproc);			/* Allow swapout of kernel stack */
10195 }
10196 
10197 /*
10198  * Called from within the procedure above to deal with unsatisfied
10199  * allocation dependencies in a directory. The buffer must be locked,
10200  * thus, no I/O completion operations can occur while we are
10201  * manipulating its associated dependencies.
10202  */
10203 static void
10204 initiate_write_filepage(pagedep, bp)
10205 	struct pagedep *pagedep;
10206 	struct buf *bp;
10207 {
10208 	struct jremref *jremref;
10209 	struct jmvref *jmvref;
10210 	struct dirrem *dirrem;
10211 	struct diradd *dap;
10212 	struct direct *ep;
10213 	int i;
10214 
10215 	if (pagedep->pd_state & IOSTARTED) {
10216 		/*
10217 		 * This can only happen if there is a driver that does not
10218 		 * understand chaining. Here biodone will reissue the call
10219 		 * to strategy for the incomplete buffers.
10220 		 */
10221 		printf("initiate_write_filepage: already started\n");
10222 		return;
10223 	}
10224 	pagedep->pd_state |= IOSTARTED;
10225 	/*
10226 	 * Wait for all journal remove dependencies to hit the disk.
10227 	 * We can not allow any potentially conflicting directory adds
10228 	 * to be visible before removes and rollback is too difficult.
10229 	 * The per-filesystem lock may be dropped and re-acquired, however
10230 	 * we hold the buf locked so the dependency can not go away.
10231 	 */
10232 	LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next)
10233 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL)
10234 			jwait(&jremref->jr_list, MNT_WAIT);
10235 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL)
10236 		jwait(&jmvref->jm_list, MNT_WAIT);
10237 	for (i = 0; i < DAHASHSZ; i++) {
10238 		LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
10239 			ep = (struct direct *)
10240 			    ((char *)bp->b_data + dap->da_offset);
10241 			if (ep->d_ino != dap->da_newinum)
10242 				panic("%s: dir inum %ju != new %ju",
10243 				    "initiate_write_filepage",
10244 				    (uintmax_t)ep->d_ino,
10245 				    (uintmax_t)dap->da_newinum);
10246 			if (dap->da_state & DIRCHG)
10247 				ep->d_ino = dap->da_previous->dm_oldinum;
10248 			else
10249 				ep->d_ino = 0;
10250 			dap->da_state &= ~ATTACHED;
10251 			dap->da_state |= UNDONE;
10252 		}
10253 	}
10254 }
10255 
10256 /*
10257  * Version of initiate_write_inodeblock that handles UFS1 dinodes.
10258  * Note that any bug fixes made to this routine must be done in the
10259  * version found below.
10260  *
10261  * Called from within the procedure above to deal with unsatisfied
10262  * allocation dependencies in an inodeblock. The buffer must be
10263  * locked, thus, no I/O completion operations can occur while we
10264  * are manipulating its associated dependencies.
10265  */
10266 static void
10267 initiate_write_inodeblock_ufs1(inodedep, bp)
10268 	struct inodedep *inodedep;
10269 	struct buf *bp;			/* The inode block */
10270 {
10271 	struct allocdirect *adp, *lastadp;
10272 	struct ufs1_dinode *dp;
10273 	struct ufs1_dinode *sip;
10274 	struct inoref *inoref;
10275 	struct ufsmount *ump;
10276 	struct fs *fs;
10277 	ufs_lbn_t i;
10278 #ifdef INVARIANTS
10279 	ufs_lbn_t prevlbn = 0;
10280 #endif
10281 	int deplist;
10282 
10283 	if (inodedep->id_state & IOSTARTED)
10284 		panic("initiate_write_inodeblock_ufs1: already started");
10285 	inodedep->id_state |= IOSTARTED;
10286 	fs = inodedep->id_fs;
10287 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10288 	LOCK_OWNED(ump);
10289 	dp = (struct ufs1_dinode *)bp->b_data +
10290 	    ino_to_fsbo(fs, inodedep->id_ino);
10291 
10292 	/*
10293 	 * If we're on the unlinked list but have not yet written our
10294 	 * next pointer initialize it here.
10295 	 */
10296 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10297 		struct inodedep *inon;
10298 
10299 		inon = TAILQ_NEXT(inodedep, id_unlinked);
10300 		dp->di_freelink = inon ? inon->id_ino : 0;
10301 	}
10302 	/*
10303 	 * If the bitmap is not yet written, then the allocated
10304 	 * inode cannot be written to disk.
10305 	 */
10306 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10307 		if (inodedep->id_savedino1 != NULL)
10308 			panic("initiate_write_inodeblock_ufs1: I/O underway");
10309 		FREE_LOCK(ump);
10310 		sip = malloc(sizeof(struct ufs1_dinode),
10311 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
10312 		ACQUIRE_LOCK(ump);
10313 		inodedep->id_savedino1 = sip;
10314 		*inodedep->id_savedino1 = *dp;
10315 		bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
10316 		dp->di_gen = inodedep->id_savedino1->di_gen;
10317 		dp->di_freelink = inodedep->id_savedino1->di_freelink;
10318 		return;
10319 	}
10320 	/*
10321 	 * If no dependencies, then there is nothing to roll back.
10322 	 */
10323 	inodedep->id_savedsize = dp->di_size;
10324 	inodedep->id_savedextsize = 0;
10325 	inodedep->id_savednlink = dp->di_nlink;
10326 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10327 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
10328 		return;
10329 	/*
10330 	 * Revert the link count to that of the first unwritten journal entry.
10331 	 */
10332 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10333 	if (inoref)
10334 		dp->di_nlink = inoref->if_nlink;
10335 	/*
10336 	 * Set the dependencies to busy.
10337 	 */
10338 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10339 	     adp = TAILQ_NEXT(adp, ad_next)) {
10340 #ifdef INVARIANTS
10341 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10342 			panic("softdep_write_inodeblock: lbn order");
10343 		prevlbn = adp->ad_offset;
10344 		if (adp->ad_offset < UFS_NDADDR &&
10345 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10346 			panic("initiate_write_inodeblock_ufs1: "
10347 			    "direct pointer #%jd mismatch %d != %jd",
10348 			    (intmax_t)adp->ad_offset,
10349 			    dp->di_db[adp->ad_offset],
10350 			    (intmax_t)adp->ad_newblkno);
10351 		if (adp->ad_offset >= UFS_NDADDR &&
10352 		    dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10353 			panic("initiate_write_inodeblock_ufs1: "
10354 			    "indirect pointer #%jd mismatch %d != %jd",
10355 			    (intmax_t)adp->ad_offset - UFS_NDADDR,
10356 			    dp->di_ib[adp->ad_offset - UFS_NDADDR],
10357 			    (intmax_t)adp->ad_newblkno);
10358 		deplist |= 1 << adp->ad_offset;
10359 		if ((adp->ad_state & ATTACHED) == 0)
10360 			panic("initiate_write_inodeblock_ufs1: "
10361 			    "Unknown state 0x%x", 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 file
10370 	 * which would corrupt the filesystem.
10371 	 */
10372 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10373 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10374 		if (adp->ad_offset >= UFS_NDADDR)
10375 			break;
10376 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10377 		/* keep going until hitting a rollback to a frag */
10378 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10379 			continue;
10380 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10381 		for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10382 #ifdef INVARIANTS
10383 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10384 				panic("initiate_write_inodeblock_ufs1: "
10385 				    "lost dep1");
10386 #endif /* INVARIANTS */
10387 			dp->di_db[i] = 0;
10388 		}
10389 		for (i = 0; i < UFS_NIADDR; i++) {
10390 #ifdef INVARIANTS
10391 			if (dp->di_ib[i] != 0 &&
10392 			    (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10393 				panic("initiate_write_inodeblock_ufs1: "
10394 				    "lost dep2");
10395 #endif /* INVARIANTS */
10396 			dp->di_ib[i] = 0;
10397 		}
10398 		return;
10399 	}
10400 	/*
10401 	 * If we have zero'ed out the last allocated block of the file,
10402 	 * roll back the size to the last currently allocated block.
10403 	 * We know that this last allocated block is a full-sized as
10404 	 * we already checked for fragments in the loop above.
10405 	 */
10406 	if (lastadp != NULL &&
10407 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10408 		for (i = lastadp->ad_offset; i >= 0; i--)
10409 			if (dp->di_db[i] != 0)
10410 				break;
10411 		dp->di_size = (i + 1) * fs->fs_bsize;
10412 	}
10413 	/*
10414 	 * The only dependencies are for indirect blocks.
10415 	 *
10416 	 * The file size for indirect block additions is not guaranteed.
10417 	 * Such a guarantee would be non-trivial to achieve. The conventional
10418 	 * synchronous write implementation also does not make this guarantee.
10419 	 * Fsck should catch and fix discrepancies. Arguably, the file size
10420 	 * can be over-estimated without destroying integrity when the file
10421 	 * moves into the indirect blocks (i.e., is large). If we want to
10422 	 * postpone fsck, we are stuck with this argument.
10423 	 */
10424 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10425 		dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10426 }
10427 
10428 /*
10429  * Version of initiate_write_inodeblock that handles UFS2 dinodes.
10430  * Note that any bug fixes made to this routine must be done in the
10431  * version found above.
10432  *
10433  * Called from within the procedure above to deal with unsatisfied
10434  * allocation dependencies in an inodeblock. The buffer must be
10435  * locked, thus, no I/O completion operations can occur while we
10436  * are manipulating its associated dependencies.
10437  */
10438 static void
10439 initiate_write_inodeblock_ufs2(inodedep, bp)
10440 	struct inodedep *inodedep;
10441 	struct buf *bp;			/* The inode block */
10442 {
10443 	struct allocdirect *adp, *lastadp;
10444 	struct ufs2_dinode *dp;
10445 	struct ufs2_dinode *sip;
10446 	struct inoref *inoref;
10447 	struct ufsmount *ump;
10448 	struct fs *fs;
10449 	ufs_lbn_t i;
10450 #ifdef INVARIANTS
10451 	ufs_lbn_t prevlbn = 0;
10452 #endif
10453 	int deplist;
10454 
10455 	if (inodedep->id_state & IOSTARTED)
10456 		panic("initiate_write_inodeblock_ufs2: already started");
10457 	inodedep->id_state |= IOSTARTED;
10458 	fs = inodedep->id_fs;
10459 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10460 	LOCK_OWNED(ump);
10461 	dp = (struct ufs2_dinode *)bp->b_data +
10462 	    ino_to_fsbo(fs, inodedep->id_ino);
10463 
10464 	/*
10465 	 * If we're on the unlinked list but have not yet written our
10466 	 * next pointer initialize it here.
10467 	 */
10468 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10469 		struct inodedep *inon;
10470 
10471 		inon = TAILQ_NEXT(inodedep, id_unlinked);
10472 		dp->di_freelink = inon ? inon->id_ino : 0;
10473 		ffs_update_dinode_ckhash(fs, dp);
10474 	}
10475 	/*
10476 	 * If the bitmap is not yet written, then the allocated
10477 	 * inode cannot be written to disk.
10478 	 */
10479 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10480 		if (inodedep->id_savedino2 != NULL)
10481 			panic("initiate_write_inodeblock_ufs2: I/O underway");
10482 		FREE_LOCK(ump);
10483 		sip = malloc(sizeof(struct ufs2_dinode),
10484 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
10485 		ACQUIRE_LOCK(ump);
10486 		inodedep->id_savedino2 = sip;
10487 		*inodedep->id_savedino2 = *dp;
10488 		bzero((caddr_t)dp, sizeof(struct ufs2_dinode));
10489 		dp->di_gen = inodedep->id_savedino2->di_gen;
10490 		dp->di_freelink = inodedep->id_savedino2->di_freelink;
10491 		return;
10492 	}
10493 	/*
10494 	 * If no dependencies, then there is nothing to roll back.
10495 	 */
10496 	inodedep->id_savedsize = dp->di_size;
10497 	inodedep->id_savedextsize = dp->di_extsize;
10498 	inodedep->id_savednlink = dp->di_nlink;
10499 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10500 	    TAILQ_EMPTY(&inodedep->id_extupdt) &&
10501 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
10502 		return;
10503 	/*
10504 	 * Revert the link count to that of the first unwritten journal entry.
10505 	 */
10506 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10507 	if (inoref)
10508 		dp->di_nlink = inoref->if_nlink;
10509 
10510 	/*
10511 	 * Set the ext data dependencies to busy.
10512 	 */
10513 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10514 	     adp = TAILQ_NEXT(adp, ad_next)) {
10515 #ifdef INVARIANTS
10516 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10517 			panic("initiate_write_inodeblock_ufs2: lbn order");
10518 		prevlbn = adp->ad_offset;
10519 		if (dp->di_extb[adp->ad_offset] != adp->ad_newblkno)
10520 			panic("initiate_write_inodeblock_ufs2: "
10521 			    "ext pointer #%jd mismatch %jd != %jd",
10522 			    (intmax_t)adp->ad_offset,
10523 			    (intmax_t)dp->di_extb[adp->ad_offset],
10524 			    (intmax_t)adp->ad_newblkno);
10525 		deplist |= 1 << adp->ad_offset;
10526 		if ((adp->ad_state & ATTACHED) == 0)
10527 			panic("initiate_write_inodeblock_ufs2: Unknown "
10528 			    "state 0x%x", adp->ad_state);
10529 #endif /* INVARIANTS */
10530 		adp->ad_state &= ~ATTACHED;
10531 		adp->ad_state |= UNDONE;
10532 	}
10533 	/*
10534 	 * The on-disk inode cannot claim to be any larger than the last
10535 	 * fragment that has been written. Otherwise, the on-disk inode
10536 	 * might have fragments that were not the last block in the ext
10537 	 * data which would corrupt the filesystem.
10538 	 */
10539 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10540 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10541 		dp->di_extb[adp->ad_offset] = adp->ad_oldblkno;
10542 		/* keep going until hitting a rollback to a frag */
10543 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10544 			continue;
10545 		dp->di_extsize = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10546 		for (i = adp->ad_offset + 1; i < UFS_NXADDR; i++) {
10547 #ifdef INVARIANTS
10548 			if (dp->di_extb[i] != 0 && (deplist & (1 << i)) == 0)
10549 				panic("initiate_write_inodeblock_ufs2: "
10550 				    "lost dep1");
10551 #endif /* INVARIANTS */
10552 			dp->di_extb[i] = 0;
10553 		}
10554 		lastadp = NULL;
10555 		break;
10556 	}
10557 	/*
10558 	 * If we have zero'ed out the last allocated block of the ext
10559 	 * data, roll back the size to the last currently allocated block.
10560 	 * We know that this last allocated block is a full-sized as
10561 	 * we already checked for fragments in the loop above.
10562 	 */
10563 	if (lastadp != NULL &&
10564 	    dp->di_extsize <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10565 		for (i = lastadp->ad_offset; i >= 0; i--)
10566 			if (dp->di_extb[i] != 0)
10567 				break;
10568 		dp->di_extsize = (i + 1) * fs->fs_bsize;
10569 	}
10570 	/*
10571 	 * Set the file data dependencies to busy.
10572 	 */
10573 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10574 	     adp = TAILQ_NEXT(adp, ad_next)) {
10575 #ifdef INVARIANTS
10576 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10577 			panic("softdep_write_inodeblock: lbn order");
10578 		if ((adp->ad_state & ATTACHED) == 0)
10579 			panic("inodedep %p and adp %p not attached", inodedep, adp);
10580 		prevlbn = adp->ad_offset;
10581 		if (adp->ad_offset < UFS_NDADDR &&
10582 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10583 			panic("initiate_write_inodeblock_ufs2: "
10584 			    "direct pointer #%jd mismatch %jd != %jd",
10585 			    (intmax_t)adp->ad_offset,
10586 			    (intmax_t)dp->di_db[adp->ad_offset],
10587 			    (intmax_t)adp->ad_newblkno);
10588 		if (adp->ad_offset >= UFS_NDADDR &&
10589 		    dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10590 			panic("initiate_write_inodeblock_ufs2: "
10591 			    "indirect pointer #%jd mismatch %jd != %jd",
10592 			    (intmax_t)adp->ad_offset - UFS_NDADDR,
10593 			    (intmax_t)dp->di_ib[adp->ad_offset - UFS_NDADDR],
10594 			    (intmax_t)adp->ad_newblkno);
10595 		deplist |= 1 << adp->ad_offset;
10596 		if ((adp->ad_state & ATTACHED) == 0)
10597 			panic("initiate_write_inodeblock_ufs2: Unknown "
10598 			     "state 0x%x", adp->ad_state);
10599 #endif /* INVARIANTS */
10600 		adp->ad_state &= ~ATTACHED;
10601 		adp->ad_state |= UNDONE;
10602 	}
10603 	/*
10604 	 * The on-disk inode cannot claim to be any larger than the last
10605 	 * fragment that has been written. Otherwise, the on-disk inode
10606 	 * might have fragments that were not the last block in the file
10607 	 * which would corrupt the filesystem.
10608 	 */
10609 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10610 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10611 		if (adp->ad_offset >= UFS_NDADDR)
10612 			break;
10613 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10614 		/* keep going until hitting a rollback to a frag */
10615 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10616 			continue;
10617 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10618 		for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10619 #ifdef INVARIANTS
10620 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10621 				panic("initiate_write_inodeblock_ufs2: "
10622 				    "lost dep2");
10623 #endif /* INVARIANTS */
10624 			dp->di_db[i] = 0;
10625 		}
10626 		for (i = 0; i < UFS_NIADDR; i++) {
10627 #ifdef INVARIANTS
10628 			if (dp->di_ib[i] != 0 &&
10629 			    (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10630 				panic("initiate_write_inodeblock_ufs2: "
10631 				    "lost dep3");
10632 #endif /* INVARIANTS */
10633 			dp->di_ib[i] = 0;
10634 		}
10635 		ffs_update_dinode_ckhash(fs, dp);
10636 		return;
10637 	}
10638 	/*
10639 	 * If we have zero'ed out the last allocated block of the file,
10640 	 * roll back the size to the last currently allocated block.
10641 	 * We know that this last allocated block is a full-sized as
10642 	 * we already checked for fragments in the loop above.
10643 	 */
10644 	if (lastadp != NULL &&
10645 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10646 		for (i = lastadp->ad_offset; i >= 0; i--)
10647 			if (dp->di_db[i] != 0)
10648 				break;
10649 		dp->di_size = (i + 1) * fs->fs_bsize;
10650 	}
10651 	/*
10652 	 * The only dependencies are for indirect blocks.
10653 	 *
10654 	 * The file size for indirect block additions is not guaranteed.
10655 	 * Such a guarantee would be non-trivial to achieve. The conventional
10656 	 * synchronous write implementation also does not make this guarantee.
10657 	 * Fsck should catch and fix discrepancies. Arguably, the file size
10658 	 * can be over-estimated without destroying integrity when the file
10659 	 * moves into the indirect blocks (i.e., is large). If we want to
10660 	 * postpone fsck, we are stuck with this argument.
10661 	 */
10662 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10663 		dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10664 	ffs_update_dinode_ckhash(fs, dp);
10665 }
10666 
10667 /*
10668  * Cancel an indirdep as a result of truncation.  Release all of the
10669  * children allocindirs and place their journal work on the appropriate
10670  * list.
10671  */
10672 static void
10673 cancel_indirdep(indirdep, bp, freeblks)
10674 	struct indirdep *indirdep;
10675 	struct buf *bp;
10676 	struct freeblks *freeblks;
10677 {
10678 	struct allocindir *aip;
10679 
10680 	/*
10681 	 * None of the indirect pointers will ever be visible,
10682 	 * so they can simply be tossed. GOINGAWAY ensures
10683 	 * that allocated pointers will be saved in the buffer
10684 	 * cache until they are freed. Note that they will
10685 	 * only be able to be found by their physical address
10686 	 * since the inode mapping the logical address will
10687 	 * be gone. The save buffer used for the safe copy
10688 	 * was allocated in setup_allocindir_phase2 using
10689 	 * the physical address so it could be used for this
10690 	 * purpose. Hence we swap the safe copy with the real
10691 	 * copy, allowing the safe copy to be freed and holding
10692 	 * on to the real copy for later use in indir_trunc.
10693 	 */
10694 	if (indirdep->ir_state & GOINGAWAY)
10695 		panic("cancel_indirdep: already gone");
10696 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
10697 		indirdep->ir_state |= DEPCOMPLETE;
10698 		LIST_REMOVE(indirdep, ir_next);
10699 	}
10700 	indirdep->ir_state |= GOINGAWAY;
10701 	/*
10702 	 * Pass in bp for blocks still have journal writes
10703 	 * pending so we can cancel them on their own.
10704 	 */
10705 	while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != NULL)
10706 		cancel_allocindir(aip, bp, freeblks, 0);
10707 	while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL)
10708 		cancel_allocindir(aip, NULL, freeblks, 0);
10709 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL)
10710 		cancel_allocindir(aip, NULL, freeblks, 0);
10711 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL)
10712 		cancel_allocindir(aip, NULL, freeblks, 0);
10713 	/*
10714 	 * If there are pending partial truncations we need to keep the
10715 	 * old block copy around until they complete.  This is because
10716 	 * the current b_data is not a perfect superset of the available
10717 	 * blocks.
10718 	 */
10719 	if (TAILQ_EMPTY(&indirdep->ir_trunc))
10720 		bcopy(bp->b_data, indirdep->ir_savebp->b_data, bp->b_bcount);
10721 	else
10722 		bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10723 	WORKLIST_REMOVE(&indirdep->ir_list);
10724 	WORKLIST_INSERT(&indirdep->ir_savebp->b_dep, &indirdep->ir_list);
10725 	indirdep->ir_bp = NULL;
10726 	indirdep->ir_freeblks = freeblks;
10727 }
10728 
10729 /*
10730  * Free an indirdep once it no longer has new pointers to track.
10731  */
10732 static void
10733 free_indirdep(indirdep)
10734 	struct indirdep *indirdep;
10735 {
10736 
10737 	KASSERT(TAILQ_EMPTY(&indirdep->ir_trunc),
10738 	    ("free_indirdep: Indir trunc list not empty."));
10739 	KASSERT(LIST_EMPTY(&indirdep->ir_completehd),
10740 	    ("free_indirdep: Complete head not empty."));
10741 	KASSERT(LIST_EMPTY(&indirdep->ir_writehd),
10742 	    ("free_indirdep: write head not empty."));
10743 	KASSERT(LIST_EMPTY(&indirdep->ir_donehd),
10744 	    ("free_indirdep: done head not empty."));
10745 	KASSERT(LIST_EMPTY(&indirdep->ir_deplisthd),
10746 	    ("free_indirdep: deplist head not empty."));
10747 	KASSERT((indirdep->ir_state & DEPCOMPLETE),
10748 	    ("free_indirdep: %p still on newblk list.", indirdep));
10749 	KASSERT(indirdep->ir_saveddata == NULL,
10750 	    ("free_indirdep: %p still has saved data.", indirdep));
10751 	KASSERT(indirdep->ir_savebp == NULL,
10752 	    ("free_indirdep: %p still has savebp buffer.", indirdep));
10753 	if (indirdep->ir_state & ONWORKLIST)
10754 		WORKLIST_REMOVE(&indirdep->ir_list);
10755 	WORKITEM_FREE(indirdep, D_INDIRDEP);
10756 }
10757 
10758 /*
10759  * Called before a write to an indirdep.  This routine is responsible for
10760  * rolling back pointers to a safe state which includes only those
10761  * allocindirs which have been completed.
10762  */
10763 static void
10764 initiate_write_indirdep(indirdep, bp)
10765 	struct indirdep *indirdep;
10766 	struct buf *bp;
10767 {
10768 	struct ufsmount *ump;
10769 
10770 	indirdep->ir_state |= IOSTARTED;
10771 	if (indirdep->ir_state & GOINGAWAY)
10772 		panic("disk_io_initiation: indirdep gone");
10773 	/*
10774 	 * If there are no remaining dependencies, this will be writing
10775 	 * the real pointers.
10776 	 */
10777 	if (LIST_EMPTY(&indirdep->ir_deplisthd) &&
10778 	    TAILQ_EMPTY(&indirdep->ir_trunc))
10779 		return;
10780 	/*
10781 	 * Replace up-to-date version with safe version.
10782 	 */
10783 	if (indirdep->ir_saveddata == NULL) {
10784 		ump = VFSTOUFS(indirdep->ir_list.wk_mp);
10785 		LOCK_OWNED(ump);
10786 		FREE_LOCK(ump);
10787 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
10788 		    M_SOFTDEP_FLAGS);
10789 		ACQUIRE_LOCK(ump);
10790 	}
10791 	indirdep->ir_state &= ~ATTACHED;
10792 	indirdep->ir_state |= UNDONE;
10793 	bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10794 	bcopy(indirdep->ir_savebp->b_data, bp->b_data,
10795 	    bp->b_bcount);
10796 }
10797 
10798 /*
10799  * Called when an inode has been cleared in a cg bitmap.  This finally
10800  * eliminates any canceled jaddrefs
10801  */
10802 void
10803 softdep_setup_inofree(mp, bp, ino, wkhd)
10804 	struct mount *mp;
10805 	struct buf *bp;
10806 	ino_t ino;
10807 	struct workhead *wkhd;
10808 {
10809 	struct worklist *wk, *wkn;
10810 	struct inodedep *inodedep;
10811 	struct ufsmount *ump;
10812 	uint8_t *inosused;
10813 	struct cg *cgp;
10814 	struct fs *fs;
10815 
10816 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
10817 	    ("softdep_setup_inofree called on non-softdep filesystem"));
10818 	ump = VFSTOUFS(mp);
10819 	ACQUIRE_LOCK(ump);
10820 	fs = ump->um_fs;
10821 	cgp = (struct cg *)bp->b_data;
10822 	inosused = cg_inosused(cgp);
10823 	if (isset(inosused, ino % fs->fs_ipg))
10824 		panic("softdep_setup_inofree: inode %ju not freed.",
10825 		    (uintmax_t)ino);
10826 	if (inodedep_lookup(mp, ino, 0, &inodedep))
10827 		panic("softdep_setup_inofree: ino %ju has existing inodedep %p",
10828 		    (uintmax_t)ino, inodedep);
10829 	if (wkhd) {
10830 		LIST_FOREACH_SAFE(wk, wkhd, wk_list, wkn) {
10831 			if (wk->wk_type != D_JADDREF)
10832 				continue;
10833 			WORKLIST_REMOVE(wk);
10834 			/*
10835 			 * We can free immediately even if the jaddref
10836 			 * isn't attached in a background write as now
10837 			 * the bitmaps are reconciled.
10838 			 */
10839 			wk->wk_state |= COMPLETE | ATTACHED;
10840 			free_jaddref(WK_JADDREF(wk));
10841 		}
10842 		jwork_move(&bp->b_dep, wkhd);
10843 	}
10844 	FREE_LOCK(ump);
10845 }
10846 
10847 /*
10848  * Called via ffs_blkfree() after a set of frags has been cleared from a cg
10849  * map.  Any dependencies waiting for the write to clear are added to the
10850  * buf's list and any jnewblks that are being canceled are discarded
10851  * immediately.
10852  */
10853 void
10854 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
10855 	struct mount *mp;
10856 	struct buf *bp;
10857 	ufs2_daddr_t blkno;
10858 	int frags;
10859 	struct workhead *wkhd;
10860 {
10861 	struct bmsafemap *bmsafemap;
10862 	struct jnewblk *jnewblk;
10863 	struct ufsmount *ump;
10864 	struct worklist *wk;
10865 	struct fs *fs;
10866 #ifdef INVARIANTS
10867 	uint8_t *blksfree;
10868 	struct cg *cgp;
10869 	ufs2_daddr_t jstart;
10870 	ufs2_daddr_t jend;
10871 	ufs2_daddr_t end;
10872 	long bno;
10873 	int i;
10874 #endif
10875 
10876 	CTR3(KTR_SUJ,
10877 	    "softdep_setup_blkfree: blkno %jd frags %d wk head %p",
10878 	    blkno, frags, wkhd);
10879 
10880 	ump = VFSTOUFS(mp);
10881 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
10882 	    ("softdep_setup_blkfree called on non-softdep filesystem"));
10883 	ACQUIRE_LOCK(ump);
10884 	/* Lookup the bmsafemap so we track when it is dirty. */
10885 	fs = ump->um_fs;
10886 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10887 	/*
10888 	 * Detach any jnewblks which have been canceled.  They must linger
10889 	 * until the bitmap is cleared again by ffs_blkfree() to prevent
10890 	 * an unjournaled allocation from hitting the disk.
10891 	 */
10892 	if (wkhd) {
10893 		while ((wk = LIST_FIRST(wkhd)) != NULL) {
10894 			CTR2(KTR_SUJ,
10895 			    "softdep_setup_blkfree: blkno %jd wk type %d",
10896 			    blkno, wk->wk_type);
10897 			WORKLIST_REMOVE(wk);
10898 			if (wk->wk_type != D_JNEWBLK) {
10899 				WORKLIST_INSERT(&bmsafemap->sm_freehd, wk);
10900 				continue;
10901 			}
10902 			jnewblk = WK_JNEWBLK(wk);
10903 			KASSERT(jnewblk->jn_state & GOINGAWAY,
10904 			    ("softdep_setup_blkfree: jnewblk not canceled."));
10905 #ifdef INVARIANTS
10906 			/*
10907 			 * Assert that this block is free in the bitmap
10908 			 * before we discard the jnewblk.
10909 			 */
10910 			cgp = (struct cg *)bp->b_data;
10911 			blksfree = cg_blksfree(cgp);
10912 			bno = dtogd(fs, jnewblk->jn_blkno);
10913 			for (i = jnewblk->jn_oldfrags;
10914 			    i < jnewblk->jn_frags; i++) {
10915 				if (isset(blksfree, bno + i))
10916 					continue;
10917 				panic("softdep_setup_blkfree: not free");
10918 			}
10919 #endif
10920 			/*
10921 			 * Even if it's not attached we can free immediately
10922 			 * as the new bitmap is correct.
10923 			 */
10924 			wk->wk_state |= COMPLETE | ATTACHED;
10925 			free_jnewblk(jnewblk);
10926 		}
10927 	}
10928 
10929 #ifdef INVARIANTS
10930 	/*
10931 	 * Assert that we are not freeing a block which has an outstanding
10932 	 * allocation dependency.
10933 	 */
10934 	fs = VFSTOUFS(mp)->um_fs;
10935 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10936 	end = blkno + frags;
10937 	LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
10938 		/*
10939 		 * Don't match against blocks that will be freed when the
10940 		 * background write is done.
10941 		 */
10942 		if ((jnewblk->jn_state & (ATTACHED | COMPLETE | DEPCOMPLETE)) ==
10943 		    (COMPLETE | DEPCOMPLETE))
10944 			continue;
10945 		jstart = jnewblk->jn_blkno + jnewblk->jn_oldfrags;
10946 		jend = jnewblk->jn_blkno + jnewblk->jn_frags;
10947 		if ((blkno >= jstart && blkno < jend) ||
10948 		    (end > jstart && end <= jend)) {
10949 			printf("state 0x%X %jd - %d %d dep %p\n",
10950 			    jnewblk->jn_state, jnewblk->jn_blkno,
10951 			    jnewblk->jn_oldfrags, jnewblk->jn_frags,
10952 			    jnewblk->jn_dep);
10953 			panic("softdep_setup_blkfree: "
10954 			    "%jd-%jd(%d) overlaps with %jd-%jd",
10955 			    blkno, end, frags, jstart, jend);
10956 		}
10957 	}
10958 #endif
10959 	FREE_LOCK(ump);
10960 }
10961 
10962 /*
10963  * Revert a block allocation when the journal record that describes it
10964  * is not yet written.
10965  */
10966 static int
10967 jnewblk_rollback(jnewblk, fs, cgp, blksfree)
10968 	struct jnewblk *jnewblk;
10969 	struct fs *fs;
10970 	struct cg *cgp;
10971 	uint8_t *blksfree;
10972 {
10973 	ufs1_daddr_t fragno;
10974 	long cgbno, bbase;
10975 	int frags, blk;
10976 	int i;
10977 
10978 	frags = 0;
10979 	cgbno = dtogd(fs, jnewblk->jn_blkno);
10980 	/*
10981 	 * We have to test which frags need to be rolled back.  We may
10982 	 * be operating on a stale copy when doing background writes.
10983 	 */
10984 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++)
10985 		if (isclr(blksfree, cgbno + i))
10986 			frags++;
10987 	if (frags == 0)
10988 		return (0);
10989 	/*
10990 	 * This is mostly ffs_blkfree() sans some validation and
10991 	 * superblock updates.
10992 	 */
10993 	if (frags == fs->fs_frag) {
10994 		fragno = fragstoblks(fs, cgbno);
10995 		ffs_setblock(fs, blksfree, fragno);
10996 		ffs_clusteracct(fs, cgp, fragno, 1);
10997 		cgp->cg_cs.cs_nbfree++;
10998 	} else {
10999 		cgbno += jnewblk->jn_oldfrags;
11000 		bbase = cgbno - fragnum(fs, cgbno);
11001 		/* Decrement the old frags.  */
11002 		blk = blkmap(fs, blksfree, bbase);
11003 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
11004 		/* Deallocate the fragment */
11005 		for (i = 0; i < frags; i++)
11006 			setbit(blksfree, cgbno + i);
11007 		cgp->cg_cs.cs_nffree += frags;
11008 		/* Add back in counts associated with the new frags */
11009 		blk = blkmap(fs, blksfree, bbase);
11010 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
11011 		/* If a complete block has been reassembled, account for it. */
11012 		fragno = fragstoblks(fs, bbase);
11013 		if (ffs_isblock(fs, blksfree, fragno)) {
11014 			cgp->cg_cs.cs_nffree -= fs->fs_frag;
11015 			ffs_clusteracct(fs, cgp, fragno, 1);
11016 			cgp->cg_cs.cs_nbfree++;
11017 		}
11018 	}
11019 	stat_jnewblk++;
11020 	jnewblk->jn_state &= ~ATTACHED;
11021 	jnewblk->jn_state |= UNDONE;
11022 
11023 	return (frags);
11024 }
11025 
11026 static void
11027 initiate_write_bmsafemap(bmsafemap, bp)
11028 	struct bmsafemap *bmsafemap;
11029 	struct buf *bp;			/* The cg block. */
11030 {
11031 	struct jaddref *jaddref;
11032 	struct jnewblk *jnewblk;
11033 	uint8_t *inosused;
11034 	uint8_t *blksfree;
11035 	struct cg *cgp;
11036 	struct fs *fs;
11037 	ino_t ino;
11038 
11039 	/*
11040 	 * If this is a background write, we did this at the time that
11041 	 * the copy was made, so do not need to do it again.
11042 	 */
11043 	if (bmsafemap->sm_state & IOSTARTED)
11044 		return;
11045 	bmsafemap->sm_state |= IOSTARTED;
11046 	/*
11047 	 * Clear any inode allocations which are pending journal writes.
11048 	 */
11049 	if (LIST_FIRST(&bmsafemap->sm_jaddrefhd) != NULL) {
11050 		cgp = (struct cg *)bp->b_data;
11051 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11052 		inosused = cg_inosused(cgp);
11053 		LIST_FOREACH(jaddref, &bmsafemap->sm_jaddrefhd, ja_bmdeps) {
11054 			ino = jaddref->ja_ino % fs->fs_ipg;
11055 			if (isset(inosused, ino)) {
11056 				if ((jaddref->ja_mode & IFMT) == IFDIR)
11057 					cgp->cg_cs.cs_ndir--;
11058 				cgp->cg_cs.cs_nifree++;
11059 				clrbit(inosused, ino);
11060 				jaddref->ja_state &= ~ATTACHED;
11061 				jaddref->ja_state |= UNDONE;
11062 				stat_jaddref++;
11063 			} else
11064 				panic("initiate_write_bmsafemap: inode %ju "
11065 				    "marked free", (uintmax_t)jaddref->ja_ino);
11066 		}
11067 	}
11068 	/*
11069 	 * Clear any block allocations which are pending journal writes.
11070 	 */
11071 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
11072 		cgp = (struct cg *)bp->b_data;
11073 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11074 		blksfree = cg_blksfree(cgp);
11075 		LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
11076 			if (jnewblk_rollback(jnewblk, fs, cgp, blksfree))
11077 				continue;
11078 			panic("initiate_write_bmsafemap: block %jd "
11079 			    "marked free", jnewblk->jn_blkno);
11080 		}
11081 	}
11082 	/*
11083 	 * Move allocation lists to the written lists so they can be
11084 	 * cleared once the block write is complete.
11085 	 */
11086 	LIST_SWAP(&bmsafemap->sm_inodedephd, &bmsafemap->sm_inodedepwr,
11087 	    inodedep, id_deps);
11088 	LIST_SWAP(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
11089 	    newblk, nb_deps);
11090 	LIST_SWAP(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr, worklist,
11091 	    wk_list);
11092 }
11093 
11094 /*
11095  * This routine is called during the completion interrupt
11096  * service routine for a disk write (from the procedure called
11097  * by the device driver to inform the filesystem caches of
11098  * a request completion).  It should be called early in this
11099  * procedure, before the block is made available to other
11100  * processes or other routines are called.
11101  *
11102  */
11103 static void
11104 softdep_disk_write_complete(bp)
11105 	struct buf *bp;		/* describes the completed disk write */
11106 {
11107 	struct worklist *wk;
11108 	struct worklist *owk;
11109 	struct ufsmount *ump;
11110 	struct workhead reattach;
11111 	struct freeblks *freeblks;
11112 	struct buf *sbp;
11113 
11114 	ump = softdep_bp_to_mp(bp);
11115 	KASSERT(LIST_EMPTY(&bp->b_dep) || ump != NULL,
11116 	    ("softdep_disk_write_complete: softdep_bp_to_mp returned NULL "
11117 	     "with outstanding dependencies for buffer %p", bp));
11118 	if (ump == NULL)
11119 		return;
11120 	/*
11121 	 * If an error occurred while doing the write, then the data
11122 	 * has not hit the disk and the dependencies cannot be processed.
11123 	 * But we do have to go through and roll forward any dependencies
11124 	 * that were rolled back before the disk write.
11125 	 */
11126 	sbp = NULL;
11127 	ACQUIRE_LOCK(ump);
11128 	if ((bp->b_ioflags & BIO_ERROR) != 0 && (bp->b_flags & B_INVAL) == 0) {
11129 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
11130 			switch (wk->wk_type) {
11131 
11132 			case D_PAGEDEP:
11133 				handle_written_filepage(WK_PAGEDEP(wk), bp, 0);
11134 				continue;
11135 
11136 			case D_INODEDEP:
11137 				handle_written_inodeblock(WK_INODEDEP(wk),
11138 				    bp, 0);
11139 				continue;
11140 
11141 			case D_BMSAFEMAP:
11142 				handle_written_bmsafemap(WK_BMSAFEMAP(wk),
11143 				    bp, 0);
11144 				continue;
11145 
11146 			case D_INDIRDEP:
11147 				handle_written_indirdep(WK_INDIRDEP(wk),
11148 				    bp, &sbp, 0);
11149 				continue;
11150 			default:
11151 				/* nothing to roll forward */
11152 				continue;
11153 			}
11154 		}
11155 		FREE_LOCK(ump);
11156 		if (sbp)
11157 			brelse(sbp);
11158 		return;
11159 	}
11160 	LIST_INIT(&reattach);
11161 
11162 	/*
11163 	 * Ump SU lock must not be released anywhere in this code segment.
11164 	 */
11165 	owk = NULL;
11166 	while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
11167 		WORKLIST_REMOVE(wk);
11168 		atomic_add_long(&dep_write[wk->wk_type], 1);
11169 		if (wk == owk)
11170 			panic("duplicate worklist: %p\n", wk);
11171 		owk = wk;
11172 		switch (wk->wk_type) {
11173 
11174 		case D_PAGEDEP:
11175 			if (handle_written_filepage(WK_PAGEDEP(wk), bp,
11176 			    WRITESUCCEEDED))
11177 				WORKLIST_INSERT(&reattach, wk);
11178 			continue;
11179 
11180 		case D_INODEDEP:
11181 			if (handle_written_inodeblock(WK_INODEDEP(wk), bp,
11182 			    WRITESUCCEEDED))
11183 				WORKLIST_INSERT(&reattach, wk);
11184 			continue;
11185 
11186 		case D_BMSAFEMAP:
11187 			if (handle_written_bmsafemap(WK_BMSAFEMAP(wk), bp,
11188 			    WRITESUCCEEDED))
11189 				WORKLIST_INSERT(&reattach, wk);
11190 			continue;
11191 
11192 		case D_MKDIR:
11193 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
11194 			continue;
11195 
11196 		case D_ALLOCDIRECT:
11197 			wk->wk_state |= COMPLETE;
11198 			handle_allocdirect_partdone(WK_ALLOCDIRECT(wk), NULL);
11199 			continue;
11200 
11201 		case D_ALLOCINDIR:
11202 			wk->wk_state |= COMPLETE;
11203 			handle_allocindir_partdone(WK_ALLOCINDIR(wk));
11204 			continue;
11205 
11206 		case D_INDIRDEP:
11207 			if (handle_written_indirdep(WK_INDIRDEP(wk), bp, &sbp,
11208 			    WRITESUCCEEDED))
11209 				WORKLIST_INSERT(&reattach, wk);
11210 			continue;
11211 
11212 		case D_FREEBLKS:
11213 			wk->wk_state |= COMPLETE;
11214 			freeblks = WK_FREEBLKS(wk);
11215 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE &&
11216 			    LIST_EMPTY(&freeblks->fb_jblkdephd))
11217 				add_to_worklist(wk, WK_NODELAY);
11218 			continue;
11219 
11220 		case D_FREEWORK:
11221 			handle_written_freework(WK_FREEWORK(wk));
11222 			break;
11223 
11224 		case D_JSEGDEP:
11225 			free_jsegdep(WK_JSEGDEP(wk));
11226 			continue;
11227 
11228 		case D_JSEG:
11229 			handle_written_jseg(WK_JSEG(wk), bp);
11230 			continue;
11231 
11232 		case D_SBDEP:
11233 			if (handle_written_sbdep(WK_SBDEP(wk), bp))
11234 				WORKLIST_INSERT(&reattach, wk);
11235 			continue;
11236 
11237 		case D_FREEDEP:
11238 			free_freedep(WK_FREEDEP(wk));
11239 			continue;
11240 
11241 		default:
11242 			panic("handle_disk_write_complete: Unknown type %s",
11243 			    TYPENAME(wk->wk_type));
11244 			/* NOTREACHED */
11245 		}
11246 	}
11247 	/*
11248 	 * Reattach any requests that must be redone.
11249 	 */
11250 	while ((wk = LIST_FIRST(&reattach)) != NULL) {
11251 		WORKLIST_REMOVE(wk);
11252 		WORKLIST_INSERT(&bp->b_dep, wk);
11253 	}
11254 	FREE_LOCK(ump);
11255 	if (sbp)
11256 		brelse(sbp);
11257 }
11258 
11259 /*
11260  * Called from within softdep_disk_write_complete above.
11261  */
11262 static void
11263 handle_allocdirect_partdone(adp, wkhd)
11264 	struct allocdirect *adp;	/* the completed allocdirect */
11265 	struct workhead *wkhd;		/* Work to do when inode is writtne. */
11266 {
11267 	struct allocdirectlst *listhead;
11268 	struct allocdirect *listadp;
11269 	struct inodedep *inodedep;
11270 	long bsize;
11271 
11272 	LOCK_OWNED(VFSTOUFS(adp->ad_block.nb_list.wk_mp));
11273 	if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11274 		return;
11275 	/*
11276 	 * The on-disk inode cannot claim to be any larger than the last
11277 	 * fragment that has been written. Otherwise, the on-disk inode
11278 	 * might have fragments that were not the last block in the file
11279 	 * which would corrupt the filesystem. Thus, we cannot free any
11280 	 * allocdirects after one whose ad_oldblkno claims a fragment as
11281 	 * these blocks must be rolled back to zero before writing the inode.
11282 	 * We check the currently active set of allocdirects in id_inoupdt
11283 	 * or id_extupdt as appropriate.
11284 	 */
11285 	inodedep = adp->ad_inodedep;
11286 	bsize = inodedep->id_fs->fs_bsize;
11287 	if (adp->ad_state & EXTDATA)
11288 		listhead = &inodedep->id_extupdt;
11289 	else
11290 		listhead = &inodedep->id_inoupdt;
11291 	TAILQ_FOREACH(listadp, listhead, ad_next) {
11292 		/* found our block */
11293 		if (listadp == adp)
11294 			break;
11295 		/* continue if ad_oldlbn is not a fragment */
11296 		if (listadp->ad_oldsize == 0 ||
11297 		    listadp->ad_oldsize == bsize)
11298 			continue;
11299 		/* hit a fragment */
11300 		return;
11301 	}
11302 	/*
11303 	 * If we have reached the end of the current list without
11304 	 * finding the just finished dependency, then it must be
11305 	 * on the future dependency list. Future dependencies cannot
11306 	 * be freed until they are moved to the current list.
11307 	 */
11308 	if (listadp == NULL) {
11309 #ifdef INVARIANTS
11310 		if (adp->ad_state & EXTDATA)
11311 			listhead = &inodedep->id_newextupdt;
11312 		else
11313 			listhead = &inodedep->id_newinoupdt;
11314 		TAILQ_FOREACH(listadp, listhead, ad_next)
11315 			/* found our block */
11316 			if (listadp == adp)
11317 				break;
11318 		if (listadp == NULL)
11319 			panic("handle_allocdirect_partdone: lost dep");
11320 #endif /* INVARIANTS */
11321 		return;
11322 	}
11323 	/*
11324 	 * If we have found the just finished dependency, then queue
11325 	 * it along with anything that follows it that is complete.
11326 	 * Since the pointer has not yet been written in the inode
11327 	 * as the dependency prevents it, place the allocdirect on the
11328 	 * bufwait list where it will be freed once the pointer is
11329 	 * valid.
11330 	 */
11331 	if (wkhd == NULL)
11332 		wkhd = &inodedep->id_bufwait;
11333 	for (; adp; adp = listadp) {
11334 		listadp = TAILQ_NEXT(adp, ad_next);
11335 		if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11336 			return;
11337 		TAILQ_REMOVE(listhead, adp, ad_next);
11338 		WORKLIST_INSERT(wkhd, &adp->ad_block.nb_list);
11339 	}
11340 }
11341 
11342 /*
11343  * Called from within softdep_disk_write_complete above.  This routine
11344  * completes successfully written allocindirs.
11345  */
11346 static void
11347 handle_allocindir_partdone(aip)
11348 	struct allocindir *aip;		/* the completed allocindir */
11349 {
11350 	struct indirdep *indirdep;
11351 
11352 	if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
11353 		return;
11354 	indirdep = aip->ai_indirdep;
11355 	LIST_REMOVE(aip, ai_next);
11356 	/*
11357 	 * Don't set a pointer while the buffer is undergoing IO or while
11358 	 * we have active truncations.
11359 	 */
11360 	if (indirdep->ir_state & UNDONE || !TAILQ_EMPTY(&indirdep->ir_trunc)) {
11361 		LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
11362 		return;
11363 	}
11364 	if (indirdep->ir_state & UFS1FMT)
11365 		((ufs1_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11366 		    aip->ai_newblkno;
11367 	else
11368 		((ufs2_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11369 		    aip->ai_newblkno;
11370 	/*
11371 	 * Await the pointer write before freeing the allocindir.
11372 	 */
11373 	LIST_INSERT_HEAD(&indirdep->ir_writehd, aip, ai_next);
11374 }
11375 
11376 /*
11377  * Release segments held on a jwork list.
11378  */
11379 static void
11380 handle_jwork(wkhd)
11381 	struct workhead *wkhd;
11382 {
11383 	struct worklist *wk;
11384 
11385 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
11386 		WORKLIST_REMOVE(wk);
11387 		switch (wk->wk_type) {
11388 		case D_JSEGDEP:
11389 			free_jsegdep(WK_JSEGDEP(wk));
11390 			continue;
11391 		case D_FREEDEP:
11392 			free_freedep(WK_FREEDEP(wk));
11393 			continue;
11394 		case D_FREEFRAG:
11395 			rele_jseg(WK_JSEG(WK_FREEFRAG(wk)->ff_jdep));
11396 			WORKITEM_FREE(wk, D_FREEFRAG);
11397 			continue;
11398 		case D_FREEWORK:
11399 			handle_written_freework(WK_FREEWORK(wk));
11400 			continue;
11401 		default:
11402 			panic("handle_jwork: Unknown type %s\n",
11403 			    TYPENAME(wk->wk_type));
11404 		}
11405 	}
11406 }
11407 
11408 /*
11409  * Handle the bufwait list on an inode when it is safe to release items
11410  * held there.  This normally happens after an inode block is written but
11411  * may be delayed and handled later if there are pending journal items that
11412  * are not yet safe to be released.
11413  */
11414 static struct freefile *
11415 handle_bufwait(inodedep, refhd)
11416 	struct inodedep *inodedep;
11417 	struct workhead *refhd;
11418 {
11419 	struct jaddref *jaddref;
11420 	struct freefile *freefile;
11421 	struct worklist *wk;
11422 
11423 	freefile = NULL;
11424 	while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
11425 		WORKLIST_REMOVE(wk);
11426 		switch (wk->wk_type) {
11427 		case D_FREEFILE:
11428 			/*
11429 			 * We defer adding freefile to the worklist
11430 			 * until all other additions have been made to
11431 			 * ensure that it will be done after all the
11432 			 * old blocks have been freed.
11433 			 */
11434 			if (freefile != NULL)
11435 				panic("handle_bufwait: freefile");
11436 			freefile = WK_FREEFILE(wk);
11437 			continue;
11438 
11439 		case D_MKDIR:
11440 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
11441 			continue;
11442 
11443 		case D_DIRADD:
11444 			diradd_inode_written(WK_DIRADD(wk), inodedep);
11445 			continue;
11446 
11447 		case D_FREEFRAG:
11448 			wk->wk_state |= COMPLETE;
11449 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE)
11450 				add_to_worklist(wk, 0);
11451 			continue;
11452 
11453 		case D_DIRREM:
11454 			wk->wk_state |= COMPLETE;
11455 			add_to_worklist(wk, 0);
11456 			continue;
11457 
11458 		case D_ALLOCDIRECT:
11459 		case D_ALLOCINDIR:
11460 			free_newblk(WK_NEWBLK(wk));
11461 			continue;
11462 
11463 		case D_JNEWBLK:
11464 			wk->wk_state |= COMPLETE;
11465 			free_jnewblk(WK_JNEWBLK(wk));
11466 			continue;
11467 
11468 		/*
11469 		 * Save freed journal segments and add references on
11470 		 * the supplied list which will delay their release
11471 		 * until the cg bitmap is cleared on disk.
11472 		 */
11473 		case D_JSEGDEP:
11474 			if (refhd == NULL)
11475 				free_jsegdep(WK_JSEGDEP(wk));
11476 			else
11477 				WORKLIST_INSERT(refhd, wk);
11478 			continue;
11479 
11480 		case D_JADDREF:
11481 			jaddref = WK_JADDREF(wk);
11482 			TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
11483 			    if_deps);
11484 			/*
11485 			 * Transfer any jaddrefs to the list to be freed with
11486 			 * the bitmap if we're handling a removed file.
11487 			 */
11488 			if (refhd == NULL) {
11489 				wk->wk_state |= COMPLETE;
11490 				free_jaddref(jaddref);
11491 			} else
11492 				WORKLIST_INSERT(refhd, wk);
11493 			continue;
11494 
11495 		default:
11496 			panic("handle_bufwait: Unknown type %p(%s)",
11497 			    wk, TYPENAME(wk->wk_type));
11498 			/* NOTREACHED */
11499 		}
11500 	}
11501 	return (freefile);
11502 }
11503 /*
11504  * Called from within softdep_disk_write_complete above to restore
11505  * in-memory inode block contents to their most up-to-date state. Note
11506  * that this routine is always called from interrupt level with further
11507  * interrupts from this device blocked.
11508  *
11509  * If the write did not succeed, we will do all the roll-forward
11510  * operations, but we will not take the actions that will allow its
11511  * dependencies to be processed.
11512  */
11513 static int
11514 handle_written_inodeblock(inodedep, bp, flags)
11515 	struct inodedep *inodedep;
11516 	struct buf *bp;		/* buffer containing the inode block */
11517 	int flags;
11518 {
11519 	struct freefile *freefile;
11520 	struct allocdirect *adp, *nextadp;
11521 	struct ufs1_dinode *dp1 = NULL;
11522 	struct ufs2_dinode *dp2 = NULL;
11523 	struct workhead wkhd;
11524 	int hadchanges, fstype;
11525 	ino_t freelink;
11526 
11527 	LIST_INIT(&wkhd);
11528 	hadchanges = 0;
11529 	freefile = NULL;
11530 	if ((inodedep->id_state & IOSTARTED) == 0)
11531 		panic("handle_written_inodeblock: not started");
11532 	inodedep->id_state &= ~IOSTARTED;
11533 	if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC) {
11534 		fstype = UFS1;
11535 		dp1 = (struct ufs1_dinode *)bp->b_data +
11536 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11537 		freelink = dp1->di_freelink;
11538 	} else {
11539 		fstype = UFS2;
11540 		dp2 = (struct ufs2_dinode *)bp->b_data +
11541 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11542 		freelink = dp2->di_freelink;
11543 	}
11544 	/*
11545 	 * Leave this inodeblock dirty until it's in the list.
11546 	 */
11547 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) == UNLINKED &&
11548 	    (flags & WRITESUCCEEDED)) {
11549 		struct inodedep *inon;
11550 
11551 		inon = TAILQ_NEXT(inodedep, id_unlinked);
11552 		if ((inon == NULL && freelink == 0) ||
11553 		    (inon && inon->id_ino == freelink)) {
11554 			if (inon)
11555 				inon->id_state |= UNLINKPREV;
11556 			inodedep->id_state |= UNLINKNEXT;
11557 		}
11558 		hadchanges = 1;
11559 	}
11560 	/*
11561 	 * If we had to rollback the inode allocation because of
11562 	 * bitmaps being incomplete, then simply restore it.
11563 	 * Keep the block dirty so that it will not be reclaimed until
11564 	 * all associated dependencies have been cleared and the
11565 	 * corresponding updates written to disk.
11566 	 */
11567 	if (inodedep->id_savedino1 != NULL) {
11568 		hadchanges = 1;
11569 		if (fstype == UFS1)
11570 			*dp1 = *inodedep->id_savedino1;
11571 		else
11572 			*dp2 = *inodedep->id_savedino2;
11573 		free(inodedep->id_savedino1, M_SAVEDINO);
11574 		inodedep->id_savedino1 = NULL;
11575 		if ((bp->b_flags & B_DELWRI) == 0)
11576 			stat_inode_bitmap++;
11577 		bdirty(bp);
11578 		/*
11579 		 * If the inode is clear here and GOINGAWAY it will never
11580 		 * be written.  Process the bufwait and clear any pending
11581 		 * work which may include the freefile.
11582 		 */
11583 		if (inodedep->id_state & GOINGAWAY)
11584 			goto bufwait;
11585 		return (1);
11586 	}
11587 	if (flags & WRITESUCCEEDED)
11588 		inodedep->id_state |= COMPLETE;
11589 	/*
11590 	 * Roll forward anything that had to be rolled back before
11591 	 * the inode could be updated.
11592 	 */
11593 	for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
11594 		nextadp = TAILQ_NEXT(adp, ad_next);
11595 		if (adp->ad_state & ATTACHED)
11596 			panic("handle_written_inodeblock: new entry");
11597 		if (fstype == UFS1) {
11598 			if (adp->ad_offset < UFS_NDADDR) {
11599 				if (dp1->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11600 					panic("%s %s #%jd mismatch %d != %jd",
11601 					    "handle_written_inodeblock:",
11602 					    "direct pointer",
11603 					    (intmax_t)adp->ad_offset,
11604 					    dp1->di_db[adp->ad_offset],
11605 					    (intmax_t)adp->ad_oldblkno);
11606 				dp1->di_db[adp->ad_offset] = adp->ad_newblkno;
11607 			} else {
11608 				if (dp1->di_ib[adp->ad_offset - UFS_NDADDR] !=
11609 				    0)
11610 					panic("%s: %s #%jd allocated as %d",
11611 					    "handle_written_inodeblock",
11612 					    "indirect pointer",
11613 					    (intmax_t)adp->ad_offset -
11614 					    UFS_NDADDR,
11615 					    dp1->di_ib[adp->ad_offset -
11616 					    UFS_NDADDR]);
11617 				dp1->di_ib[adp->ad_offset - UFS_NDADDR] =
11618 				    adp->ad_newblkno;
11619 			}
11620 		} else {
11621 			if (adp->ad_offset < UFS_NDADDR) {
11622 				if (dp2->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11623 					panic("%s: %s #%jd %s %jd != %jd",
11624 					    "handle_written_inodeblock",
11625 					    "direct pointer",
11626 					    (intmax_t)adp->ad_offset, "mismatch",
11627 					    (intmax_t)dp2->di_db[adp->ad_offset],
11628 					    (intmax_t)adp->ad_oldblkno);
11629 				dp2->di_db[adp->ad_offset] = adp->ad_newblkno;
11630 			} else {
11631 				if (dp2->di_ib[adp->ad_offset - UFS_NDADDR] !=
11632 				    0)
11633 					panic("%s: %s #%jd allocated as %jd",
11634 					    "handle_written_inodeblock",
11635 					    "indirect pointer",
11636 					    (intmax_t)adp->ad_offset -
11637 					    UFS_NDADDR,
11638 					    (intmax_t)
11639 					    dp2->di_ib[adp->ad_offset -
11640 					    UFS_NDADDR]);
11641 				dp2->di_ib[adp->ad_offset - UFS_NDADDR] =
11642 				    adp->ad_newblkno;
11643 			}
11644 		}
11645 		adp->ad_state &= ~UNDONE;
11646 		adp->ad_state |= ATTACHED;
11647 		hadchanges = 1;
11648 	}
11649 	for (adp = TAILQ_FIRST(&inodedep->id_extupdt); adp; adp = nextadp) {
11650 		nextadp = TAILQ_NEXT(adp, ad_next);
11651 		if (adp->ad_state & ATTACHED)
11652 			panic("handle_written_inodeblock: new entry");
11653 		if (dp2->di_extb[adp->ad_offset] != adp->ad_oldblkno)
11654 			panic("%s: direct pointers #%jd %s %jd != %jd",
11655 			    "handle_written_inodeblock",
11656 			    (intmax_t)adp->ad_offset, "mismatch",
11657 			    (intmax_t)dp2->di_extb[adp->ad_offset],
11658 			    (intmax_t)adp->ad_oldblkno);
11659 		dp2->di_extb[adp->ad_offset] = adp->ad_newblkno;
11660 		adp->ad_state &= ~UNDONE;
11661 		adp->ad_state |= ATTACHED;
11662 		hadchanges = 1;
11663 	}
11664 	if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
11665 		stat_direct_blk_ptrs++;
11666 	/*
11667 	 * Reset the file size to its most up-to-date value.
11668 	 */
11669 	if (inodedep->id_savedsize == -1 || inodedep->id_savedextsize == -1)
11670 		panic("handle_written_inodeblock: bad size");
11671 	if (inodedep->id_savednlink > UFS_LINK_MAX)
11672 		panic("handle_written_inodeblock: Invalid link count "
11673 		    "%jd for inodedep %p", (uintmax_t)inodedep->id_savednlink,
11674 		    inodedep);
11675 	if (fstype == UFS1) {
11676 		if (dp1->di_nlink != inodedep->id_savednlink) {
11677 			dp1->di_nlink = inodedep->id_savednlink;
11678 			hadchanges = 1;
11679 		}
11680 		if (dp1->di_size != inodedep->id_savedsize) {
11681 			dp1->di_size = inodedep->id_savedsize;
11682 			hadchanges = 1;
11683 		}
11684 	} else {
11685 		if (dp2->di_nlink != inodedep->id_savednlink) {
11686 			dp2->di_nlink = inodedep->id_savednlink;
11687 			hadchanges = 1;
11688 		}
11689 		if (dp2->di_size != inodedep->id_savedsize) {
11690 			dp2->di_size = inodedep->id_savedsize;
11691 			hadchanges = 1;
11692 		}
11693 		if (dp2->di_extsize != inodedep->id_savedextsize) {
11694 			dp2->di_extsize = inodedep->id_savedextsize;
11695 			hadchanges = 1;
11696 		}
11697 	}
11698 	inodedep->id_savedsize = -1;
11699 	inodedep->id_savedextsize = -1;
11700 	inodedep->id_savednlink = -1;
11701 	/*
11702 	 * If there were any rollbacks in the inode block, then it must be
11703 	 * marked dirty so that its will eventually get written back in
11704 	 * its correct form.
11705 	 */
11706 	if (hadchanges) {
11707 		if (fstype == UFS2)
11708 			ffs_update_dinode_ckhash(inodedep->id_fs, dp2);
11709 		bdirty(bp);
11710 	}
11711 bufwait:
11712 	/*
11713 	 * If the write did not succeed, we have done all the roll-forward
11714 	 * operations, but we cannot take the actions that will allow its
11715 	 * dependencies to be processed.
11716 	 */
11717 	if ((flags & WRITESUCCEEDED) == 0)
11718 		return (hadchanges);
11719 	/*
11720 	 * Process any allocdirects that completed during the update.
11721 	 */
11722 	if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
11723 		handle_allocdirect_partdone(adp, &wkhd);
11724 	if ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
11725 		handle_allocdirect_partdone(adp, &wkhd);
11726 	/*
11727 	 * Process deallocations that were held pending until the
11728 	 * inode had been written to disk. Freeing of the inode
11729 	 * is delayed until after all blocks have been freed to
11730 	 * avoid creation of new <vfsid, inum, lbn> triples
11731 	 * before the old ones have been deleted.  Completely
11732 	 * unlinked inodes are not processed until the unlinked
11733 	 * inode list is written or the last reference is removed.
11734 	 */
11735 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) != UNLINKED) {
11736 		freefile = handle_bufwait(inodedep, NULL);
11737 		if (freefile && !LIST_EMPTY(&wkhd)) {
11738 			WORKLIST_INSERT(&wkhd, &freefile->fx_list);
11739 			freefile = NULL;
11740 		}
11741 	}
11742 	/*
11743 	 * Move rolled forward dependency completions to the bufwait list
11744 	 * now that those that were already written have been processed.
11745 	 */
11746 	if (!LIST_EMPTY(&wkhd) && hadchanges == 0)
11747 		panic("handle_written_inodeblock: bufwait but no changes");
11748 	jwork_move(&inodedep->id_bufwait, &wkhd);
11749 
11750 	if (freefile != NULL) {
11751 		/*
11752 		 * If the inode is goingaway it was never written.  Fake up
11753 		 * the state here so free_inodedep() can succeed.
11754 		 */
11755 		if (inodedep->id_state & GOINGAWAY)
11756 			inodedep->id_state |= COMPLETE | DEPCOMPLETE;
11757 		if (free_inodedep(inodedep) == 0)
11758 			panic("handle_written_inodeblock: live inodedep %p",
11759 			    inodedep);
11760 		add_to_worklist(&freefile->fx_list, 0);
11761 		return (0);
11762 	}
11763 
11764 	/*
11765 	 * If no outstanding dependencies, free it.
11766 	 */
11767 	if (free_inodedep(inodedep) ||
11768 	    (TAILQ_FIRST(&inodedep->id_inoreflst) == 0 &&
11769 	     TAILQ_FIRST(&inodedep->id_inoupdt) == 0 &&
11770 	     TAILQ_FIRST(&inodedep->id_extupdt) == 0 &&
11771 	     LIST_FIRST(&inodedep->id_bufwait) == 0))
11772 		return (0);
11773 	return (hadchanges);
11774 }
11775 
11776 /*
11777  * Perform needed roll-forwards and kick off any dependencies that
11778  * can now be processed.
11779  *
11780  * If the write did not succeed, we will do all the roll-forward
11781  * operations, but we will not take the actions that will allow its
11782  * dependencies to be processed.
11783  */
11784 static int
11785 handle_written_indirdep(indirdep, bp, bpp, flags)
11786 	struct indirdep *indirdep;
11787 	struct buf *bp;
11788 	struct buf **bpp;
11789 	int flags;
11790 {
11791 	struct allocindir *aip;
11792 	struct buf *sbp;
11793 	int chgs;
11794 
11795 	if (indirdep->ir_state & GOINGAWAY)
11796 		panic("handle_written_indirdep: indirdep gone");
11797 	if ((indirdep->ir_state & IOSTARTED) == 0)
11798 		panic("handle_written_indirdep: IO not started");
11799 	chgs = 0;
11800 	/*
11801 	 * If there were rollbacks revert them here.
11802 	 */
11803 	if (indirdep->ir_saveddata) {
11804 		bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
11805 		if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11806 			free(indirdep->ir_saveddata, M_INDIRDEP);
11807 			indirdep->ir_saveddata = NULL;
11808 		}
11809 		chgs = 1;
11810 	}
11811 	indirdep->ir_state &= ~(UNDONE | IOSTARTED);
11812 	indirdep->ir_state |= ATTACHED;
11813 	/*
11814 	 * If the write did not succeed, we have done all the roll-forward
11815 	 * operations, but we cannot take the actions that will allow its
11816 	 * dependencies to be processed.
11817 	 */
11818 	if ((flags & WRITESUCCEEDED) == 0) {
11819 		stat_indir_blk_ptrs++;
11820 		bdirty(bp);
11821 		return (1);
11822 	}
11823 	/*
11824 	 * Move allocindirs with written pointers to the completehd if
11825 	 * the indirdep's pointer is not yet written.  Otherwise
11826 	 * free them here.
11827 	 */
11828 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL) {
11829 		LIST_REMOVE(aip, ai_next);
11830 		if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
11831 			LIST_INSERT_HEAD(&indirdep->ir_completehd, aip,
11832 			    ai_next);
11833 			newblk_freefrag(&aip->ai_block);
11834 			continue;
11835 		}
11836 		free_newblk(&aip->ai_block);
11837 	}
11838 	/*
11839 	 * Move allocindirs that have finished dependency processing from
11840 	 * the done list to the write list after updating the pointers.
11841 	 */
11842 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11843 		while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL) {
11844 			handle_allocindir_partdone(aip);
11845 			if (aip == LIST_FIRST(&indirdep->ir_donehd))
11846 				panic("disk_write_complete: not gone");
11847 			chgs = 1;
11848 		}
11849 	}
11850 	/*
11851 	 * Preserve the indirdep if there were any changes or if it is not
11852 	 * yet valid on disk.
11853 	 */
11854 	if (chgs) {
11855 		stat_indir_blk_ptrs++;
11856 		bdirty(bp);
11857 		return (1);
11858 	}
11859 	/*
11860 	 * If there were no changes we can discard the savedbp and detach
11861 	 * ourselves from the buf.  We are only carrying completed pointers
11862 	 * in this case.
11863 	 */
11864 	sbp = indirdep->ir_savebp;
11865 	sbp->b_flags |= B_INVAL | B_NOCACHE;
11866 	indirdep->ir_savebp = NULL;
11867 	indirdep->ir_bp = NULL;
11868 	if (*bpp != NULL)
11869 		panic("handle_written_indirdep: bp already exists.");
11870 	*bpp = sbp;
11871 	/*
11872 	 * The indirdep may not be freed until its parent points at it.
11873 	 */
11874 	if (indirdep->ir_state & DEPCOMPLETE)
11875 		free_indirdep(indirdep);
11876 
11877 	return (0);
11878 }
11879 
11880 /*
11881  * Process a diradd entry after its dependent inode has been written.
11882  */
11883 static void
11884 diradd_inode_written(dap, inodedep)
11885 	struct diradd *dap;
11886 	struct inodedep *inodedep;
11887 {
11888 
11889 	LOCK_OWNED(VFSTOUFS(dap->da_list.wk_mp));
11890 	dap->da_state |= COMPLETE;
11891 	complete_diradd(dap);
11892 	WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
11893 }
11894 
11895 /*
11896  * Returns true if the bmsafemap will have rollbacks when written.  Must only
11897  * be called with the per-filesystem lock and the buf lock on the cg held.
11898  */
11899 static int
11900 bmsafemap_backgroundwrite(bmsafemap, bp)
11901 	struct bmsafemap *bmsafemap;
11902 	struct buf *bp;
11903 {
11904 	int dirty;
11905 
11906 	LOCK_OWNED(VFSTOUFS(bmsafemap->sm_list.wk_mp));
11907 	dirty = !LIST_EMPTY(&bmsafemap->sm_jaddrefhd) |
11908 	    !LIST_EMPTY(&bmsafemap->sm_jnewblkhd);
11909 	/*
11910 	 * If we're initiating a background write we need to process the
11911 	 * rollbacks as they exist now, not as they exist when IO starts.
11912 	 * No other consumers will look at the contents of the shadowed
11913 	 * buf so this is safe to do here.
11914 	 */
11915 	if (bp->b_xflags & BX_BKGRDMARKER)
11916 		initiate_write_bmsafemap(bmsafemap, bp);
11917 
11918 	return (dirty);
11919 }
11920 
11921 /*
11922  * Re-apply an allocation when a cg write is complete.
11923  */
11924 static int
11925 jnewblk_rollforward(jnewblk, fs, cgp, blksfree)
11926 	struct jnewblk *jnewblk;
11927 	struct fs *fs;
11928 	struct cg *cgp;
11929 	uint8_t *blksfree;
11930 {
11931 	ufs1_daddr_t fragno;
11932 	ufs2_daddr_t blkno;
11933 	long cgbno, bbase;
11934 	int frags, blk;
11935 	int i;
11936 
11937 	frags = 0;
11938 	cgbno = dtogd(fs, jnewblk->jn_blkno);
11939 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++) {
11940 		if (isclr(blksfree, cgbno + i))
11941 			panic("jnewblk_rollforward: re-allocated fragment");
11942 		frags++;
11943 	}
11944 	if (frags == fs->fs_frag) {
11945 		blkno = fragstoblks(fs, cgbno);
11946 		ffs_clrblock(fs, blksfree, (long)blkno);
11947 		ffs_clusteracct(fs, cgp, blkno, -1);
11948 		cgp->cg_cs.cs_nbfree--;
11949 	} else {
11950 		bbase = cgbno - fragnum(fs, cgbno);
11951 		cgbno += jnewblk->jn_oldfrags;
11952                 /* If a complete block had been reassembled, account for it. */
11953 		fragno = fragstoblks(fs, bbase);
11954 		if (ffs_isblock(fs, blksfree, fragno)) {
11955 			cgp->cg_cs.cs_nffree += fs->fs_frag;
11956 			ffs_clusteracct(fs, cgp, fragno, -1);
11957 			cgp->cg_cs.cs_nbfree--;
11958 		}
11959 		/* Decrement the old frags.  */
11960 		blk = blkmap(fs, blksfree, bbase);
11961 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
11962 		/* Allocate the fragment */
11963 		for (i = 0; i < frags; i++)
11964 			clrbit(blksfree, cgbno + i);
11965 		cgp->cg_cs.cs_nffree -= frags;
11966 		/* Add back in counts associated with the new frags */
11967 		blk = blkmap(fs, blksfree, bbase);
11968 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
11969 	}
11970 	return (frags);
11971 }
11972 
11973 /*
11974  * Complete a write to a bmsafemap structure.  Roll forward any bitmap
11975  * changes if it's not a background write.  Set all written dependencies
11976  * to DEPCOMPLETE and free the structure if possible.
11977  *
11978  * If the write did not succeed, we will do all the roll-forward
11979  * operations, but we will not take the actions that will allow its
11980  * dependencies to be processed.
11981  */
11982 static int
11983 handle_written_bmsafemap(bmsafemap, bp, flags)
11984 	struct bmsafemap *bmsafemap;
11985 	struct buf *bp;
11986 	int flags;
11987 {
11988 	struct newblk *newblk;
11989 	struct inodedep *inodedep;
11990 	struct jaddref *jaddref, *jatmp;
11991 	struct jnewblk *jnewblk, *jntmp;
11992 	struct ufsmount *ump;
11993 	uint8_t *inosused;
11994 	uint8_t *blksfree;
11995 	struct cg *cgp;
11996 	struct fs *fs;
11997 	ino_t ino;
11998 	int foreground;
11999 	int chgs;
12000 
12001 	if ((bmsafemap->sm_state & IOSTARTED) == 0)
12002 		panic("handle_written_bmsafemap: Not started\n");
12003 	ump = VFSTOUFS(bmsafemap->sm_list.wk_mp);
12004 	chgs = 0;
12005 	bmsafemap->sm_state &= ~IOSTARTED;
12006 	foreground = (bp->b_xflags & BX_BKGRDMARKER) == 0;
12007 	/*
12008 	 * If write was successful, release journal work that was waiting
12009 	 * on the write. Otherwise move the work back.
12010 	 */
12011 	if (flags & WRITESUCCEEDED)
12012 		handle_jwork(&bmsafemap->sm_freewr);
12013 	else
12014 		LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
12015 		    worklist, wk_list);
12016 
12017 	/*
12018 	 * Restore unwritten inode allocation pending jaddref writes.
12019 	 */
12020 	if (!LIST_EMPTY(&bmsafemap->sm_jaddrefhd)) {
12021 		cgp = (struct cg *)bp->b_data;
12022 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
12023 		inosused = cg_inosused(cgp);
12024 		LIST_FOREACH_SAFE(jaddref, &bmsafemap->sm_jaddrefhd,
12025 		    ja_bmdeps, jatmp) {
12026 			if ((jaddref->ja_state & UNDONE) == 0)
12027 				continue;
12028 			ino = jaddref->ja_ino % fs->fs_ipg;
12029 			if (isset(inosused, ino))
12030 				panic("handle_written_bmsafemap: "
12031 				    "re-allocated inode");
12032 			/* Do the roll-forward only if it's a real copy. */
12033 			if (foreground) {
12034 				if ((jaddref->ja_mode & IFMT) == IFDIR)
12035 					cgp->cg_cs.cs_ndir++;
12036 				cgp->cg_cs.cs_nifree--;
12037 				setbit(inosused, ino);
12038 				chgs = 1;
12039 			}
12040 			jaddref->ja_state &= ~UNDONE;
12041 			jaddref->ja_state |= ATTACHED;
12042 			free_jaddref(jaddref);
12043 		}
12044 	}
12045 	/*
12046 	 * Restore any block allocations which are pending journal writes.
12047 	 */
12048 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
12049 		cgp = (struct cg *)bp->b_data;
12050 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
12051 		blksfree = cg_blksfree(cgp);
12052 		LIST_FOREACH_SAFE(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps,
12053 		    jntmp) {
12054 			if ((jnewblk->jn_state & UNDONE) == 0)
12055 				continue;
12056 			/* Do the roll-forward only if it's a real copy. */
12057 			if (foreground &&
12058 			    jnewblk_rollforward(jnewblk, fs, cgp, blksfree))
12059 				chgs = 1;
12060 			jnewblk->jn_state &= ~(UNDONE | NEWBLOCK);
12061 			jnewblk->jn_state |= ATTACHED;
12062 			free_jnewblk(jnewblk);
12063 		}
12064 	}
12065 	/*
12066 	 * If the write did not succeed, we have done all the roll-forward
12067 	 * operations, but we cannot take the actions that will allow its
12068 	 * dependencies to be processed.
12069 	 */
12070 	if ((flags & WRITESUCCEEDED) == 0) {
12071 		LIST_CONCAT(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
12072 		    newblk, nb_deps);
12073 		LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
12074 		    worklist, wk_list);
12075 		if (foreground)
12076 			bdirty(bp);
12077 		return (1);
12078 	}
12079 	while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkwr))) {
12080 		newblk->nb_state |= DEPCOMPLETE;
12081 		newblk->nb_state &= ~ONDEPLIST;
12082 		newblk->nb_bmsafemap = NULL;
12083 		LIST_REMOVE(newblk, nb_deps);
12084 		if (newblk->nb_list.wk_type == D_ALLOCDIRECT)
12085 			handle_allocdirect_partdone(
12086 			    WK_ALLOCDIRECT(&newblk->nb_list), NULL);
12087 		else if (newblk->nb_list.wk_type == D_ALLOCINDIR)
12088 			handle_allocindir_partdone(
12089 			    WK_ALLOCINDIR(&newblk->nb_list));
12090 		else if (newblk->nb_list.wk_type != D_NEWBLK)
12091 			panic("handle_written_bmsafemap: Unexpected type: %s",
12092 			    TYPENAME(newblk->nb_list.wk_type));
12093 	}
12094 	while ((inodedep = LIST_FIRST(&bmsafemap->sm_inodedepwr)) != NULL) {
12095 		inodedep->id_state |= DEPCOMPLETE;
12096 		inodedep->id_state &= ~ONDEPLIST;
12097 		LIST_REMOVE(inodedep, id_deps);
12098 		inodedep->id_bmsafemap = NULL;
12099 	}
12100 	LIST_REMOVE(bmsafemap, sm_next);
12101 	if (chgs == 0 && LIST_EMPTY(&bmsafemap->sm_jaddrefhd) &&
12102 	    LIST_EMPTY(&bmsafemap->sm_jnewblkhd) &&
12103 	    LIST_EMPTY(&bmsafemap->sm_newblkhd) &&
12104 	    LIST_EMPTY(&bmsafemap->sm_inodedephd) &&
12105 	    LIST_EMPTY(&bmsafemap->sm_freehd)) {
12106 		LIST_REMOVE(bmsafemap, sm_hash);
12107 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
12108 		return (0);
12109 	}
12110 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
12111 	if (foreground)
12112 		bdirty(bp);
12113 	return (1);
12114 }
12115 
12116 /*
12117  * Try to free a mkdir dependency.
12118  */
12119 static void
12120 complete_mkdir(mkdir)
12121 	struct mkdir *mkdir;
12122 {
12123 	struct diradd *dap;
12124 
12125 	if ((mkdir->md_state & ALLCOMPLETE) != ALLCOMPLETE)
12126 		return;
12127 	LIST_REMOVE(mkdir, md_mkdirs);
12128 	dap = mkdir->md_diradd;
12129 	dap->da_state &= ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
12130 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0) {
12131 		dap->da_state |= DEPCOMPLETE;
12132 		complete_diradd(dap);
12133 	}
12134 	WORKITEM_FREE(mkdir, D_MKDIR);
12135 }
12136 
12137 /*
12138  * Handle the completion of a mkdir dependency.
12139  */
12140 static void
12141 handle_written_mkdir(mkdir, type)
12142 	struct mkdir *mkdir;
12143 	int type;
12144 {
12145 
12146 	if ((mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY)) != type)
12147 		panic("handle_written_mkdir: bad type");
12148 	mkdir->md_state |= COMPLETE;
12149 	complete_mkdir(mkdir);
12150 }
12151 
12152 static int
12153 free_pagedep(pagedep)
12154 	struct pagedep *pagedep;
12155 {
12156 	int i;
12157 
12158 	if (pagedep->pd_state & NEWBLOCK)
12159 		return (0);
12160 	if (!LIST_EMPTY(&pagedep->pd_dirremhd))
12161 		return (0);
12162 	for (i = 0; i < DAHASHSZ; i++)
12163 		if (!LIST_EMPTY(&pagedep->pd_diraddhd[i]))
12164 			return (0);
12165 	if (!LIST_EMPTY(&pagedep->pd_pendinghd))
12166 		return (0);
12167 	if (!LIST_EMPTY(&pagedep->pd_jmvrefhd))
12168 		return (0);
12169 	if (pagedep->pd_state & ONWORKLIST)
12170 		WORKLIST_REMOVE(&pagedep->pd_list);
12171 	LIST_REMOVE(pagedep, pd_hash);
12172 	WORKITEM_FREE(pagedep, D_PAGEDEP);
12173 
12174 	return (1);
12175 }
12176 
12177 /*
12178  * Called from within softdep_disk_write_complete above.
12179  * A write operation was just completed. Removed inodes can
12180  * now be freed and associated block pointers may be committed.
12181  * Note that this routine is always called from interrupt level
12182  * with further interrupts from this device blocked.
12183  *
12184  * If the write did not succeed, we will do all the roll-forward
12185  * operations, but we will not take the actions that will allow its
12186  * dependencies to be processed.
12187  */
12188 static int
12189 handle_written_filepage(pagedep, bp, flags)
12190 	struct pagedep *pagedep;
12191 	struct buf *bp;		/* buffer containing the written page */
12192 	int flags;
12193 {
12194 	struct dirrem *dirrem;
12195 	struct diradd *dap, *nextdap;
12196 	struct direct *ep;
12197 	int i, chgs;
12198 
12199 	if ((pagedep->pd_state & IOSTARTED) == 0)
12200 		panic("handle_written_filepage: not started");
12201 	pagedep->pd_state &= ~IOSTARTED;
12202 	if ((flags & WRITESUCCEEDED) == 0)
12203 		goto rollforward;
12204 	/*
12205 	 * Process any directory removals that have been committed.
12206 	 */
12207 	while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
12208 		LIST_REMOVE(dirrem, dm_next);
12209 		dirrem->dm_state |= COMPLETE;
12210 		dirrem->dm_dirinum = pagedep->pd_ino;
12211 		KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
12212 		    ("handle_written_filepage: Journal entries not written."));
12213 		add_to_worklist(&dirrem->dm_list, 0);
12214 	}
12215 	/*
12216 	 * Free any directory additions that have been committed.
12217 	 * If it is a newly allocated block, we have to wait until
12218 	 * the on-disk directory inode claims the new block.
12219 	 */
12220 	if ((pagedep->pd_state & NEWBLOCK) == 0)
12221 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
12222 			free_diradd(dap, NULL);
12223 rollforward:
12224 	/*
12225 	 * Uncommitted directory entries must be restored.
12226 	 */
12227 	for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
12228 		for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
12229 		     dap = nextdap) {
12230 			nextdap = LIST_NEXT(dap, da_pdlist);
12231 			if (dap->da_state & ATTACHED)
12232 				panic("handle_written_filepage: attached");
12233 			ep = (struct direct *)
12234 			    ((char *)bp->b_data + dap->da_offset);
12235 			ep->d_ino = dap->da_newinum;
12236 			dap->da_state &= ~UNDONE;
12237 			dap->da_state |= ATTACHED;
12238 			chgs = 1;
12239 			/*
12240 			 * If the inode referenced by the directory has
12241 			 * been written out, then the dependency can be
12242 			 * moved to the pending list.
12243 			 */
12244 			if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
12245 				LIST_REMOVE(dap, da_pdlist);
12246 				LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
12247 				    da_pdlist);
12248 			}
12249 		}
12250 	}
12251 	/*
12252 	 * If there were any rollbacks in the directory, then it must be
12253 	 * marked dirty so that its will eventually get written back in
12254 	 * its correct form.
12255 	 */
12256 	if (chgs || (flags & WRITESUCCEEDED) == 0) {
12257 		if ((bp->b_flags & B_DELWRI) == 0)
12258 			stat_dir_entry++;
12259 		bdirty(bp);
12260 		return (1);
12261 	}
12262 	/*
12263 	 * If we are not waiting for a new directory block to be
12264 	 * claimed by its inode, then the pagedep will be freed.
12265 	 * Otherwise it will remain to track any new entries on
12266 	 * the page in case they are fsync'ed.
12267 	 */
12268 	free_pagedep(pagedep);
12269 	return (0);
12270 }
12271 
12272 /*
12273  * Writing back in-core inode structures.
12274  *
12275  * The filesystem only accesses an inode's contents when it occupies an
12276  * "in-core" inode structure.  These "in-core" structures are separate from
12277  * the page frames used to cache inode blocks.  Only the latter are
12278  * transferred to/from the disk.  So, when the updated contents of the
12279  * "in-core" inode structure are copied to the corresponding in-memory inode
12280  * block, the dependencies are also transferred.  The following procedure is
12281  * called when copying a dirty "in-core" inode to a cached inode block.
12282  */
12283 
12284 /*
12285  * Called when an inode is loaded from disk. If the effective link count
12286  * differed from the actual link count when it was last flushed, then we
12287  * need to ensure that the correct effective link count is put back.
12288  */
12289 void
12290 softdep_load_inodeblock(ip)
12291 	struct inode *ip;	/* the "in_core" copy of the inode */
12292 {
12293 	struct inodedep *inodedep;
12294 	struct ufsmount *ump;
12295 
12296 	ump = ITOUMP(ip);
12297 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
12298 	    ("softdep_load_inodeblock called on non-softdep filesystem"));
12299 	/*
12300 	 * Check for alternate nlink count.
12301 	 */
12302 	ip->i_effnlink = ip->i_nlink;
12303 	ACQUIRE_LOCK(ump);
12304 	if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0) {
12305 		FREE_LOCK(ump);
12306 		return;
12307 	}
12308 	ip->i_effnlink -= inodedep->id_nlinkdelta;
12309 	KASSERT(ip->i_effnlink >= 0,
12310 	    ("softdep_load_inodeblock: negative i_effnlink"));
12311 	FREE_LOCK(ump);
12312 }
12313 
12314 /*
12315  * This routine is called just before the "in-core" inode
12316  * information is to be copied to the in-memory inode block.
12317  * Recall that an inode block contains several inodes. If
12318  * the force flag is set, then the dependencies will be
12319  * cleared so that the update can always be made. Note that
12320  * the buffer is locked when this routine is called, so we
12321  * will never be in the middle of writing the inode block
12322  * to disk.
12323  */
12324 void
12325 softdep_update_inodeblock(ip, bp, waitfor)
12326 	struct inode *ip;	/* the "in_core" copy of the inode */
12327 	struct buf *bp;		/* the buffer containing the inode block */
12328 	int waitfor;		/* nonzero => update must be allowed */
12329 {
12330 	struct inodedep *inodedep;
12331 	struct inoref *inoref;
12332 	struct ufsmount *ump;
12333 	struct worklist *wk;
12334 	struct mount *mp;
12335 	struct buf *ibp;
12336 	struct fs *fs;
12337 	int error;
12338 
12339 	ump = ITOUMP(ip);
12340 	mp = UFSTOVFS(ump);
12341 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
12342 	    ("softdep_update_inodeblock called on non-softdep filesystem"));
12343 	fs = ump->um_fs;
12344 	/*
12345 	 * Preserve the freelink that is on disk.  clear_unlinked_inodedep()
12346 	 * does not have access to the in-core ip so must write directly into
12347 	 * the inode block buffer when setting freelink.
12348 	 */
12349 	if (fs->fs_magic == FS_UFS1_MAGIC)
12350 		DIP_SET(ip, i_freelink, ((struct ufs1_dinode *)bp->b_data +
12351 		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
12352 	else
12353 		DIP_SET(ip, i_freelink, ((struct ufs2_dinode *)bp->b_data +
12354 		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
12355 	/*
12356 	 * If the effective link count is not equal to the actual link
12357 	 * count, then we must track the difference in an inodedep while
12358 	 * the inode is (potentially) tossed out of the cache. Otherwise,
12359 	 * if there is no existing inodedep, then there are no dependencies
12360 	 * to track.
12361 	 */
12362 	ACQUIRE_LOCK(ump);
12363 again:
12364 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12365 		FREE_LOCK(ump);
12366 		if (ip->i_effnlink != ip->i_nlink)
12367 			panic("softdep_update_inodeblock: bad link count");
12368 		return;
12369 	}
12370 	if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink)
12371 		panic("softdep_update_inodeblock: bad delta");
12372 	/*
12373 	 * If we're flushing all dependencies we must also move any waiting
12374 	 * for journal writes onto the bufwait list prior to I/O.
12375 	 */
12376 	if (waitfor) {
12377 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12378 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12379 			    == DEPCOMPLETE) {
12380 				jwait(&inoref->if_list, MNT_WAIT);
12381 				goto again;
12382 			}
12383 		}
12384 	}
12385 	/*
12386 	 * Changes have been initiated. Anything depending on these
12387 	 * changes cannot occur until this inode has been written.
12388 	 */
12389 	inodedep->id_state &= ~COMPLETE;
12390 	if ((inodedep->id_state & ONWORKLIST) == 0)
12391 		WORKLIST_INSERT(&bp->b_dep, &inodedep->id_list);
12392 	/*
12393 	 * Any new dependencies associated with the incore inode must
12394 	 * now be moved to the list associated with the buffer holding
12395 	 * the in-memory copy of the inode. Once merged process any
12396 	 * allocdirects that are completed by the merger.
12397 	 */
12398 	merge_inode_lists(&inodedep->id_newinoupdt, &inodedep->id_inoupdt);
12399 	if (!TAILQ_EMPTY(&inodedep->id_inoupdt))
12400 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt),
12401 		    NULL);
12402 	merge_inode_lists(&inodedep->id_newextupdt, &inodedep->id_extupdt);
12403 	if (!TAILQ_EMPTY(&inodedep->id_extupdt))
12404 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_extupdt),
12405 		    NULL);
12406 	/*
12407 	 * Now that the inode has been pushed into the buffer, the
12408 	 * operations dependent on the inode being written to disk
12409 	 * can be moved to the id_bufwait so that they will be
12410 	 * processed when the buffer I/O completes.
12411 	 */
12412 	while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
12413 		WORKLIST_REMOVE(wk);
12414 		WORKLIST_INSERT(&inodedep->id_bufwait, wk);
12415 	}
12416 	/*
12417 	 * Newly allocated inodes cannot be written until the bitmap
12418 	 * that allocates them have been written (indicated by
12419 	 * DEPCOMPLETE being set in id_state). If we are doing a
12420 	 * forced sync (e.g., an fsync on a file), we force the bitmap
12421 	 * to be written so that the update can be done.
12422 	 */
12423 	if (waitfor == 0) {
12424 		FREE_LOCK(ump);
12425 		return;
12426 	}
12427 retry:
12428 	if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) != 0) {
12429 		FREE_LOCK(ump);
12430 		return;
12431 	}
12432 	ibp = inodedep->id_bmsafemap->sm_buf;
12433 	ibp = getdirtybuf(ibp, LOCK_PTR(ump), MNT_WAIT);
12434 	if (ibp == NULL) {
12435 		/*
12436 		 * If ibp came back as NULL, the dependency could have been
12437 		 * freed while we slept.  Look it up again, and check to see
12438 		 * that it has completed.
12439 		 */
12440 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
12441 			goto retry;
12442 		FREE_LOCK(ump);
12443 		return;
12444 	}
12445 	FREE_LOCK(ump);
12446 	if ((error = bwrite(ibp)) != 0)
12447 		softdep_error("softdep_update_inodeblock: bwrite", error);
12448 }
12449 
12450 /*
12451  * Merge the a new inode dependency list (such as id_newinoupdt) into an
12452  * old inode dependency list (such as id_inoupdt).
12453  */
12454 static void
12455 merge_inode_lists(newlisthead, oldlisthead)
12456 	struct allocdirectlst *newlisthead;
12457 	struct allocdirectlst *oldlisthead;
12458 {
12459 	struct allocdirect *listadp, *newadp;
12460 
12461 	newadp = TAILQ_FIRST(newlisthead);
12462 	if (newadp != NULL)
12463 		LOCK_OWNED(VFSTOUFS(newadp->ad_block.nb_list.wk_mp));
12464 	for (listadp = TAILQ_FIRST(oldlisthead); listadp && newadp;) {
12465 		if (listadp->ad_offset < newadp->ad_offset) {
12466 			listadp = TAILQ_NEXT(listadp, ad_next);
12467 			continue;
12468 		}
12469 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
12470 		TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
12471 		if (listadp->ad_offset == newadp->ad_offset) {
12472 			allocdirect_merge(oldlisthead, newadp,
12473 			    listadp);
12474 			listadp = newadp;
12475 		}
12476 		newadp = TAILQ_FIRST(newlisthead);
12477 	}
12478 	while ((newadp = TAILQ_FIRST(newlisthead)) != NULL) {
12479 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
12480 		TAILQ_INSERT_TAIL(oldlisthead, newadp, ad_next);
12481 	}
12482 }
12483 
12484 /*
12485  * If we are doing an fsync, then we must ensure that any directory
12486  * entries for the inode have been written after the inode gets to disk.
12487  */
12488 int
12489 softdep_fsync(vp)
12490 	struct vnode *vp;	/* the "in_core" copy of the inode */
12491 {
12492 	struct inodedep *inodedep;
12493 	struct pagedep *pagedep;
12494 	struct inoref *inoref;
12495 	struct ufsmount *ump;
12496 	struct worklist *wk;
12497 	struct diradd *dap;
12498 	struct mount *mp;
12499 	struct vnode *pvp;
12500 	struct inode *ip;
12501 	struct buf *bp;
12502 	struct fs *fs;
12503 	struct thread *td = curthread;
12504 	int error, flushparent, pagedep_new_block;
12505 	ino_t parentino;
12506 	ufs_lbn_t lbn;
12507 
12508 	ip = VTOI(vp);
12509 	mp = vp->v_mount;
12510 	ump = VFSTOUFS(mp);
12511 	fs = ump->um_fs;
12512 	if (MOUNTEDSOFTDEP(mp) == 0)
12513 		return (0);
12514 	ACQUIRE_LOCK(ump);
12515 restart:
12516 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12517 		FREE_LOCK(ump);
12518 		return (0);
12519 	}
12520 	TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12521 		if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12522 		    == DEPCOMPLETE) {
12523 			jwait(&inoref->if_list, MNT_WAIT);
12524 			goto restart;
12525 		}
12526 	}
12527 	if (!LIST_EMPTY(&inodedep->id_inowait) ||
12528 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
12529 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
12530 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
12531 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt))
12532 		panic("softdep_fsync: pending ops %p", inodedep);
12533 	for (error = 0, flushparent = 0; ; ) {
12534 		if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
12535 			break;
12536 		if (wk->wk_type != D_DIRADD)
12537 			panic("softdep_fsync: Unexpected type %s",
12538 			    TYPENAME(wk->wk_type));
12539 		dap = WK_DIRADD(wk);
12540 		/*
12541 		 * Flush our parent if this directory entry has a MKDIR_PARENT
12542 		 * dependency or is contained in a newly allocated block.
12543 		 */
12544 		if (dap->da_state & DIRCHG)
12545 			pagedep = dap->da_previous->dm_pagedep;
12546 		else
12547 			pagedep = dap->da_pagedep;
12548 		parentino = pagedep->pd_ino;
12549 		lbn = pagedep->pd_lbn;
12550 		if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE)
12551 			panic("softdep_fsync: dirty");
12552 		if ((dap->da_state & MKDIR_PARENT) ||
12553 		    (pagedep->pd_state & NEWBLOCK))
12554 			flushparent = 1;
12555 		else
12556 			flushparent = 0;
12557 		/*
12558 		 * If we are being fsync'ed as part of vgone'ing this vnode,
12559 		 * then we will not be able to release and recover the
12560 		 * vnode below, so we just have to give up on writing its
12561 		 * directory entry out. It will eventually be written, just
12562 		 * not now, but then the user was not asking to have it
12563 		 * written, so we are not breaking any promises.
12564 		 */
12565 		if (VN_IS_DOOMED(vp))
12566 			break;
12567 		/*
12568 		 * We prevent deadlock by always fetching inodes from the
12569 		 * root, moving down the directory tree. Thus, when fetching
12570 		 * our parent directory, we first try to get the lock. If
12571 		 * that fails, we must unlock ourselves before requesting
12572 		 * the lock on our parent. See the comment in ufs_lookup
12573 		 * for details on possible races.
12574 		 */
12575 		FREE_LOCK(ump);
12576 		if (ffs_vgetf(mp, parentino, LK_NOWAIT | LK_EXCLUSIVE, &pvp,
12577 		    FFSV_FORCEINSMQ)) {
12578 			/*
12579 			 * Unmount cannot proceed after unlock because
12580 			 * caller must have called vn_start_write().
12581 			 */
12582 			VOP_UNLOCK(vp);
12583 			error = ffs_vgetf(mp, parentino, LK_EXCLUSIVE,
12584 			    &pvp, FFSV_FORCEINSMQ);
12585 			MPASS(VTOI(pvp)->i_mode != 0);
12586 			vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
12587 			if (VN_IS_DOOMED(vp)) {
12588 				if (error == 0)
12589 					vput(pvp);
12590 				error = ENOENT;
12591 			}
12592 			if (error != 0)
12593 				return (error);
12594 		}
12595 		/*
12596 		 * All MKDIR_PARENT dependencies and all the NEWBLOCK pagedeps
12597 		 * that are contained in direct blocks will be resolved by
12598 		 * doing a ffs_update. Pagedeps contained in indirect blocks
12599 		 * may require a complete sync'ing of the directory. So, we
12600 		 * try the cheap and fast ffs_update first, and if that fails,
12601 		 * then we do the slower ffs_syncvnode of the directory.
12602 		 */
12603 		if (flushparent) {
12604 			int locked;
12605 
12606 			if ((error = ffs_update(pvp, 1)) != 0) {
12607 				vput(pvp);
12608 				return (error);
12609 			}
12610 			ACQUIRE_LOCK(ump);
12611 			locked = 1;
12612 			if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0) {
12613 				if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) != NULL) {
12614 					if (wk->wk_type != D_DIRADD)
12615 						panic("softdep_fsync: Unexpected type %s",
12616 						      TYPENAME(wk->wk_type));
12617 					dap = WK_DIRADD(wk);
12618 					if (dap->da_state & DIRCHG)
12619 						pagedep = dap->da_previous->dm_pagedep;
12620 					else
12621 						pagedep = dap->da_pagedep;
12622 					pagedep_new_block = pagedep->pd_state & NEWBLOCK;
12623 					FREE_LOCK(ump);
12624 					locked = 0;
12625 					if (pagedep_new_block && (error =
12626 					    ffs_syncvnode(pvp, MNT_WAIT, 0))) {
12627 						vput(pvp);
12628 						return (error);
12629 					}
12630 				}
12631 			}
12632 			if (locked)
12633 				FREE_LOCK(ump);
12634 		}
12635 		/*
12636 		 * Flush directory page containing the inode's name.
12637 		 */
12638 		error = bread(pvp, lbn, blksize(fs, VTOI(pvp), lbn), td->td_ucred,
12639 		    &bp);
12640 		if (error == 0)
12641 			error = bwrite(bp);
12642 		else
12643 			brelse(bp);
12644 		vput(pvp);
12645 		if (error != 0)
12646 			return (error);
12647 		ACQUIRE_LOCK(ump);
12648 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
12649 			break;
12650 	}
12651 	FREE_LOCK(ump);
12652 	return (0);
12653 }
12654 
12655 /*
12656  * Flush all the dirty bitmaps associated with the block device
12657  * before flushing the rest of the dirty blocks so as to reduce
12658  * the number of dependencies that will have to be rolled back.
12659  *
12660  * XXX Unused?
12661  */
12662 void
12663 softdep_fsync_mountdev(vp)
12664 	struct vnode *vp;
12665 {
12666 	struct buf *bp, *nbp;
12667 	struct worklist *wk;
12668 	struct bufobj *bo;
12669 
12670 	if (!vn_isdisk(vp, NULL))
12671 		panic("softdep_fsync_mountdev: vnode not a disk");
12672 	bo = &vp->v_bufobj;
12673 restart:
12674 	BO_LOCK(bo);
12675 	TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
12676 		/*
12677 		 * If it is already scheduled, skip to the next buffer.
12678 		 */
12679 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL))
12680 			continue;
12681 
12682 		if ((bp->b_flags & B_DELWRI) == 0)
12683 			panic("softdep_fsync_mountdev: not dirty");
12684 		/*
12685 		 * We are only interested in bitmaps with outstanding
12686 		 * dependencies.
12687 		 */
12688 		if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
12689 		    wk->wk_type != D_BMSAFEMAP ||
12690 		    (bp->b_vflags & BV_BKGRDINPROG)) {
12691 			BUF_UNLOCK(bp);
12692 			continue;
12693 		}
12694 		BO_UNLOCK(bo);
12695 		bremfree(bp);
12696 		(void) bawrite(bp);
12697 		goto restart;
12698 	}
12699 	drain_output(vp);
12700 	BO_UNLOCK(bo);
12701 }
12702 
12703 /*
12704  * Sync all cylinder groups that were dirty at the time this function is
12705  * called.  Newly dirtied cgs will be inserted before the sentinel.  This
12706  * is used to flush freedep activity that may be holding up writes to a
12707  * indirect block.
12708  */
12709 static int
12710 sync_cgs(mp, waitfor)
12711 	struct mount *mp;
12712 	int waitfor;
12713 {
12714 	struct bmsafemap *bmsafemap;
12715 	struct bmsafemap *sentinel;
12716 	struct ufsmount *ump;
12717 	struct buf *bp;
12718 	int error;
12719 
12720 	sentinel = malloc(sizeof(*sentinel), M_BMSAFEMAP, M_ZERO | M_WAITOK);
12721 	sentinel->sm_cg = -1;
12722 	ump = VFSTOUFS(mp);
12723 	error = 0;
12724 	ACQUIRE_LOCK(ump);
12725 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, sentinel, sm_next);
12726 	for (bmsafemap = LIST_NEXT(sentinel, sm_next); bmsafemap != NULL;
12727 	    bmsafemap = LIST_NEXT(sentinel, sm_next)) {
12728 		/* Skip sentinels and cgs with no work to release. */
12729 		if (bmsafemap->sm_cg == -1 ||
12730 		    (LIST_EMPTY(&bmsafemap->sm_freehd) &&
12731 		    LIST_EMPTY(&bmsafemap->sm_freewr))) {
12732 			LIST_REMOVE(sentinel, sm_next);
12733 			LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12734 			continue;
12735 		}
12736 		/*
12737 		 * If we don't get the lock and we're waiting try again, if
12738 		 * not move on to the next buf and try to sync it.
12739 		 */
12740 		bp = getdirtybuf(bmsafemap->sm_buf, LOCK_PTR(ump), waitfor);
12741 		if (bp == NULL && waitfor == MNT_WAIT)
12742 			continue;
12743 		LIST_REMOVE(sentinel, sm_next);
12744 		LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12745 		if (bp == NULL)
12746 			continue;
12747 		FREE_LOCK(ump);
12748 		if (waitfor == MNT_NOWAIT)
12749 			bawrite(bp);
12750 		else
12751 			error = bwrite(bp);
12752 		ACQUIRE_LOCK(ump);
12753 		if (error)
12754 			break;
12755 	}
12756 	LIST_REMOVE(sentinel, sm_next);
12757 	FREE_LOCK(ump);
12758 	free(sentinel, M_BMSAFEMAP);
12759 	return (error);
12760 }
12761 
12762 /*
12763  * This routine is called when we are trying to synchronously flush a
12764  * file. This routine must eliminate any filesystem metadata dependencies
12765  * so that the syncing routine can succeed.
12766  */
12767 int
12768 softdep_sync_metadata(struct vnode *vp)
12769 {
12770 	struct inode *ip;
12771 	int error;
12772 
12773 	ip = VTOI(vp);
12774 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12775 	    ("softdep_sync_metadata called on non-softdep filesystem"));
12776 	/*
12777 	 * Ensure that any direct block dependencies have been cleared,
12778 	 * truncations are started, and inode references are journaled.
12779 	 */
12780 	ACQUIRE_LOCK(VFSTOUFS(vp->v_mount));
12781 	/*
12782 	 * Write all journal records to prevent rollbacks on devvp.
12783 	 */
12784 	if (vp->v_type == VCHR)
12785 		softdep_flushjournal(vp->v_mount);
12786 	error = flush_inodedep_deps(vp, vp->v_mount, ip->i_number);
12787 	/*
12788 	 * Ensure that all truncates are written so we won't find deps on
12789 	 * indirect blocks.
12790 	 */
12791 	process_truncates(vp);
12792 	FREE_LOCK(VFSTOUFS(vp->v_mount));
12793 
12794 	return (error);
12795 }
12796 
12797 /*
12798  * This routine is called when we are attempting to sync a buf with
12799  * dependencies.  If waitfor is MNT_NOWAIT it attempts to schedule any
12800  * other IO it can but returns EBUSY if the buffer is not yet able to
12801  * be written.  Dependencies which will not cause rollbacks will always
12802  * return 0.
12803  */
12804 int
12805 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
12806 {
12807 	struct indirdep *indirdep;
12808 	struct pagedep *pagedep;
12809 	struct allocindir *aip;
12810 	struct newblk *newblk;
12811 	struct ufsmount *ump;
12812 	struct buf *nbp;
12813 	struct worklist *wk;
12814 	int i, error;
12815 
12816 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12817 	    ("softdep_sync_buf called on non-softdep filesystem"));
12818 	/*
12819 	 * For VCHR we just don't want to force flush any dependencies that
12820 	 * will cause rollbacks.
12821 	 */
12822 	if (vp->v_type == VCHR) {
12823 		if (waitfor == MNT_NOWAIT && softdep_count_dependencies(bp, 0))
12824 			return (EBUSY);
12825 		return (0);
12826 	}
12827 	ump = VFSTOUFS(vp->v_mount);
12828 	ACQUIRE_LOCK(ump);
12829 	/*
12830 	 * As we hold the buffer locked, none of its dependencies
12831 	 * will disappear.
12832 	 */
12833 	error = 0;
12834 top:
12835 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
12836 		switch (wk->wk_type) {
12837 
12838 		case D_ALLOCDIRECT:
12839 		case D_ALLOCINDIR:
12840 			newblk = WK_NEWBLK(wk);
12841 			if (newblk->nb_jnewblk != NULL) {
12842 				if (waitfor == MNT_NOWAIT) {
12843 					error = EBUSY;
12844 					goto out_unlock;
12845 				}
12846 				jwait(&newblk->nb_jnewblk->jn_list, waitfor);
12847 				goto top;
12848 			}
12849 			if (newblk->nb_state & DEPCOMPLETE ||
12850 			    waitfor == MNT_NOWAIT)
12851 				continue;
12852 			nbp = newblk->nb_bmsafemap->sm_buf;
12853 			nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
12854 			if (nbp == NULL)
12855 				goto top;
12856 			FREE_LOCK(ump);
12857 			if ((error = bwrite(nbp)) != 0)
12858 				goto out;
12859 			ACQUIRE_LOCK(ump);
12860 			continue;
12861 
12862 		case D_INDIRDEP:
12863 			indirdep = WK_INDIRDEP(wk);
12864 			if (waitfor == MNT_NOWAIT) {
12865 				if (!TAILQ_EMPTY(&indirdep->ir_trunc) ||
12866 				    !LIST_EMPTY(&indirdep->ir_deplisthd)) {
12867 					error = EBUSY;
12868 					goto out_unlock;
12869 				}
12870 			}
12871 			if (!TAILQ_EMPTY(&indirdep->ir_trunc))
12872 				panic("softdep_sync_buf: truncation pending.");
12873 		restart:
12874 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
12875 				newblk = (struct newblk *)aip;
12876 				if (newblk->nb_jnewblk != NULL) {
12877 					jwait(&newblk->nb_jnewblk->jn_list,
12878 					    waitfor);
12879 					goto restart;
12880 				}
12881 				if (newblk->nb_state & DEPCOMPLETE)
12882 					continue;
12883 				nbp = newblk->nb_bmsafemap->sm_buf;
12884 				nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
12885 				if (nbp == NULL)
12886 					goto restart;
12887 				FREE_LOCK(ump);
12888 				if ((error = bwrite(nbp)) != 0)
12889 					goto out;
12890 				ACQUIRE_LOCK(ump);
12891 				goto restart;
12892 			}
12893 			continue;
12894 
12895 		case D_PAGEDEP:
12896 			/*
12897 			 * Only flush directory entries in synchronous passes.
12898 			 */
12899 			if (waitfor != MNT_WAIT) {
12900 				error = EBUSY;
12901 				goto out_unlock;
12902 			}
12903 			/*
12904 			 * While syncing snapshots, we must allow recursive
12905 			 * lookups.
12906 			 */
12907 			BUF_AREC(bp);
12908 			/*
12909 			 * We are trying to sync a directory that may
12910 			 * have dependencies on both its own metadata
12911 			 * and/or dependencies on the inodes of any
12912 			 * recently allocated files. We walk its diradd
12913 			 * lists pushing out the associated inode.
12914 			 */
12915 			pagedep = WK_PAGEDEP(wk);
12916 			for (i = 0; i < DAHASHSZ; i++) {
12917 				if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
12918 					continue;
12919 				if ((error = flush_pagedep_deps(vp, wk->wk_mp,
12920 				    &pagedep->pd_diraddhd[i]))) {
12921 					BUF_NOREC(bp);
12922 					goto out_unlock;
12923 				}
12924 			}
12925 			BUF_NOREC(bp);
12926 			continue;
12927 
12928 		case D_FREEWORK:
12929 		case D_FREEDEP:
12930 		case D_JSEGDEP:
12931 		case D_JNEWBLK:
12932 			continue;
12933 
12934 		default:
12935 			panic("softdep_sync_buf: Unknown type %s",
12936 			    TYPENAME(wk->wk_type));
12937 			/* NOTREACHED */
12938 		}
12939 	}
12940 out_unlock:
12941 	FREE_LOCK(ump);
12942 out:
12943 	return (error);
12944 }
12945 
12946 /*
12947  * Flush the dependencies associated with an inodedep.
12948  */
12949 static int
12950 flush_inodedep_deps(vp, mp, ino)
12951 	struct vnode *vp;
12952 	struct mount *mp;
12953 	ino_t ino;
12954 {
12955 	struct inodedep *inodedep;
12956 	struct inoref *inoref;
12957 	struct ufsmount *ump;
12958 	int error, waitfor;
12959 
12960 	/*
12961 	 * This work is done in two passes. The first pass grabs most
12962 	 * of the buffers and begins asynchronously writing them. The
12963 	 * only way to wait for these asynchronous writes is to sleep
12964 	 * on the filesystem vnode which may stay busy for a long time
12965 	 * if the filesystem is active. So, instead, we make a second
12966 	 * pass over the dependencies blocking on each write. In the
12967 	 * usual case we will be blocking against a write that we
12968 	 * initiated, so when it is done the dependency will have been
12969 	 * resolved. Thus the second pass is expected to end quickly.
12970 	 * We give a brief window at the top of the loop to allow
12971 	 * any pending I/O to complete.
12972 	 */
12973 	ump = VFSTOUFS(mp);
12974 	LOCK_OWNED(ump);
12975 	for (error = 0, waitfor = MNT_NOWAIT; ; ) {
12976 		if (error)
12977 			return (error);
12978 		FREE_LOCK(ump);
12979 		ACQUIRE_LOCK(ump);
12980 restart:
12981 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
12982 			return (0);
12983 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12984 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12985 			    == DEPCOMPLETE) {
12986 				jwait(&inoref->if_list, MNT_WAIT);
12987 				goto restart;
12988 			}
12989 		}
12990 		if (flush_deplist(&inodedep->id_inoupdt, waitfor, &error) ||
12991 		    flush_deplist(&inodedep->id_newinoupdt, waitfor, &error) ||
12992 		    flush_deplist(&inodedep->id_extupdt, waitfor, &error) ||
12993 		    flush_deplist(&inodedep->id_newextupdt, waitfor, &error))
12994 			continue;
12995 		/*
12996 		 * If pass2, we are done, otherwise do pass 2.
12997 		 */
12998 		if (waitfor == MNT_WAIT)
12999 			break;
13000 		waitfor = MNT_WAIT;
13001 	}
13002 	/*
13003 	 * Try freeing inodedep in case all dependencies have been removed.
13004 	 */
13005 	if (inodedep_lookup(mp, ino, 0, &inodedep) != 0)
13006 		(void) free_inodedep(inodedep);
13007 	return (0);
13008 }
13009 
13010 /*
13011  * Flush an inode dependency list.
13012  */
13013 static int
13014 flush_deplist(listhead, waitfor, errorp)
13015 	struct allocdirectlst *listhead;
13016 	int waitfor;
13017 	int *errorp;
13018 {
13019 	struct allocdirect *adp;
13020 	struct newblk *newblk;
13021 	struct ufsmount *ump;
13022 	struct buf *bp;
13023 
13024 	if ((adp = TAILQ_FIRST(listhead)) == NULL)
13025 		return (0);
13026 	ump = VFSTOUFS(adp->ad_list.wk_mp);
13027 	LOCK_OWNED(ump);
13028 	TAILQ_FOREACH(adp, listhead, ad_next) {
13029 		newblk = (struct newblk *)adp;
13030 		if (newblk->nb_jnewblk != NULL) {
13031 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
13032 			return (1);
13033 		}
13034 		if (newblk->nb_state & DEPCOMPLETE)
13035 			continue;
13036 		bp = newblk->nb_bmsafemap->sm_buf;
13037 		bp = getdirtybuf(bp, LOCK_PTR(ump), waitfor);
13038 		if (bp == NULL) {
13039 			if (waitfor == MNT_NOWAIT)
13040 				continue;
13041 			return (1);
13042 		}
13043 		FREE_LOCK(ump);
13044 		if (waitfor == MNT_NOWAIT)
13045 			bawrite(bp);
13046 		else
13047 			*errorp = bwrite(bp);
13048 		ACQUIRE_LOCK(ump);
13049 		return (1);
13050 	}
13051 	return (0);
13052 }
13053 
13054 /*
13055  * Flush dependencies associated with an allocdirect block.
13056  */
13057 static int
13058 flush_newblk_dep(vp, mp, lbn)
13059 	struct vnode *vp;
13060 	struct mount *mp;
13061 	ufs_lbn_t lbn;
13062 {
13063 	struct newblk *newblk;
13064 	struct ufsmount *ump;
13065 	struct bufobj *bo;
13066 	struct inode *ip;
13067 	struct buf *bp;
13068 	ufs2_daddr_t blkno;
13069 	int error;
13070 
13071 	error = 0;
13072 	bo = &vp->v_bufobj;
13073 	ip = VTOI(vp);
13074 	blkno = DIP(ip, i_db[lbn]);
13075 	if (blkno == 0)
13076 		panic("flush_newblk_dep: Missing block");
13077 	ump = VFSTOUFS(mp);
13078 	ACQUIRE_LOCK(ump);
13079 	/*
13080 	 * Loop until all dependencies related to this block are satisfied.
13081 	 * We must be careful to restart after each sleep in case a write
13082 	 * completes some part of this process for us.
13083 	 */
13084 	for (;;) {
13085 		if (newblk_lookup(mp, blkno, 0, &newblk) == 0) {
13086 			FREE_LOCK(ump);
13087 			break;
13088 		}
13089 		if (newblk->nb_list.wk_type != D_ALLOCDIRECT)
13090 			panic("flush_newblk_dep: Bad newblk %p", newblk);
13091 		/*
13092 		 * Flush the journal.
13093 		 */
13094 		if (newblk->nb_jnewblk != NULL) {
13095 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
13096 			continue;
13097 		}
13098 		/*
13099 		 * Write the bitmap dependency.
13100 		 */
13101 		if ((newblk->nb_state & DEPCOMPLETE) == 0) {
13102 			bp = newblk->nb_bmsafemap->sm_buf;
13103 			bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13104 			if (bp == NULL)
13105 				continue;
13106 			FREE_LOCK(ump);
13107 			error = bwrite(bp);
13108 			if (error)
13109 				break;
13110 			ACQUIRE_LOCK(ump);
13111 			continue;
13112 		}
13113 		/*
13114 		 * Write the buffer.
13115 		 */
13116 		FREE_LOCK(ump);
13117 		BO_LOCK(bo);
13118 		bp = gbincore(bo, lbn);
13119 		if (bp != NULL) {
13120 			error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
13121 			    LK_INTERLOCK, BO_LOCKPTR(bo));
13122 			if (error == ENOLCK) {
13123 				ACQUIRE_LOCK(ump);
13124 				error = 0;
13125 				continue; /* Slept, retry */
13126 			}
13127 			if (error != 0)
13128 				break;	/* Failed */
13129 			if (bp->b_flags & B_DELWRI) {
13130 				bremfree(bp);
13131 				error = bwrite(bp);
13132 				if (error)
13133 					break;
13134 			} else
13135 				BUF_UNLOCK(bp);
13136 		} else
13137 			BO_UNLOCK(bo);
13138 		/*
13139 		 * We have to wait for the direct pointers to
13140 		 * point at the newdirblk before the dependency
13141 		 * will go away.
13142 		 */
13143 		error = ffs_update(vp, 1);
13144 		if (error)
13145 			break;
13146 		ACQUIRE_LOCK(ump);
13147 	}
13148 	return (error);
13149 }
13150 
13151 /*
13152  * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
13153  */
13154 static int
13155 flush_pagedep_deps(pvp, mp, diraddhdp)
13156 	struct vnode *pvp;
13157 	struct mount *mp;
13158 	struct diraddhd *diraddhdp;
13159 {
13160 	struct inodedep *inodedep;
13161 	struct inoref *inoref;
13162 	struct ufsmount *ump;
13163 	struct diradd *dap;
13164 	struct vnode *vp;
13165 	int error = 0;
13166 	struct buf *bp;
13167 	ino_t inum;
13168 	struct diraddhd unfinished;
13169 
13170 	LIST_INIT(&unfinished);
13171 	ump = VFSTOUFS(mp);
13172 	LOCK_OWNED(ump);
13173 restart:
13174 	while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
13175 		/*
13176 		 * Flush ourselves if this directory entry
13177 		 * has a MKDIR_PARENT dependency.
13178 		 */
13179 		if (dap->da_state & MKDIR_PARENT) {
13180 			FREE_LOCK(ump);
13181 			if ((error = ffs_update(pvp, 1)) != 0)
13182 				break;
13183 			ACQUIRE_LOCK(ump);
13184 			/*
13185 			 * If that cleared dependencies, go on to next.
13186 			 */
13187 			if (dap != LIST_FIRST(diraddhdp))
13188 				continue;
13189 			/*
13190 			 * All MKDIR_PARENT dependencies and all the
13191 			 * NEWBLOCK pagedeps that are contained in direct
13192 			 * blocks were resolved by doing above ffs_update.
13193 			 * Pagedeps contained in indirect blocks may
13194 			 * require a complete sync'ing of the directory.
13195 			 * We are in the midst of doing a complete sync,
13196 			 * so if they are not resolved in this pass we
13197 			 * defer them for now as they will be sync'ed by
13198 			 * our caller shortly.
13199 			 */
13200 			LIST_REMOVE(dap, da_pdlist);
13201 			LIST_INSERT_HEAD(&unfinished, dap, da_pdlist);
13202 			continue;
13203 		}
13204 		/*
13205 		 * A newly allocated directory must have its "." and
13206 		 * ".." entries written out before its name can be
13207 		 * committed in its parent.
13208 		 */
13209 		inum = dap->da_newinum;
13210 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13211 			panic("flush_pagedep_deps: lost inode1");
13212 		/*
13213 		 * Wait for any pending journal adds to complete so we don't
13214 		 * cause rollbacks while syncing.
13215 		 */
13216 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
13217 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
13218 			    == DEPCOMPLETE) {
13219 				jwait(&inoref->if_list, MNT_WAIT);
13220 				goto restart;
13221 			}
13222 		}
13223 		if (dap->da_state & MKDIR_BODY) {
13224 			FREE_LOCK(ump);
13225 			if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
13226 			    FFSV_FORCEINSMQ)))
13227 				break;
13228 			MPASS(VTOI(vp)->i_mode != 0);
13229 			error = flush_newblk_dep(vp, mp, 0);
13230 			/*
13231 			 * If we still have the dependency we might need to
13232 			 * update the vnode to sync the new link count to
13233 			 * disk.
13234 			 */
13235 			if (error == 0 && dap == LIST_FIRST(diraddhdp))
13236 				error = ffs_update(vp, 1);
13237 			vput(vp);
13238 			if (error != 0)
13239 				break;
13240 			ACQUIRE_LOCK(ump);
13241 			/*
13242 			 * If that cleared dependencies, go on to next.
13243 			 */
13244 			if (dap != LIST_FIRST(diraddhdp))
13245 				continue;
13246 			if (dap->da_state & MKDIR_BODY) {
13247 				inodedep_lookup(UFSTOVFS(ump), inum, 0,
13248 				    &inodedep);
13249 				panic("flush_pagedep_deps: MKDIR_BODY "
13250 				    "inodedep %p dap %p vp %p",
13251 				    inodedep, dap, vp);
13252 			}
13253 		}
13254 		/*
13255 		 * Flush the inode on which the directory entry depends.
13256 		 * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
13257 		 * the only remaining dependency is that the updated inode
13258 		 * count must get pushed to disk. The inode has already
13259 		 * been pushed into its inode buffer (via VOP_UPDATE) at
13260 		 * the time of the reference count change. So we need only
13261 		 * locate that buffer, ensure that there will be no rollback
13262 		 * caused by a bitmap dependency, then write the inode buffer.
13263 		 */
13264 retry:
13265 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13266 			panic("flush_pagedep_deps: lost inode");
13267 		/*
13268 		 * If the inode still has bitmap dependencies,
13269 		 * push them to disk.
13270 		 */
13271 		if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) == 0) {
13272 			bp = inodedep->id_bmsafemap->sm_buf;
13273 			bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13274 			if (bp == NULL)
13275 				goto retry;
13276 			FREE_LOCK(ump);
13277 			if ((error = bwrite(bp)) != 0)
13278 				break;
13279 			ACQUIRE_LOCK(ump);
13280 			if (dap != LIST_FIRST(diraddhdp))
13281 				continue;
13282 		}
13283 		/*
13284 		 * If the inode is still sitting in a buffer waiting
13285 		 * to be written or waiting for the link count to be
13286 		 * adjusted update it here to flush it to disk.
13287 		 */
13288 		if (dap == LIST_FIRST(diraddhdp)) {
13289 			FREE_LOCK(ump);
13290 			if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
13291 			    FFSV_FORCEINSMQ)))
13292 				break;
13293 			MPASS(VTOI(vp)->i_mode != 0);
13294 			error = ffs_update(vp, 1);
13295 			vput(vp);
13296 			if (error)
13297 				break;
13298 			ACQUIRE_LOCK(ump);
13299 		}
13300 		/*
13301 		 * If we have failed to get rid of all the dependencies
13302 		 * then something is seriously wrong.
13303 		 */
13304 		if (dap == LIST_FIRST(diraddhdp)) {
13305 			inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep);
13306 			panic("flush_pagedep_deps: failed to flush "
13307 			    "inodedep %p ino %ju dap %p",
13308 			    inodedep, (uintmax_t)inum, dap);
13309 		}
13310 	}
13311 	if (error)
13312 		ACQUIRE_LOCK(ump);
13313 	while ((dap = LIST_FIRST(&unfinished)) != NULL) {
13314 		LIST_REMOVE(dap, da_pdlist);
13315 		LIST_INSERT_HEAD(diraddhdp, dap, da_pdlist);
13316 	}
13317 	return (error);
13318 }
13319 
13320 /*
13321  * A large burst of file addition or deletion activity can drive the
13322  * memory load excessively high. First attempt to slow things down
13323  * using the techniques below. If that fails, this routine requests
13324  * the offending operations to fall back to running synchronously
13325  * until the memory load returns to a reasonable level.
13326  */
13327 int
13328 softdep_slowdown(vp)
13329 	struct vnode *vp;
13330 {
13331 	struct ufsmount *ump;
13332 	int jlow;
13333 	int max_softdeps_hard;
13334 
13335 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
13336 	    ("softdep_slowdown called on non-softdep filesystem"));
13337 	ump = VFSTOUFS(vp->v_mount);
13338 	ACQUIRE_LOCK(ump);
13339 	jlow = 0;
13340 	/*
13341 	 * Check for journal space if needed.
13342 	 */
13343 	if (DOINGSUJ(vp)) {
13344 		if (journal_space(ump, 0) == 0)
13345 			jlow = 1;
13346 	}
13347 	/*
13348 	 * If the system is under its limits and our filesystem is
13349 	 * not responsible for more than our share of the usage and
13350 	 * we are not low on journal space, then no need to slow down.
13351 	 */
13352 	max_softdeps_hard = max_softdeps * 11 / 10;
13353 	if (dep_current[D_DIRREM] < max_softdeps_hard / 2 &&
13354 	    dep_current[D_INODEDEP] < max_softdeps_hard &&
13355 	    dep_current[D_INDIRDEP] < max_softdeps_hard / 1000 &&
13356 	    dep_current[D_FREEBLKS] < max_softdeps_hard && jlow == 0 &&
13357 	    ump->softdep_curdeps[D_DIRREM] <
13358 	    (max_softdeps_hard / 2) / stat_flush_threads &&
13359 	    ump->softdep_curdeps[D_INODEDEP] <
13360 	    max_softdeps_hard / stat_flush_threads &&
13361 	    ump->softdep_curdeps[D_INDIRDEP] <
13362 	    (max_softdeps_hard / 1000) / stat_flush_threads &&
13363 	    ump->softdep_curdeps[D_FREEBLKS] <
13364 	    max_softdeps_hard / stat_flush_threads) {
13365 		FREE_LOCK(ump);
13366   		return (0);
13367 	}
13368 	/*
13369 	 * If the journal is low or our filesystem is over its limit
13370 	 * then speedup the cleanup.
13371 	 */
13372 	if (ump->softdep_curdeps[D_INDIRDEP] <
13373 	    (max_softdeps_hard / 1000) / stat_flush_threads || jlow)
13374 		softdep_speedup(ump);
13375 	stat_sync_limit_hit += 1;
13376 	FREE_LOCK(ump);
13377 	/*
13378 	 * We only slow down the rate at which new dependencies are
13379 	 * generated if we are not using journaling. With journaling,
13380 	 * the cleanup should always be sufficient to keep things
13381 	 * under control.
13382 	 */
13383 	if (DOINGSUJ(vp))
13384 		return (0);
13385 	return (1);
13386 }
13387 
13388 /*
13389  * Called by the allocation routines when they are about to fail
13390  * in the hope that we can free up the requested resource (inodes
13391  * or disk space).
13392  *
13393  * First check to see if the work list has anything on it. If it has,
13394  * clean up entries until we successfully free the requested resource.
13395  * Because this process holds inodes locked, we cannot handle any remove
13396  * requests that might block on a locked inode as that could lead to
13397  * deadlock. If the worklist yields none of the requested resource,
13398  * start syncing out vnodes to free up the needed space.
13399  */
13400 int
13401 softdep_request_cleanup(fs, vp, cred, resource)
13402 	struct fs *fs;
13403 	struct vnode *vp;
13404 	struct ucred *cred;
13405 	int resource;
13406 {
13407 	struct ufsmount *ump;
13408 	struct mount *mp;
13409 	long starttime;
13410 	ufs2_daddr_t needed;
13411 	int error, failed_vnode;
13412 
13413 	/*
13414 	 * If we are being called because of a process doing a
13415 	 * copy-on-write, then it is not safe to process any
13416 	 * worklist items as we will recurse into the copyonwrite
13417 	 * routine.  This will result in an incoherent snapshot.
13418 	 * If the vnode that we hold is a snapshot, we must avoid
13419 	 * handling other resources that could cause deadlock.
13420 	 */
13421 	if ((curthread->td_pflags & TDP_COWINPROGRESS) || IS_SNAPSHOT(VTOI(vp)))
13422 		return (0);
13423 
13424 	if (resource == FLUSH_BLOCKS_WAIT)
13425 		stat_cleanup_blkrequests += 1;
13426 	else
13427 		stat_cleanup_inorequests += 1;
13428 
13429 	mp = vp->v_mount;
13430 	ump = VFSTOUFS(mp);
13431 	mtx_assert(UFS_MTX(ump), MA_OWNED);
13432 	UFS_UNLOCK(ump);
13433 	error = ffs_update(vp, 1);
13434 	if (error != 0 || MOUNTEDSOFTDEP(mp) == 0) {
13435 		UFS_LOCK(ump);
13436 		return (0);
13437 	}
13438 	/*
13439 	 * If we are in need of resources, start by cleaning up
13440 	 * any block removals associated with our inode.
13441 	 */
13442 	ACQUIRE_LOCK(ump);
13443 	process_removes(vp);
13444 	process_truncates(vp);
13445 	FREE_LOCK(ump);
13446 	/*
13447 	 * Now clean up at least as many resources as we will need.
13448 	 *
13449 	 * When requested to clean up inodes, the number that are needed
13450 	 * is set by the number of simultaneous writers (mnt_writeopcount)
13451 	 * plus a bit of slop (2) in case some more writers show up while
13452 	 * we are cleaning.
13453 	 *
13454 	 * When requested to free up space, the amount of space that
13455 	 * we need is enough blocks to allocate a full-sized segment
13456 	 * (fs_contigsumsize). The number of such segments that will
13457 	 * be needed is set by the number of simultaneous writers
13458 	 * (mnt_writeopcount) plus a bit of slop (2) in case some more
13459 	 * writers show up while we are cleaning.
13460 	 *
13461 	 * Additionally, if we are unpriviledged and allocating space,
13462 	 * we need to ensure that we clean up enough blocks to get the
13463 	 * needed number of blocks over the threshold of the minimum
13464 	 * number of blocks required to be kept free by the filesystem
13465 	 * (fs_minfree).
13466 	 */
13467 	if (resource == FLUSH_INODES_WAIT) {
13468 		needed = vfs_mount_fetch_counter(vp->v_mount,
13469 		    MNT_COUNT_WRITEOPCOUNT) + 2;
13470 	} else if (resource == FLUSH_BLOCKS_WAIT) {
13471 		needed = (vfs_mount_fetch_counter(vp->v_mount,
13472 		    MNT_COUNT_WRITEOPCOUNT) + 2) * fs->fs_contigsumsize;
13473 		if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE))
13474 			needed += fragstoblks(fs,
13475 			    roundup((fs->fs_dsize * fs->fs_minfree / 100) -
13476 			    fs->fs_cstotal.cs_nffree, fs->fs_frag));
13477 	} else {
13478 		printf("softdep_request_cleanup: Unknown resource type %d\n",
13479 		    resource);
13480 		UFS_LOCK(ump);
13481 		return (0);
13482 	}
13483 	starttime = time_second;
13484 retry:
13485 	if (resource == FLUSH_BLOCKS_WAIT &&
13486 	    fs->fs_cstotal.cs_nbfree <= needed)
13487 		softdep_send_speedup(ump, needed * fs->fs_bsize,
13488 		    BIO_SPEEDUP_TRIM);
13489 	if ((resource == FLUSH_BLOCKS_WAIT && ump->softdep_on_worklist > 0 &&
13490 	    fs->fs_cstotal.cs_nbfree <= needed) ||
13491 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13492 	    fs->fs_cstotal.cs_nifree <= needed)) {
13493 		ACQUIRE_LOCK(ump);
13494 		if (ump->softdep_on_worklist > 0 &&
13495 		    process_worklist_item(UFSTOVFS(ump),
13496 		    ump->softdep_on_worklist, LK_NOWAIT) != 0)
13497 			stat_worklist_push += 1;
13498 		FREE_LOCK(ump);
13499 	}
13500 	/*
13501 	 * If we still need resources and there are no more worklist
13502 	 * entries to process to obtain them, we have to start flushing
13503 	 * the dirty vnodes to force the release of additional requests
13504 	 * to the worklist that we can then process to reap addition
13505 	 * resources. We walk the vnodes associated with the mount point
13506 	 * until we get the needed worklist requests that we can reap.
13507 	 *
13508 	 * If there are several threads all needing to clean the same
13509 	 * mount point, only one is allowed to walk the mount list.
13510 	 * When several threads all try to walk the same mount list,
13511 	 * they end up competing with each other and often end up in
13512 	 * livelock. This approach ensures that forward progress is
13513 	 * made at the cost of occational ENOSPC errors being returned
13514 	 * that might otherwise have been avoided.
13515 	 */
13516 	error = 1;
13517 	if ((resource == FLUSH_BLOCKS_WAIT &&
13518 	     fs->fs_cstotal.cs_nbfree <= needed) ||
13519 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13520 	     fs->fs_cstotal.cs_nifree <= needed)) {
13521 		ACQUIRE_LOCK(ump);
13522 		if ((ump->um_softdep->sd_flags & FLUSH_RC_ACTIVE) == 0) {
13523 			ump->um_softdep->sd_flags |= FLUSH_RC_ACTIVE;
13524 			FREE_LOCK(ump);
13525 			failed_vnode = softdep_request_cleanup_flush(mp, ump);
13526 			ACQUIRE_LOCK(ump);
13527 			ump->um_softdep->sd_flags &= ~FLUSH_RC_ACTIVE;
13528 			FREE_LOCK(ump);
13529 			if (ump->softdep_on_worklist > 0) {
13530 				stat_cleanup_retries += 1;
13531 				if (!failed_vnode)
13532 					goto retry;
13533 			}
13534 		} else {
13535 			FREE_LOCK(ump);
13536 			error = 0;
13537 		}
13538 		stat_cleanup_failures += 1;
13539 	}
13540 	if (time_second - starttime > stat_cleanup_high_delay)
13541 		stat_cleanup_high_delay = time_second - starttime;
13542 	UFS_LOCK(ump);
13543 	return (error);
13544 }
13545 
13546 /*
13547  * Scan the vnodes for the specified mount point flushing out any
13548  * vnodes that can be locked without waiting. Finally, try to flush
13549  * the device associated with the mount point if it can be locked
13550  * without waiting.
13551  *
13552  * We return 0 if we were able to lock every vnode in our scan.
13553  * If we had to skip one or more vnodes, we return 1.
13554  */
13555 static int
13556 softdep_request_cleanup_flush(mp, ump)
13557 	struct mount *mp;
13558 	struct ufsmount *ump;
13559 {
13560 	struct thread *td;
13561 	struct vnode *lvp, *mvp;
13562 	int failed_vnode;
13563 
13564 	failed_vnode = 0;
13565 	td = curthread;
13566 	MNT_VNODE_FOREACH_ALL(lvp, mp, mvp) {
13567 		if (TAILQ_FIRST(&lvp->v_bufobj.bo_dirty.bv_hd) == 0) {
13568 			VI_UNLOCK(lvp);
13569 			continue;
13570 		}
13571 		if (vget(lvp, LK_EXCLUSIVE | LK_INTERLOCK | LK_NOWAIT,
13572 		    td) != 0) {
13573 			failed_vnode = 1;
13574 			continue;
13575 		}
13576 		if (lvp->v_vflag & VV_NOSYNC) {	/* unlinked */
13577 			vput(lvp);
13578 			continue;
13579 		}
13580 		(void) ffs_syncvnode(lvp, MNT_NOWAIT, 0);
13581 		vput(lvp);
13582 	}
13583 	lvp = ump->um_devvp;
13584 	if (vn_lock(lvp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
13585 		VOP_FSYNC(lvp, MNT_NOWAIT, td);
13586 		VOP_UNLOCK(lvp);
13587 	}
13588 	return (failed_vnode);
13589 }
13590 
13591 static bool
13592 softdep_excess_items(struct ufsmount *ump, int item)
13593 {
13594 
13595 	KASSERT(item >= 0 && item < D_LAST, ("item %d", item));
13596 	return (dep_current[item] > max_softdeps &&
13597 	    ump->softdep_curdeps[item] > max_softdeps /
13598 	    stat_flush_threads);
13599 }
13600 
13601 static void
13602 schedule_cleanup(struct mount *mp)
13603 {
13604 	struct ufsmount *ump;
13605 	struct thread *td;
13606 
13607 	ump = VFSTOUFS(mp);
13608 	LOCK_OWNED(ump);
13609 	FREE_LOCK(ump);
13610 	td = curthread;
13611 	if ((td->td_pflags & TDP_KTHREAD) != 0 &&
13612 	    (td->td_proc->p_flag2 & P2_AST_SU) == 0) {
13613 		/*
13614 		 * No ast is delivered to kernel threads, so nobody
13615 		 * would deref the mp.  Some kernel threads
13616 		 * explicitely check for AST, e.g. NFS daemon does
13617 		 * this in the serving loop.
13618 		 */
13619 		return;
13620 	}
13621 	if (td->td_su != NULL)
13622 		vfs_rel(td->td_su);
13623 	vfs_ref(mp);
13624 	td->td_su = mp;
13625 	thread_lock(td);
13626 	td->td_flags |= TDF_ASTPENDING;
13627 	thread_unlock(td);
13628 }
13629 
13630 static void
13631 softdep_ast_cleanup_proc(struct thread *td)
13632 {
13633 	struct mount *mp;
13634 	struct ufsmount *ump;
13635 	int error;
13636 	bool req;
13637 
13638 	while ((mp = td->td_su) != NULL) {
13639 		td->td_su = NULL;
13640 		error = vfs_busy(mp, MBF_NOWAIT);
13641 		vfs_rel(mp);
13642 		if (error != 0)
13643 			return;
13644 		if (ffs_own_mount(mp) && MOUNTEDSOFTDEP(mp)) {
13645 			ump = VFSTOUFS(mp);
13646 			for (;;) {
13647 				req = false;
13648 				ACQUIRE_LOCK(ump);
13649 				if (softdep_excess_items(ump, D_INODEDEP)) {
13650 					req = true;
13651 					request_cleanup(mp, FLUSH_INODES);
13652 				}
13653 				if (softdep_excess_items(ump, D_DIRREM)) {
13654 					req = true;
13655 					request_cleanup(mp, FLUSH_BLOCKS);
13656 				}
13657 				FREE_LOCK(ump);
13658 				if (softdep_excess_items(ump, D_NEWBLK) ||
13659 				    softdep_excess_items(ump, D_ALLOCDIRECT) ||
13660 				    softdep_excess_items(ump, D_ALLOCINDIR)) {
13661 					error = vn_start_write(NULL, &mp,
13662 					    V_WAIT);
13663 					if (error == 0) {
13664 						req = true;
13665 						VFS_SYNC(mp, MNT_WAIT);
13666 						vn_finished_write(mp);
13667 					}
13668 				}
13669 				if ((td->td_pflags & TDP_KTHREAD) != 0 || !req)
13670 					break;
13671 			}
13672 		}
13673 		vfs_unbusy(mp);
13674 	}
13675 	if ((mp = td->td_su) != NULL) {
13676 		td->td_su = NULL;
13677 		vfs_rel(mp);
13678 	}
13679 }
13680 
13681 /*
13682  * If memory utilization has gotten too high, deliberately slow things
13683  * down and speed up the I/O processing.
13684  */
13685 static int
13686 request_cleanup(mp, resource)
13687 	struct mount *mp;
13688 	int resource;
13689 {
13690 	struct thread *td = curthread;
13691 	struct ufsmount *ump;
13692 
13693 	ump = VFSTOUFS(mp);
13694 	LOCK_OWNED(ump);
13695 	/*
13696 	 * We never hold up the filesystem syncer or buf daemon.
13697 	 */
13698 	if (td->td_pflags & (TDP_SOFTDEP|TDP_NORUNNINGBUF))
13699 		return (0);
13700 	/*
13701 	 * First check to see if the work list has gotten backlogged.
13702 	 * If it has, co-opt this process to help clean up two entries.
13703 	 * Because this process may hold inodes locked, we cannot
13704 	 * handle any remove requests that might block on a locked
13705 	 * inode as that could lead to deadlock.  We set TDP_SOFTDEP
13706 	 * to avoid recursively processing the worklist.
13707 	 */
13708 	if (ump->softdep_on_worklist > max_softdeps / 10) {
13709 		td->td_pflags |= TDP_SOFTDEP;
13710 		process_worklist_item(mp, 2, LK_NOWAIT);
13711 		td->td_pflags &= ~TDP_SOFTDEP;
13712 		stat_worklist_push += 2;
13713 		return(1);
13714 	}
13715 	/*
13716 	 * Next, we attempt to speed up the syncer process. If that
13717 	 * is successful, then we allow the process to continue.
13718 	 */
13719 	if (softdep_speedup(ump) &&
13720 	    resource != FLUSH_BLOCKS_WAIT &&
13721 	    resource != FLUSH_INODES_WAIT)
13722 		return(0);
13723 	/*
13724 	 * If we are resource constrained on inode dependencies, try
13725 	 * flushing some dirty inodes. Otherwise, we are constrained
13726 	 * by file deletions, so try accelerating flushes of directories
13727 	 * with removal dependencies. We would like to do the cleanup
13728 	 * here, but we probably hold an inode locked at this point and
13729 	 * that might deadlock against one that we try to clean. So,
13730 	 * the best that we can do is request the syncer daemon to do
13731 	 * the cleanup for us.
13732 	 */
13733 	switch (resource) {
13734 
13735 	case FLUSH_INODES:
13736 	case FLUSH_INODES_WAIT:
13737 		ACQUIRE_GBLLOCK(&lk);
13738 		stat_ino_limit_push += 1;
13739 		req_clear_inodedeps += 1;
13740 		FREE_GBLLOCK(&lk);
13741 		stat_countp = &stat_ino_limit_hit;
13742 		break;
13743 
13744 	case FLUSH_BLOCKS:
13745 	case FLUSH_BLOCKS_WAIT:
13746 		ACQUIRE_GBLLOCK(&lk);
13747 		stat_blk_limit_push += 1;
13748 		req_clear_remove += 1;
13749 		FREE_GBLLOCK(&lk);
13750 		stat_countp = &stat_blk_limit_hit;
13751 		break;
13752 
13753 	default:
13754 		panic("request_cleanup: unknown type");
13755 	}
13756 	/*
13757 	 * Hopefully the syncer daemon will catch up and awaken us.
13758 	 * We wait at most tickdelay before proceeding in any case.
13759 	 */
13760 	ACQUIRE_GBLLOCK(&lk);
13761 	FREE_LOCK(ump);
13762 	proc_waiting += 1;
13763 	if (callout_pending(&softdep_callout) == FALSE)
13764 		callout_reset(&softdep_callout, tickdelay > 2 ? tickdelay : 2,
13765 		    pause_timer, 0);
13766 
13767 	if ((td->td_pflags & TDP_KTHREAD) == 0)
13768 		msleep((caddr_t)&proc_waiting, &lk, PPAUSE, "softupdate", 0);
13769 	proc_waiting -= 1;
13770 	FREE_GBLLOCK(&lk);
13771 	ACQUIRE_LOCK(ump);
13772 	return (1);
13773 }
13774 
13775 /*
13776  * Awaken processes pausing in request_cleanup and clear proc_waiting
13777  * to indicate that there is no longer a timer running. Pause_timer
13778  * will be called with the global softdep mutex (&lk) locked.
13779  */
13780 static void
13781 pause_timer(arg)
13782 	void *arg;
13783 {
13784 
13785 	GBLLOCK_OWNED(&lk);
13786 	/*
13787 	 * The callout_ API has acquired mtx and will hold it around this
13788 	 * function call.
13789 	 */
13790 	*stat_countp += proc_waiting;
13791 	wakeup(&proc_waiting);
13792 }
13793 
13794 /*
13795  * If requested, try removing inode or removal dependencies.
13796  */
13797 static void
13798 check_clear_deps(mp)
13799 	struct mount *mp;
13800 {
13801 	struct ufsmount *ump;
13802 	bool suj_susp;
13803 
13804 	/*
13805 	 * Tell the lower layers that any TRIM or WRITE transactions that have
13806 	 * been delayed for performance reasons should proceed to help alleviate
13807 	 * the shortage faster. The race between checking req_* and the softdep
13808 	 * mutex (lk) is fine since this is an advisory operation that at most
13809 	 * causes deferred work to be done sooner.
13810 	 */
13811 	ump = VFSTOUFS(mp);
13812 	suj_susp = MOUNTEDSUJ(mp) && ump->softdep_jblocks->jb_suspended;
13813 	if (req_clear_remove || req_clear_inodedeps || suj_susp) {
13814 		FREE_LOCK(ump);
13815 		softdep_send_speedup(ump, 0, BIO_SPEEDUP_TRIM | BIO_SPEEDUP_WRITE);
13816 		ACQUIRE_LOCK(ump);
13817 	}
13818 
13819 	/*
13820 	 * If we are suspended, it may be because of our using
13821 	 * too many inodedeps, so help clear them out.
13822 	 */
13823 	if (suj_susp)
13824 		clear_inodedeps(mp);
13825 
13826 	/*
13827 	 * General requests for cleanup of backed up dependencies
13828 	 */
13829 	ACQUIRE_GBLLOCK(&lk);
13830 	if (req_clear_inodedeps) {
13831 		req_clear_inodedeps -= 1;
13832 		FREE_GBLLOCK(&lk);
13833 		clear_inodedeps(mp);
13834 		ACQUIRE_GBLLOCK(&lk);
13835 		wakeup(&proc_waiting);
13836 	}
13837 	if (req_clear_remove) {
13838 		req_clear_remove -= 1;
13839 		FREE_GBLLOCK(&lk);
13840 		clear_remove(mp);
13841 		ACQUIRE_GBLLOCK(&lk);
13842 		wakeup(&proc_waiting);
13843 	}
13844 	FREE_GBLLOCK(&lk);
13845 }
13846 
13847 /*
13848  * Flush out a directory with at least one removal dependency in an effort to
13849  * reduce the number of dirrem, freefile, and freeblks dependency structures.
13850  */
13851 static void
13852 clear_remove(mp)
13853 	struct mount *mp;
13854 {
13855 	struct pagedep_hashhead *pagedephd;
13856 	struct pagedep *pagedep;
13857 	struct ufsmount *ump;
13858 	struct vnode *vp;
13859 	struct bufobj *bo;
13860 	int error, cnt;
13861 	ino_t ino;
13862 
13863 	ump = VFSTOUFS(mp);
13864 	LOCK_OWNED(ump);
13865 
13866 	for (cnt = 0; cnt <= ump->pagedep_hash_size; cnt++) {
13867 		pagedephd = &ump->pagedep_hashtbl[ump->pagedep_nextclean++];
13868 		if (ump->pagedep_nextclean > ump->pagedep_hash_size)
13869 			ump->pagedep_nextclean = 0;
13870 		LIST_FOREACH(pagedep, pagedephd, pd_hash) {
13871 			if (LIST_EMPTY(&pagedep->pd_dirremhd))
13872 				continue;
13873 			ino = pagedep->pd_ino;
13874 			if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13875 				continue;
13876 			FREE_LOCK(ump);
13877 
13878 			/*
13879 			 * Let unmount clear deps
13880 			 */
13881 			error = vfs_busy(mp, MBF_NOWAIT);
13882 			if (error != 0)
13883 				goto finish_write;
13884 			error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13885 			     FFSV_FORCEINSMQ);
13886 			vfs_unbusy(mp);
13887 			if (error != 0) {
13888 				softdep_error("clear_remove: vget", error);
13889 				goto finish_write;
13890 			}
13891 			MPASS(VTOI(vp)->i_mode != 0);
13892 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13893 				softdep_error("clear_remove: fsync", error);
13894 			bo = &vp->v_bufobj;
13895 			BO_LOCK(bo);
13896 			drain_output(vp);
13897 			BO_UNLOCK(bo);
13898 			vput(vp);
13899 		finish_write:
13900 			vn_finished_write(mp);
13901 			ACQUIRE_LOCK(ump);
13902 			return;
13903 		}
13904 	}
13905 }
13906 
13907 /*
13908  * Clear out a block of dirty inodes in an effort to reduce
13909  * the number of inodedep dependency structures.
13910  */
13911 static void
13912 clear_inodedeps(mp)
13913 	struct mount *mp;
13914 {
13915 	struct inodedep_hashhead *inodedephd;
13916 	struct inodedep *inodedep;
13917 	struct ufsmount *ump;
13918 	struct vnode *vp;
13919 	struct fs *fs;
13920 	int error, cnt;
13921 	ino_t firstino, lastino, ino;
13922 
13923 	ump = VFSTOUFS(mp);
13924 	fs = ump->um_fs;
13925 	LOCK_OWNED(ump);
13926 	/*
13927 	 * Pick a random inode dependency to be cleared.
13928 	 * We will then gather up all the inodes in its block
13929 	 * that have dependencies and flush them out.
13930 	 */
13931 	for (cnt = 0; cnt <= ump->inodedep_hash_size; cnt++) {
13932 		inodedephd = &ump->inodedep_hashtbl[ump->inodedep_nextclean++];
13933 		if (ump->inodedep_nextclean > ump->inodedep_hash_size)
13934 			ump->inodedep_nextclean = 0;
13935 		if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
13936 			break;
13937 	}
13938 	if (inodedep == NULL)
13939 		return;
13940 	/*
13941 	 * Find the last inode in the block with dependencies.
13942 	 */
13943 	firstino = rounddown2(inodedep->id_ino, INOPB(fs));
13944 	for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
13945 		if (inodedep_lookup(mp, lastino, 0, &inodedep) != 0)
13946 			break;
13947 	/*
13948 	 * Asynchronously push all but the last inode with dependencies.
13949 	 * Synchronously push the last inode with dependencies to ensure
13950 	 * that the inode block gets written to free up the inodedeps.
13951 	 */
13952 	for (ino = firstino; ino <= lastino; ino++) {
13953 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
13954 			continue;
13955 		if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13956 			continue;
13957 		FREE_LOCK(ump);
13958 		error = vfs_busy(mp, MBF_NOWAIT); /* Let unmount clear deps */
13959 		if (error != 0) {
13960 			vn_finished_write(mp);
13961 			ACQUIRE_LOCK(ump);
13962 			return;
13963 		}
13964 		if ((error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13965 		    FFSV_FORCEINSMQ)) != 0) {
13966 			softdep_error("clear_inodedeps: vget", error);
13967 			vfs_unbusy(mp);
13968 			vn_finished_write(mp);
13969 			ACQUIRE_LOCK(ump);
13970 			return;
13971 		}
13972 		vfs_unbusy(mp);
13973 		if (VTOI(vp)->i_mode == 0) {
13974 			vgone(vp);
13975 		} else if (ino == lastino) {
13976 			if ((error = ffs_syncvnode(vp, MNT_WAIT, 0)))
13977 				softdep_error("clear_inodedeps: fsync1", error);
13978 		} else {
13979 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13980 				softdep_error("clear_inodedeps: fsync2", error);
13981 			BO_LOCK(&vp->v_bufobj);
13982 			drain_output(vp);
13983 			BO_UNLOCK(&vp->v_bufobj);
13984 		}
13985 		vput(vp);
13986 		vn_finished_write(mp);
13987 		ACQUIRE_LOCK(ump);
13988 	}
13989 }
13990 
13991 void
13992 softdep_buf_append(bp, wkhd)
13993 	struct buf *bp;
13994 	struct workhead *wkhd;
13995 {
13996 	struct worklist *wk;
13997 	struct ufsmount *ump;
13998 
13999 	if ((wk = LIST_FIRST(wkhd)) == NULL)
14000 		return;
14001 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
14002 	    ("softdep_buf_append called on non-softdep filesystem"));
14003 	ump = VFSTOUFS(wk->wk_mp);
14004 	ACQUIRE_LOCK(ump);
14005 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
14006 		WORKLIST_REMOVE(wk);
14007 		WORKLIST_INSERT(&bp->b_dep, wk);
14008 	}
14009 	FREE_LOCK(ump);
14010 
14011 }
14012 
14013 void
14014 softdep_inode_append(ip, cred, wkhd)
14015 	struct inode *ip;
14016 	struct ucred *cred;
14017 	struct workhead *wkhd;
14018 {
14019 	struct buf *bp;
14020 	struct fs *fs;
14021 	struct ufsmount *ump;
14022 	int error;
14023 
14024 	ump = ITOUMP(ip);
14025 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
14026 	    ("softdep_inode_append called on non-softdep filesystem"));
14027 	fs = ump->um_fs;
14028 	error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
14029 	    (int)fs->fs_bsize, cred, &bp);
14030 	if (error) {
14031 		bqrelse(bp);
14032 		softdep_freework(wkhd);
14033 		return;
14034 	}
14035 	softdep_buf_append(bp, wkhd);
14036 	bqrelse(bp);
14037 }
14038 
14039 void
14040 softdep_freework(wkhd)
14041 	struct workhead *wkhd;
14042 {
14043 	struct worklist *wk;
14044 	struct ufsmount *ump;
14045 
14046 	if ((wk = LIST_FIRST(wkhd)) == NULL)
14047 		return;
14048 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
14049 	    ("softdep_freework called on non-softdep filesystem"));
14050 	ump = VFSTOUFS(wk->wk_mp);
14051 	ACQUIRE_LOCK(ump);
14052 	handle_jwork(wkhd);
14053 	FREE_LOCK(ump);
14054 }
14055 
14056 static struct ufsmount *
14057 softdep_bp_to_mp(bp)
14058 	struct buf *bp;
14059 {
14060 	struct mount *mp;
14061 	struct vnode *vp;
14062 
14063 	if (LIST_EMPTY(&bp->b_dep))
14064 		return (NULL);
14065 	vp = bp->b_vp;
14066 	KASSERT(vp != NULL,
14067 	    ("%s, buffer with dependencies lacks vnode", __func__));
14068 
14069 	/*
14070 	 * The ump mount point is stable after we get a correct
14071 	 * pointer, since bp is locked and this prevents unmount from
14072 	 * proceeding.  But to get to it, we cannot dereference bp->b_dep
14073 	 * head wk_mp, because we do not yet own SU ump lock and
14074 	 * workitem might be freed while dereferenced.
14075 	 */
14076 retry:
14077 	switch (vp->v_type) {
14078 	case VCHR:
14079 		VI_LOCK(vp);
14080 		mp = vp->v_type == VCHR ? vp->v_rdev->si_mountpt : NULL;
14081 		VI_UNLOCK(vp);
14082 		if (mp == NULL)
14083 			goto retry;
14084 		break;
14085 	case VREG:
14086 	case VDIR:
14087 	case VLNK:
14088 	case VFIFO:
14089 	case VSOCK:
14090 		mp = vp->v_mount;
14091 		break;
14092 	case VBLK:
14093 		vn_printf(vp, "softdep_bp_to_mp: unexpected block device\n");
14094 		/* FALLTHROUGH */
14095 	case VNON:
14096 	case VBAD:
14097 	case VMARKER:
14098 		mp = NULL;
14099 		break;
14100 	default:
14101 		vn_printf(vp, "unknown vnode type");
14102 		mp = NULL;
14103 		break;
14104 	}
14105 	return (VFSTOUFS(mp));
14106 }
14107 
14108 /*
14109  * Function to determine if the buffer has outstanding dependencies
14110  * that will cause a roll-back if the buffer is written. If wantcount
14111  * is set, return number of dependencies, otherwise just yes or no.
14112  */
14113 static int
14114 softdep_count_dependencies(bp, wantcount)
14115 	struct buf *bp;
14116 	int wantcount;
14117 {
14118 	struct worklist *wk;
14119 	struct ufsmount *ump;
14120 	struct bmsafemap *bmsafemap;
14121 	struct freework *freework;
14122 	struct inodedep *inodedep;
14123 	struct indirdep *indirdep;
14124 	struct freeblks *freeblks;
14125 	struct allocindir *aip;
14126 	struct pagedep *pagedep;
14127 	struct dirrem *dirrem;
14128 	struct newblk *newblk;
14129 	struct mkdir *mkdir;
14130 	struct diradd *dap;
14131 	int i, retval;
14132 
14133 	ump = softdep_bp_to_mp(bp);
14134 	if (ump == NULL)
14135 		return (0);
14136 	retval = 0;
14137 	ACQUIRE_LOCK(ump);
14138 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
14139 		switch (wk->wk_type) {
14140 
14141 		case D_INODEDEP:
14142 			inodedep = WK_INODEDEP(wk);
14143 			if ((inodedep->id_state & DEPCOMPLETE) == 0) {
14144 				/* bitmap allocation dependency */
14145 				retval += 1;
14146 				if (!wantcount)
14147 					goto out;
14148 			}
14149 			if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
14150 				/* direct block pointer dependency */
14151 				retval += 1;
14152 				if (!wantcount)
14153 					goto out;
14154 			}
14155 			if (TAILQ_FIRST(&inodedep->id_extupdt)) {
14156 				/* direct block pointer dependency */
14157 				retval += 1;
14158 				if (!wantcount)
14159 					goto out;
14160 			}
14161 			if (TAILQ_FIRST(&inodedep->id_inoreflst)) {
14162 				/* Add reference dependency. */
14163 				retval += 1;
14164 				if (!wantcount)
14165 					goto out;
14166 			}
14167 			continue;
14168 
14169 		case D_INDIRDEP:
14170 			indirdep = WK_INDIRDEP(wk);
14171 
14172 			TAILQ_FOREACH(freework, &indirdep->ir_trunc, fw_next) {
14173 				/* indirect truncation dependency */
14174 				retval += 1;
14175 				if (!wantcount)
14176 					goto out;
14177 			}
14178 
14179 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
14180 				/* indirect block pointer dependency */
14181 				retval += 1;
14182 				if (!wantcount)
14183 					goto out;
14184 			}
14185 			continue;
14186 
14187 		case D_PAGEDEP:
14188 			pagedep = WK_PAGEDEP(wk);
14189 			LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
14190 				if (LIST_FIRST(&dirrem->dm_jremrefhd)) {
14191 					/* Journal remove ref dependency. */
14192 					retval += 1;
14193 					if (!wantcount)
14194 						goto out;
14195 				}
14196 			}
14197 			for (i = 0; i < DAHASHSZ; i++) {
14198 
14199 				LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
14200 					/* directory entry dependency */
14201 					retval += 1;
14202 					if (!wantcount)
14203 						goto out;
14204 				}
14205 			}
14206 			continue;
14207 
14208 		case D_BMSAFEMAP:
14209 			bmsafemap = WK_BMSAFEMAP(wk);
14210 			if (LIST_FIRST(&bmsafemap->sm_jaddrefhd)) {
14211 				/* Add reference dependency. */
14212 				retval += 1;
14213 				if (!wantcount)
14214 					goto out;
14215 			}
14216 			if (LIST_FIRST(&bmsafemap->sm_jnewblkhd)) {
14217 				/* Allocate block dependency. */
14218 				retval += 1;
14219 				if (!wantcount)
14220 					goto out;
14221 			}
14222 			continue;
14223 
14224 		case D_FREEBLKS:
14225 			freeblks = WK_FREEBLKS(wk);
14226 			if (LIST_FIRST(&freeblks->fb_jblkdephd)) {
14227 				/* Freeblk journal dependency. */
14228 				retval += 1;
14229 				if (!wantcount)
14230 					goto out;
14231 			}
14232 			continue;
14233 
14234 		case D_ALLOCDIRECT:
14235 		case D_ALLOCINDIR:
14236 			newblk = WK_NEWBLK(wk);
14237 			if (newblk->nb_jnewblk) {
14238 				/* Journal allocate dependency. */
14239 				retval += 1;
14240 				if (!wantcount)
14241 					goto out;
14242 			}
14243 			continue;
14244 
14245 		case D_MKDIR:
14246 			mkdir = WK_MKDIR(wk);
14247 			if (mkdir->md_jaddref) {
14248 				/* Journal reference dependency. */
14249 				retval += 1;
14250 				if (!wantcount)
14251 					goto out;
14252 			}
14253 			continue;
14254 
14255 		case D_FREEWORK:
14256 		case D_FREEDEP:
14257 		case D_JSEGDEP:
14258 		case D_JSEG:
14259 		case D_SBDEP:
14260 			/* never a dependency on these blocks */
14261 			continue;
14262 
14263 		default:
14264 			panic("softdep_count_dependencies: Unexpected type %s",
14265 			    TYPENAME(wk->wk_type));
14266 			/* NOTREACHED */
14267 		}
14268 	}
14269 out:
14270 	FREE_LOCK(ump);
14271 	return (retval);
14272 }
14273 
14274 /*
14275  * Acquire exclusive access to a buffer.
14276  * Must be called with a locked mtx parameter.
14277  * Return acquired buffer or NULL on failure.
14278  */
14279 static struct buf *
14280 getdirtybuf(bp, lock, waitfor)
14281 	struct buf *bp;
14282 	struct rwlock *lock;
14283 	int waitfor;
14284 {
14285 	int error;
14286 
14287 	if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0) {
14288 		if (waitfor != MNT_WAIT)
14289 			return (NULL);
14290 		error = BUF_LOCK(bp,
14291 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, lock);
14292 		/*
14293 		 * Even if we successfully acquire bp here, we have dropped
14294 		 * lock, which may violates our guarantee.
14295 		 */
14296 		if (error == 0)
14297 			BUF_UNLOCK(bp);
14298 		else if (error != ENOLCK)
14299 			panic("getdirtybuf: inconsistent lock: %d", error);
14300 		rw_wlock(lock);
14301 		return (NULL);
14302 	}
14303 	if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14304 		if (lock != BO_LOCKPTR(bp->b_bufobj) && waitfor == MNT_WAIT) {
14305 			rw_wunlock(lock);
14306 			BO_LOCK(bp->b_bufobj);
14307 			BUF_UNLOCK(bp);
14308 			if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14309 				bp->b_vflags |= BV_BKGRDWAIT;
14310 				msleep(&bp->b_xflags, BO_LOCKPTR(bp->b_bufobj),
14311 				       PRIBIO | PDROP, "getbuf", 0);
14312 			} else
14313 				BO_UNLOCK(bp->b_bufobj);
14314 			rw_wlock(lock);
14315 			return (NULL);
14316 		}
14317 		BUF_UNLOCK(bp);
14318 		if (waitfor != MNT_WAIT)
14319 			return (NULL);
14320 #ifdef DEBUG_VFS_LOCKS
14321 		if (bp->b_vp->v_type != VCHR)
14322 			ASSERT_BO_WLOCKED(bp->b_bufobj);
14323 #endif
14324 		bp->b_vflags |= BV_BKGRDWAIT;
14325 		rw_sleep(&bp->b_xflags, lock, PRIBIO, "getbuf", 0);
14326 		return (NULL);
14327 	}
14328 	if ((bp->b_flags & B_DELWRI) == 0) {
14329 		BUF_UNLOCK(bp);
14330 		return (NULL);
14331 	}
14332 	bremfree(bp);
14333 	return (bp);
14334 }
14335 
14336 
14337 /*
14338  * Check if it is safe to suspend the file system now.  On entry,
14339  * the vnode interlock for devvp should be held.  Return 0 with
14340  * the mount interlock held if the file system can be suspended now,
14341  * otherwise return EAGAIN with the mount interlock held.
14342  */
14343 int
14344 softdep_check_suspend(struct mount *mp,
14345 		      struct vnode *devvp,
14346 		      int softdep_depcnt,
14347 		      int softdep_accdepcnt,
14348 		      int secondary_writes,
14349 		      int secondary_accwrites)
14350 {
14351 	struct bufobj *bo;
14352 	struct ufsmount *ump;
14353 	struct inodedep *inodedep;
14354 	int error, unlinked;
14355 
14356 	bo = &devvp->v_bufobj;
14357 	ASSERT_BO_WLOCKED(bo);
14358 
14359 	/*
14360 	 * If we are not running with soft updates, then we need only
14361 	 * deal with secondary writes as we try to suspend.
14362 	 */
14363 	if (MOUNTEDSOFTDEP(mp) == 0) {
14364 		MNT_ILOCK(mp);
14365 		while (mp->mnt_secondary_writes != 0) {
14366 			BO_UNLOCK(bo);
14367 			msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
14368 			    (PUSER - 1) | PDROP, "secwr", 0);
14369 			BO_LOCK(bo);
14370 			MNT_ILOCK(mp);
14371 		}
14372 
14373 		/*
14374 		 * Reasons for needing more work before suspend:
14375 		 * - Dirty buffers on devvp.
14376 		 * - Secondary writes occurred after start of vnode sync loop
14377 		 */
14378 		error = 0;
14379 		if (bo->bo_numoutput > 0 ||
14380 		    bo->bo_dirty.bv_cnt > 0 ||
14381 		    secondary_writes != 0 ||
14382 		    mp->mnt_secondary_writes != 0 ||
14383 		    secondary_accwrites != mp->mnt_secondary_accwrites)
14384 			error = EAGAIN;
14385 		BO_UNLOCK(bo);
14386 		return (error);
14387 	}
14388 
14389 	/*
14390 	 * If we are running with soft updates, then we need to coordinate
14391 	 * with them as we try to suspend.
14392 	 */
14393 	ump = VFSTOUFS(mp);
14394 	for (;;) {
14395 		if (!TRY_ACQUIRE_LOCK(ump)) {
14396 			BO_UNLOCK(bo);
14397 			ACQUIRE_LOCK(ump);
14398 			FREE_LOCK(ump);
14399 			BO_LOCK(bo);
14400 			continue;
14401 		}
14402 		MNT_ILOCK(mp);
14403 		if (mp->mnt_secondary_writes != 0) {
14404 			FREE_LOCK(ump);
14405 			BO_UNLOCK(bo);
14406 			msleep(&mp->mnt_secondary_writes,
14407 			       MNT_MTX(mp),
14408 			       (PUSER - 1) | PDROP, "secwr", 0);
14409 			BO_LOCK(bo);
14410 			continue;
14411 		}
14412 		break;
14413 	}
14414 
14415 	unlinked = 0;
14416 	if (MOUNTEDSUJ(mp)) {
14417 		for (inodedep = TAILQ_FIRST(&ump->softdep_unlinked);
14418 		    inodedep != NULL;
14419 		    inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
14420 			if ((inodedep->id_state & (UNLINKED | UNLINKLINKS |
14421 			    UNLINKONLIST)) != (UNLINKED | UNLINKLINKS |
14422 			    UNLINKONLIST) ||
14423 			    !check_inodedep_free(inodedep))
14424 				continue;
14425 			unlinked++;
14426 		}
14427 	}
14428 
14429 	/*
14430 	 * Reasons for needing more work before suspend:
14431 	 * - Dirty buffers on devvp.
14432 	 * - Softdep activity occurred after start of vnode sync loop
14433 	 * - Secondary writes occurred after start of vnode sync loop
14434 	 */
14435 	error = 0;
14436 	if (bo->bo_numoutput > 0 ||
14437 	    bo->bo_dirty.bv_cnt > 0 ||
14438 	    softdep_depcnt != unlinked ||
14439 	    ump->softdep_deps != unlinked ||
14440 	    softdep_accdepcnt != ump->softdep_accdeps ||
14441 	    secondary_writes != 0 ||
14442 	    mp->mnt_secondary_writes != 0 ||
14443 	    secondary_accwrites != mp->mnt_secondary_accwrites)
14444 		error = EAGAIN;
14445 	FREE_LOCK(ump);
14446 	BO_UNLOCK(bo);
14447 	return (error);
14448 }
14449 
14450 
14451 /*
14452  * Get the number of dependency structures for the file system, both
14453  * the current number and the total number allocated.  These will
14454  * later be used to detect that softdep processing has occurred.
14455  */
14456 void
14457 softdep_get_depcounts(struct mount *mp,
14458 		      int *softdep_depsp,
14459 		      int *softdep_accdepsp)
14460 {
14461 	struct ufsmount *ump;
14462 
14463 	if (MOUNTEDSOFTDEP(mp) == 0) {
14464 		*softdep_depsp = 0;
14465 		*softdep_accdepsp = 0;
14466 		return;
14467 	}
14468 	ump = VFSTOUFS(mp);
14469 	ACQUIRE_LOCK(ump);
14470 	*softdep_depsp = ump->softdep_deps;
14471 	*softdep_accdepsp = ump->softdep_accdeps;
14472 	FREE_LOCK(ump);
14473 }
14474 
14475 /*
14476  * Wait for pending output on a vnode to complete.
14477  */
14478 static void
14479 drain_output(vp)
14480 	struct vnode *vp;
14481 {
14482 
14483 	ASSERT_VOP_LOCKED(vp, "drain_output");
14484 	(void)bufobj_wwait(&vp->v_bufobj, 0, 0);
14485 }
14486 
14487 /*
14488  * Called whenever a buffer that is being invalidated or reallocated
14489  * contains dependencies. This should only happen if an I/O error has
14490  * occurred. The routine is called with the buffer locked.
14491  */
14492 static void
14493 softdep_deallocate_dependencies(bp)
14494 	struct buf *bp;
14495 {
14496 
14497 	if ((bp->b_ioflags & BIO_ERROR) == 0)
14498 		panic("softdep_deallocate_dependencies: dangling deps");
14499 	if (bp->b_vp != NULL && bp->b_vp->v_mount != NULL)
14500 		softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntonname, bp->b_error);
14501 	else
14502 		printf("softdep_deallocate_dependencies: "
14503 		    "got error %d while accessing filesystem\n", bp->b_error);
14504 	if (bp->b_error != ENXIO)
14505 		panic("softdep_deallocate_dependencies: unrecovered I/O error");
14506 }
14507 
14508 /*
14509  * Function to handle asynchronous write errors in the filesystem.
14510  */
14511 static void
14512 softdep_error(func, error)
14513 	char *func;
14514 	int error;
14515 {
14516 
14517 	/* XXX should do something better! */
14518 	printf("%s: got error %d while accessing filesystem\n", func, error);
14519 }
14520 
14521 #ifdef DDB
14522 
14523 /* exported to ffs_vfsops.c */
14524 extern void db_print_ffs(struct ufsmount *ump);
14525 void
14526 db_print_ffs(struct ufsmount *ump)
14527 {
14528 	db_printf("mp %p (%s) devvp %p\n", ump->um_mountp,
14529 	    ump->um_mountp->mnt_stat.f_mntonname, ump->um_devvp);
14530 	db_printf("    fs %p su_wl %d su_deps %d su_req %d\n",
14531 	    ump->um_fs, ump->softdep_on_worklist,
14532 	    ump->softdep_deps, ump->softdep_req);
14533 }
14534 
14535 static void
14536 worklist_print(struct worklist *wk, int verbose)
14537 {
14538 
14539 	if (!verbose) {
14540 		db_printf("%s: %p state 0x%b\n", TYPENAME(wk->wk_type), wk,
14541 		    (u_int)wk->wk_state, PRINT_SOFTDEP_FLAGS);
14542 		return;
14543 	}
14544 	db_printf("worklist: %p type %s state 0x%b next %p\n    ", wk,
14545 	    TYPENAME(wk->wk_type), (u_int)wk->wk_state, PRINT_SOFTDEP_FLAGS,
14546 	    LIST_NEXT(wk, wk_list));
14547 	db_print_ffs(VFSTOUFS(wk->wk_mp));
14548 }
14549 
14550 static void
14551 inodedep_print(struct inodedep *inodedep, int verbose)
14552 {
14553 
14554 	worklist_print(&inodedep->id_list, 0);
14555 	db_printf("    fs %p ino %jd inoblk %jd delta %jd nlink %jd\n",
14556 	    inodedep->id_fs,
14557 	    (intmax_t)inodedep->id_ino,
14558 	    (intmax_t)fsbtodb(inodedep->id_fs,
14559 	        ino_to_fsba(inodedep->id_fs, inodedep->id_ino)),
14560 	    (intmax_t)inodedep->id_nlinkdelta,
14561 	    (intmax_t)inodedep->id_savednlink);
14562 
14563 	if (verbose == 0)
14564 		return;
14565 
14566 	db_printf("    bmsafemap %p, mkdiradd %p, inoreflst %p\n",
14567 	    inodedep->id_bmsafemap,
14568 	    inodedep->id_mkdiradd,
14569 	    TAILQ_FIRST(&inodedep->id_inoreflst));
14570 	db_printf("    dirremhd %p, pendinghd %p, bufwait %p\n",
14571 	    LIST_FIRST(&inodedep->id_dirremhd),
14572 	    LIST_FIRST(&inodedep->id_pendinghd),
14573 	    LIST_FIRST(&inodedep->id_bufwait));
14574 	db_printf("    inowait %p, inoupdt %p, newinoupdt %p\n",
14575 	    LIST_FIRST(&inodedep->id_inowait),
14576 	    TAILQ_FIRST(&inodedep->id_inoupdt),
14577 	    TAILQ_FIRST(&inodedep->id_newinoupdt));
14578 	db_printf("    extupdt %p, newextupdt %p, freeblklst %p\n",
14579 	    TAILQ_FIRST(&inodedep->id_extupdt),
14580 	    TAILQ_FIRST(&inodedep->id_newextupdt),
14581 	    TAILQ_FIRST(&inodedep->id_freeblklst));
14582 	db_printf("    saveino %p, savedsize %jd, savedextsize %jd\n",
14583 	    inodedep->id_savedino1,
14584 	    (intmax_t)inodedep->id_savedsize,
14585 	    (intmax_t)inodedep->id_savedextsize);
14586 }
14587 
14588 static void
14589 newblk_print(struct newblk *nbp)
14590 {
14591 
14592 	worklist_print(&nbp->nb_list, 0);
14593 	db_printf("    newblkno %jd\n", (intmax_t)nbp->nb_newblkno);
14594 	db_printf("    jnewblk %p, bmsafemap %p, freefrag %p\n",
14595 	    &nbp->nb_jnewblk,
14596 	    &nbp->nb_bmsafemap,
14597 	    &nbp->nb_freefrag);
14598 	db_printf("    indirdeps %p, newdirblk %p, jwork %p\n",
14599 	    LIST_FIRST(&nbp->nb_indirdeps),
14600 	    LIST_FIRST(&nbp->nb_newdirblk),
14601 	    LIST_FIRST(&nbp->nb_jwork));
14602 }
14603 
14604 static void
14605 allocdirect_print(struct allocdirect *adp)
14606 {
14607 
14608 	newblk_print(&adp->ad_block);
14609 	db_printf("    oldblkno %jd, oldsize %ld, newsize %ld\n",
14610 	    adp->ad_oldblkno, adp->ad_oldsize, adp->ad_newsize);
14611 	db_printf("    offset %d, inodedep %p\n",
14612 	    adp->ad_offset, adp->ad_inodedep);
14613 }
14614 
14615 static void
14616 allocindir_print(struct allocindir *aip)
14617 {
14618 
14619 	newblk_print(&aip->ai_block);
14620 	db_printf("    oldblkno %jd, lbn %jd\n",
14621 	    (intmax_t)aip->ai_oldblkno, (intmax_t)aip->ai_lbn);
14622 	db_printf("    offset %d, indirdep %p\n",
14623 	    aip->ai_offset, aip->ai_indirdep);
14624 }
14625 
14626 static void
14627 mkdir_print(struct mkdir *mkdir)
14628 {
14629 
14630 	worklist_print(&mkdir->md_list, 0);
14631 	db_printf("    diradd %p, jaddref %p, buf %p\n",
14632 		mkdir->md_diradd, mkdir->md_jaddref, mkdir->md_buf);
14633 }
14634 
14635 DB_SHOW_COMMAND(sd_inodedep, db_show_sd_inodedep)
14636 {
14637 
14638 	if (have_addr == 0) {
14639 		db_printf("inodedep address required\n");
14640 		return;
14641 	}
14642 	inodedep_print((struct inodedep*)addr, 1);
14643 }
14644 
14645 DB_SHOW_COMMAND(sd_allinodedeps, db_show_sd_allinodedeps)
14646 {
14647 	struct inodedep_hashhead *inodedephd;
14648 	struct inodedep *inodedep;
14649 	struct ufsmount *ump;
14650 	int cnt;
14651 
14652 	if (have_addr == 0) {
14653 		db_printf("ufsmount address required\n");
14654 		return;
14655 	}
14656 	ump = (struct ufsmount *)addr;
14657 	for (cnt = 0; cnt < ump->inodedep_hash_size; cnt++) {
14658 		inodedephd = &ump->inodedep_hashtbl[cnt];
14659 		LIST_FOREACH(inodedep, inodedephd, id_hash) {
14660 			inodedep_print(inodedep, 0);
14661 		}
14662 	}
14663 }
14664 
14665 DB_SHOW_COMMAND(sd_worklist, db_show_sd_worklist)
14666 {
14667 
14668 	if (have_addr == 0) {
14669 		db_printf("worklist address required\n");
14670 		return;
14671 	}
14672 	worklist_print((struct worklist *)addr, 1);
14673 }
14674 
14675 DB_SHOW_COMMAND(sd_workhead, db_show_sd_workhead)
14676 {
14677 	struct worklist *wk;
14678 	struct workhead *wkhd;
14679 
14680 	if (have_addr == 0) {
14681 		db_printf("worklist address required "
14682 		    "(for example value in bp->b_dep)\n");
14683 		return;
14684 	}
14685 	/*
14686 	 * We often do not have the address of the worklist head but
14687 	 * instead a pointer to its first entry (e.g., we have the
14688 	 * contents of bp->b_dep rather than &bp->b_dep). But the back
14689 	 * pointer of bp->b_dep will point at the head of the list, so
14690 	 * we cheat and use that instead. If we are in the middle of
14691 	 * a list we will still get the same result, so nothing
14692 	 * unexpected will result.
14693 	 */
14694 	wk = (struct worklist *)addr;
14695 	if (wk == NULL)
14696 		return;
14697 	wkhd = (struct workhead *)wk->wk_list.le_prev;
14698 	LIST_FOREACH(wk, wkhd, wk_list) {
14699 		switch(wk->wk_type) {
14700 		case D_INODEDEP:
14701 			inodedep_print(WK_INODEDEP(wk), 0);
14702 			continue;
14703 		case D_ALLOCDIRECT:
14704 			allocdirect_print(WK_ALLOCDIRECT(wk));
14705 			continue;
14706 		case D_ALLOCINDIR:
14707 			allocindir_print(WK_ALLOCINDIR(wk));
14708 			continue;
14709 		case D_MKDIR:
14710 			mkdir_print(WK_MKDIR(wk));
14711 			continue;
14712 		default:
14713 			worklist_print(wk, 0);
14714 			continue;
14715 		}
14716 	}
14717 }
14718 
14719 DB_SHOW_COMMAND(sd_mkdir, db_show_sd_mkdir)
14720 {
14721 	if (have_addr == 0) {
14722 		db_printf("mkdir address required\n");
14723 		return;
14724 	}
14725 	mkdir_print((struct mkdir *)addr);
14726 }
14727 
14728 DB_SHOW_COMMAND(sd_mkdir_list, db_show_sd_mkdir_list)
14729 {
14730 	struct mkdirlist *mkdirlisthd;
14731 	struct mkdir *mkdir;
14732 
14733 	if (have_addr == 0) {
14734 		db_printf("mkdir listhead address required\n");
14735 		return;
14736 	}
14737 	mkdirlisthd = (struct mkdirlist *)addr;
14738 	LIST_FOREACH(mkdir, mkdirlisthd, md_mkdirs) {
14739 		mkdir_print(mkdir);
14740 		if (mkdir->md_diradd != NULL) {
14741 			db_printf("    ");
14742 			worklist_print(&mkdir->md_diradd->da_list, 0);
14743 		}
14744 		if (mkdir->md_jaddref != NULL) {
14745 			db_printf("    ");
14746 			worklist_print(&mkdir->md_jaddref->ja_list, 0);
14747 		}
14748 	}
14749 }
14750 
14751 DB_SHOW_COMMAND(sd_allocdirect, db_show_sd_allocdirect)
14752 {
14753 	if (have_addr == 0) {
14754 		db_printf("allocdirect address required\n");
14755 		return;
14756 	}
14757 	allocdirect_print((struct allocdirect *)addr);
14758 }
14759 
14760 DB_SHOW_COMMAND(sd_allocindir, db_show_sd_allocindir)
14761 {
14762 	if (have_addr == 0) {
14763 		db_printf("allocindir address required\n");
14764 		return;
14765 	}
14766 	allocindir_print((struct allocindir *)addr);
14767 }
14768 
14769 #endif /* DDB */
14770 
14771 #endif /* SOFTUPDATES */
14772