xref: /freebsd/sys/ufs/ffs/ffs_softdep.c (revision cefe58791b0fc5243250b2449107540b03d64689)
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(struct mount *oldmnt,
100 	int flags,
101 	struct thread *td)
102 {
103 
104 	panic("softdep_flushfiles called");
105 }
106 
107 int
108 softdep_mount(struct vnode *devvp,
109 	struct mount *mp,
110 	struct fs *fs,
111 	struct ucred *cred)
112 {
113 
114 	return (0);
115 }
116 
117 void
118 softdep_initialize(void)
119 {
120 
121 	return;
122 }
123 
124 void
125 softdep_uninitialize(void)
126 {
127 
128 	return;
129 }
130 
131 void
132 softdep_unmount(struct mount *mp)
133 {
134 
135 	panic("softdep_unmount called");
136 }
137 
138 void
139 softdep_setup_sbupdate(struct ufsmount *ump,
140 	struct fs *fs,
141 	struct buf *bp)
142 {
143 
144 	panic("softdep_setup_sbupdate called");
145 }
146 
147 void
148 softdep_setup_inomapdep(struct buf *bp,
149 	struct inode *ip,
150 	ino_t newinum,
151 	int mode)
152 {
153 
154 	panic("softdep_setup_inomapdep called");
155 }
156 
157 void
158 softdep_setup_blkmapdep(struct buf *bp,
159 	struct mount *mp,
160 	ufs2_daddr_t newblkno,
161 	int frags,
162 	int oldfrags)
163 {
164 
165 	panic("softdep_setup_blkmapdep called");
166 }
167 
168 void
169 softdep_setup_allocdirect(struct inode *ip,
170 	ufs_lbn_t lbn,
171 	ufs2_daddr_t newblkno,
172 	ufs2_daddr_t oldblkno,
173 	long newsize,
174 	long oldsize,
175 	struct buf *bp)
176 {
177 
178 	panic("softdep_setup_allocdirect called");
179 }
180 
181 void
182 softdep_setup_allocext(struct inode *ip,
183 	ufs_lbn_t lbn,
184 	ufs2_daddr_t newblkno,
185 	ufs2_daddr_t oldblkno,
186 	long newsize,
187 	long oldsize,
188 	struct buf *bp)
189 {
190 
191 	panic("softdep_setup_allocext called");
192 }
193 
194 void
195 softdep_setup_allocindir_page(struct inode *ip,
196 	ufs_lbn_t lbn,
197 	struct buf *bp,
198 	int ptrno,
199 	ufs2_daddr_t newblkno,
200 	ufs2_daddr_t oldblkno,
201 	struct buf *nbp)
202 {
203 
204 	panic("softdep_setup_allocindir_page called");
205 }
206 
207 void
208 softdep_setup_allocindir_meta(struct buf *nbp,
209 	struct inode *ip,
210 	struct buf *bp,
211 	int ptrno,
212 	ufs2_daddr_t newblkno)
213 {
214 
215 	panic("softdep_setup_allocindir_meta called");
216 }
217 
218 void
219 softdep_journal_freeblocks(struct inode *ip,
220 	struct ucred *cred,
221 	off_t length,
222 	int flags)
223 {
224 
225 	panic("softdep_journal_freeblocks called");
226 }
227 
228 void
229 softdep_journal_fsync(struct inode *ip)
230 {
231 
232 	panic("softdep_journal_fsync called");
233 }
234 
235 void
236 softdep_setup_freeblocks(struct inode *ip,
237 	off_t length,
238 	int flags)
239 {
240 
241 	panic("softdep_setup_freeblocks called");
242 }
243 
244 void
245 softdep_freefile(struct vnode *pvp,
246 		ino_t ino,
247 		int mode)
248 {
249 
250 	panic("softdep_freefile called");
251 }
252 
253 int
254 softdep_setup_directory_add(struct buf *bp,
255 	struct inode *dp,
256 	off_t diroffset,
257 	ino_t newinum,
258 	struct buf *newdirbp,
259 	int isnewblk)
260 {
261 
262 	panic("softdep_setup_directory_add called");
263 }
264 
265 void
266 softdep_change_directoryentry_offset(struct buf *bp,
267 	struct inode *dp,
268 	caddr_t base,
269 	caddr_t oldloc,
270 	caddr_t newloc,
271 	int entrysize)
272 {
273 
274 	panic("softdep_change_directoryentry_offset called");
275 }
276 
277 void
278 softdep_setup_remove(struct buf *bp,
279 	struct inode *dp,
280 	struct inode *ip,
281 	int isrmdir)
282 {
283 
284 	panic("softdep_setup_remove called");
285 }
286 
287 void
288 softdep_setup_directory_change(struct buf *bp,
289 	struct inode *dp,
290 	struct inode *ip,
291 	ino_t newinum,
292 	int isrmdir)
293 {
294 
295 	panic("softdep_setup_directory_change called");
296 }
297 
298 void
299 softdep_setup_blkfree(struct mount *mp,
300 	struct buf *bp,
301 	ufs2_daddr_t blkno,
302 	int frags,
303 	struct workhead *wkhd)
304 {
305 
306 	panic("%s called", __FUNCTION__);
307 }
308 
309 void
310 softdep_setup_inofree(struct mount *mp,
311 	struct buf *bp,
312 	ino_t ino,
313 	struct workhead *wkhd)
314 {
315 
316 	panic("%s called", __FUNCTION__);
317 }
318 
319 void
320 softdep_setup_unlink(struct inode *dp, struct inode *ip)
321 {
322 
323 	panic("%s called", __FUNCTION__);
324 }
325 
326 void
327 softdep_setup_link(struct inode *dp, struct inode *ip)
328 {
329 
330 	panic("%s called", __FUNCTION__);
331 }
332 
333 void
334 softdep_revert_link(struct inode *dp, struct inode *ip)
335 {
336 
337 	panic("%s called", __FUNCTION__);
338 }
339 
340 void
341 softdep_setup_rmdir(struct inode *dp, struct inode *ip)
342 {
343 
344 	panic("%s called", __FUNCTION__);
345 }
346 
347 void
348 softdep_revert_rmdir(struct inode *dp, struct inode *ip)
349 {
350 
351 	panic("%s called", __FUNCTION__);
352 }
353 
354 void
355 softdep_setup_create(struct inode *dp, struct inode *ip)
356 {
357 
358 	panic("%s called", __FUNCTION__);
359 }
360 
361 void
362 softdep_revert_create(struct inode *dp, struct inode *ip)
363 {
364 
365 	panic("%s called", __FUNCTION__);
366 }
367 
368 void
369 softdep_setup_mkdir(struct inode *dp, struct inode *ip)
370 {
371 
372 	panic("%s called", __FUNCTION__);
373 }
374 
375 void
376 softdep_revert_mkdir(struct inode *dp, struct inode *ip)
377 {
378 
379 	panic("%s called", __FUNCTION__);
380 }
381 
382 void
383 softdep_setup_dotdot_link(struct inode *dp, struct inode *ip)
384 {
385 
386 	panic("%s called", __FUNCTION__);
387 }
388 
389 int
390 softdep_prealloc(struct vnode *vp, int waitok)
391 {
392 
393 	panic("%s called", __FUNCTION__);
394 }
395 
396 int
397 softdep_journal_lookup(struct mount *mp, struct vnode **vpp)
398 {
399 
400 	return (ENOENT);
401 }
402 
403 void
404 softdep_change_linkcnt(struct inode *ip)
405 {
406 
407 	panic("softdep_change_linkcnt called");
408 }
409 
410 void
411 softdep_load_inodeblock(struct inode *ip)
412 {
413 
414 	panic("softdep_load_inodeblock called");
415 }
416 
417 void
418 softdep_update_inodeblock(struct inode *ip,
419 	struct buf *bp,
420 	int waitfor)
421 {
422 
423 	panic("softdep_update_inodeblock called");
424 }
425 
426 int
427 softdep_fsync(struct vnode *vp)	/* the "in_core" copy of the inode */
428 {
429 
430 	return (0);
431 }
432 
433 void
434 softdep_fsync_mountdev(struct vnode *vp)
435 {
436 
437 	return;
438 }
439 
440 int
441 softdep_flushworklist(struct mount *oldmnt,
442 	int *countp,
443 	struct thread *td)
444 {
445 
446 	*countp = 0;
447 	return (0);
448 }
449 
450 int
451 softdep_sync_metadata(struct vnode *vp)
452 {
453 
454 	panic("softdep_sync_metadata called");
455 }
456 
457 int
458 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
459 {
460 
461 	panic("softdep_sync_buf called");
462 }
463 
464 int
465 softdep_slowdown(struct vnode *vp)
466 {
467 
468 	panic("softdep_slowdown called");
469 }
470 
471 int
472 softdep_request_cleanup(struct fs *fs,
473 	struct vnode *vp,
474 	struct ucred *cred,
475 	int resource)
476 {
477 
478 	return (0);
479 }
480 
481 int
482 softdep_check_suspend(struct mount *mp,
483 		      struct vnode *devvp,
484 		      int softdep_depcnt,
485 		      int softdep_accdepcnt,
486 		      int secondary_writes,
487 		      int secondary_accwrites)
488 {
489 	struct bufobj *bo;
490 	int error;
491 
492 	(void) softdep_depcnt,
493 	(void) softdep_accdepcnt;
494 
495 	bo = &devvp->v_bufobj;
496 	ASSERT_BO_WLOCKED(bo);
497 
498 	MNT_ILOCK(mp);
499 	while (mp->mnt_secondary_writes != 0) {
500 		BO_UNLOCK(bo);
501 		msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
502 		    (PUSER - 1) | PDROP, "secwr", 0);
503 		BO_LOCK(bo);
504 		MNT_ILOCK(mp);
505 	}
506 
507 	/*
508 	 * Reasons for needing more work before suspend:
509 	 * - Dirty buffers on devvp.
510 	 * - Secondary writes occurred after start of vnode sync loop
511 	 */
512 	error = 0;
513 	if (bo->bo_numoutput > 0 ||
514 	    bo->bo_dirty.bv_cnt > 0 ||
515 	    secondary_writes != 0 ||
516 	    mp->mnt_secondary_writes != 0 ||
517 	    secondary_accwrites != mp->mnt_secondary_accwrites)
518 		error = EAGAIN;
519 	BO_UNLOCK(bo);
520 	return (error);
521 }
522 
523 void
524 softdep_get_depcounts(struct mount *mp,
525 		      int *softdepactivep,
526 		      int *softdepactiveaccp)
527 {
528 	(void) mp;
529 	*softdepactivep = 0;
530 	*softdepactiveaccp = 0;
531 }
532 
533 void
534 softdep_buf_append(struct buf *bp, struct workhead *wkhd)
535 {
536 
537 	panic("softdep_buf_appendwork called");
538 }
539 
540 void
541 softdep_inode_append(struct inode *ip,
542 	struct ucred *cred,
543 	struct workhead *wkhd)
544 {
545 
546 	panic("softdep_inode_appendwork called");
547 }
548 
549 void
550 softdep_freework(struct workhead *wkhd)
551 {
552 
553 	panic("softdep_freework called");
554 }
555 
556 int
557 softdep_prerename(struct vnode *fdvp,
558 	struct vnode *fvp,
559 	struct vnode *tdvp,
560 	struct vnode *tvp)
561 {
562 
563 	panic("softdep_prerename called");
564 }
565 
566 int
567 softdep_prelink(struct vnode *dvp,
568 	struct vnode *vp,
569 	struct componentname *cnp)
570 {
571 
572 	panic("softdep_prelink called");
573 }
574 
575 #else
576 
577 FEATURE(softupdates, "FFS soft-updates support");
578 
579 static SYSCTL_NODE(_debug, OID_AUTO, softdep, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
580     "soft updates stats");
581 static SYSCTL_NODE(_debug_softdep, OID_AUTO, total,
582     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
583     "total dependencies allocated");
584 static SYSCTL_NODE(_debug_softdep, OID_AUTO, highuse,
585     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
586     "high use dependencies allocated");
587 static SYSCTL_NODE(_debug_softdep, OID_AUTO, current,
588     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
589     "current dependencies allocated");
590 static SYSCTL_NODE(_debug_softdep, OID_AUTO, write,
591     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
592     "current dependencies written");
593 
594 unsigned long dep_current[D_LAST + 1];
595 unsigned long dep_highuse[D_LAST + 1];
596 unsigned long dep_total[D_LAST + 1];
597 unsigned long dep_write[D_LAST + 1];
598 
599 #define	SOFTDEP_TYPE(type, str, long)					\
600     static MALLOC_DEFINE(M_ ## type, #str, long);			\
601     SYSCTL_ULONG(_debug_softdep_total, OID_AUTO, str, CTLFLAG_RD,	\
602 	&dep_total[D_ ## type], 0, "");					\
603     SYSCTL_ULONG(_debug_softdep_current, OID_AUTO, str, CTLFLAG_RD, 	\
604 	&dep_current[D_ ## type], 0, "");				\
605     SYSCTL_ULONG(_debug_softdep_highuse, OID_AUTO, str, CTLFLAG_RD, 	\
606 	&dep_highuse[D_ ## type], 0, "");				\
607     SYSCTL_ULONG(_debug_softdep_write, OID_AUTO, str, CTLFLAG_RD, 	\
608 	&dep_write[D_ ## type], 0, "");
609 
610 SOFTDEP_TYPE(PAGEDEP, pagedep, "File page dependencies");
611 SOFTDEP_TYPE(INODEDEP, inodedep, "Inode dependencies");
612 SOFTDEP_TYPE(BMSAFEMAP, bmsafemap,
613     "Block or frag allocated from cyl group map");
614 SOFTDEP_TYPE(NEWBLK, newblk, "New block or frag allocation dependency");
615 SOFTDEP_TYPE(ALLOCDIRECT, allocdirect, "Block or frag dependency for an inode");
616 SOFTDEP_TYPE(INDIRDEP, indirdep, "Indirect block dependencies");
617 SOFTDEP_TYPE(ALLOCINDIR, allocindir, "Block dependency for an indirect block");
618 SOFTDEP_TYPE(FREEFRAG, freefrag, "Previously used frag for an inode");
619 SOFTDEP_TYPE(FREEBLKS, freeblks, "Blocks freed from an inode");
620 SOFTDEP_TYPE(FREEFILE, freefile, "Inode deallocated");
621 SOFTDEP_TYPE(DIRADD, diradd, "New directory entry");
622 SOFTDEP_TYPE(MKDIR, mkdir, "New directory");
623 SOFTDEP_TYPE(DIRREM, dirrem, "Directory entry deleted");
624 SOFTDEP_TYPE(NEWDIRBLK, newdirblk, "Unclaimed new directory block");
625 SOFTDEP_TYPE(FREEWORK, freework, "free an inode block");
626 SOFTDEP_TYPE(FREEDEP, freedep, "track a block free");
627 SOFTDEP_TYPE(JADDREF, jaddref, "Journal inode ref add");
628 SOFTDEP_TYPE(JREMREF, jremref, "Journal inode ref remove");
629 SOFTDEP_TYPE(JMVREF, jmvref, "Journal inode ref move");
630 SOFTDEP_TYPE(JNEWBLK, jnewblk, "Journal new block");
631 SOFTDEP_TYPE(JFREEBLK, jfreeblk, "Journal free block");
632 SOFTDEP_TYPE(JFREEFRAG, jfreefrag, "Journal free frag");
633 SOFTDEP_TYPE(JSEG, jseg, "Journal segment");
634 SOFTDEP_TYPE(JSEGDEP, jsegdep, "Journal segment complete");
635 SOFTDEP_TYPE(SBDEP, sbdep, "Superblock write dependency");
636 SOFTDEP_TYPE(JTRUNC, jtrunc, "Journal inode truncation");
637 SOFTDEP_TYPE(JFSYNC, jfsync, "Journal fsync complete");
638 
639 static MALLOC_DEFINE(M_SENTINEL, "sentinel", "Worklist sentinel");
640 
641 static MALLOC_DEFINE(M_SAVEDINO, "savedino", "Saved inodes");
642 static MALLOC_DEFINE(M_JBLOCKS, "jblocks", "Journal block locations");
643 static MALLOC_DEFINE(M_MOUNTDATA, "softdep", "Softdep per-mount data");
644 
645 #define M_SOFTDEP_FLAGS	(M_WAITOK)
646 
647 /*
648  * translate from workitem type to memory type
649  * MUST match the defines above, such that memtype[D_XXX] == M_XXX
650  */
651 static struct malloc_type *memtype[] = {
652 	NULL,
653 	M_PAGEDEP,
654 	M_INODEDEP,
655 	M_BMSAFEMAP,
656 	M_NEWBLK,
657 	M_ALLOCDIRECT,
658 	M_INDIRDEP,
659 	M_ALLOCINDIR,
660 	M_FREEFRAG,
661 	M_FREEBLKS,
662 	M_FREEFILE,
663 	M_DIRADD,
664 	M_MKDIR,
665 	M_DIRREM,
666 	M_NEWDIRBLK,
667 	M_FREEWORK,
668 	M_FREEDEP,
669 	M_JADDREF,
670 	M_JREMREF,
671 	M_JMVREF,
672 	M_JNEWBLK,
673 	M_JFREEBLK,
674 	M_JFREEFRAG,
675 	M_JSEG,
676 	M_JSEGDEP,
677 	M_SBDEP,
678 	M_JTRUNC,
679 	M_JFSYNC,
680 	M_SENTINEL
681 };
682 
683 #define DtoM(type) (memtype[type])
684 
685 /*
686  * Names of malloc types.
687  */
688 #define TYPENAME(type)  \
689 	((unsigned)(type) <= D_LAST && (unsigned)(type) >= D_FIRST ? \
690 	memtype[type]->ks_shortdesc : "???")
691 /*
692  * End system adaptation definitions.
693  */
694 
695 #define	DOTDOT_OFFSET	offsetof(struct dirtemplate, dotdot_ino)
696 #define	DOT_OFFSET	offsetof(struct dirtemplate, dot_ino)
697 
698 /*
699  * Internal function prototypes.
700  */
701 static	void check_clear_deps(struct mount *);
702 static	void softdep_error(char *, int);
703 static	int softdep_prerename_vnode(struct ufsmount *, struct vnode *);
704 static	int softdep_process_worklist(struct mount *, int);
705 static	int softdep_waitidle(struct mount *, int);
706 static	void drain_output(struct vnode *);
707 static	struct buf *getdirtybuf(struct buf *, struct rwlock *, int);
708 static	int check_inodedep_free(struct inodedep *);
709 static	void clear_remove(struct mount *);
710 static	void clear_inodedeps(struct mount *);
711 static	void unlinked_inodedep(struct mount *, struct inodedep *);
712 static	void clear_unlinked_inodedep(struct inodedep *);
713 static	struct inodedep *first_unlinked_inodedep(struct ufsmount *);
714 static	int flush_pagedep_deps(struct vnode *, struct mount *,
715 	    struct diraddhd *, struct buf *);
716 static	int free_pagedep(struct pagedep *);
717 static	int flush_newblk_dep(struct vnode *, struct mount *, ufs_lbn_t);
718 static	int flush_inodedep_deps(struct vnode *, struct mount *, ino_t);
719 static	int flush_deplist(struct allocdirectlst *, int, int *);
720 static	int sync_cgs(struct mount *, int);
721 static	int handle_written_filepage(struct pagedep *, struct buf *, int);
722 static	int handle_written_sbdep(struct sbdep *, struct buf *);
723 static	void initiate_write_sbdep(struct sbdep *);
724 static	void diradd_inode_written(struct diradd *, struct inodedep *);
725 static	int handle_written_indirdep(struct indirdep *, struct buf *,
726 	    struct buf**, int);
727 static	int handle_written_inodeblock(struct inodedep *, struct buf *, int);
728 static	int jnewblk_rollforward(struct jnewblk *, struct fs *, struct cg *,
729 	    uint8_t *);
730 static	int handle_written_bmsafemap(struct bmsafemap *, struct buf *, int);
731 static	void handle_written_jaddref(struct jaddref *);
732 static	void handle_written_jremref(struct jremref *);
733 static	void handle_written_jseg(struct jseg *, struct buf *);
734 static	void handle_written_jnewblk(struct jnewblk *);
735 static	void handle_written_jblkdep(struct jblkdep *);
736 static	void handle_written_jfreefrag(struct jfreefrag *);
737 static	void complete_jseg(struct jseg *);
738 static	void complete_jsegs(struct jseg *);
739 static	void jseg_write(struct ufsmount *ump, struct jseg *, uint8_t *);
740 static	void jaddref_write(struct jaddref *, struct jseg *, uint8_t *);
741 static	void jremref_write(struct jremref *, struct jseg *, uint8_t *);
742 static	void jmvref_write(struct jmvref *, struct jseg *, uint8_t *);
743 static	void jtrunc_write(struct jtrunc *, struct jseg *, uint8_t *);
744 static	void jfsync_write(struct jfsync *, struct jseg *, uint8_t *data);
745 static	void jnewblk_write(struct jnewblk *, struct jseg *, uint8_t *);
746 static	void jfreeblk_write(struct jfreeblk *, struct jseg *, uint8_t *);
747 static	void jfreefrag_write(struct jfreefrag *, struct jseg *, uint8_t *);
748 static	inline void inoref_write(struct inoref *, struct jseg *,
749 	    struct jrefrec *);
750 static	void handle_allocdirect_partdone(struct allocdirect *,
751 	    struct workhead *);
752 static	struct jnewblk *cancel_newblk(struct newblk *, struct worklist *,
753 	    struct workhead *);
754 static	void indirdep_complete(struct indirdep *);
755 static	int indirblk_lookup(struct mount *, ufs2_daddr_t);
756 static	void indirblk_insert(struct freework *);
757 static	void indirblk_remove(struct freework *);
758 static	void handle_allocindir_partdone(struct allocindir *);
759 static	void initiate_write_filepage(struct pagedep *, struct buf *);
760 static	void initiate_write_indirdep(struct indirdep*, struct buf *);
761 static	void handle_written_mkdir(struct mkdir *, int);
762 static	int jnewblk_rollback(struct jnewblk *, struct fs *, struct cg *,
763 	    uint8_t *);
764 static	void initiate_write_bmsafemap(struct bmsafemap *, struct buf *);
765 static	void initiate_write_inodeblock_ufs1(struct inodedep *, struct buf *);
766 static	void initiate_write_inodeblock_ufs2(struct inodedep *, struct buf *);
767 static	void handle_workitem_freefile(struct freefile *);
768 static	int handle_workitem_remove(struct dirrem *, int);
769 static	struct dirrem *newdirrem(struct buf *, struct inode *,
770 	    struct inode *, int, struct dirrem **);
771 static	struct indirdep *indirdep_lookup(struct mount *, struct inode *,
772 	    struct buf *);
773 static	void cancel_indirdep(struct indirdep *, struct buf *,
774 	    struct freeblks *);
775 static	void free_indirdep(struct indirdep *);
776 static	void free_diradd(struct diradd *, struct workhead *);
777 static	void merge_diradd(struct inodedep *, struct diradd *);
778 static	void complete_diradd(struct diradd *);
779 static	struct diradd *diradd_lookup(struct pagedep *, int);
780 static	struct jremref *cancel_diradd_dotdot(struct inode *, struct dirrem *,
781 	    struct jremref *);
782 static	struct jremref *cancel_mkdir_dotdot(struct inode *, struct dirrem *,
783 	    struct jremref *);
784 static	void cancel_diradd(struct diradd *, struct dirrem *, struct jremref *,
785 	    struct jremref *, struct jremref *);
786 static	void dirrem_journal(struct dirrem *, struct jremref *, struct jremref *,
787 	    struct jremref *);
788 static	void cancel_allocindir(struct allocindir *, struct buf *bp,
789 	    struct freeblks *, int);
790 static	int setup_trunc_indir(struct freeblks *, struct inode *,
791 	    ufs_lbn_t, ufs_lbn_t, ufs2_daddr_t);
792 static	void complete_trunc_indir(struct freework *);
793 static	void trunc_indirdep(struct indirdep *, struct freeblks *, struct buf *,
794 	    int);
795 static	void complete_mkdir(struct mkdir *);
796 static	void free_newdirblk(struct newdirblk *);
797 static	void free_jremref(struct jremref *);
798 static	void free_jaddref(struct jaddref *);
799 static	void free_jsegdep(struct jsegdep *);
800 static	void free_jsegs(struct jblocks *);
801 static	void rele_jseg(struct jseg *);
802 static	void free_jseg(struct jseg *, struct jblocks *);
803 static	void free_jnewblk(struct jnewblk *);
804 static	void free_jblkdep(struct jblkdep *);
805 static	void free_jfreefrag(struct jfreefrag *);
806 static	void free_freedep(struct freedep *);
807 static	void journal_jremref(struct dirrem *, struct jremref *,
808 	    struct inodedep *);
809 static	void cancel_jnewblk(struct jnewblk *, struct workhead *);
810 static	int cancel_jaddref(struct jaddref *, struct inodedep *,
811 	    struct workhead *);
812 static	void cancel_jfreefrag(struct jfreefrag *);
813 static	inline void setup_freedirect(struct freeblks *, struct inode *,
814 	    int, int);
815 static	inline void setup_freeext(struct freeblks *, struct inode *, int, int);
816 static	inline void setup_freeindir(struct freeblks *, struct inode *, int,
817 	    ufs_lbn_t, int);
818 static	inline struct freeblks *newfreeblks(struct mount *, struct inode *);
819 static	void freeblks_free(struct ufsmount *, struct freeblks *, int);
820 static	void indir_trunc(struct freework *, ufs2_daddr_t, ufs_lbn_t);
821 static	ufs2_daddr_t blkcount(struct fs *, ufs2_daddr_t, off_t);
822 static	int trunc_check_buf(struct buf *, int *, ufs_lbn_t, int, int);
823 static	void trunc_dependencies(struct inode *, struct freeblks *, ufs_lbn_t,
824 	    int, int);
825 static	void trunc_pages(struct inode *, off_t, ufs2_daddr_t, int);
826 static 	int cancel_pagedep(struct pagedep *, struct freeblks *, int);
827 static	int deallocate_dependencies(struct buf *, struct freeblks *, int);
828 static	void newblk_freefrag(struct newblk*);
829 static	void free_newblk(struct newblk *);
830 static	void cancel_allocdirect(struct allocdirectlst *,
831 	    struct allocdirect *, struct freeblks *);
832 static	int check_inode_unwritten(struct inodedep *);
833 static	int free_inodedep(struct inodedep *);
834 static	void freework_freeblock(struct freework *, u_long);
835 static	void freework_enqueue(struct freework *);
836 static	int handle_workitem_freeblocks(struct freeblks *, int);
837 static	int handle_complete_freeblocks(struct freeblks *, int);
838 static	void handle_workitem_indirblk(struct freework *);
839 static	void handle_written_freework(struct freework *);
840 static	void merge_inode_lists(struct allocdirectlst *,struct allocdirectlst *);
841 static	struct worklist *jnewblk_merge(struct worklist *, struct worklist *,
842 	    struct workhead *);
843 static	struct freefrag *setup_allocindir_phase2(struct buf *, struct inode *,
844 	    struct inodedep *, struct allocindir *, ufs_lbn_t);
845 static	struct allocindir *newallocindir(struct inode *, int, ufs2_daddr_t,
846 	    ufs2_daddr_t, ufs_lbn_t);
847 static	void handle_workitem_freefrag(struct freefrag *);
848 static	struct freefrag *newfreefrag(struct inode *, ufs2_daddr_t, long,
849 	    ufs_lbn_t, u_long);
850 static	void allocdirect_merge(struct allocdirectlst *,
851 	    struct allocdirect *, struct allocdirect *);
852 static	struct freefrag *allocindir_merge(struct allocindir *,
853 	    struct allocindir *);
854 static	int bmsafemap_find(struct bmsafemap_hashhead *, int,
855 	    struct bmsafemap **);
856 static	struct bmsafemap *bmsafemap_lookup(struct mount *, struct buf *,
857 	    int cg, struct bmsafemap *);
858 static	int newblk_find(struct newblk_hashhead *, ufs2_daddr_t, int,
859 	    struct newblk **);
860 static	int newblk_lookup(struct mount *, ufs2_daddr_t, int, struct newblk **);
861 static	int inodedep_find(struct inodedep_hashhead *, ino_t,
862 	    struct inodedep **);
863 static	int inodedep_lookup(struct mount *, ino_t, int, struct inodedep **);
864 static	int pagedep_lookup(struct mount *, struct buf *bp, ino_t, ufs_lbn_t,
865 	    int, struct pagedep **);
866 static	int pagedep_find(struct pagedep_hashhead *, ino_t, ufs_lbn_t,
867 	    struct pagedep **);
868 static	void pause_timer(void *);
869 static	int request_cleanup(struct mount *, int);
870 static	int softdep_request_cleanup_flush(struct mount *, struct ufsmount *);
871 static	void schedule_cleanup(struct mount *);
872 static void softdep_ast_cleanup_proc(struct thread *);
873 static struct ufsmount *softdep_bp_to_mp(struct buf *bp);
874 static	int process_worklist_item(struct mount *, int, int);
875 static	void process_removes(struct vnode *);
876 static	void process_truncates(struct vnode *);
877 static	void jwork_move(struct workhead *, struct workhead *);
878 static	void jwork_insert(struct workhead *, struct jsegdep *);
879 static	void add_to_worklist(struct worklist *, int);
880 static	void wake_worklist(struct worklist *);
881 static	void wait_worklist(struct worklist *, char *);
882 static	void remove_from_worklist(struct worklist *);
883 static	void softdep_flush(void *);
884 static	void softdep_flushjournal(struct mount *);
885 static	int softdep_speedup(struct ufsmount *);
886 static	void worklist_speedup(struct mount *);
887 static	int journal_mount(struct mount *, struct fs *, struct ucred *);
888 static	void journal_unmount(struct ufsmount *);
889 static	int journal_space(struct ufsmount *, int);
890 static	void journal_suspend(struct ufsmount *);
891 static	int journal_unsuspend(struct ufsmount *ump);
892 static	void add_to_journal(struct worklist *);
893 static	void remove_from_journal(struct worklist *);
894 static	bool softdep_excess_items(struct ufsmount *, int);
895 static	void softdep_process_journal(struct mount *, struct worklist *, int);
896 static	struct jremref *newjremref(struct dirrem *, struct inode *,
897 	    struct inode *ip, off_t, nlink_t);
898 static	struct jaddref *newjaddref(struct inode *, ino_t, off_t, int16_t,
899 	    uint16_t);
900 static	inline void newinoref(struct inoref *, ino_t, ino_t, off_t, nlink_t,
901 	    uint16_t);
902 static	inline struct jsegdep *inoref_jseg(struct inoref *);
903 static	struct jmvref *newjmvref(struct inode *, ino_t, off_t, off_t);
904 static	struct jfreeblk *newjfreeblk(struct freeblks *, ufs_lbn_t,
905 	    ufs2_daddr_t, int);
906 static	void adjust_newfreework(struct freeblks *, int);
907 static	struct jtrunc *newjtrunc(struct freeblks *, off_t, int);
908 static	void move_newblock_dep(struct jaddref *, struct inodedep *);
909 static	void cancel_jfreeblk(struct freeblks *, ufs2_daddr_t);
910 static	struct jfreefrag *newjfreefrag(struct freefrag *, struct inode *,
911 	    ufs2_daddr_t, long, ufs_lbn_t);
912 static	struct freework *newfreework(struct ufsmount *, struct freeblks *,
913 	    struct freework *, ufs_lbn_t, ufs2_daddr_t, int, int, int);
914 static	int jwait(struct worklist *, int);
915 static	struct inodedep *inodedep_lookup_ip(struct inode *);
916 static	int bmsafemap_backgroundwrite(struct bmsafemap *, struct buf *);
917 static	struct freefile *handle_bufwait(struct inodedep *, struct workhead *);
918 static	void handle_jwork(struct workhead *);
919 static	struct mkdir *setup_newdir(struct diradd *, ino_t, ino_t, struct buf *,
920 	    struct mkdir **);
921 static	struct jblocks *jblocks_create(void);
922 static	ufs2_daddr_t jblocks_alloc(struct jblocks *, int, int *);
923 static	void jblocks_free(struct jblocks *, struct mount *, int);
924 static	void jblocks_destroy(struct jblocks *);
925 static	void jblocks_add(struct jblocks *, ufs2_daddr_t, int);
926 
927 /*
928  * Exported softdep operations.
929  */
930 static	void softdep_disk_io_initiation(struct buf *);
931 static	void softdep_disk_write_complete(struct buf *);
932 static	void softdep_deallocate_dependencies(struct buf *);
933 static	int softdep_count_dependencies(struct buf *bp, int);
934 
935 /*
936  * Global lock over all of soft updates.
937  */
938 static struct mtx lk;
939 MTX_SYSINIT(softdep_lock, &lk, "global softdep", MTX_DEF);
940 
941 #define ACQUIRE_GBLLOCK(lk)	mtx_lock(lk)
942 #define FREE_GBLLOCK(lk)	mtx_unlock(lk)
943 #define GBLLOCK_OWNED(lk)	mtx_assert((lk), MA_OWNED)
944 
945 /*
946  * Per-filesystem soft-updates locking.
947  */
948 #define LOCK_PTR(ump)		(&(ump)->um_softdep->sd_fslock)
949 #define TRY_ACQUIRE_LOCK(ump)	rw_try_wlock(&(ump)->um_softdep->sd_fslock)
950 #define ACQUIRE_LOCK(ump)	rw_wlock(&(ump)->um_softdep->sd_fslock)
951 #define FREE_LOCK(ump)		rw_wunlock(&(ump)->um_softdep->sd_fslock)
952 #define LOCK_OWNED(ump)		rw_assert(&(ump)->um_softdep->sd_fslock, \
953 				    RA_WLOCKED)
954 
955 #define	BUF_AREC(bp)		lockallowrecurse(&(bp)->b_lock)
956 #define	BUF_NOREC(bp)		lockdisablerecurse(&(bp)->b_lock)
957 
958 /*
959  * Worklist queue management.
960  * These routines require that the lock be held.
961  */
962 #ifndef /* NOT */ INVARIANTS
963 #define WORKLIST_INSERT(head, item) do {	\
964 	(item)->wk_state |= ONWORKLIST;		\
965 	LIST_INSERT_HEAD(head, item, wk_list);	\
966 } while (0)
967 #define WORKLIST_REMOVE(item) do {		\
968 	(item)->wk_state &= ~ONWORKLIST;	\
969 	LIST_REMOVE(item, wk_list);		\
970 } while (0)
971 #define WORKLIST_INSERT_UNLOCKED	WORKLIST_INSERT
972 #define WORKLIST_REMOVE_UNLOCKED	WORKLIST_REMOVE
973 
974 #else /* INVARIANTS */
975 static	void worklist_insert(struct workhead *, struct worklist *, int,
976 	const char *, int);
977 static	void worklist_remove(struct worklist *, int, const char *, int);
978 
979 #define WORKLIST_INSERT(head, item) \
980 	worklist_insert(head, item, 1, __func__, __LINE__)
981 #define WORKLIST_INSERT_UNLOCKED(head, item)\
982 	worklist_insert(head, item, 0, __func__, __LINE__)
983 #define WORKLIST_REMOVE(item)\
984 	worklist_remove(item, 1, __func__, __LINE__)
985 #define WORKLIST_REMOVE_UNLOCKED(item)\
986 	worklist_remove(item, 0, __func__, __LINE__)
987 
988 static void
989 worklist_insert(struct workhead *head,
990 	struct worklist *item,
991 	int locked,
992 	const char *func,
993 	int line)
994 {
995 
996 	if (locked)
997 		LOCK_OWNED(VFSTOUFS(item->wk_mp));
998 	if (item->wk_state & ONWORKLIST)
999 		panic("worklist_insert: %p %s(0x%X) already on list, "
1000 		    "added in function %s at line %d",
1001 		    item, TYPENAME(item->wk_type), item->wk_state,
1002 		    item->wk_func, item->wk_line);
1003 	item->wk_state |= ONWORKLIST;
1004 	item->wk_func = func;
1005 	item->wk_line = line;
1006 	LIST_INSERT_HEAD(head, item, wk_list);
1007 }
1008 
1009 static void
1010 worklist_remove(struct worklist *item,
1011 	int locked,
1012 	const char *func,
1013 	int line)
1014 {
1015 
1016 	if (locked)
1017 		LOCK_OWNED(VFSTOUFS(item->wk_mp));
1018 	if ((item->wk_state & ONWORKLIST) == 0)
1019 		panic("worklist_remove: %p %s(0x%X) not on list, "
1020 		    "removed in function %s at line %d",
1021 		    item, TYPENAME(item->wk_type), item->wk_state,
1022 		    item->wk_func, item->wk_line);
1023 	item->wk_state &= ~ONWORKLIST;
1024 	item->wk_func = func;
1025 	item->wk_line = line;
1026 	LIST_REMOVE(item, wk_list);
1027 }
1028 #endif /* INVARIANTS */
1029 
1030 /*
1031  * Merge two jsegdeps keeping only the oldest one as newer references
1032  * can't be discarded until after older references.
1033  */
1034 static inline struct jsegdep *
1035 jsegdep_merge(struct jsegdep *one, struct jsegdep *two)
1036 {
1037 	struct jsegdep *swp;
1038 
1039 	if (two == NULL)
1040 		return (one);
1041 
1042 	if (one->jd_seg->js_seq > two->jd_seg->js_seq) {
1043 		swp = one;
1044 		one = two;
1045 		two = swp;
1046 	}
1047 	WORKLIST_REMOVE(&two->jd_list);
1048 	free_jsegdep(two);
1049 
1050 	return (one);
1051 }
1052 
1053 /*
1054  * If two freedeps are compatible free one to reduce list size.
1055  */
1056 static inline struct freedep *
1057 freedep_merge(struct freedep *one, struct freedep *two)
1058 {
1059 	if (two == NULL)
1060 		return (one);
1061 
1062 	if (one->fd_freework == two->fd_freework) {
1063 		WORKLIST_REMOVE(&two->fd_list);
1064 		free_freedep(two);
1065 	}
1066 	return (one);
1067 }
1068 
1069 /*
1070  * Move journal work from one list to another.  Duplicate freedeps and
1071  * jsegdeps are coalesced to keep the lists as small as possible.
1072  */
1073 static void
1074 jwork_move(struct workhead *dst, struct workhead *src)
1075 {
1076 	struct freedep *freedep;
1077 	struct jsegdep *jsegdep;
1078 	struct worklist *wkn;
1079 	struct worklist *wk;
1080 
1081 	KASSERT(dst != src,
1082 	    ("jwork_move: dst == src"));
1083 	freedep = NULL;
1084 	jsegdep = NULL;
1085 	LIST_FOREACH_SAFE(wk, dst, wk_list, wkn) {
1086 		if (wk->wk_type == D_JSEGDEP)
1087 			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1088 		else if (wk->wk_type == D_FREEDEP)
1089 			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1090 	}
1091 
1092 	while ((wk = LIST_FIRST(src)) != NULL) {
1093 		WORKLIST_REMOVE(wk);
1094 		WORKLIST_INSERT(dst, wk);
1095 		if (wk->wk_type == D_JSEGDEP) {
1096 			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1097 			continue;
1098 		}
1099 		if (wk->wk_type == D_FREEDEP)
1100 			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1101 	}
1102 }
1103 
1104 static void
1105 jwork_insert(struct workhead *dst, struct jsegdep *jsegdep)
1106 {
1107 	struct jsegdep *jsegdepn;
1108 	struct worklist *wk;
1109 
1110 	LIST_FOREACH(wk, dst, wk_list)
1111 		if (wk->wk_type == D_JSEGDEP)
1112 			break;
1113 	if (wk == NULL) {
1114 		WORKLIST_INSERT(dst, &jsegdep->jd_list);
1115 		return;
1116 	}
1117 	jsegdepn = WK_JSEGDEP(wk);
1118 	if (jsegdep->jd_seg->js_seq < jsegdepn->jd_seg->js_seq) {
1119 		WORKLIST_REMOVE(wk);
1120 		free_jsegdep(jsegdepn);
1121 		WORKLIST_INSERT(dst, &jsegdep->jd_list);
1122 	} else
1123 		free_jsegdep(jsegdep);
1124 }
1125 
1126 /*
1127  * Routines for tracking and managing workitems.
1128  */
1129 static	void workitem_free(struct worklist *, int);
1130 static	void workitem_alloc(struct worklist *, int, struct mount *);
1131 static	void workitem_reassign(struct worklist *, int);
1132 
1133 #define	WORKITEM_FREE(item, type) \
1134 	workitem_free((struct worklist *)(item), (type))
1135 #define	WORKITEM_REASSIGN(item, type) \
1136 	workitem_reassign((struct worklist *)(item), (type))
1137 
1138 static void
1139 workitem_free(struct worklist *item, int type)
1140 {
1141 	struct ufsmount *ump;
1142 
1143 #ifdef INVARIANTS
1144 	if (item->wk_state & ONWORKLIST)
1145 		panic("workitem_free: %s(0x%X) still on list, "
1146 		    "added in function %s at line %d",
1147 		    TYPENAME(item->wk_type), item->wk_state,
1148 		    item->wk_func, item->wk_line);
1149 	if (item->wk_type != type && type != D_NEWBLK)
1150 		panic("workitem_free: type mismatch %s != %s",
1151 		    TYPENAME(item->wk_type), TYPENAME(type));
1152 #endif
1153 	if (item->wk_state & IOWAITING)
1154 		wakeup(item);
1155 	ump = VFSTOUFS(item->wk_mp);
1156 	LOCK_OWNED(ump);
1157 	KASSERT(ump->softdep_deps > 0,
1158 	    ("workitem_free: %s: softdep_deps going negative",
1159 	    ump->um_fs->fs_fsmnt));
1160 	if (--ump->softdep_deps == 0 && ump->softdep_req)
1161 		wakeup(&ump->softdep_deps);
1162 	KASSERT(dep_current[item->wk_type] > 0,
1163 	    ("workitem_free: %s: dep_current[%s] going negative",
1164 	    ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1165 	KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1166 	    ("workitem_free: %s: softdep_curdeps[%s] going negative",
1167 	    ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1168 	atomic_subtract_long(&dep_current[item->wk_type], 1);
1169 	ump->softdep_curdeps[item->wk_type] -= 1;
1170 	LIST_REMOVE(item, wk_all);
1171 	free(item, DtoM(type));
1172 }
1173 
1174 static void
1175 workitem_alloc(struct worklist *item,
1176 	int type,
1177 	struct mount *mp)
1178 {
1179 	struct ufsmount *ump;
1180 
1181 	item->wk_type = type;
1182 	item->wk_mp = mp;
1183 	item->wk_state = 0;
1184 
1185 	ump = VFSTOUFS(mp);
1186 	ACQUIRE_GBLLOCK(&lk);
1187 	dep_current[type]++;
1188 	if (dep_current[type] > dep_highuse[type])
1189 		dep_highuse[type] = dep_current[type];
1190 	dep_total[type]++;
1191 	FREE_GBLLOCK(&lk);
1192 	ACQUIRE_LOCK(ump);
1193 	ump->softdep_curdeps[type] += 1;
1194 	ump->softdep_deps++;
1195 	ump->softdep_accdeps++;
1196 	LIST_INSERT_HEAD(&ump->softdep_alldeps[type], item, wk_all);
1197 	FREE_LOCK(ump);
1198 }
1199 
1200 static void
1201 workitem_reassign(struct worklist *item, int newtype)
1202 {
1203 	struct ufsmount *ump;
1204 
1205 	ump = VFSTOUFS(item->wk_mp);
1206 	LOCK_OWNED(ump);
1207 	KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1208 	    ("workitem_reassign: %s: softdep_curdeps[%s] going negative",
1209 	    VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1210 	ump->softdep_curdeps[item->wk_type] -= 1;
1211 	ump->softdep_curdeps[newtype] += 1;
1212 	KASSERT(dep_current[item->wk_type] > 0,
1213 	    ("workitem_reassign: %s: dep_current[%s] going negative",
1214 	    VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1215 	ACQUIRE_GBLLOCK(&lk);
1216 	dep_current[newtype]++;
1217 	dep_current[item->wk_type]--;
1218 	if (dep_current[newtype] > dep_highuse[newtype])
1219 		dep_highuse[newtype] = dep_current[newtype];
1220 	dep_total[newtype]++;
1221 	FREE_GBLLOCK(&lk);
1222 	item->wk_type = newtype;
1223 	LIST_REMOVE(item, wk_all);
1224 	LIST_INSERT_HEAD(&ump->softdep_alldeps[newtype], item, wk_all);
1225 }
1226 
1227 /*
1228  * Workitem queue management
1229  */
1230 static int max_softdeps;	/* maximum number of structs before slowdown */
1231 static int tickdelay = 2;	/* number of ticks to pause during slowdown */
1232 static int proc_waiting;	/* tracks whether we have a timeout posted */
1233 static int *stat_countp;	/* statistic to count in proc_waiting timeout */
1234 static struct callout softdep_callout;
1235 static int req_clear_inodedeps;	/* syncer process flush some inodedeps */
1236 static int req_clear_remove;	/* syncer process flush some freeblks */
1237 static int softdep_flushcache = 0; /* Should we do BIO_FLUSH? */
1238 
1239 /*
1240  * runtime statistics
1241  */
1242 static int stat_flush_threads;	/* number of softdep flushing threads */
1243 static int stat_worklist_push;	/* number of worklist cleanups */
1244 static int stat_delayed_inact;	/* number of delayed inactivation cleanups */
1245 static int stat_blk_limit_push;	/* number of times block limit neared */
1246 static int stat_ino_limit_push;	/* number of times inode limit neared */
1247 static int stat_blk_limit_hit;	/* number of times block slowdown imposed */
1248 static int stat_ino_limit_hit;	/* number of times inode slowdown imposed */
1249 static int stat_sync_limit_hit;	/* number of synchronous slowdowns imposed */
1250 static int stat_indir_blk_ptrs;	/* bufs redirtied as indir ptrs not written */
1251 static int stat_inode_bitmap;	/* bufs redirtied as inode bitmap not written */
1252 static int stat_direct_blk_ptrs;/* bufs redirtied as direct ptrs not written */
1253 static int stat_dir_entry;	/* bufs redirtied as dir entry cannot write */
1254 static int stat_jaddref;	/* bufs redirtied as ino bitmap can not write */
1255 static int stat_jnewblk;	/* bufs redirtied as blk bitmap can not write */
1256 static int stat_journal_min;	/* Times hit journal min threshold */
1257 static int stat_journal_low;	/* Times hit journal low threshold */
1258 static int stat_journal_wait;	/* Times blocked in jwait(). */
1259 static int stat_jwait_filepage;	/* Times blocked in jwait() for filepage. */
1260 static int stat_jwait_freeblks;	/* Times blocked in jwait() for freeblks. */
1261 static int stat_jwait_inode;	/* Times blocked in jwait() for inodes. */
1262 static int stat_jwait_newblk;	/* Times blocked in jwait() for newblks. */
1263 static int stat_cleanup_high_delay; /* Maximum cleanup delay (in ticks) */
1264 static int stat_cleanup_blkrequests; /* Number of block cleanup requests */
1265 static int stat_cleanup_inorequests; /* Number of inode cleanup requests */
1266 static int stat_cleanup_retries; /* Number of cleanups that needed to flush */
1267 static int stat_cleanup_failures; /* Number of cleanup requests that failed */
1268 static int stat_emptyjblocks; /* Number of potentially empty journal blocks */
1269 
1270 SYSCTL_INT(_debug_softdep, OID_AUTO, max_softdeps, CTLFLAG_RW,
1271     &max_softdeps, 0, "");
1272 SYSCTL_INT(_debug_softdep, OID_AUTO, tickdelay, CTLFLAG_RW,
1273     &tickdelay, 0, "");
1274 SYSCTL_INT(_debug_softdep, OID_AUTO, flush_threads, CTLFLAG_RD,
1275     &stat_flush_threads, 0, "");
1276 SYSCTL_INT(_debug_softdep, OID_AUTO, worklist_push,
1277     CTLFLAG_RW | CTLFLAG_STATS, &stat_worklist_push, 0,"");
1278 SYSCTL_INT(_debug_softdep, OID_AUTO, delayed_inactivations, CTLFLAG_RD,
1279     &stat_delayed_inact, 0, "");
1280 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_push,
1281     CTLFLAG_RW | CTLFLAG_STATS, &stat_blk_limit_push, 0,"");
1282 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_push,
1283     CTLFLAG_RW | CTLFLAG_STATS, &stat_ino_limit_push, 0,"");
1284 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_hit,
1285     CTLFLAG_RW | CTLFLAG_STATS, &stat_blk_limit_hit, 0, "");
1286 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_hit,
1287     CTLFLAG_RW | CTLFLAG_STATS, &stat_ino_limit_hit, 0, "");
1288 SYSCTL_INT(_debug_softdep, OID_AUTO, sync_limit_hit,
1289     CTLFLAG_RW | CTLFLAG_STATS, &stat_sync_limit_hit, 0, "");
1290 SYSCTL_INT(_debug_softdep, OID_AUTO, indir_blk_ptrs,
1291     CTLFLAG_RW | CTLFLAG_STATS, &stat_indir_blk_ptrs, 0, "");
1292 SYSCTL_INT(_debug_softdep, OID_AUTO, inode_bitmap,
1293     CTLFLAG_RW | CTLFLAG_STATS, &stat_inode_bitmap, 0, "");
1294 SYSCTL_INT(_debug_softdep, OID_AUTO, direct_blk_ptrs,
1295     CTLFLAG_RW | CTLFLAG_STATS, &stat_direct_blk_ptrs, 0, "");
1296 SYSCTL_INT(_debug_softdep, OID_AUTO, dir_entry,
1297     CTLFLAG_RW | CTLFLAG_STATS, &stat_dir_entry, 0, "");
1298 SYSCTL_INT(_debug_softdep, OID_AUTO, jaddref_rollback,
1299     CTLFLAG_RW | CTLFLAG_STATS, &stat_jaddref, 0, "");
1300 SYSCTL_INT(_debug_softdep, OID_AUTO, jnewblk_rollback,
1301     CTLFLAG_RW | CTLFLAG_STATS, &stat_jnewblk, 0, "");
1302 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_low,
1303     CTLFLAG_RW | CTLFLAG_STATS, &stat_journal_low, 0, "");
1304 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_min,
1305     CTLFLAG_RW | CTLFLAG_STATS, &stat_journal_min, 0, "");
1306 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_wait,
1307     CTLFLAG_RW | CTLFLAG_STATS, &stat_journal_wait, 0, "");
1308 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_filepage,
1309     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_filepage, 0, "");
1310 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_freeblks,
1311     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_freeblks, 0, "");
1312 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_inode,
1313     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_inode, 0, "");
1314 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_newblk,
1315     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_newblk, 0, "");
1316 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_blkrequests,
1317     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_blkrequests, 0, "");
1318 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_inorequests,
1319     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_inorequests, 0, "");
1320 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_high_delay,
1321     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_high_delay, 0, "");
1322 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_retries,
1323     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_retries, 0, "");
1324 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_failures,
1325     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_failures, 0, "");
1326 
1327 SYSCTL_INT(_debug_softdep, OID_AUTO, flushcache, CTLFLAG_RW,
1328     &softdep_flushcache, 0, "");
1329 SYSCTL_INT(_debug_softdep, OID_AUTO, emptyjblocks, CTLFLAG_RD,
1330     &stat_emptyjblocks, 0, "");
1331 
1332 SYSCTL_DECL(_vfs_ffs);
1333 
1334 /* Whether to recompute the summary at mount time */
1335 static int compute_summary_at_mount = 0;
1336 SYSCTL_INT(_vfs_ffs, OID_AUTO, compute_summary_at_mount, CTLFLAG_RW,
1337 	   &compute_summary_at_mount, 0, "Recompute summary at mount");
1338 static int print_threads = 0;
1339 SYSCTL_INT(_debug_softdep, OID_AUTO, print_threads, CTLFLAG_RW,
1340     &print_threads, 0, "Notify flusher thread start/stop");
1341 
1342 /* List of all filesystems mounted with soft updates */
1343 static TAILQ_HEAD(, mount_softdeps) softdepmounts;
1344 
1345 static void
1346 get_parent_vp_unlock_bp(struct mount *mp,
1347 	struct buf *bp,
1348 	struct diraddhd *diraddhdp,
1349 	struct diraddhd *unfinishedp)
1350 {
1351 	struct diradd *dap;
1352 
1353 	/*
1354 	 * Requeue unfinished dependencies before
1355 	 * unlocking buffer, which could make
1356 	 * diraddhdp invalid.
1357 	 */
1358 	ACQUIRE_LOCK(VFSTOUFS(mp));
1359 	while ((dap = LIST_FIRST(unfinishedp)) != NULL) {
1360 		LIST_REMOVE(dap, da_pdlist);
1361 		LIST_INSERT_HEAD(diraddhdp, dap, da_pdlist);
1362 	}
1363 	FREE_LOCK(VFSTOUFS(mp));
1364 
1365 	bp->b_vflags &= ~BV_SCANNED;
1366 	BUF_NOREC(bp);
1367 	BUF_UNLOCK(bp);
1368 }
1369 
1370 /*
1371  * This function fetches inode inum on mount point mp.  We already
1372  * hold a locked vnode vp, and might have a locked buffer bp belonging
1373  * to vp.
1374 
1375  * We must not block on acquiring the new inode lock as we will get
1376  * into a lock-order reversal with the buffer lock and possibly get a
1377  * deadlock.  Thus if we cannot instantiate the requested vnode
1378  * without sleeping on its lock, we must unlock the vnode and the
1379  * buffer before doing a blocking on the vnode lock.  We return
1380  * ERELOOKUP if we have had to unlock either the vnode or the buffer so
1381  * that the caller can reassess its state.
1382  *
1383  * Top-level VFS code (for syscalls and other consumers, e.g. callers
1384  * of VOP_FSYNC() in syncer) check for ERELOOKUP and restart at safe
1385  * point.
1386  *
1387  * Since callers expect to operate on fully constructed vnode, we also
1388  * recheck v_data after relock, and return ENOENT if NULL.
1389  *
1390  * If unlocking bp, we must unroll dequeueing its unfinished
1391  * dependencies, and clear scan flag, before unlocking.  If unlocking
1392  * vp while it is under deactivation, we re-queue deactivation.
1393  */
1394 static int
1395 get_parent_vp(struct vnode *vp,
1396 	struct mount *mp,
1397 	ino_t inum,
1398 	struct buf *bp,
1399 	struct diraddhd *diraddhdp,
1400 	struct diraddhd *unfinishedp,
1401 	struct vnode **rvp)
1402 {
1403 	struct vnode *pvp;
1404 	int error;
1405 	bool bplocked;
1406 
1407 	ASSERT_VOP_ELOCKED(vp, "child vnode must be locked");
1408 	for (bplocked = true, pvp = NULL;;) {
1409 		error = ffs_vgetf(mp, inum, LK_EXCLUSIVE | LK_NOWAIT, &pvp,
1410 		    FFSV_FORCEINSMQ | FFSV_FORCEINODEDEP);
1411 		if (error == 0) {
1412 			/*
1413 			 * Since we could have unlocked vp, the inode
1414 			 * number could no longer indicate a
1415 			 * constructed node.  In this case, we must
1416 			 * restart the syscall.
1417 			 */
1418 			if (VTOI(pvp)->i_mode == 0 || !bplocked) {
1419 				if (bp != NULL && bplocked)
1420 					get_parent_vp_unlock_bp(mp, bp,
1421 					    diraddhdp, unfinishedp);
1422 				if (VTOI(pvp)->i_mode == 0)
1423 					vgone(pvp);
1424 				error = ERELOOKUP;
1425 				goto out2;
1426 			}
1427 			goto out1;
1428 		}
1429 		if (bp != NULL && bplocked) {
1430 			get_parent_vp_unlock_bp(mp, bp, diraddhdp, unfinishedp);
1431 			bplocked = false;
1432 		}
1433 
1434 		/*
1435 		 * Do not drop vnode lock while inactivating during
1436 		 * vunref.  This would result in leaks of the VI flags
1437 		 * and reclaiming of non-truncated vnode.  Instead,
1438 		 * re-schedule inactivation hoping that we would be
1439 		 * able to sync inode later.
1440 		 */
1441 		if ((vp->v_iflag & VI_DOINGINACT) != 0 &&
1442 		    (vp->v_vflag & VV_UNREF) != 0) {
1443 			VI_LOCK(vp);
1444 			vp->v_iflag |= VI_OWEINACT;
1445 			VI_UNLOCK(vp);
1446 			return (ERELOOKUP);
1447 		}
1448 
1449 		VOP_UNLOCK(vp);
1450 		error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &pvp,
1451 		    FFSV_FORCEINSMQ | FFSV_FORCEINODEDEP);
1452 		if (error != 0) {
1453 			MPASS(error != ERELOOKUP);
1454 			vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1455 			break;
1456 		}
1457 		if (VTOI(pvp)->i_mode == 0) {
1458 			vgone(pvp);
1459 			vput(pvp);
1460 			pvp = NULL;
1461 			vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1462 			error = ERELOOKUP;
1463 			break;
1464 		}
1465 		error = vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT);
1466 		if (error == 0)
1467 			break;
1468 		vput(pvp);
1469 		pvp = NULL;
1470 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1471 		if (vp->v_data == NULL) {
1472 			error = ENOENT;
1473 			break;
1474 		}
1475 	}
1476 	if (bp != NULL) {
1477 		MPASS(!bplocked);
1478 		error = ERELOOKUP;
1479 	}
1480 out2:
1481 	if (error != 0 && pvp != NULL) {
1482 		vput(pvp);
1483 		pvp = NULL;
1484 	}
1485 out1:
1486 	*rvp = pvp;
1487 	ASSERT_VOP_ELOCKED(vp, "child vnode must be locked on return");
1488 	return (error);
1489 }
1490 
1491 /*
1492  * This function cleans the worklist for a filesystem.
1493  * Each filesystem running with soft dependencies gets its own
1494  * thread to run in this function. The thread is started up in
1495  * softdep_mount and shutdown in softdep_unmount. They show up
1496  * as part of the kernel "bufdaemon" process whose process
1497  * entry is available in bufdaemonproc.
1498  */
1499 static int searchfailed;
1500 extern struct proc *bufdaemonproc;
1501 static void
1502 softdep_flush(void *addr)
1503 {
1504 	struct mount *mp;
1505 	struct thread *td;
1506 	struct ufsmount *ump;
1507 	int cleanups;
1508 
1509 	td = curthread;
1510 	td->td_pflags |= TDP_NORUNNINGBUF;
1511 	mp = (struct mount *)addr;
1512 	ump = VFSTOUFS(mp);
1513 	atomic_add_int(&stat_flush_threads, 1);
1514 	ACQUIRE_LOCK(ump);
1515 	ump->softdep_flags &= ~FLUSH_STARTING;
1516 	wakeup(&ump->softdep_flushtd);
1517 	FREE_LOCK(ump);
1518 	if (print_threads) {
1519 		if (stat_flush_threads == 1)
1520 			printf("Running %s at pid %d\n", bufdaemonproc->p_comm,
1521 			    bufdaemonproc->p_pid);
1522 		printf("Start thread %s\n", td->td_name);
1523 	}
1524 	for (;;) {
1525 		while (softdep_process_worklist(mp, 0) > 0 ||
1526 		    (MOUNTEDSUJ(mp) &&
1527 		    VFSTOUFS(mp)->softdep_jblocks->jb_suspended))
1528 			kthread_suspend_check();
1529 		ACQUIRE_LOCK(ump);
1530 		if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1531 			msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM,
1532 			    "sdflush", hz / 2);
1533 		ump->softdep_flags &= ~FLUSH_CLEANUP;
1534 		/*
1535 		 * Check to see if we are done and need to exit.
1536 		 */
1537 		if ((ump->softdep_flags & FLUSH_EXIT) == 0) {
1538 			FREE_LOCK(ump);
1539 			continue;
1540 		}
1541 		ump->softdep_flags &= ~FLUSH_EXIT;
1542 		cleanups = ump->um_softdep->sd_cleanups;
1543 		FREE_LOCK(ump);
1544 		wakeup(&ump->softdep_flags);
1545 		if (print_threads) {
1546 			printf("Stop thread %s: searchfailed %d, "
1547 			    "did cleanups %d\n",
1548 			    td->td_name, searchfailed, cleanups);
1549 		}
1550 		atomic_subtract_int(&stat_flush_threads, 1);
1551 		kthread_exit();
1552 		panic("kthread_exit failed\n");
1553 	}
1554 }
1555 
1556 static void
1557 worklist_speedup(struct mount *mp)
1558 {
1559 	struct ufsmount *ump;
1560 
1561 	ump = VFSTOUFS(mp);
1562 	LOCK_OWNED(ump);
1563 	if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1564 		ump->softdep_flags |= FLUSH_CLEANUP;
1565 	wakeup(&ump->softdep_flushtd);
1566 }
1567 
1568 static void
1569 softdep_send_speedup(struct ufsmount *ump,
1570 	off_t shortage,
1571 	u_int flags)
1572 {
1573 	struct buf *bp;
1574 
1575 	if ((ump->um_flags & UM_CANSPEEDUP) == 0)
1576 		return;
1577 
1578 	bp = malloc(sizeof(*bp), M_TRIM, M_WAITOK | M_ZERO);
1579 	bp->b_iocmd = BIO_SPEEDUP;
1580 	bp->b_ioflags = flags;
1581 	bp->b_bcount = omin(shortage, LONG_MAX);
1582 	g_vfs_strategy(ump->um_bo, bp);
1583 	bufwait(bp);
1584 	free(bp, M_TRIM);
1585 }
1586 
1587 static int
1588 softdep_speedup(struct ufsmount *ump)
1589 {
1590 	struct ufsmount *altump;
1591 	struct mount_softdeps *sdp;
1592 
1593 	LOCK_OWNED(ump);
1594 	worklist_speedup(ump->um_mountp);
1595 	bd_speedup();
1596 	/*
1597 	 * If we have global shortages, then we need other
1598 	 * filesystems to help with the cleanup. Here we wakeup a
1599 	 * flusher thread for a filesystem that is over its fair
1600 	 * share of resources.
1601 	 */
1602 	if (req_clear_inodedeps || req_clear_remove) {
1603 		ACQUIRE_GBLLOCK(&lk);
1604 		TAILQ_FOREACH(sdp, &softdepmounts, sd_next) {
1605 			if ((altump = sdp->sd_ump) == ump)
1606 				continue;
1607 			if (((req_clear_inodedeps &&
1608 			    altump->softdep_curdeps[D_INODEDEP] >
1609 			    max_softdeps / stat_flush_threads) ||
1610 			    (req_clear_remove &&
1611 			    altump->softdep_curdeps[D_DIRREM] >
1612 			    (max_softdeps / 2) / stat_flush_threads)) &&
1613 			    TRY_ACQUIRE_LOCK(altump))
1614 				break;
1615 		}
1616 		if (sdp == NULL) {
1617 			searchfailed++;
1618 			FREE_GBLLOCK(&lk);
1619 		} else {
1620 			/*
1621 			 * Move to the end of the list so we pick a
1622 			 * different one on out next try.
1623 			 */
1624 			TAILQ_REMOVE(&softdepmounts, sdp, sd_next);
1625 			TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
1626 			FREE_GBLLOCK(&lk);
1627 			if ((altump->softdep_flags &
1628 			    (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1629 				altump->softdep_flags |= FLUSH_CLEANUP;
1630 			altump->um_softdep->sd_cleanups++;
1631 			wakeup(&altump->softdep_flushtd);
1632 			FREE_LOCK(altump);
1633 		}
1634 	}
1635 	return (speedup_syncer());
1636 }
1637 
1638 /*
1639  * Add an item to the end of the work queue.
1640  * This routine requires that the lock be held.
1641  * This is the only routine that adds items to the list.
1642  * The following routine is the only one that removes items
1643  * and does so in order from first to last.
1644  */
1645 
1646 #define	WK_HEAD		0x0001	/* Add to HEAD. */
1647 #define	WK_NODELAY	0x0002	/* Process immediately. */
1648 
1649 static void
1650 add_to_worklist(struct worklist *wk, int flags)
1651 {
1652 	struct ufsmount *ump;
1653 
1654 	ump = VFSTOUFS(wk->wk_mp);
1655 	LOCK_OWNED(ump);
1656 	if (wk->wk_state & ONWORKLIST)
1657 		panic("add_to_worklist: %s(0x%X) already on list",
1658 		    TYPENAME(wk->wk_type), wk->wk_state);
1659 	wk->wk_state |= ONWORKLIST;
1660 	if (ump->softdep_on_worklist == 0) {
1661 		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1662 		ump->softdep_worklist_tail = wk;
1663 	} else if (flags & WK_HEAD) {
1664 		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1665 	} else {
1666 		LIST_INSERT_AFTER(ump->softdep_worklist_tail, wk, wk_list);
1667 		ump->softdep_worklist_tail = wk;
1668 	}
1669 	ump->softdep_on_worklist += 1;
1670 	if (flags & WK_NODELAY)
1671 		worklist_speedup(wk->wk_mp);
1672 }
1673 
1674 /*
1675  * Remove the item to be processed. If we are removing the last
1676  * item on the list, we need to recalculate the tail pointer.
1677  */
1678 static void
1679 remove_from_worklist(struct worklist *wk)
1680 {
1681 	struct ufsmount *ump;
1682 
1683 	ump = VFSTOUFS(wk->wk_mp);
1684 	if (ump->softdep_worklist_tail == wk)
1685 		ump->softdep_worklist_tail =
1686 		    (struct worklist *)wk->wk_list.le_prev;
1687 	WORKLIST_REMOVE(wk);
1688 	ump->softdep_on_worklist -= 1;
1689 }
1690 
1691 static void
1692 wake_worklist(struct worklist *wk)
1693 {
1694 	if (wk->wk_state & IOWAITING) {
1695 		wk->wk_state &= ~IOWAITING;
1696 		wakeup(wk);
1697 	}
1698 }
1699 
1700 static void
1701 wait_worklist(struct worklist *wk, char *wmesg)
1702 {
1703 	struct ufsmount *ump;
1704 
1705 	ump = VFSTOUFS(wk->wk_mp);
1706 	wk->wk_state |= IOWAITING;
1707 	msleep(wk, LOCK_PTR(ump), PVM, wmesg, 0);
1708 }
1709 
1710 /*
1711  * Process that runs once per second to handle items in the background queue.
1712  *
1713  * Note that we ensure that everything is done in the order in which they
1714  * appear in the queue. The code below depends on this property to ensure
1715  * that blocks of a file are freed before the inode itself is freed. This
1716  * ordering ensures that no new <vfsid, inum, lbn> triples will be generated
1717  * until all the old ones have been purged from the dependency lists.
1718  */
1719 static int
1720 softdep_process_worklist(struct mount *mp, int full)
1721 {
1722 	int cnt, matchcnt;
1723 	struct ufsmount *ump;
1724 	long starttime;
1725 
1726 	KASSERT(mp != NULL, ("softdep_process_worklist: NULL mp"));
1727 	ump = VFSTOUFS(mp);
1728 	if (ump->um_softdep == NULL)
1729 		return (0);
1730 	matchcnt = 0;
1731 	ACQUIRE_LOCK(ump);
1732 	starttime = time_second;
1733 	softdep_process_journal(mp, NULL, full ? MNT_WAIT : 0);
1734 	check_clear_deps(mp);
1735 	while (ump->softdep_on_worklist > 0) {
1736 		if ((cnt = process_worklist_item(mp, 10, LK_NOWAIT)) == 0)
1737 			break;
1738 		else
1739 			matchcnt += cnt;
1740 		check_clear_deps(mp);
1741 		/*
1742 		 * We do not generally want to stop for buffer space, but if
1743 		 * we are really being a buffer hog, we will stop and wait.
1744 		 */
1745 		if (should_yield()) {
1746 			FREE_LOCK(ump);
1747 			kern_yield(PRI_USER);
1748 			bwillwrite();
1749 			ACQUIRE_LOCK(ump);
1750 		}
1751 		/*
1752 		 * Never allow processing to run for more than one
1753 		 * second. This gives the syncer thread the opportunity
1754 		 * to pause if appropriate.
1755 		 */
1756 		if (!full && starttime != time_second)
1757 			break;
1758 	}
1759 	if (full == 0)
1760 		journal_unsuspend(ump);
1761 	FREE_LOCK(ump);
1762 	return (matchcnt);
1763 }
1764 
1765 /*
1766  * Process all removes associated with a vnode if we are running out of
1767  * journal space.  Any other process which attempts to flush these will
1768  * be unable as we have the vnodes locked.
1769  */
1770 static void
1771 process_removes(struct vnode *vp)
1772 {
1773 	struct inodedep *inodedep;
1774 	struct dirrem *dirrem;
1775 	struct ufsmount *ump;
1776 	struct mount *mp;
1777 	ino_t inum;
1778 
1779 	mp = vp->v_mount;
1780 	ump = VFSTOUFS(mp);
1781 	LOCK_OWNED(ump);
1782 	inum = VTOI(vp)->i_number;
1783 	for (;;) {
1784 top:
1785 		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1786 			return;
1787 		LIST_FOREACH(dirrem, &inodedep->id_dirremhd, dm_inonext) {
1788 			/*
1789 			 * If another thread is trying to lock this vnode
1790 			 * it will fail but we must wait for it to do so
1791 			 * before we can proceed.
1792 			 */
1793 			if (dirrem->dm_state & INPROGRESS) {
1794 				wait_worklist(&dirrem->dm_list, "pwrwait");
1795 				goto top;
1796 			}
1797 			if ((dirrem->dm_state & (COMPLETE | ONWORKLIST)) ==
1798 			    (COMPLETE | ONWORKLIST))
1799 				break;
1800 		}
1801 		if (dirrem == NULL)
1802 			return;
1803 		remove_from_worklist(&dirrem->dm_list);
1804 		FREE_LOCK(ump);
1805 		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1806 			panic("process_removes: suspended filesystem");
1807 		handle_workitem_remove(dirrem, 0);
1808 		vn_finished_secondary_write(mp);
1809 		ACQUIRE_LOCK(ump);
1810 	}
1811 }
1812 
1813 /*
1814  * Process all truncations associated with a vnode if we are running out
1815  * of journal space.  This is called when the vnode lock is already held
1816  * and no other process can clear the truncation.  This function returns
1817  * a value greater than zero if it did any work.
1818  */
1819 static void
1820 process_truncates(struct vnode *vp)
1821 {
1822 	struct inodedep *inodedep;
1823 	struct freeblks *freeblks;
1824 	struct ufsmount *ump;
1825 	struct mount *mp;
1826 	ino_t inum;
1827 	int cgwait;
1828 
1829 	mp = vp->v_mount;
1830 	ump = VFSTOUFS(mp);
1831 	LOCK_OWNED(ump);
1832 	inum = VTOI(vp)->i_number;
1833 	for (;;) {
1834 		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1835 			return;
1836 		cgwait = 0;
1837 		TAILQ_FOREACH(freeblks, &inodedep->id_freeblklst, fb_next) {
1838 			/* Journal entries not yet written.  */
1839 			if (!LIST_EMPTY(&freeblks->fb_jblkdephd)) {
1840 				jwait(&LIST_FIRST(
1841 				    &freeblks->fb_jblkdephd)->jb_list,
1842 				    MNT_WAIT);
1843 				break;
1844 			}
1845 			/* Another thread is executing this item. */
1846 			if (freeblks->fb_state & INPROGRESS) {
1847 				wait_worklist(&freeblks->fb_list, "ptrwait");
1848 				break;
1849 			}
1850 			/* Freeblks is waiting on a inode write. */
1851 			if ((freeblks->fb_state & COMPLETE) == 0) {
1852 				FREE_LOCK(ump);
1853 				ffs_update(vp, 1);
1854 				ACQUIRE_LOCK(ump);
1855 				break;
1856 			}
1857 			if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST)) ==
1858 			    (ALLCOMPLETE | ONWORKLIST)) {
1859 				remove_from_worklist(&freeblks->fb_list);
1860 				freeblks->fb_state |= INPROGRESS;
1861 				FREE_LOCK(ump);
1862 				if (vn_start_secondary_write(NULL, &mp,
1863 				    V_NOWAIT))
1864 					panic("process_truncates: "
1865 					    "suspended filesystem");
1866 				handle_workitem_freeblocks(freeblks, 0);
1867 				vn_finished_secondary_write(mp);
1868 				ACQUIRE_LOCK(ump);
1869 				break;
1870 			}
1871 			if (freeblks->fb_cgwait)
1872 				cgwait++;
1873 		}
1874 		if (cgwait) {
1875 			FREE_LOCK(ump);
1876 			sync_cgs(mp, MNT_WAIT);
1877 			ffs_sync_snap(mp, MNT_WAIT);
1878 			ACQUIRE_LOCK(ump);
1879 			continue;
1880 		}
1881 		if (freeblks == NULL)
1882 			break;
1883 	}
1884 	return;
1885 }
1886 
1887 /*
1888  * Process one item on the worklist.
1889  */
1890 static int
1891 process_worklist_item(struct mount *mp,
1892 	int target,
1893 	int flags)
1894 {
1895 	struct worklist sentinel;
1896 	struct worklist *wk;
1897 	struct ufsmount *ump;
1898 	int matchcnt;
1899 	int error;
1900 
1901 	KASSERT(mp != NULL, ("process_worklist_item: NULL mp"));
1902 	/*
1903 	 * If we are being called because of a process doing a
1904 	 * copy-on-write, then it is not safe to write as we may
1905 	 * recurse into the copy-on-write routine.
1906 	 */
1907 	if (curthread->td_pflags & TDP_COWINPROGRESS)
1908 		return (-1);
1909 	PHOLD(curproc);	/* Don't let the stack go away. */
1910 	ump = VFSTOUFS(mp);
1911 	LOCK_OWNED(ump);
1912 	matchcnt = 0;
1913 	sentinel.wk_mp = NULL;
1914 	sentinel.wk_type = D_SENTINEL;
1915 	LIST_INSERT_HEAD(&ump->softdep_workitem_pending, &sentinel, wk_list);
1916 	for (wk = LIST_NEXT(&sentinel, wk_list); wk != NULL;
1917 	    wk = LIST_NEXT(&sentinel, wk_list)) {
1918 		if (wk->wk_type == D_SENTINEL) {
1919 			LIST_REMOVE(&sentinel, wk_list);
1920 			LIST_INSERT_AFTER(wk, &sentinel, wk_list);
1921 			continue;
1922 		}
1923 		if (wk->wk_state & INPROGRESS)
1924 			panic("process_worklist_item: %p already in progress.",
1925 			    wk);
1926 		wk->wk_state |= INPROGRESS;
1927 		remove_from_worklist(wk);
1928 		FREE_LOCK(ump);
1929 		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1930 			panic("process_worklist_item: suspended filesystem");
1931 		switch (wk->wk_type) {
1932 		case D_DIRREM:
1933 			/* removal of a directory entry */
1934 			error = handle_workitem_remove(WK_DIRREM(wk), flags);
1935 			break;
1936 
1937 		case D_FREEBLKS:
1938 			/* releasing blocks and/or fragments from a file */
1939 			error = handle_workitem_freeblocks(WK_FREEBLKS(wk),
1940 			    flags);
1941 			break;
1942 
1943 		case D_FREEFRAG:
1944 			/* releasing a fragment when replaced as a file grows */
1945 			handle_workitem_freefrag(WK_FREEFRAG(wk));
1946 			error = 0;
1947 			break;
1948 
1949 		case D_FREEFILE:
1950 			/* releasing an inode when its link count drops to 0 */
1951 			handle_workitem_freefile(WK_FREEFILE(wk));
1952 			error = 0;
1953 			break;
1954 
1955 		default:
1956 			panic("%s_process_worklist: Unknown type %s",
1957 			    "softdep", TYPENAME(wk->wk_type));
1958 			/* NOTREACHED */
1959 		}
1960 		vn_finished_secondary_write(mp);
1961 		ACQUIRE_LOCK(ump);
1962 		if (error == 0) {
1963 			if (++matchcnt == target)
1964 				break;
1965 			continue;
1966 		}
1967 		/*
1968 		 * We have to retry the worklist item later.  Wake up any
1969 		 * waiters who may be able to complete it immediately and
1970 		 * add the item back to the head so we don't try to execute
1971 		 * it again.
1972 		 */
1973 		wk->wk_state &= ~INPROGRESS;
1974 		wake_worklist(wk);
1975 		add_to_worklist(wk, WK_HEAD);
1976 	}
1977 	/* Sentinal could've become the tail from remove_from_worklist. */
1978 	if (ump->softdep_worklist_tail == &sentinel)
1979 		ump->softdep_worklist_tail =
1980 		    (struct worklist *)sentinel.wk_list.le_prev;
1981 	LIST_REMOVE(&sentinel, wk_list);
1982 	PRELE(curproc);
1983 	return (matchcnt);
1984 }
1985 
1986 /*
1987  * Move dependencies from one buffer to another.
1988  */
1989 int
1990 softdep_move_dependencies(struct buf *oldbp, struct buf *newbp)
1991 {
1992 	struct worklist *wk, *wktail;
1993 	struct ufsmount *ump;
1994 	int dirty;
1995 
1996 	if ((wk = LIST_FIRST(&oldbp->b_dep)) == NULL)
1997 		return (0);
1998 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
1999 	    ("softdep_move_dependencies called on non-softdep filesystem"));
2000 	dirty = 0;
2001 	wktail = NULL;
2002 	ump = VFSTOUFS(wk->wk_mp);
2003 	ACQUIRE_LOCK(ump);
2004 	while ((wk = LIST_FIRST(&oldbp->b_dep)) != NULL) {
2005 		LIST_REMOVE(wk, wk_list);
2006 		if (wk->wk_type == D_BMSAFEMAP &&
2007 		    bmsafemap_backgroundwrite(WK_BMSAFEMAP(wk), newbp))
2008 			dirty = 1;
2009 		if (wktail == NULL)
2010 			LIST_INSERT_HEAD(&newbp->b_dep, wk, wk_list);
2011 		else
2012 			LIST_INSERT_AFTER(wktail, wk, wk_list);
2013 		wktail = wk;
2014 	}
2015 	FREE_LOCK(ump);
2016 
2017 	return (dirty);
2018 }
2019 
2020 /*
2021  * Purge the work list of all items associated with a particular mount point.
2022  */
2023 int
2024 softdep_flushworklist(struct mount *oldmnt,
2025 	int *countp,
2026 	struct thread *td)
2027 {
2028 	struct vnode *devvp;
2029 	struct ufsmount *ump;
2030 	int count, error;
2031 
2032 	/*
2033 	 * Alternately flush the block device associated with the mount
2034 	 * point and process any dependencies that the flushing
2035 	 * creates. We continue until no more worklist dependencies
2036 	 * are found.
2037 	 */
2038 	*countp = 0;
2039 	error = 0;
2040 	ump = VFSTOUFS(oldmnt);
2041 	devvp = ump->um_devvp;
2042 	while ((count = softdep_process_worklist(oldmnt, 1)) > 0) {
2043 		*countp += count;
2044 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
2045 		error = VOP_FSYNC(devvp, MNT_WAIT, td);
2046 		VOP_UNLOCK(devvp);
2047 		if (error != 0)
2048 			break;
2049 	}
2050 	return (error);
2051 }
2052 
2053 #define	SU_WAITIDLE_RETRIES	20
2054 static int
2055 softdep_waitidle(struct mount *mp, int flags __unused)
2056 {
2057 	struct ufsmount *ump;
2058 	struct vnode *devvp;
2059 	struct thread *td;
2060 	int error, i;
2061 
2062 	ump = VFSTOUFS(mp);
2063 	KASSERT(ump->um_softdep != NULL,
2064 	    ("softdep_waitidle called on non-softdep filesystem"));
2065 	devvp = ump->um_devvp;
2066 	td = curthread;
2067 	error = 0;
2068 	ACQUIRE_LOCK(ump);
2069 	for (i = 0; i < SU_WAITIDLE_RETRIES && ump->softdep_deps != 0; i++) {
2070 		ump->softdep_req = 1;
2071 		KASSERT((flags & FORCECLOSE) == 0 ||
2072 		    ump->softdep_on_worklist == 0,
2073 		    ("softdep_waitidle: work added after flush"));
2074 		msleep(&ump->softdep_deps, LOCK_PTR(ump), PVM | PDROP,
2075 		    "softdeps", 10 * hz);
2076 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
2077 		error = VOP_FSYNC(devvp, MNT_WAIT, td);
2078 		VOP_UNLOCK(devvp);
2079 		ACQUIRE_LOCK(ump);
2080 		if (error != 0)
2081 			break;
2082 	}
2083 	ump->softdep_req = 0;
2084 	if (i == SU_WAITIDLE_RETRIES && error == 0 && ump->softdep_deps != 0) {
2085 		error = EBUSY;
2086 		printf("softdep_waitidle: Failed to flush worklist for %p\n",
2087 		    mp);
2088 	}
2089 	FREE_LOCK(ump);
2090 	return (error);
2091 }
2092 
2093 /*
2094  * Flush all vnodes and worklist items associated with a specified mount point.
2095  */
2096 int
2097 softdep_flushfiles(struct mount *oldmnt,
2098 	int flags,
2099 	struct thread *td)
2100 {
2101 	struct ufsmount *ump __unused;
2102 #ifdef QUOTA
2103 	int i;
2104 #endif
2105 	int error, early, depcount, loopcnt, retry_flush_count, retry;
2106 	int morework;
2107 
2108 	ump = VFSTOUFS(oldmnt);
2109 	KASSERT(ump->um_softdep != NULL,
2110 	    ("softdep_flushfiles called on non-softdep filesystem"));
2111 	loopcnt = 10;
2112 	retry_flush_count = 3;
2113 retry_flush:
2114 	error = 0;
2115 
2116 	/*
2117 	 * Alternately flush the vnodes associated with the mount
2118 	 * point and process any dependencies that the flushing
2119 	 * creates. In theory, this loop can happen at most twice,
2120 	 * but we give it a few extra just to be sure.
2121 	 */
2122 	for (; loopcnt > 0; loopcnt--) {
2123 		/*
2124 		 * Do another flush in case any vnodes were brought in
2125 		 * as part of the cleanup operations.
2126 		 */
2127 		early = retry_flush_count == 1 || (oldmnt->mnt_kern_flag &
2128 		    MNTK_UNMOUNT) == 0 ? 0 : EARLYFLUSH;
2129 		if ((error = ffs_flushfiles(oldmnt, flags | early, td)) != 0)
2130 			break;
2131 		if ((error = softdep_flushworklist(oldmnt, &depcount, td)) != 0 ||
2132 		    depcount == 0)
2133 			break;
2134 	}
2135 	/*
2136 	 * If we are unmounting then it is an error to fail. If we
2137 	 * are simply trying to downgrade to read-only, then filesystem
2138 	 * activity can keep us busy forever, so we just fail with EBUSY.
2139 	 */
2140 	if (loopcnt == 0) {
2141 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT)
2142 			panic("softdep_flushfiles: looping");
2143 		error = EBUSY;
2144 	}
2145 	if (!error)
2146 		error = softdep_waitidle(oldmnt, flags);
2147 	if (!error) {
2148 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT) {
2149 			retry = 0;
2150 			MNT_ILOCK(oldmnt);
2151 			morework = oldmnt->mnt_nvnodelistsize > 0;
2152 #ifdef QUOTA
2153 			UFS_LOCK(ump);
2154 			for (i = 0; i < MAXQUOTAS; i++) {
2155 				if (ump->um_quotas[i] != NULLVP)
2156 					morework = 1;
2157 			}
2158 			UFS_UNLOCK(ump);
2159 #endif
2160 			if (morework) {
2161 				if (--retry_flush_count > 0) {
2162 					retry = 1;
2163 					loopcnt = 3;
2164 				} else
2165 					error = EBUSY;
2166 			}
2167 			MNT_IUNLOCK(oldmnt);
2168 			if (retry)
2169 				goto retry_flush;
2170 		}
2171 	}
2172 	return (error);
2173 }
2174 
2175 /*
2176  * Structure hashing.
2177  *
2178  * There are four types of structures that can be looked up:
2179  *	1) pagedep structures identified by mount point, inode number,
2180  *	   and logical block.
2181  *	2) inodedep structures identified by mount point and inode number.
2182  *	3) newblk structures identified by mount point and
2183  *	   physical block number.
2184  *	4) bmsafemap structures identified by mount point and
2185  *	   cylinder group number.
2186  *
2187  * The "pagedep" and "inodedep" dependency structures are hashed
2188  * separately from the file blocks and inodes to which they correspond.
2189  * This separation helps when the in-memory copy of an inode or
2190  * file block must be replaced. It also obviates the need to access
2191  * an inode or file page when simply updating (or de-allocating)
2192  * dependency structures. Lookup of newblk structures is needed to
2193  * find newly allocated blocks when trying to associate them with
2194  * their allocdirect or allocindir structure.
2195  *
2196  * The lookup routines optionally create and hash a new instance when
2197  * an existing entry is not found. The bmsafemap lookup routine always
2198  * allocates a new structure if an existing one is not found.
2199  */
2200 #define DEPALLOC	0x0001	/* allocate structure if lookup fails */
2201 
2202 /*
2203  * Structures and routines associated with pagedep caching.
2204  */
2205 #define	PAGEDEP_HASH(ump, inum, lbn) \
2206 	(&(ump)->pagedep_hashtbl[((inum) + (lbn)) & (ump)->pagedep_hash_size])
2207 
2208 static int
2209 pagedep_find(struct pagedep_hashhead *pagedephd,
2210 	ino_t ino,
2211 	ufs_lbn_t lbn,
2212 	struct pagedep **pagedeppp)
2213 {
2214 	struct pagedep *pagedep;
2215 
2216 	LIST_FOREACH(pagedep, pagedephd, pd_hash) {
2217 		if (ino == pagedep->pd_ino && lbn == pagedep->pd_lbn) {
2218 			*pagedeppp = pagedep;
2219 			return (1);
2220 		}
2221 	}
2222 	*pagedeppp = NULL;
2223 	return (0);
2224 }
2225 /*
2226  * Look up a pagedep. Return 1 if found, 0 otherwise.
2227  * If not found, allocate if DEPALLOC flag is passed.
2228  * Found or allocated entry is returned in pagedeppp.
2229  */
2230 static int
2231 pagedep_lookup(struct mount *mp,
2232 	struct buf *bp,
2233 	ino_t ino,
2234 	ufs_lbn_t lbn,
2235 	int flags,
2236 	struct pagedep **pagedeppp)
2237 {
2238 	struct pagedep *pagedep;
2239 	struct pagedep_hashhead *pagedephd;
2240 	struct worklist *wk;
2241 	struct ufsmount *ump;
2242 	int ret;
2243 	int i;
2244 
2245 	ump = VFSTOUFS(mp);
2246 	LOCK_OWNED(ump);
2247 	if (bp) {
2248 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
2249 			if (wk->wk_type == D_PAGEDEP) {
2250 				*pagedeppp = WK_PAGEDEP(wk);
2251 				return (1);
2252 			}
2253 		}
2254 	}
2255 	pagedephd = PAGEDEP_HASH(ump, ino, lbn);
2256 	ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2257 	if (ret) {
2258 		if (((*pagedeppp)->pd_state & ONWORKLIST) == 0 && bp)
2259 			WORKLIST_INSERT(&bp->b_dep, &(*pagedeppp)->pd_list);
2260 		return (1);
2261 	}
2262 	if ((flags & DEPALLOC) == 0)
2263 		return (0);
2264 	FREE_LOCK(ump);
2265 	pagedep = malloc(sizeof(struct pagedep),
2266 	    M_PAGEDEP, M_SOFTDEP_FLAGS|M_ZERO);
2267 	workitem_alloc(&pagedep->pd_list, D_PAGEDEP, mp);
2268 	ACQUIRE_LOCK(ump);
2269 	ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2270 	if (*pagedeppp) {
2271 		/*
2272 		 * This should never happen since we only create pagedeps
2273 		 * with the vnode lock held.  Could be an assert.
2274 		 */
2275 		WORKITEM_FREE(pagedep, D_PAGEDEP);
2276 		return (ret);
2277 	}
2278 	pagedep->pd_ino = ino;
2279 	pagedep->pd_lbn = lbn;
2280 	LIST_INIT(&pagedep->pd_dirremhd);
2281 	LIST_INIT(&pagedep->pd_pendinghd);
2282 	for (i = 0; i < DAHASHSZ; i++)
2283 		LIST_INIT(&pagedep->pd_diraddhd[i]);
2284 	LIST_INSERT_HEAD(pagedephd, pagedep, pd_hash);
2285 	WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
2286 	*pagedeppp = pagedep;
2287 	return (0);
2288 }
2289 
2290 /*
2291  * Structures and routines associated with inodedep caching.
2292  */
2293 #define	INODEDEP_HASH(ump, inum) \
2294       (&(ump)->inodedep_hashtbl[(inum) & (ump)->inodedep_hash_size])
2295 
2296 static int
2297 inodedep_find(struct inodedep_hashhead *inodedephd,
2298 	ino_t inum,
2299 	struct inodedep **inodedeppp)
2300 {
2301 	struct inodedep *inodedep;
2302 
2303 	LIST_FOREACH(inodedep, inodedephd, id_hash)
2304 		if (inum == inodedep->id_ino)
2305 			break;
2306 	if (inodedep) {
2307 		*inodedeppp = inodedep;
2308 		return (1);
2309 	}
2310 	*inodedeppp = NULL;
2311 
2312 	return (0);
2313 }
2314 /*
2315  * Look up an inodedep. Return 1 if found, 0 if not found.
2316  * If not found, allocate if DEPALLOC flag is passed.
2317  * Found or allocated entry is returned in inodedeppp.
2318  */
2319 static int
2320 inodedep_lookup(struct mount *mp,
2321 	ino_t inum,
2322 	int flags,
2323 	struct inodedep **inodedeppp)
2324 {
2325 	struct inodedep *inodedep;
2326 	struct inodedep_hashhead *inodedephd;
2327 	struct ufsmount *ump;
2328 	struct fs *fs;
2329 
2330 	ump = VFSTOUFS(mp);
2331 	LOCK_OWNED(ump);
2332 	fs = ump->um_fs;
2333 	inodedephd = INODEDEP_HASH(ump, inum);
2334 
2335 	if (inodedep_find(inodedephd, inum, inodedeppp))
2336 		return (1);
2337 	if ((flags & DEPALLOC) == 0)
2338 		return (0);
2339 	/*
2340 	 * If the system is over its limit and our filesystem is
2341 	 * responsible for more than our share of that usage and
2342 	 * we are not in a rush, request some inodedep cleanup.
2343 	 */
2344 	if (softdep_excess_items(ump, D_INODEDEP))
2345 		schedule_cleanup(mp);
2346 	else
2347 		FREE_LOCK(ump);
2348 	inodedep = malloc(sizeof(struct inodedep),
2349 		M_INODEDEP, M_SOFTDEP_FLAGS);
2350 	workitem_alloc(&inodedep->id_list, D_INODEDEP, mp);
2351 	ACQUIRE_LOCK(ump);
2352 	if (inodedep_find(inodedephd, inum, inodedeppp)) {
2353 		WORKITEM_FREE(inodedep, D_INODEDEP);
2354 		return (1);
2355 	}
2356 	inodedep->id_fs = fs;
2357 	inodedep->id_ino = inum;
2358 	inodedep->id_state = ALLCOMPLETE;
2359 	inodedep->id_nlinkdelta = 0;
2360 	inodedep->id_nlinkwrote = -1;
2361 	inodedep->id_savedino1 = NULL;
2362 	inodedep->id_savedsize = -1;
2363 	inodedep->id_savedextsize = -1;
2364 	inodedep->id_savednlink = -1;
2365 	inodedep->id_bmsafemap = NULL;
2366 	inodedep->id_mkdiradd = NULL;
2367 	LIST_INIT(&inodedep->id_dirremhd);
2368 	LIST_INIT(&inodedep->id_pendinghd);
2369 	LIST_INIT(&inodedep->id_inowait);
2370 	LIST_INIT(&inodedep->id_bufwait);
2371 	TAILQ_INIT(&inodedep->id_inoreflst);
2372 	TAILQ_INIT(&inodedep->id_inoupdt);
2373 	TAILQ_INIT(&inodedep->id_newinoupdt);
2374 	TAILQ_INIT(&inodedep->id_extupdt);
2375 	TAILQ_INIT(&inodedep->id_newextupdt);
2376 	TAILQ_INIT(&inodedep->id_freeblklst);
2377 	LIST_INSERT_HEAD(inodedephd, inodedep, id_hash);
2378 	*inodedeppp = inodedep;
2379 	return (0);
2380 }
2381 
2382 /*
2383  * Structures and routines associated with newblk caching.
2384  */
2385 #define	NEWBLK_HASH(ump, inum) \
2386 	(&(ump)->newblk_hashtbl[(inum) & (ump)->newblk_hash_size])
2387 
2388 static int
2389 newblk_find(struct newblk_hashhead *newblkhd,
2390 	ufs2_daddr_t newblkno,
2391 	int flags,
2392 	struct newblk **newblkpp)
2393 {
2394 	struct newblk *newblk;
2395 
2396 	LIST_FOREACH(newblk, newblkhd, nb_hash) {
2397 		if (newblkno != newblk->nb_newblkno)
2398 			continue;
2399 		/*
2400 		 * If we're creating a new dependency don't match those that
2401 		 * have already been converted to allocdirects.  This is for
2402 		 * a frag extend.
2403 		 */
2404 		if ((flags & DEPALLOC) && newblk->nb_list.wk_type != D_NEWBLK)
2405 			continue;
2406 		break;
2407 	}
2408 	if (newblk) {
2409 		*newblkpp = newblk;
2410 		return (1);
2411 	}
2412 	*newblkpp = NULL;
2413 	return (0);
2414 }
2415 
2416 /*
2417  * Look up a newblk. Return 1 if found, 0 if not found.
2418  * If not found, allocate if DEPALLOC flag is passed.
2419  * Found or allocated entry is returned in newblkpp.
2420  */
2421 static int
2422 newblk_lookup(struct mount *mp,
2423 	ufs2_daddr_t newblkno,
2424 	int flags,
2425 	struct newblk **newblkpp)
2426 {
2427 	struct newblk *newblk;
2428 	struct newblk_hashhead *newblkhd;
2429 	struct ufsmount *ump;
2430 
2431 	ump = VFSTOUFS(mp);
2432 	LOCK_OWNED(ump);
2433 	newblkhd = NEWBLK_HASH(ump, newblkno);
2434 	if (newblk_find(newblkhd, newblkno, flags, newblkpp))
2435 		return (1);
2436 	if ((flags & DEPALLOC) == 0)
2437 		return (0);
2438 	if (softdep_excess_items(ump, D_NEWBLK) ||
2439 	    softdep_excess_items(ump, D_ALLOCDIRECT) ||
2440 	    softdep_excess_items(ump, D_ALLOCINDIR))
2441 		schedule_cleanup(mp);
2442 	else
2443 		FREE_LOCK(ump);
2444 	newblk = malloc(sizeof(union allblk), M_NEWBLK,
2445 	    M_SOFTDEP_FLAGS | M_ZERO);
2446 	workitem_alloc(&newblk->nb_list, D_NEWBLK, mp);
2447 	ACQUIRE_LOCK(ump);
2448 	if (newblk_find(newblkhd, newblkno, flags, newblkpp)) {
2449 		WORKITEM_FREE(newblk, D_NEWBLK);
2450 		return (1);
2451 	}
2452 	newblk->nb_freefrag = NULL;
2453 	LIST_INIT(&newblk->nb_indirdeps);
2454 	LIST_INIT(&newblk->nb_newdirblk);
2455 	LIST_INIT(&newblk->nb_jwork);
2456 	newblk->nb_state = ATTACHED;
2457 	newblk->nb_newblkno = newblkno;
2458 	LIST_INSERT_HEAD(newblkhd, newblk, nb_hash);
2459 	*newblkpp = newblk;
2460 	return (0);
2461 }
2462 
2463 /*
2464  * Structures and routines associated with freed indirect block caching.
2465  */
2466 #define	INDIR_HASH(ump, blkno) \
2467 	(&(ump)->indir_hashtbl[(blkno) & (ump)->indir_hash_size])
2468 
2469 /*
2470  * Lookup an indirect block in the indir hash table.  The freework is
2471  * removed and potentially freed.  The caller must do a blocking journal
2472  * write before writing to the blkno.
2473  */
2474 static int
2475 indirblk_lookup(struct mount *mp, ufs2_daddr_t blkno)
2476 {
2477 	struct freework *freework;
2478 	struct indir_hashhead *wkhd;
2479 	struct ufsmount *ump;
2480 
2481 	ump = VFSTOUFS(mp);
2482 	wkhd = INDIR_HASH(ump, blkno);
2483 	TAILQ_FOREACH(freework, wkhd, fw_next) {
2484 		if (freework->fw_blkno != blkno)
2485 			continue;
2486 		indirblk_remove(freework);
2487 		return (1);
2488 	}
2489 	return (0);
2490 }
2491 
2492 /*
2493  * Insert an indirect block represented by freework into the indirblk
2494  * hash table so that it may prevent the block from being re-used prior
2495  * to the journal being written.
2496  */
2497 static void
2498 indirblk_insert(struct freework *freework)
2499 {
2500 	struct jblocks *jblocks;
2501 	struct jseg *jseg;
2502 	struct ufsmount *ump;
2503 
2504 	ump = VFSTOUFS(freework->fw_list.wk_mp);
2505 	jblocks = ump->softdep_jblocks;
2506 	jseg = TAILQ_LAST(&jblocks->jb_segs, jseglst);
2507 	if (jseg == NULL)
2508 		return;
2509 
2510 	LIST_INSERT_HEAD(&jseg->js_indirs, freework, fw_segs);
2511 	TAILQ_INSERT_HEAD(INDIR_HASH(ump, freework->fw_blkno), freework,
2512 	    fw_next);
2513 	freework->fw_state &= ~DEPCOMPLETE;
2514 }
2515 
2516 static void
2517 indirblk_remove(struct freework *freework)
2518 {
2519 	struct ufsmount *ump;
2520 
2521 	ump = VFSTOUFS(freework->fw_list.wk_mp);
2522 	LIST_REMOVE(freework, fw_segs);
2523 	TAILQ_REMOVE(INDIR_HASH(ump, freework->fw_blkno), freework, fw_next);
2524 	freework->fw_state |= DEPCOMPLETE;
2525 	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
2526 		WORKITEM_FREE(freework, D_FREEWORK);
2527 }
2528 
2529 /*
2530  * Executed during filesystem system initialization before
2531  * mounting any filesystems.
2532  */
2533 void
2534 softdep_initialize(void)
2535 {
2536 
2537 	TAILQ_INIT(&softdepmounts);
2538 #ifdef __LP64__
2539 	max_softdeps = desiredvnodes * 4;
2540 #else
2541 	max_softdeps = desiredvnodes * 2;
2542 #endif
2543 
2544 	/* initialise bioops hack */
2545 	bioops.io_start = softdep_disk_io_initiation;
2546 	bioops.io_complete = softdep_disk_write_complete;
2547 	bioops.io_deallocate = softdep_deallocate_dependencies;
2548 	bioops.io_countdeps = softdep_count_dependencies;
2549 	softdep_ast_cleanup = softdep_ast_cleanup_proc;
2550 
2551 	/* Initialize the callout with an mtx. */
2552 	callout_init_mtx(&softdep_callout, &lk, 0);
2553 }
2554 
2555 /*
2556  * Executed after all filesystems have been unmounted during
2557  * filesystem module unload.
2558  */
2559 void
2560 softdep_uninitialize(void)
2561 {
2562 
2563 	/* clear bioops hack */
2564 	bioops.io_start = NULL;
2565 	bioops.io_complete = NULL;
2566 	bioops.io_deallocate = NULL;
2567 	bioops.io_countdeps = NULL;
2568 	softdep_ast_cleanup = NULL;
2569 
2570 	callout_drain(&softdep_callout);
2571 }
2572 
2573 /*
2574  * Called at mount time to notify the dependency code that a
2575  * filesystem wishes to use it.
2576  */
2577 int
2578 softdep_mount(struct vnode *devvp,
2579 	struct mount *mp,
2580 	struct fs *fs,
2581 	struct ucred *cred)
2582 {
2583 	struct csum_total cstotal;
2584 	struct mount_softdeps *sdp;
2585 	struct ufsmount *ump;
2586 	struct cg *cgp;
2587 	struct buf *bp;
2588 	u_int cyl, i;
2589 	int error;
2590 
2591 	ump = VFSTOUFS(mp);
2592 
2593 	sdp = malloc(sizeof(struct mount_softdeps), M_MOUNTDATA,
2594 	    M_WAITOK | M_ZERO);
2595 	rw_init(&sdp->sd_fslock, "SUrw");
2596 	sdp->sd_ump = ump;
2597 	LIST_INIT(&sdp->sd_workitem_pending);
2598 	LIST_INIT(&sdp->sd_journal_pending);
2599 	TAILQ_INIT(&sdp->sd_unlinked);
2600 	LIST_INIT(&sdp->sd_dirtycg);
2601 	sdp->sd_worklist_tail = NULL;
2602 	sdp->sd_on_worklist = 0;
2603 	sdp->sd_deps = 0;
2604 	LIST_INIT(&sdp->sd_mkdirlisthd);
2605 	sdp->sd_pdhash = hashinit(desiredvnodes / 5, M_PAGEDEP,
2606 	    &sdp->sd_pdhashsize);
2607 	sdp->sd_pdnextclean = 0;
2608 	sdp->sd_idhash = hashinit(desiredvnodes, M_INODEDEP,
2609 	    &sdp->sd_idhashsize);
2610 	sdp->sd_idnextclean = 0;
2611 	sdp->sd_newblkhash = hashinit(max_softdeps / 2,  M_NEWBLK,
2612 	    &sdp->sd_newblkhashsize);
2613 	sdp->sd_bmhash = hashinit(1024, M_BMSAFEMAP, &sdp->sd_bmhashsize);
2614 	i = 1 << (ffs(desiredvnodes / 10) - 1);
2615 	sdp->sd_indirhash = malloc(i * sizeof(struct indir_hashhead),
2616 	    M_FREEWORK, M_WAITOK);
2617 	sdp->sd_indirhashsize = i - 1;
2618 	for (i = 0; i <= sdp->sd_indirhashsize; i++)
2619 		TAILQ_INIT(&sdp->sd_indirhash[i]);
2620 	for (i = 0; i <= D_LAST; i++)
2621 		LIST_INIT(&sdp->sd_alldeps[i]);
2622 	ACQUIRE_GBLLOCK(&lk);
2623 	TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
2624 	FREE_GBLLOCK(&lk);
2625 
2626 	ump->um_softdep = sdp;
2627 	MNT_ILOCK(mp);
2628 	mp->mnt_flag = (mp->mnt_flag & ~MNT_ASYNC) | MNT_SOFTDEP;
2629 	if ((mp->mnt_kern_flag & MNTK_SOFTDEP) == 0) {
2630 		mp->mnt_kern_flag = (mp->mnt_kern_flag & ~MNTK_ASYNC) |
2631 		    MNTK_SOFTDEP | MNTK_NOASYNC;
2632 	}
2633 	MNT_IUNLOCK(mp);
2634 
2635 	if ((fs->fs_flags & FS_SUJ) &&
2636 	    (error = journal_mount(mp, fs, cred)) != 0) {
2637 		printf("Failed to start journal: %d\n", error);
2638 		softdep_unmount(mp);
2639 		return (error);
2640 	}
2641 	/*
2642 	 * Start our flushing thread in the bufdaemon process.
2643 	 */
2644 	ACQUIRE_LOCK(ump);
2645 	ump->softdep_flags |= FLUSH_STARTING;
2646 	FREE_LOCK(ump);
2647 	kproc_kthread_add(&softdep_flush, mp, &bufdaemonproc,
2648 	    &ump->softdep_flushtd, 0, 0, "softdepflush", "%s worker",
2649 	    mp->mnt_stat.f_mntonname);
2650 	ACQUIRE_LOCK(ump);
2651 	while ((ump->softdep_flags & FLUSH_STARTING) != 0) {
2652 		msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM, "sdstart",
2653 		    hz / 2);
2654 	}
2655 	FREE_LOCK(ump);
2656 	/*
2657 	 * When doing soft updates, the counters in the
2658 	 * superblock may have gotten out of sync. Recomputation
2659 	 * can take a long time and can be deferred for background
2660 	 * fsck.  However, the old behavior of scanning the cylinder
2661 	 * groups and recalculating them at mount time is available
2662 	 * by setting vfs.ffs.compute_summary_at_mount to one.
2663 	 */
2664 	if (compute_summary_at_mount == 0 || fs->fs_clean != 0)
2665 		return (0);
2666 	bzero(&cstotal, sizeof cstotal);
2667 	for (cyl = 0; cyl < fs->fs_ncg; cyl++) {
2668 		if ((error = bread(devvp, fsbtodb(fs, cgtod(fs, cyl)),
2669 		    fs->fs_cgsize, cred, &bp)) != 0) {
2670 			brelse(bp);
2671 			softdep_unmount(mp);
2672 			return (error);
2673 		}
2674 		cgp = (struct cg *)bp->b_data;
2675 		cstotal.cs_nffree += cgp->cg_cs.cs_nffree;
2676 		cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree;
2677 		cstotal.cs_nifree += cgp->cg_cs.cs_nifree;
2678 		cstotal.cs_ndir += cgp->cg_cs.cs_ndir;
2679 		fs->fs_cs(fs, cyl) = cgp->cg_cs;
2680 		brelse(bp);
2681 	}
2682 #ifdef INVARIANTS
2683 	if (bcmp(&cstotal, &fs->fs_cstotal, sizeof cstotal))
2684 		printf("%s: superblock summary recomputed\n", fs->fs_fsmnt);
2685 #endif
2686 	bcopy(&cstotal, &fs->fs_cstotal, sizeof cstotal);
2687 	return (0);
2688 }
2689 
2690 void
2691 softdep_unmount(struct mount *mp)
2692 {
2693 	struct ufsmount *ump;
2694 	struct mount_softdeps *ums;
2695 
2696 	ump = VFSTOUFS(mp);
2697 	KASSERT(ump->um_softdep != NULL,
2698 	    ("softdep_unmount called on non-softdep filesystem"));
2699 	MNT_ILOCK(mp);
2700 	mp->mnt_flag &= ~MNT_SOFTDEP;
2701 	if ((mp->mnt_flag & MNT_SUJ) == 0) {
2702 		MNT_IUNLOCK(mp);
2703 	} else {
2704 		mp->mnt_flag &= ~MNT_SUJ;
2705 		MNT_IUNLOCK(mp);
2706 		journal_unmount(ump);
2707 	}
2708 	/*
2709 	 * Shut down our flushing thread. Check for NULL is if
2710 	 * softdep_mount errors out before the thread has been created.
2711 	 */
2712 	if (ump->softdep_flushtd != NULL) {
2713 		ACQUIRE_LOCK(ump);
2714 		ump->softdep_flags |= FLUSH_EXIT;
2715 		wakeup(&ump->softdep_flushtd);
2716 		while ((ump->softdep_flags & FLUSH_EXIT) != 0) {
2717 			msleep(&ump->softdep_flags, LOCK_PTR(ump), PVM,
2718 			    "sdwait", 0);
2719 		}
2720 		KASSERT((ump->softdep_flags & FLUSH_EXIT) == 0,
2721 		    ("Thread shutdown failed"));
2722 		FREE_LOCK(ump);
2723 	}
2724 
2725 	/*
2726 	 * We are no longer have softdep structure attached to ump.
2727 	 */
2728 	ums = ump->um_softdep;
2729 	ACQUIRE_GBLLOCK(&lk);
2730 	TAILQ_REMOVE(&softdepmounts, ums, sd_next);
2731 	FREE_GBLLOCK(&lk);
2732 	ump->um_softdep = NULL;
2733 
2734 	KASSERT(ums->sd_on_journal == 0,
2735 	    ("ump %p ums %p on_journal %d", ump, ums, ums->sd_on_journal));
2736 	KASSERT(ums->sd_on_worklist == 0,
2737 	    ("ump %p ums %p on_worklist %d", ump, ums, ums->sd_on_worklist));
2738 	KASSERT(ums->sd_deps == 0,
2739 	    ("ump %p ums %p deps %d", ump, ums, ums->sd_deps));
2740 
2741 	/*
2742 	 * Free up our resources.
2743 	 */
2744 	rw_destroy(&ums->sd_fslock);
2745 	hashdestroy(ums->sd_pdhash, M_PAGEDEP, ums->sd_pdhashsize);
2746 	hashdestroy(ums->sd_idhash, M_INODEDEP, ums->sd_idhashsize);
2747 	hashdestroy(ums->sd_newblkhash, M_NEWBLK, ums->sd_newblkhashsize);
2748 	hashdestroy(ums->sd_bmhash, M_BMSAFEMAP, ums->sd_bmhashsize);
2749 	free(ums->sd_indirhash, M_FREEWORK);
2750 #ifdef INVARIANTS
2751 	for (int i = 0; i <= D_LAST; i++) {
2752 		KASSERT(ums->sd_curdeps[i] == 0,
2753 		    ("Unmount %s: Dep type %s != 0 (%ld)", ump->um_fs->fs_fsmnt,
2754 		    TYPENAME(i), ums->sd_curdeps[i]));
2755 		KASSERT(LIST_EMPTY(&ums->sd_alldeps[i]),
2756 		    ("Unmount %s: Dep type %s not empty (%p)",
2757 		    ump->um_fs->fs_fsmnt,
2758 		    TYPENAME(i), LIST_FIRST(&ums->sd_alldeps[i])));
2759 	}
2760 #endif
2761 	free(ums, M_MOUNTDATA);
2762 }
2763 
2764 static struct jblocks *
2765 jblocks_create(void)
2766 {
2767 	struct jblocks *jblocks;
2768 
2769 	jblocks = malloc(sizeof(*jblocks), M_JBLOCKS, M_WAITOK | M_ZERO);
2770 	TAILQ_INIT(&jblocks->jb_segs);
2771 	jblocks->jb_avail = 10;
2772 	jblocks->jb_extent = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2773 	    M_JBLOCKS, M_WAITOK | M_ZERO);
2774 
2775 	return (jblocks);
2776 }
2777 
2778 static ufs2_daddr_t
2779 jblocks_alloc(struct jblocks *jblocks,
2780 	int bytes,
2781 	int *actual)
2782 {
2783 	ufs2_daddr_t daddr;
2784 	struct jextent *jext;
2785 	int freecnt;
2786 	int blocks;
2787 
2788 	blocks = bytes / DEV_BSIZE;
2789 	jext = &jblocks->jb_extent[jblocks->jb_head];
2790 	freecnt = jext->je_blocks - jblocks->jb_off;
2791 	if (freecnt == 0) {
2792 		jblocks->jb_off = 0;
2793 		if (++jblocks->jb_head > jblocks->jb_used)
2794 			jblocks->jb_head = 0;
2795 		jext = &jblocks->jb_extent[jblocks->jb_head];
2796 		freecnt = jext->je_blocks;
2797 	}
2798 	if (freecnt > blocks)
2799 		freecnt = blocks;
2800 	*actual = freecnt * DEV_BSIZE;
2801 	daddr = jext->je_daddr + jblocks->jb_off;
2802 	jblocks->jb_off += freecnt;
2803 	jblocks->jb_free -= freecnt;
2804 
2805 	return (daddr);
2806 }
2807 
2808 static void
2809 jblocks_free(struct jblocks *jblocks,
2810 	struct mount *mp,
2811 	int bytes)
2812 {
2813 
2814 	LOCK_OWNED(VFSTOUFS(mp));
2815 	jblocks->jb_free += bytes / DEV_BSIZE;
2816 	if (jblocks->jb_suspended)
2817 		worklist_speedup(mp);
2818 	wakeup(jblocks);
2819 }
2820 
2821 static void
2822 jblocks_destroy(struct jblocks *jblocks)
2823 {
2824 
2825 	if (jblocks->jb_extent)
2826 		free(jblocks->jb_extent, M_JBLOCKS);
2827 	free(jblocks, M_JBLOCKS);
2828 }
2829 
2830 static void
2831 jblocks_add(struct jblocks *jblocks,
2832 	ufs2_daddr_t daddr,
2833 	int blocks)
2834 {
2835 	struct jextent *jext;
2836 
2837 	jblocks->jb_blocks += blocks;
2838 	jblocks->jb_free += blocks;
2839 	jext = &jblocks->jb_extent[jblocks->jb_used];
2840 	/* Adding the first block. */
2841 	if (jext->je_daddr == 0) {
2842 		jext->je_daddr = daddr;
2843 		jext->je_blocks = blocks;
2844 		return;
2845 	}
2846 	/* Extending the last extent. */
2847 	if (jext->je_daddr + jext->je_blocks == daddr) {
2848 		jext->je_blocks += blocks;
2849 		return;
2850 	}
2851 	/* Adding a new extent. */
2852 	if (++jblocks->jb_used == jblocks->jb_avail) {
2853 		jblocks->jb_avail *= 2;
2854 		jext = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2855 		    M_JBLOCKS, M_WAITOK | M_ZERO);
2856 		memcpy(jext, jblocks->jb_extent,
2857 		    sizeof(struct jextent) * jblocks->jb_used);
2858 		free(jblocks->jb_extent, M_JBLOCKS);
2859 		jblocks->jb_extent = jext;
2860 	}
2861 	jext = &jblocks->jb_extent[jblocks->jb_used];
2862 	jext->je_daddr = daddr;
2863 	jext->je_blocks = blocks;
2864 	return;
2865 }
2866 
2867 int
2868 softdep_journal_lookup(struct mount *mp, struct vnode **vpp)
2869 {
2870 	struct componentname cnp;
2871 	struct vnode *dvp;
2872 	ino_t sujournal;
2873 	int error;
2874 
2875 	error = VFS_VGET(mp, UFS_ROOTINO, LK_EXCLUSIVE, &dvp);
2876 	if (error)
2877 		return (error);
2878 	bzero(&cnp, sizeof(cnp));
2879 	cnp.cn_nameiop = LOOKUP;
2880 	cnp.cn_flags = ISLASTCN;
2881 	cnp.cn_cred = curthread->td_ucred;
2882 	cnp.cn_pnbuf = SUJ_FILE;
2883 	cnp.cn_nameptr = SUJ_FILE;
2884 	cnp.cn_namelen = strlen(SUJ_FILE);
2885 	error = ufs_lookup_ino(dvp, NULL, &cnp, &sujournal);
2886 	vput(dvp);
2887 	if (error != 0)
2888 		return (error);
2889 	error = VFS_VGET(mp, sujournal, LK_EXCLUSIVE, vpp);
2890 	return (error);
2891 }
2892 
2893 /*
2894  * Open and verify the journal file.
2895  */
2896 static int
2897 journal_mount(struct mount *mp,
2898 	struct fs *fs,
2899 	struct ucred *cred)
2900 {
2901 	struct jblocks *jblocks;
2902 	struct ufsmount *ump;
2903 	struct vnode *vp;
2904 	struct inode *ip;
2905 	ufs2_daddr_t blkno;
2906 	int bcount;
2907 	int error;
2908 	int i;
2909 
2910 	ump = VFSTOUFS(mp);
2911 	ump->softdep_journal_tail = NULL;
2912 	ump->softdep_on_journal = 0;
2913 	ump->softdep_accdeps = 0;
2914 	ump->softdep_req = 0;
2915 	ump->softdep_jblocks = NULL;
2916 	error = softdep_journal_lookup(mp, &vp);
2917 	if (error != 0) {
2918 		printf("Failed to find journal.  Use tunefs to create one\n");
2919 		return (error);
2920 	}
2921 	ip = VTOI(vp);
2922 	if (ip->i_size < SUJ_MIN) {
2923 		error = ENOSPC;
2924 		goto out;
2925 	}
2926 	bcount = lblkno(fs, ip->i_size);	/* Only use whole blocks. */
2927 	jblocks = jblocks_create();
2928 	for (i = 0; i < bcount; i++) {
2929 		error = ufs_bmaparray(vp, i, &blkno, NULL, NULL, NULL);
2930 		if (error)
2931 			break;
2932 		jblocks_add(jblocks, blkno, fsbtodb(fs, fs->fs_frag));
2933 	}
2934 	if (error) {
2935 		jblocks_destroy(jblocks);
2936 		goto out;
2937 	}
2938 	jblocks->jb_low = jblocks->jb_free / 3;	/* Reserve 33%. */
2939 	jblocks->jb_min = jblocks->jb_free / 10; /* Suspend at 10%. */
2940 	ump->softdep_jblocks = jblocks;
2941 
2942 	MNT_ILOCK(mp);
2943 	mp->mnt_flag |= MNT_SUJ;
2944 	MNT_IUNLOCK(mp);
2945 
2946 	/*
2947 	 * Only validate the journal contents if the
2948 	 * filesystem is clean, otherwise we write the logs
2949 	 * but they'll never be used.  If the filesystem was
2950 	 * still dirty when we mounted it the journal is
2951 	 * invalid and a new journal can only be valid if it
2952 	 * starts from a clean mount.
2953 	 */
2954 	if (fs->fs_clean) {
2955 		DIP_SET(ip, i_modrev, fs->fs_mtime);
2956 		ip->i_flags |= IN_MODIFIED;
2957 		ffs_update(vp, 1);
2958 	}
2959 out:
2960 	vput(vp);
2961 	return (error);
2962 }
2963 
2964 static void
2965 journal_unmount(struct ufsmount *ump)
2966 {
2967 
2968 	if (ump->softdep_jblocks)
2969 		jblocks_destroy(ump->softdep_jblocks);
2970 	ump->softdep_jblocks = NULL;
2971 }
2972 
2973 /*
2974  * Called when a journal record is ready to be written.  Space is allocated
2975  * and the journal entry is created when the journal is flushed to stable
2976  * store.
2977  */
2978 static void
2979 add_to_journal(struct worklist *wk)
2980 {
2981 	struct ufsmount *ump;
2982 
2983 	ump = VFSTOUFS(wk->wk_mp);
2984 	LOCK_OWNED(ump);
2985 	if (wk->wk_state & ONWORKLIST)
2986 		panic("add_to_journal: %s(0x%X) already on list",
2987 		    TYPENAME(wk->wk_type), wk->wk_state);
2988 	wk->wk_state |= ONWORKLIST | DEPCOMPLETE;
2989 	if (LIST_EMPTY(&ump->softdep_journal_pending)) {
2990 		ump->softdep_jblocks->jb_age = ticks;
2991 		LIST_INSERT_HEAD(&ump->softdep_journal_pending, wk, wk_list);
2992 	} else
2993 		LIST_INSERT_AFTER(ump->softdep_journal_tail, wk, wk_list);
2994 	ump->softdep_journal_tail = wk;
2995 	ump->softdep_on_journal += 1;
2996 }
2997 
2998 /*
2999  * Remove an arbitrary item for the journal worklist maintain the tail
3000  * pointer.  This happens when a new operation obviates the need to
3001  * journal an old operation.
3002  */
3003 static void
3004 remove_from_journal(struct worklist *wk)
3005 {
3006 	struct ufsmount *ump;
3007 
3008 	ump = VFSTOUFS(wk->wk_mp);
3009 	LOCK_OWNED(ump);
3010 #ifdef INVARIANTS
3011 	{
3012 		struct worklist *wkn;
3013 
3014 		LIST_FOREACH(wkn, &ump->softdep_journal_pending, wk_list)
3015 			if (wkn == wk)
3016 				break;
3017 		if (wkn == NULL)
3018 			panic("remove_from_journal: %p is not in journal", wk);
3019 	}
3020 #endif
3021 	/*
3022 	 * We emulate a TAILQ to save space in most structures which do not
3023 	 * require TAILQ semantics.  Here we must update the tail position
3024 	 * when removing the tail which is not the final entry. This works
3025 	 * only if the worklist linkage are at the beginning of the structure.
3026 	 */
3027 	if (ump->softdep_journal_tail == wk)
3028 		ump->softdep_journal_tail =
3029 		    (struct worklist *)wk->wk_list.le_prev;
3030 	WORKLIST_REMOVE(wk);
3031 	ump->softdep_on_journal -= 1;
3032 }
3033 
3034 /*
3035  * Check for journal space as well as dependency limits so the prelink
3036  * code can throttle both journaled and non-journaled filesystems.
3037  * Threshold is 0 for low and 1 for min.
3038  */
3039 static int
3040 journal_space(struct ufsmount *ump, int thresh)
3041 {
3042 	struct jblocks *jblocks;
3043 	int limit, avail;
3044 
3045 	jblocks = ump->softdep_jblocks;
3046 	if (jblocks == NULL)
3047 		return (1);
3048 	/*
3049 	 * We use a tighter restriction here to prevent request_cleanup()
3050 	 * running in threads from running into locks we currently hold.
3051 	 * We have to be over the limit and our filesystem has to be
3052 	 * responsible for more than our share of that usage.
3053 	 */
3054 	limit = (max_softdeps / 10) * 9;
3055 	if (dep_current[D_INODEDEP] > limit &&
3056 	    ump->softdep_curdeps[D_INODEDEP] > limit / stat_flush_threads)
3057 		return (0);
3058 	if (thresh)
3059 		thresh = jblocks->jb_min;
3060 	else
3061 		thresh = jblocks->jb_low;
3062 	avail = (ump->softdep_on_journal * JREC_SIZE) / DEV_BSIZE;
3063 	avail = jblocks->jb_free - avail;
3064 
3065 	return (avail > thresh);
3066 }
3067 
3068 static void
3069 journal_suspend(struct ufsmount *ump)
3070 {
3071 	struct jblocks *jblocks;
3072 	struct mount *mp;
3073 	bool set;
3074 
3075 	mp = UFSTOVFS(ump);
3076 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0)
3077 		return;
3078 
3079 	jblocks = ump->softdep_jblocks;
3080 	vfs_op_enter(mp);
3081 	set = false;
3082 	MNT_ILOCK(mp);
3083 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
3084 		stat_journal_min++;
3085 		mp->mnt_kern_flag |= MNTK_SUSPEND;
3086 		mp->mnt_susp_owner = ump->softdep_flushtd;
3087 		set = true;
3088 	}
3089 	jblocks->jb_suspended = 1;
3090 	MNT_IUNLOCK(mp);
3091 	if (!set)
3092 		vfs_op_exit(mp);
3093 }
3094 
3095 static int
3096 journal_unsuspend(struct ufsmount *ump)
3097 {
3098 	struct jblocks *jblocks;
3099 	struct mount *mp;
3100 
3101 	mp = UFSTOVFS(ump);
3102 	jblocks = ump->softdep_jblocks;
3103 
3104 	if (jblocks != NULL && jblocks->jb_suspended &&
3105 	    journal_space(ump, jblocks->jb_min)) {
3106 		jblocks->jb_suspended = 0;
3107 		FREE_LOCK(ump);
3108 		mp->mnt_susp_owner = curthread;
3109 		vfs_write_resume(mp, 0);
3110 		ACQUIRE_LOCK(ump);
3111 		return (1);
3112 	}
3113 	return (0);
3114 }
3115 
3116 static void
3117 journal_check_space(struct ufsmount *ump)
3118 {
3119 	struct mount *mp;
3120 
3121 	LOCK_OWNED(ump);
3122 
3123 	if (journal_space(ump, 0) == 0) {
3124 		softdep_speedup(ump);
3125 		mp = UFSTOVFS(ump);
3126 		FREE_LOCK(ump);
3127 		VFS_SYNC(mp, MNT_NOWAIT);
3128 		ffs_sbupdate(ump, MNT_WAIT, 0);
3129 		ACQUIRE_LOCK(ump);
3130 		if (journal_space(ump, 1) == 0)
3131 			journal_suspend(ump);
3132 	}
3133 }
3134 
3135 /*
3136  * Called before any allocation function to be certain that there is
3137  * sufficient space in the journal prior to creating any new records.
3138  * Since in the case of block allocation we may have multiple locked
3139  * buffers at the time of the actual allocation we can not block
3140  * when the journal records are created.  Doing so would create a deadlock
3141  * if any of these buffers needed to be flushed to reclaim space.  Instead
3142  * we require a sufficiently large amount of available space such that
3143  * each thread in the system could have passed this allocation check and
3144  * still have sufficient free space.  With 20% of a minimum journal size
3145  * of 1MB we have 6553 records available.
3146  */
3147 int
3148 softdep_prealloc(struct vnode *vp, int waitok)
3149 {
3150 	struct ufsmount *ump;
3151 
3152 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
3153 	    ("softdep_prealloc called on non-softdep filesystem"));
3154 	/*
3155 	 * Nothing to do if we are not running journaled soft updates.
3156 	 * If we currently hold the snapshot lock, we must avoid
3157 	 * handling other resources that could cause deadlock.  Do not
3158 	 * touch quotas vnode since it is typically recursed with
3159 	 * other vnode locks held.
3160 	 */
3161 	if (DOINGSUJ(vp) == 0 || IS_SNAPSHOT(VTOI(vp)) ||
3162 	    (vp->v_vflag & VV_SYSTEM) != 0)
3163 		return (0);
3164 	ump = VFSTOUFS(vp->v_mount);
3165 	ACQUIRE_LOCK(ump);
3166 	if (journal_space(ump, 0)) {
3167 		FREE_LOCK(ump);
3168 		return (0);
3169 	}
3170 	stat_journal_low++;
3171 	FREE_LOCK(ump);
3172 	if (waitok == MNT_NOWAIT)
3173 		return (ENOSPC);
3174 	/*
3175 	 * Attempt to sync this vnode once to flush any journal
3176 	 * work attached to it.
3177 	 */
3178 	if ((curthread->td_pflags & TDP_COWINPROGRESS) == 0)
3179 		ffs_syncvnode(vp, waitok, 0);
3180 	ACQUIRE_LOCK(ump);
3181 	process_removes(vp);
3182 	process_truncates(vp);
3183 	journal_check_space(ump);
3184 	FREE_LOCK(ump);
3185 
3186 	return (0);
3187 }
3188 
3189 /*
3190  * Try hard to sync all data and metadata for the vnode, and workitems
3191  * flushing which might conflict with the vnode lock.  This is a
3192  * helper for softdep_prerename().
3193  */
3194 static int
3195 softdep_prerename_vnode(struct ufsmount *ump, struct vnode *vp)
3196 {
3197 	int error;
3198 
3199 	ASSERT_VOP_ELOCKED(vp, "prehandle");
3200 	if (vp->v_data == NULL)
3201 		return (0);
3202 	error = VOP_FSYNC(vp, MNT_WAIT, curthread);
3203 	if (error != 0)
3204 		return (error);
3205 	ACQUIRE_LOCK(ump);
3206 	process_removes(vp);
3207 	process_truncates(vp);
3208 	FREE_LOCK(ump);
3209 	return (0);
3210 }
3211 
3212 /*
3213  * Must be called from VOP_RENAME() after all vnodes are locked.
3214  * Ensures that there is enough journal space for rename.  It is
3215  * sufficiently different from softdep_prelink() by having to handle
3216  * four vnodes.
3217  */
3218 int
3219 softdep_prerename(struct vnode *fdvp,
3220 	struct vnode *fvp,
3221 	struct vnode *tdvp,
3222 	struct vnode *tvp)
3223 {
3224 	struct ufsmount *ump;
3225 	int error;
3226 
3227 	ump = VFSTOUFS(fdvp->v_mount);
3228 
3229 	if (journal_space(ump, 0))
3230 		return (0);
3231 
3232 	VOP_UNLOCK(tdvp);
3233 	VOP_UNLOCK(fvp);
3234 	if (tvp != NULL && tvp != tdvp)
3235 		VOP_UNLOCK(tvp);
3236 
3237 	error = softdep_prerename_vnode(ump, fdvp);
3238 	VOP_UNLOCK(fdvp);
3239 	if (error != 0)
3240 		return (error);
3241 
3242 	VOP_LOCK(fvp, LK_EXCLUSIVE | LK_RETRY);
3243 	error = softdep_prerename_vnode(ump, fvp);
3244 	VOP_UNLOCK(fvp);
3245 	if (error != 0)
3246 		return (error);
3247 
3248 	if (tdvp != fdvp) {
3249 		VOP_LOCK(tdvp, LK_EXCLUSIVE | LK_RETRY);
3250 		error = softdep_prerename_vnode(ump, tdvp);
3251 		VOP_UNLOCK(tdvp);
3252 		if (error != 0)
3253 			return (error);
3254 	}
3255 
3256 	if (tvp != fvp && tvp != NULL) {
3257 		VOP_LOCK(tvp, LK_EXCLUSIVE | LK_RETRY);
3258 		error = softdep_prerename_vnode(ump, tvp);
3259 		VOP_UNLOCK(tvp);
3260 		if (error != 0)
3261 			return (error);
3262 	}
3263 
3264 	ACQUIRE_LOCK(ump);
3265 	softdep_speedup(ump);
3266 	process_worklist_item(UFSTOVFS(ump), 2, LK_NOWAIT);
3267 	journal_check_space(ump);
3268 	FREE_LOCK(ump);
3269 	return (ERELOOKUP);
3270 }
3271 
3272 /*
3273  * Before adjusting a link count on a vnode verify that we have sufficient
3274  * journal space.  If not, process operations that depend on the currently
3275  * locked pair of vnodes to try to flush space as the syncer, buf daemon,
3276  * and softdep flush threads can not acquire these locks to reclaim space.
3277  *
3278  * Returns 0 if all owned locks are still valid and were not dropped
3279  * in the process, in other case it returns either an error from sync,
3280  * or ERELOOKUP if any of the locks were re-acquired.  In the later
3281  * case, the state of the vnodes cannot be relied upon and our VFS
3282  * syscall must be restarted at top level from the lookup.
3283  */
3284 int
3285 softdep_prelink(struct vnode *dvp,
3286 	struct vnode *vp,
3287 	struct componentname *cnp)
3288 {
3289 	struct ufsmount *ump;
3290 	struct nameidata *ndp;
3291 
3292 	ASSERT_VOP_ELOCKED(dvp, "prelink dvp");
3293 	if (vp != NULL)
3294 		ASSERT_VOP_ELOCKED(vp, "prelink vp");
3295 	ump = VFSTOUFS(dvp->v_mount);
3296 
3297 	/*
3298 	 * Nothing to do if we have sufficient journal space.  We skip
3299 	 * flushing when vp is a snapshot to avoid deadlock where
3300 	 * another thread is trying to update the inodeblock for dvp
3301 	 * and is waiting on snaplk that vp holds.
3302 	 */
3303 	if (journal_space(ump, 0) || (vp != NULL && IS_SNAPSHOT(VTOI(vp))))
3304 		return (0);
3305 
3306 	/*
3307 	 * Check if the journal space consumption can in theory be
3308 	 * accounted on dvp and vp.  If the vnodes metadata was not
3309 	 * changed comparing with the previous round-trip into
3310 	 * softdep_prelink(), as indicated by the seqc generation
3311 	 * recorded in the nameidata, then there is no point in
3312 	 * starting the sync.
3313 	 */
3314 	ndp = __containerof(cnp, struct nameidata, ni_cnd);
3315 	if (!seqc_in_modify(ndp->ni_dvp_seqc) &&
3316 	    vn_seqc_consistent(dvp, ndp->ni_dvp_seqc) &&
3317 	    (vp == NULL || (!seqc_in_modify(ndp->ni_vp_seqc) &&
3318 	    vn_seqc_consistent(vp, ndp->ni_vp_seqc))))
3319 		return (0);
3320 
3321 	stat_journal_low++;
3322 	if (vp != NULL) {
3323 		VOP_UNLOCK(dvp);
3324 		ffs_syncvnode(vp, MNT_NOWAIT, 0);
3325 		vn_lock_pair(dvp, false, vp, true);
3326 		if (dvp->v_data == NULL)
3327 			goto out;
3328 	}
3329 	if (vp != NULL)
3330 		VOP_UNLOCK(vp);
3331 	ffs_syncvnode(dvp, MNT_WAIT, 0);
3332 	/* Process vp before dvp as it may create .. removes. */
3333 	if (vp != NULL) {
3334 		VOP_UNLOCK(dvp);
3335 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3336 		if (vp->v_data == NULL) {
3337 			vn_lock_pair(dvp, false, vp, true);
3338 			goto out;
3339 		}
3340 		ACQUIRE_LOCK(ump);
3341 		process_removes(vp);
3342 		process_truncates(vp);
3343 		FREE_LOCK(ump);
3344 		VOP_UNLOCK(vp);
3345 		vn_lock(dvp, LK_EXCLUSIVE | LK_RETRY);
3346 		if (dvp->v_data == NULL) {
3347 			vn_lock_pair(dvp, true, vp, false);
3348 			goto out;
3349 		}
3350 	}
3351 
3352 	ACQUIRE_LOCK(ump);
3353 	process_removes(dvp);
3354 	process_truncates(dvp);
3355 	VOP_UNLOCK(dvp);
3356 	softdep_speedup(ump);
3357 
3358 	process_worklist_item(UFSTOVFS(ump), 2, LK_NOWAIT);
3359 	journal_check_space(ump);
3360 	FREE_LOCK(ump);
3361 
3362 	vn_lock_pair(dvp, false, vp, false);
3363 out:
3364 	ndp->ni_dvp_seqc = vn_seqc_read_any(dvp);
3365 	if (vp != NULL)
3366 		ndp->ni_vp_seqc = vn_seqc_read_any(vp);
3367 	return (ERELOOKUP);
3368 }
3369 
3370 static void
3371 jseg_write(struct ufsmount *ump,
3372 	struct jseg *jseg,
3373 	uint8_t *data)
3374 {
3375 	struct jsegrec *rec;
3376 
3377 	rec = (struct jsegrec *)data;
3378 	rec->jsr_seq = jseg->js_seq;
3379 	rec->jsr_oldest = jseg->js_oldseq;
3380 	rec->jsr_cnt = jseg->js_cnt;
3381 	rec->jsr_blocks = jseg->js_size / ump->um_devvp->v_bufobj.bo_bsize;
3382 	rec->jsr_crc = 0;
3383 	rec->jsr_time = ump->um_fs->fs_mtime;
3384 }
3385 
3386 static inline void
3387 inoref_write(struct inoref *inoref,
3388 	struct jseg *jseg,
3389 	struct jrefrec *rec)
3390 {
3391 
3392 	inoref->if_jsegdep->jd_seg = jseg;
3393 	rec->jr_ino = inoref->if_ino;
3394 	rec->jr_parent = inoref->if_parent;
3395 	rec->jr_nlink = inoref->if_nlink;
3396 	rec->jr_mode = inoref->if_mode;
3397 	rec->jr_diroff = inoref->if_diroff;
3398 }
3399 
3400 static void
3401 jaddref_write(struct jaddref *jaddref,
3402 	struct jseg *jseg,
3403 	uint8_t *data)
3404 {
3405 	struct jrefrec *rec;
3406 
3407 	rec = (struct jrefrec *)data;
3408 	rec->jr_op = JOP_ADDREF;
3409 	inoref_write(&jaddref->ja_ref, jseg, rec);
3410 }
3411 
3412 static void
3413 jremref_write(struct jremref *jremref,
3414 	struct jseg *jseg,
3415 	uint8_t *data)
3416 {
3417 	struct jrefrec *rec;
3418 
3419 	rec = (struct jrefrec *)data;
3420 	rec->jr_op = JOP_REMREF;
3421 	inoref_write(&jremref->jr_ref, jseg, rec);
3422 }
3423 
3424 static void
3425 jmvref_write(struct jmvref *jmvref,
3426 	struct jseg *jseg,
3427 	uint8_t *data)
3428 {
3429 	struct jmvrec *rec;
3430 
3431 	rec = (struct jmvrec *)data;
3432 	rec->jm_op = JOP_MVREF;
3433 	rec->jm_ino = jmvref->jm_ino;
3434 	rec->jm_parent = jmvref->jm_parent;
3435 	rec->jm_oldoff = jmvref->jm_oldoff;
3436 	rec->jm_newoff = jmvref->jm_newoff;
3437 }
3438 
3439 static void
3440 jnewblk_write(struct jnewblk *jnewblk,
3441 	struct jseg *jseg,
3442 	uint8_t *data)
3443 {
3444 	struct jblkrec *rec;
3445 
3446 	jnewblk->jn_jsegdep->jd_seg = jseg;
3447 	rec = (struct jblkrec *)data;
3448 	rec->jb_op = JOP_NEWBLK;
3449 	rec->jb_ino = jnewblk->jn_ino;
3450 	rec->jb_blkno = jnewblk->jn_blkno;
3451 	rec->jb_lbn = jnewblk->jn_lbn;
3452 	rec->jb_frags = jnewblk->jn_frags;
3453 	rec->jb_oldfrags = jnewblk->jn_oldfrags;
3454 }
3455 
3456 static void
3457 jfreeblk_write(struct jfreeblk *jfreeblk,
3458 	struct jseg *jseg,
3459 	uint8_t *data)
3460 {
3461 	struct jblkrec *rec;
3462 
3463 	jfreeblk->jf_dep.jb_jsegdep->jd_seg = jseg;
3464 	rec = (struct jblkrec *)data;
3465 	rec->jb_op = JOP_FREEBLK;
3466 	rec->jb_ino = jfreeblk->jf_ino;
3467 	rec->jb_blkno = jfreeblk->jf_blkno;
3468 	rec->jb_lbn = jfreeblk->jf_lbn;
3469 	rec->jb_frags = jfreeblk->jf_frags;
3470 	rec->jb_oldfrags = 0;
3471 }
3472 
3473 static void
3474 jfreefrag_write(struct jfreefrag *jfreefrag,
3475 	struct jseg *jseg,
3476 	uint8_t *data)
3477 {
3478 	struct jblkrec *rec;
3479 
3480 	jfreefrag->fr_jsegdep->jd_seg = jseg;
3481 	rec = (struct jblkrec *)data;
3482 	rec->jb_op = JOP_FREEBLK;
3483 	rec->jb_ino = jfreefrag->fr_ino;
3484 	rec->jb_blkno = jfreefrag->fr_blkno;
3485 	rec->jb_lbn = jfreefrag->fr_lbn;
3486 	rec->jb_frags = jfreefrag->fr_frags;
3487 	rec->jb_oldfrags = 0;
3488 }
3489 
3490 static void
3491 jtrunc_write(struct jtrunc *jtrunc,
3492 	struct jseg *jseg,
3493 	uint8_t *data)
3494 {
3495 	struct jtrncrec *rec;
3496 
3497 	jtrunc->jt_dep.jb_jsegdep->jd_seg = jseg;
3498 	rec = (struct jtrncrec *)data;
3499 	rec->jt_op = JOP_TRUNC;
3500 	rec->jt_ino = jtrunc->jt_ino;
3501 	rec->jt_size = jtrunc->jt_size;
3502 	rec->jt_extsize = jtrunc->jt_extsize;
3503 }
3504 
3505 static void
3506 jfsync_write(struct jfsync *jfsync,
3507 	struct jseg *jseg,
3508 	uint8_t *data)
3509 {
3510 	struct jtrncrec *rec;
3511 
3512 	rec = (struct jtrncrec *)data;
3513 	rec->jt_op = JOP_SYNC;
3514 	rec->jt_ino = jfsync->jfs_ino;
3515 	rec->jt_size = jfsync->jfs_size;
3516 	rec->jt_extsize = jfsync->jfs_extsize;
3517 }
3518 
3519 static void
3520 softdep_flushjournal(struct mount *mp)
3521 {
3522 	struct jblocks *jblocks;
3523 	struct ufsmount *ump;
3524 
3525 	if (MOUNTEDSUJ(mp) == 0)
3526 		return;
3527 	ump = VFSTOUFS(mp);
3528 	jblocks = ump->softdep_jblocks;
3529 	ACQUIRE_LOCK(ump);
3530 	while (ump->softdep_on_journal) {
3531 		jblocks->jb_needseg = 1;
3532 		softdep_process_journal(mp, NULL, MNT_WAIT);
3533 	}
3534 	FREE_LOCK(ump);
3535 }
3536 
3537 static void softdep_synchronize_completed(struct bio *);
3538 static void softdep_synchronize(struct bio *, struct ufsmount *, void *);
3539 
3540 static void
3541 softdep_synchronize_completed(struct bio *bp)
3542 {
3543 	struct jseg *oldest;
3544 	struct jseg *jseg;
3545 	struct ufsmount *ump;
3546 
3547 	/*
3548 	 * caller1 marks the last segment written before we issued the
3549 	 * synchronize cache.
3550 	 */
3551 	jseg = bp->bio_caller1;
3552 	if (jseg == NULL) {
3553 		g_destroy_bio(bp);
3554 		return;
3555 	}
3556 	ump = VFSTOUFS(jseg->js_list.wk_mp);
3557 	ACQUIRE_LOCK(ump);
3558 	oldest = NULL;
3559 	/*
3560 	 * Mark all the journal entries waiting on the synchronize cache
3561 	 * as completed so they may continue on.
3562 	 */
3563 	while (jseg != NULL && (jseg->js_state & COMPLETE) == 0) {
3564 		jseg->js_state |= COMPLETE;
3565 		oldest = jseg;
3566 		jseg = TAILQ_PREV(jseg, jseglst, js_next);
3567 	}
3568 	/*
3569 	 * Restart deferred journal entry processing from the oldest
3570 	 * completed jseg.
3571 	 */
3572 	if (oldest)
3573 		complete_jsegs(oldest);
3574 
3575 	FREE_LOCK(ump);
3576 	g_destroy_bio(bp);
3577 }
3578 
3579 /*
3580  * Send BIO_FLUSH/SYNCHRONIZE CACHE to the device to enforce write ordering
3581  * barriers.  The journal must be written prior to any blocks that depend
3582  * on it and the journal can not be released until the blocks have be
3583  * written.  This code handles both barriers simultaneously.
3584  */
3585 static void
3586 softdep_synchronize(struct bio *bp,
3587 	struct ufsmount *ump,
3588 	void *caller1)
3589 {
3590 
3591 	bp->bio_cmd = BIO_FLUSH;
3592 	bp->bio_flags |= BIO_ORDERED;
3593 	bp->bio_data = NULL;
3594 	bp->bio_offset = ump->um_cp->provider->mediasize;
3595 	bp->bio_length = 0;
3596 	bp->bio_done = softdep_synchronize_completed;
3597 	bp->bio_caller1 = caller1;
3598 	g_io_request(bp, ump->um_cp);
3599 }
3600 
3601 /*
3602  * Flush some journal records to disk.
3603  */
3604 static void
3605 softdep_process_journal(struct mount *mp,
3606 	struct worklist *needwk,
3607 	int flags)
3608 {
3609 	struct jblocks *jblocks;
3610 	struct ufsmount *ump;
3611 	struct worklist *wk;
3612 	struct jseg *jseg;
3613 	struct buf *bp;
3614 	struct bio *bio;
3615 	uint8_t *data;
3616 	struct fs *fs;
3617 	int shouldflush;
3618 	int segwritten;
3619 	int jrecmin;	/* Minimum records per block. */
3620 	int jrecmax;	/* Maximum records per block. */
3621 	int size;
3622 	int cnt;
3623 	int off;
3624 	int devbsize;
3625 
3626 	ump = VFSTOUFS(mp);
3627 	if (ump->um_softdep == NULL || ump->um_softdep->sd_jblocks == NULL)
3628 		return;
3629 	shouldflush = softdep_flushcache;
3630 	bio = NULL;
3631 	jseg = NULL;
3632 	LOCK_OWNED(ump);
3633 	fs = ump->um_fs;
3634 	jblocks = ump->softdep_jblocks;
3635 	devbsize = ump->um_devvp->v_bufobj.bo_bsize;
3636 	/*
3637 	 * We write anywhere between a disk block and fs block.  The upper
3638 	 * bound is picked to prevent buffer cache fragmentation and limit
3639 	 * processing time per I/O.
3640 	 */
3641 	jrecmin = (devbsize / JREC_SIZE) - 1; /* -1 for seg header */
3642 	jrecmax = (fs->fs_bsize / devbsize) * jrecmin;
3643 	segwritten = 0;
3644 	for (;;) {
3645 		cnt = ump->softdep_on_journal;
3646 		/*
3647 		 * Criteria for writing a segment:
3648 		 * 1) We have a full block.
3649 		 * 2) We're called from jwait() and haven't found the
3650 		 *    journal item yet.
3651 		 * 3) Always write if needseg is set.
3652 		 * 4) If we are called from process_worklist and have
3653 		 *    not yet written anything we write a partial block
3654 		 *    to enforce a 1 second maximum latency on journal
3655 		 *    entries.
3656 		 */
3657 		if (cnt < (jrecmax - 1) && needwk == NULL &&
3658 		    jblocks->jb_needseg == 0 && (segwritten || cnt == 0))
3659 			break;
3660 		cnt++;
3661 		/*
3662 		 * Verify some free journal space.  softdep_prealloc() should
3663 		 * guarantee that we don't run out so this is indicative of
3664 		 * a problem with the flow control.  Try to recover
3665 		 * gracefully in any event.
3666 		 */
3667 		while (jblocks->jb_free == 0) {
3668 			if (flags != MNT_WAIT)
3669 				break;
3670 			printf("softdep: Out of journal space!\n");
3671 			softdep_speedup(ump);
3672 			msleep(jblocks, LOCK_PTR(ump), PRIBIO, "jblocks", hz);
3673 		}
3674 		FREE_LOCK(ump);
3675 		jseg = malloc(sizeof(*jseg), M_JSEG, M_SOFTDEP_FLAGS);
3676 		workitem_alloc(&jseg->js_list, D_JSEG, mp);
3677 		LIST_INIT(&jseg->js_entries);
3678 		LIST_INIT(&jseg->js_indirs);
3679 		jseg->js_state = ATTACHED;
3680 		if (shouldflush == 0)
3681 			jseg->js_state |= COMPLETE;
3682 		else if (bio == NULL)
3683 			bio = g_alloc_bio();
3684 		jseg->js_jblocks = jblocks;
3685 		bp = geteblk(fs->fs_bsize, 0);
3686 		ACQUIRE_LOCK(ump);
3687 		/*
3688 		 * If there was a race while we were allocating the block
3689 		 * and jseg the entry we care about was likely written.
3690 		 * We bail out in both the WAIT and NOWAIT case and assume
3691 		 * the caller will loop if the entry it cares about is
3692 		 * not written.
3693 		 */
3694 		cnt = ump->softdep_on_journal;
3695 		if (cnt + jblocks->jb_needseg == 0 || jblocks->jb_free == 0) {
3696 			bp->b_flags |= B_INVAL | B_NOCACHE;
3697 			WORKITEM_FREE(jseg, D_JSEG);
3698 			FREE_LOCK(ump);
3699 			brelse(bp);
3700 			ACQUIRE_LOCK(ump);
3701 			break;
3702 		}
3703 		/*
3704 		 * Calculate the disk block size required for the available
3705 		 * records rounded to the min size.
3706 		 */
3707 		if (cnt == 0)
3708 			size = devbsize;
3709 		else if (cnt < jrecmax)
3710 			size = howmany(cnt, jrecmin) * devbsize;
3711 		else
3712 			size = fs->fs_bsize;
3713 		/*
3714 		 * Allocate a disk block for this journal data and account
3715 		 * for truncation of the requested size if enough contiguous
3716 		 * space was not available.
3717 		 */
3718 		bp->b_blkno = jblocks_alloc(jblocks, size, &size);
3719 		bp->b_lblkno = bp->b_blkno;
3720 		bp->b_offset = bp->b_blkno * DEV_BSIZE;
3721 		bp->b_bcount = size;
3722 		bp->b_flags &= ~B_INVAL;
3723 		bp->b_flags |= B_VALIDSUSPWRT | B_NOCOPY;
3724 		/*
3725 		 * Initialize our jseg with cnt records.  Assign the next
3726 		 * sequence number to it and link it in-order.
3727 		 */
3728 		cnt = MIN(cnt, (size / devbsize) * jrecmin);
3729 		jseg->js_buf = bp;
3730 		jseg->js_cnt = cnt;
3731 		jseg->js_refs = cnt + 1;	/* Self ref. */
3732 		jseg->js_size = size;
3733 		jseg->js_seq = jblocks->jb_nextseq++;
3734 		if (jblocks->jb_oldestseg == NULL)
3735 			jblocks->jb_oldestseg = jseg;
3736 		jseg->js_oldseq = jblocks->jb_oldestseg->js_seq;
3737 		TAILQ_INSERT_TAIL(&jblocks->jb_segs, jseg, js_next);
3738 		if (jblocks->jb_writeseg == NULL)
3739 			jblocks->jb_writeseg = jseg;
3740 		/*
3741 		 * Start filling in records from the pending list.
3742 		 */
3743 		data = bp->b_data;
3744 		off = 0;
3745 
3746 		/*
3747 		 * Always put a header on the first block.
3748 		 * XXX As with below, there might not be a chance to get
3749 		 * into the loop.  Ensure that something valid is written.
3750 		 */
3751 		jseg_write(ump, jseg, data);
3752 		off += JREC_SIZE;
3753 		data = bp->b_data + off;
3754 
3755 		/*
3756 		 * XXX Something is wrong here.  There's no work to do,
3757 		 * but we need to perform and I/O and allow it to complete
3758 		 * anyways.
3759 		 */
3760 		if (LIST_EMPTY(&ump->softdep_journal_pending))
3761 			stat_emptyjblocks++;
3762 
3763 		while ((wk = LIST_FIRST(&ump->softdep_journal_pending))
3764 		    != NULL) {
3765 			if (cnt == 0)
3766 				break;
3767 			/* Place a segment header on every device block. */
3768 			if ((off % devbsize) == 0) {
3769 				jseg_write(ump, jseg, data);
3770 				off += JREC_SIZE;
3771 				data = bp->b_data + off;
3772 			}
3773 			if (wk == needwk)
3774 				needwk = NULL;
3775 			remove_from_journal(wk);
3776 			wk->wk_state |= INPROGRESS;
3777 			WORKLIST_INSERT(&jseg->js_entries, wk);
3778 			switch (wk->wk_type) {
3779 			case D_JADDREF:
3780 				jaddref_write(WK_JADDREF(wk), jseg, data);
3781 				break;
3782 			case D_JREMREF:
3783 				jremref_write(WK_JREMREF(wk), jseg, data);
3784 				break;
3785 			case D_JMVREF:
3786 				jmvref_write(WK_JMVREF(wk), jseg, data);
3787 				break;
3788 			case D_JNEWBLK:
3789 				jnewblk_write(WK_JNEWBLK(wk), jseg, data);
3790 				break;
3791 			case D_JFREEBLK:
3792 				jfreeblk_write(WK_JFREEBLK(wk), jseg, data);
3793 				break;
3794 			case D_JFREEFRAG:
3795 				jfreefrag_write(WK_JFREEFRAG(wk), jseg, data);
3796 				break;
3797 			case D_JTRUNC:
3798 				jtrunc_write(WK_JTRUNC(wk), jseg, data);
3799 				break;
3800 			case D_JFSYNC:
3801 				jfsync_write(WK_JFSYNC(wk), jseg, data);
3802 				break;
3803 			default:
3804 				panic("process_journal: Unknown type %s",
3805 				    TYPENAME(wk->wk_type));
3806 				/* NOTREACHED */
3807 			}
3808 			off += JREC_SIZE;
3809 			data = bp->b_data + off;
3810 			cnt--;
3811 		}
3812 
3813 		/* Clear any remaining space so we don't leak kernel data */
3814 		if (size > off)
3815 			bzero(data, size - off);
3816 
3817 		/*
3818 		 * Write this one buffer and continue.
3819 		 */
3820 		segwritten = 1;
3821 		jblocks->jb_needseg = 0;
3822 		WORKLIST_INSERT(&bp->b_dep, &jseg->js_list);
3823 		FREE_LOCK(ump);
3824 		bp->b_xflags |= BX_CVTENXIO;
3825 		pbgetvp(ump->um_devvp, bp);
3826 		/*
3827 		 * We only do the blocking wait once we find the journal
3828 		 * entry we're looking for.
3829 		 */
3830 		if (needwk == NULL && flags == MNT_WAIT)
3831 			bwrite(bp);
3832 		else
3833 			bawrite(bp);
3834 		ACQUIRE_LOCK(ump);
3835 	}
3836 	/*
3837 	 * If we wrote a segment issue a synchronize cache so the journal
3838 	 * is reflected on disk before the data is written.  Since reclaiming
3839 	 * journal space also requires writing a journal record this
3840 	 * process also enforces a barrier before reclamation.
3841 	 */
3842 	if (segwritten && shouldflush) {
3843 		softdep_synchronize(bio, ump,
3844 		    TAILQ_LAST(&jblocks->jb_segs, jseglst));
3845 	} else if (bio)
3846 		g_destroy_bio(bio);
3847 	/*
3848 	 * If we've suspended the filesystem because we ran out of journal
3849 	 * space either try to sync it here to make some progress or
3850 	 * unsuspend it if we already have.
3851 	 */
3852 	if (flags == 0 && jblocks->jb_suspended) {
3853 		if (journal_unsuspend(ump))
3854 			return;
3855 		FREE_LOCK(ump);
3856 		VFS_SYNC(mp, MNT_NOWAIT);
3857 		ffs_sbupdate(ump, MNT_WAIT, 0);
3858 		ACQUIRE_LOCK(ump);
3859 	}
3860 }
3861 
3862 /*
3863  * Complete a jseg, allowing all dependencies awaiting journal writes
3864  * to proceed.  Each journal dependency also attaches a jsegdep to dependent
3865  * structures so that the journal segment can be freed to reclaim space.
3866  */
3867 static void
3868 complete_jseg(struct jseg *jseg)
3869 {
3870 	struct worklist *wk;
3871 	struct jmvref *jmvref;
3872 #ifdef INVARIANTS
3873 	int i = 0;
3874 #endif
3875 
3876 	while ((wk = LIST_FIRST(&jseg->js_entries)) != NULL) {
3877 		WORKLIST_REMOVE(wk);
3878 		wk->wk_state &= ~INPROGRESS;
3879 		wk->wk_state |= COMPLETE;
3880 		KASSERT(i++ < jseg->js_cnt,
3881 		    ("handle_written_jseg: overflow %d >= %d",
3882 		    i - 1, jseg->js_cnt));
3883 		switch (wk->wk_type) {
3884 		case D_JADDREF:
3885 			handle_written_jaddref(WK_JADDREF(wk));
3886 			break;
3887 		case D_JREMREF:
3888 			handle_written_jremref(WK_JREMREF(wk));
3889 			break;
3890 		case D_JMVREF:
3891 			rele_jseg(jseg);	/* No jsegdep. */
3892 			jmvref = WK_JMVREF(wk);
3893 			LIST_REMOVE(jmvref, jm_deps);
3894 			if ((jmvref->jm_pagedep->pd_state & ONWORKLIST) == 0)
3895 				free_pagedep(jmvref->jm_pagedep);
3896 			WORKITEM_FREE(jmvref, D_JMVREF);
3897 			break;
3898 		case D_JNEWBLK:
3899 			handle_written_jnewblk(WK_JNEWBLK(wk));
3900 			break;
3901 		case D_JFREEBLK:
3902 			handle_written_jblkdep(&WK_JFREEBLK(wk)->jf_dep);
3903 			break;
3904 		case D_JTRUNC:
3905 			handle_written_jblkdep(&WK_JTRUNC(wk)->jt_dep);
3906 			break;
3907 		case D_JFSYNC:
3908 			rele_jseg(jseg);	/* No jsegdep. */
3909 			WORKITEM_FREE(wk, D_JFSYNC);
3910 			break;
3911 		case D_JFREEFRAG:
3912 			handle_written_jfreefrag(WK_JFREEFRAG(wk));
3913 			break;
3914 		default:
3915 			panic("handle_written_jseg: Unknown type %s",
3916 			    TYPENAME(wk->wk_type));
3917 			/* NOTREACHED */
3918 		}
3919 	}
3920 	/* Release the self reference so the structure may be freed. */
3921 	rele_jseg(jseg);
3922 }
3923 
3924 /*
3925  * Determine which jsegs are ready for completion processing.  Waits for
3926  * synchronize cache to complete as well as forcing in-order completion
3927  * of journal entries.
3928  */
3929 static void
3930 complete_jsegs(struct jseg *jseg)
3931 {
3932 	struct jblocks *jblocks;
3933 	struct jseg *jsegn;
3934 
3935 	jblocks = jseg->js_jblocks;
3936 	/*
3937 	 * Don't allow out of order completions.  If this isn't the first
3938 	 * block wait for it to write before we're done.
3939 	 */
3940 	if (jseg != jblocks->jb_writeseg)
3941 		return;
3942 	/* Iterate through available jsegs processing their entries. */
3943 	while (jseg && (jseg->js_state & ALLCOMPLETE) == ALLCOMPLETE) {
3944 		jblocks->jb_oldestwrseq = jseg->js_oldseq;
3945 		jsegn = TAILQ_NEXT(jseg, js_next);
3946 		complete_jseg(jseg);
3947 		jseg = jsegn;
3948 	}
3949 	jblocks->jb_writeseg = jseg;
3950 	/*
3951 	 * Attempt to free jsegs now that oldestwrseq may have advanced.
3952 	 */
3953 	free_jsegs(jblocks);
3954 }
3955 
3956 /*
3957  * Mark a jseg as DEPCOMPLETE and throw away the buffer.  Attempt to handle
3958  * the final completions.
3959  */
3960 static void
3961 handle_written_jseg(struct jseg *jseg, struct buf *bp)
3962 {
3963 
3964 	if (jseg->js_refs == 0)
3965 		panic("handle_written_jseg: No self-reference on %p", jseg);
3966 	jseg->js_state |= DEPCOMPLETE;
3967 	/*
3968 	 * We'll never need this buffer again, set flags so it will be
3969 	 * discarded.
3970 	 */
3971 	bp->b_flags |= B_INVAL | B_NOCACHE;
3972 	pbrelvp(bp);
3973 	complete_jsegs(jseg);
3974 }
3975 
3976 static inline struct jsegdep *
3977 inoref_jseg(struct inoref *inoref)
3978 {
3979 	struct jsegdep *jsegdep;
3980 
3981 	jsegdep = inoref->if_jsegdep;
3982 	inoref->if_jsegdep = NULL;
3983 
3984 	return (jsegdep);
3985 }
3986 
3987 /*
3988  * Called once a jremref has made it to stable store.  The jremref is marked
3989  * complete and we attempt to free it.  Any pagedeps writes sleeping waiting
3990  * for the jremref to complete will be awoken by free_jremref.
3991  */
3992 static void
3993 handle_written_jremref(struct jremref *jremref)
3994 {
3995 	struct inodedep *inodedep;
3996 	struct jsegdep *jsegdep;
3997 	struct dirrem *dirrem;
3998 
3999 	/* Grab the jsegdep. */
4000 	jsegdep = inoref_jseg(&jremref->jr_ref);
4001 	/*
4002 	 * Remove us from the inoref list.
4003 	 */
4004 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino,
4005 	    0, &inodedep) == 0)
4006 		panic("handle_written_jremref: Lost inodedep");
4007 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
4008 	/*
4009 	 * Complete the dirrem.
4010 	 */
4011 	dirrem = jremref->jr_dirrem;
4012 	jremref->jr_dirrem = NULL;
4013 	LIST_REMOVE(jremref, jr_deps);
4014 	jsegdep->jd_state |= jremref->jr_state & MKDIR_PARENT;
4015 	jwork_insert(&dirrem->dm_jwork, jsegdep);
4016 	if (LIST_EMPTY(&dirrem->dm_jremrefhd) &&
4017 	    (dirrem->dm_state & COMPLETE) != 0)
4018 		add_to_worklist(&dirrem->dm_list, 0);
4019 	free_jremref(jremref);
4020 }
4021 
4022 /*
4023  * Called once a jaddref has made it to stable store.  The dependency is
4024  * marked complete and any dependent structures are added to the inode
4025  * bufwait list to be completed as soon as it is written.  If a bitmap write
4026  * depends on this entry we move the inode into the inodedephd of the
4027  * bmsafemap dependency and attempt to remove the jaddref from the bmsafemap.
4028  */
4029 static void
4030 handle_written_jaddref(struct jaddref *jaddref)
4031 {
4032 	struct jsegdep *jsegdep;
4033 	struct inodedep *inodedep;
4034 	struct diradd *diradd;
4035 	struct mkdir *mkdir;
4036 
4037 	/* Grab the jsegdep. */
4038 	jsegdep = inoref_jseg(&jaddref->ja_ref);
4039 	mkdir = NULL;
4040 	diradd = NULL;
4041 	if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
4042 	    0, &inodedep) == 0)
4043 		panic("handle_written_jaddref: Lost inodedep.");
4044 	if (jaddref->ja_diradd == NULL)
4045 		panic("handle_written_jaddref: No dependency");
4046 	if (jaddref->ja_diradd->da_list.wk_type == D_DIRADD) {
4047 		diradd = jaddref->ja_diradd;
4048 		WORKLIST_INSERT(&inodedep->id_bufwait, &diradd->da_list);
4049 	} else if (jaddref->ja_state & MKDIR_PARENT) {
4050 		mkdir = jaddref->ja_mkdir;
4051 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir->md_list);
4052 	} else if (jaddref->ja_state & MKDIR_BODY)
4053 		mkdir = jaddref->ja_mkdir;
4054 	else
4055 		panic("handle_written_jaddref: Unknown dependency %p",
4056 		    jaddref->ja_diradd);
4057 	jaddref->ja_diradd = NULL;	/* also clears ja_mkdir */
4058 	/*
4059 	 * Remove us from the inode list.
4060 	 */
4061 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref, if_deps);
4062 	/*
4063 	 * The mkdir may be waiting on the jaddref to clear before freeing.
4064 	 */
4065 	if (mkdir) {
4066 		KASSERT(mkdir->md_list.wk_type == D_MKDIR,
4067 		    ("handle_written_jaddref: Incorrect type for mkdir %s",
4068 		    TYPENAME(mkdir->md_list.wk_type)));
4069 		mkdir->md_jaddref = NULL;
4070 		diradd = mkdir->md_diradd;
4071 		mkdir->md_state |= DEPCOMPLETE;
4072 		complete_mkdir(mkdir);
4073 	}
4074 	jwork_insert(&diradd->da_jwork, jsegdep);
4075 	if (jaddref->ja_state & NEWBLOCK) {
4076 		inodedep->id_state |= ONDEPLIST;
4077 		LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_inodedephd,
4078 		    inodedep, id_deps);
4079 	}
4080 	free_jaddref(jaddref);
4081 }
4082 
4083 /*
4084  * Called once a jnewblk journal is written.  The allocdirect or allocindir
4085  * is placed in the bmsafemap to await notification of a written bitmap.  If
4086  * the operation was canceled we add the segdep to the appropriate
4087  * dependency to free the journal space once the canceling operation
4088  * completes.
4089  */
4090 static void
4091 handle_written_jnewblk(struct jnewblk *jnewblk)
4092 {
4093 	struct bmsafemap *bmsafemap;
4094 	struct freefrag *freefrag;
4095 	struct freework *freework;
4096 	struct jsegdep *jsegdep;
4097 	struct newblk *newblk;
4098 
4099 	/* Grab the jsegdep. */
4100 	jsegdep = jnewblk->jn_jsegdep;
4101 	jnewblk->jn_jsegdep = NULL;
4102 	if (jnewblk->jn_dep == NULL)
4103 		panic("handle_written_jnewblk: No dependency for the segdep.");
4104 	switch (jnewblk->jn_dep->wk_type) {
4105 	case D_NEWBLK:
4106 	case D_ALLOCDIRECT:
4107 	case D_ALLOCINDIR:
4108 		/*
4109 		 * Add the written block to the bmsafemap so it can
4110 		 * be notified when the bitmap is on disk.
4111 		 */
4112 		newblk = WK_NEWBLK(jnewblk->jn_dep);
4113 		newblk->nb_jnewblk = NULL;
4114 		if ((newblk->nb_state & GOINGAWAY) == 0) {
4115 			bmsafemap = newblk->nb_bmsafemap;
4116 			newblk->nb_state |= ONDEPLIST;
4117 			LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk,
4118 			    nb_deps);
4119 		}
4120 		jwork_insert(&newblk->nb_jwork, jsegdep);
4121 		break;
4122 	case D_FREEFRAG:
4123 		/*
4124 		 * A newblock being removed by a freefrag when replaced by
4125 		 * frag extension.
4126 		 */
4127 		freefrag = WK_FREEFRAG(jnewblk->jn_dep);
4128 		freefrag->ff_jdep = NULL;
4129 		jwork_insert(&freefrag->ff_jwork, jsegdep);
4130 		break;
4131 	case D_FREEWORK:
4132 		/*
4133 		 * A direct block was removed by truncate.
4134 		 */
4135 		freework = WK_FREEWORK(jnewblk->jn_dep);
4136 		freework->fw_jnewblk = NULL;
4137 		jwork_insert(&freework->fw_freeblks->fb_jwork, jsegdep);
4138 		break;
4139 	default:
4140 		panic("handle_written_jnewblk: Unknown type %d.",
4141 		    jnewblk->jn_dep->wk_type);
4142 	}
4143 	jnewblk->jn_dep = NULL;
4144 	free_jnewblk(jnewblk);
4145 }
4146 
4147 /*
4148  * Cancel a jfreefrag that won't be needed, probably due to colliding with
4149  * an in-flight allocation that has not yet been committed.  Divorce us
4150  * from the freefrag and mark it DEPCOMPLETE so that it may be added
4151  * to the worklist.
4152  */
4153 static void
4154 cancel_jfreefrag(struct jfreefrag *jfreefrag)
4155 {
4156 	struct freefrag *freefrag;
4157 
4158 	if (jfreefrag->fr_jsegdep) {
4159 		free_jsegdep(jfreefrag->fr_jsegdep);
4160 		jfreefrag->fr_jsegdep = NULL;
4161 	}
4162 	freefrag = jfreefrag->fr_freefrag;
4163 	jfreefrag->fr_freefrag = NULL;
4164 	free_jfreefrag(jfreefrag);
4165 	freefrag->ff_state |= DEPCOMPLETE;
4166 	CTR1(KTR_SUJ, "cancel_jfreefrag: blkno %jd", freefrag->ff_blkno);
4167 }
4168 
4169 /*
4170  * Free a jfreefrag when the parent freefrag is rendered obsolete.
4171  */
4172 static void
4173 free_jfreefrag(struct jfreefrag *jfreefrag)
4174 {
4175 
4176 	if (jfreefrag->fr_state & INPROGRESS)
4177 		WORKLIST_REMOVE(&jfreefrag->fr_list);
4178 	else if (jfreefrag->fr_state & ONWORKLIST)
4179 		remove_from_journal(&jfreefrag->fr_list);
4180 	if (jfreefrag->fr_freefrag != NULL)
4181 		panic("free_jfreefrag:  Still attached to a freefrag.");
4182 	WORKITEM_FREE(jfreefrag, D_JFREEFRAG);
4183 }
4184 
4185 /*
4186  * Called when the journal write for a jfreefrag completes.  The parent
4187  * freefrag is added to the worklist if this completes its dependencies.
4188  */
4189 static void
4190 handle_written_jfreefrag(struct jfreefrag *jfreefrag)
4191 {
4192 	struct jsegdep *jsegdep;
4193 	struct freefrag *freefrag;
4194 
4195 	/* Grab the jsegdep. */
4196 	jsegdep = jfreefrag->fr_jsegdep;
4197 	jfreefrag->fr_jsegdep = NULL;
4198 	freefrag = jfreefrag->fr_freefrag;
4199 	if (freefrag == NULL)
4200 		panic("handle_written_jfreefrag: No freefrag.");
4201 	freefrag->ff_state |= DEPCOMPLETE;
4202 	freefrag->ff_jdep = NULL;
4203 	jwork_insert(&freefrag->ff_jwork, jsegdep);
4204 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
4205 		add_to_worklist(&freefrag->ff_list, 0);
4206 	jfreefrag->fr_freefrag = NULL;
4207 	free_jfreefrag(jfreefrag);
4208 }
4209 
4210 /*
4211  * Called when the journal write for a jfreeblk completes.  The jfreeblk
4212  * is removed from the freeblks list of pending journal writes and the
4213  * jsegdep is moved to the freeblks jwork to be completed when all blocks
4214  * have been reclaimed.
4215  */
4216 static void
4217 handle_written_jblkdep(struct jblkdep *jblkdep)
4218 {
4219 	struct freeblks *freeblks;
4220 	struct jsegdep *jsegdep;
4221 
4222 	/* Grab the jsegdep. */
4223 	jsegdep = jblkdep->jb_jsegdep;
4224 	jblkdep->jb_jsegdep = NULL;
4225 	freeblks = jblkdep->jb_freeblks;
4226 	LIST_REMOVE(jblkdep, jb_deps);
4227 	jwork_insert(&freeblks->fb_jwork, jsegdep);
4228 	/*
4229 	 * If the freeblks is all journaled, we can add it to the worklist.
4230 	 */
4231 	if (LIST_EMPTY(&freeblks->fb_jblkdephd) &&
4232 	    (freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
4233 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
4234 
4235 	free_jblkdep(jblkdep);
4236 }
4237 
4238 static struct jsegdep *
4239 newjsegdep(struct worklist *wk)
4240 {
4241 	struct jsegdep *jsegdep;
4242 
4243 	jsegdep = malloc(sizeof(*jsegdep), M_JSEGDEP, M_SOFTDEP_FLAGS);
4244 	workitem_alloc(&jsegdep->jd_list, D_JSEGDEP, wk->wk_mp);
4245 	jsegdep->jd_seg = NULL;
4246 
4247 	return (jsegdep);
4248 }
4249 
4250 static struct jmvref *
4251 newjmvref(struct inode *dp,
4252 	ino_t ino,
4253 	off_t oldoff,
4254 	off_t newoff)
4255 {
4256 	struct jmvref *jmvref;
4257 
4258 	jmvref = malloc(sizeof(*jmvref), M_JMVREF, M_SOFTDEP_FLAGS);
4259 	workitem_alloc(&jmvref->jm_list, D_JMVREF, ITOVFS(dp));
4260 	jmvref->jm_list.wk_state = ATTACHED | DEPCOMPLETE;
4261 	jmvref->jm_parent = dp->i_number;
4262 	jmvref->jm_ino = ino;
4263 	jmvref->jm_oldoff = oldoff;
4264 	jmvref->jm_newoff = newoff;
4265 
4266 	return (jmvref);
4267 }
4268 
4269 /*
4270  * Allocate a new jremref that tracks the removal of ip from dp with the
4271  * directory entry offset of diroff.  Mark the entry as ATTACHED and
4272  * DEPCOMPLETE as we have all the information required for the journal write
4273  * and the directory has already been removed from the buffer.  The caller
4274  * is responsible for linking the jremref into the pagedep and adding it
4275  * to the journal to write.  The MKDIR_PARENT flag is set if we're doing
4276  * a DOTDOT addition so handle_workitem_remove() can properly assign
4277  * the jsegdep when we're done.
4278  */
4279 static struct jremref *
4280 newjremref(struct dirrem *dirrem,
4281 	struct inode *dp,
4282 	struct inode *ip,
4283 	off_t diroff,
4284 	nlink_t nlink)
4285 {
4286 	struct jremref *jremref;
4287 
4288 	jremref = malloc(sizeof(*jremref), M_JREMREF, M_SOFTDEP_FLAGS);
4289 	workitem_alloc(&jremref->jr_list, D_JREMREF, ITOVFS(dp));
4290 	jremref->jr_state = ATTACHED;
4291 	newinoref(&jremref->jr_ref, ip->i_number, dp->i_number, diroff,
4292 	   nlink, ip->i_mode);
4293 	jremref->jr_dirrem = dirrem;
4294 
4295 	return (jremref);
4296 }
4297 
4298 static inline void
4299 newinoref(struct inoref *inoref,
4300 	ino_t ino,
4301 	ino_t parent,
4302 	off_t diroff,
4303 	nlink_t nlink,
4304 	uint16_t mode)
4305 {
4306 
4307 	inoref->if_jsegdep = newjsegdep(&inoref->if_list);
4308 	inoref->if_diroff = diroff;
4309 	inoref->if_ino = ino;
4310 	inoref->if_parent = parent;
4311 	inoref->if_nlink = nlink;
4312 	inoref->if_mode = mode;
4313 }
4314 
4315 /*
4316  * Allocate a new jaddref to track the addition of ino to dp at diroff.  The
4317  * directory offset may not be known until later.  The caller is responsible
4318  * adding the entry to the journal when this information is available.  nlink
4319  * should be the link count prior to the addition and mode is only required
4320  * to have the correct FMT.
4321  */
4322 static struct jaddref *
4323 newjaddref(struct inode *dp,
4324 	ino_t ino,
4325 	off_t diroff,
4326 	int16_t nlink,
4327 	uint16_t mode)
4328 {
4329 	struct jaddref *jaddref;
4330 
4331 	jaddref = malloc(sizeof(*jaddref), M_JADDREF, M_SOFTDEP_FLAGS);
4332 	workitem_alloc(&jaddref->ja_list, D_JADDREF, ITOVFS(dp));
4333 	jaddref->ja_state = ATTACHED;
4334 	jaddref->ja_mkdir = NULL;
4335 	newinoref(&jaddref->ja_ref, ino, dp->i_number, diroff, nlink, mode);
4336 
4337 	return (jaddref);
4338 }
4339 
4340 /*
4341  * Create a new free dependency for a freework.  The caller is responsible
4342  * for adjusting the reference count when it has the lock held.  The freedep
4343  * will track an outstanding bitmap write that will ultimately clear the
4344  * freework to continue.
4345  */
4346 static struct freedep *
4347 newfreedep(struct freework *freework)
4348 {
4349 	struct freedep *freedep;
4350 
4351 	freedep = malloc(sizeof(*freedep), M_FREEDEP, M_SOFTDEP_FLAGS);
4352 	workitem_alloc(&freedep->fd_list, D_FREEDEP, freework->fw_list.wk_mp);
4353 	freedep->fd_freework = freework;
4354 
4355 	return (freedep);
4356 }
4357 
4358 /*
4359  * Free a freedep structure once the buffer it is linked to is written.  If
4360  * this is the last reference to the freework schedule it for completion.
4361  */
4362 static void
4363 free_freedep(struct freedep *freedep)
4364 {
4365 	struct freework *freework;
4366 
4367 	freework = freedep->fd_freework;
4368 	freework->fw_freeblks->fb_cgwait--;
4369 	if (--freework->fw_ref == 0)
4370 		freework_enqueue(freework);
4371 	WORKITEM_FREE(freedep, D_FREEDEP);
4372 }
4373 
4374 /*
4375  * Allocate a new freework structure that may be a level in an indirect
4376  * when parent is not NULL or a top level block when it is.  The top level
4377  * freework structures are allocated without the per-filesystem lock held
4378  * and before the freeblks is visible outside of softdep_setup_freeblocks().
4379  */
4380 static struct freework *
4381 newfreework(struct ufsmount *ump,
4382 	struct freeblks *freeblks,
4383 	struct freework *parent,
4384 	ufs_lbn_t lbn,
4385 	ufs2_daddr_t nb,
4386 	int frags,
4387 	int off,
4388 	int journal)
4389 {
4390 	struct freework *freework;
4391 
4392 	freework = malloc(sizeof(*freework), M_FREEWORK, M_SOFTDEP_FLAGS);
4393 	workitem_alloc(&freework->fw_list, D_FREEWORK, freeblks->fb_list.wk_mp);
4394 	freework->fw_state = ATTACHED;
4395 	freework->fw_jnewblk = NULL;
4396 	freework->fw_freeblks = freeblks;
4397 	freework->fw_parent = parent;
4398 	freework->fw_lbn = lbn;
4399 	freework->fw_blkno = nb;
4400 	freework->fw_frags = frags;
4401 	freework->fw_indir = NULL;
4402 	freework->fw_ref = (MOUNTEDSUJ(UFSTOVFS(ump)) == 0 ||
4403 	    lbn >= -UFS_NXADDR) ? 0 : NINDIR(ump->um_fs) + 1;
4404 	freework->fw_start = freework->fw_off = off;
4405 	if (journal)
4406 		newjfreeblk(freeblks, lbn, nb, frags);
4407 	if (parent == NULL) {
4408 		ACQUIRE_LOCK(ump);
4409 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
4410 		freeblks->fb_ref++;
4411 		FREE_LOCK(ump);
4412 	}
4413 
4414 	return (freework);
4415 }
4416 
4417 /*
4418  * Eliminate a jfreeblk for a block that does not need journaling.
4419  */
4420 static void
4421 cancel_jfreeblk(struct freeblks *freeblks, ufs2_daddr_t blkno)
4422 {
4423 	struct jfreeblk *jfreeblk;
4424 	struct jblkdep *jblkdep;
4425 
4426 	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps) {
4427 		if (jblkdep->jb_list.wk_type != D_JFREEBLK)
4428 			continue;
4429 		jfreeblk = WK_JFREEBLK(&jblkdep->jb_list);
4430 		if (jfreeblk->jf_blkno == blkno)
4431 			break;
4432 	}
4433 	if (jblkdep == NULL)
4434 		return;
4435 	CTR1(KTR_SUJ, "cancel_jfreeblk: blkno %jd", blkno);
4436 	free_jsegdep(jblkdep->jb_jsegdep);
4437 	LIST_REMOVE(jblkdep, jb_deps);
4438 	WORKITEM_FREE(jfreeblk, D_JFREEBLK);
4439 }
4440 
4441 /*
4442  * Allocate a new jfreeblk to journal top level block pointer when truncating
4443  * a file.  The caller must add this to the worklist when the per-filesystem
4444  * lock is held.
4445  */
4446 static struct jfreeblk *
4447 newjfreeblk(struct freeblks *freeblks,
4448 	ufs_lbn_t lbn,
4449 	ufs2_daddr_t blkno,
4450 	int frags)
4451 {
4452 	struct jfreeblk *jfreeblk;
4453 
4454 	jfreeblk = malloc(sizeof(*jfreeblk), M_JFREEBLK, M_SOFTDEP_FLAGS);
4455 	workitem_alloc(&jfreeblk->jf_dep.jb_list, D_JFREEBLK,
4456 	    freeblks->fb_list.wk_mp);
4457 	jfreeblk->jf_dep.jb_jsegdep = newjsegdep(&jfreeblk->jf_dep.jb_list);
4458 	jfreeblk->jf_dep.jb_freeblks = freeblks;
4459 	jfreeblk->jf_ino = freeblks->fb_inum;
4460 	jfreeblk->jf_lbn = lbn;
4461 	jfreeblk->jf_blkno = blkno;
4462 	jfreeblk->jf_frags = frags;
4463 	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jfreeblk->jf_dep, jb_deps);
4464 
4465 	return (jfreeblk);
4466 }
4467 
4468 /*
4469  * The journal is only prepared to handle full-size block numbers, so we
4470  * have to adjust the record to reflect the change to a full-size block.
4471  * For example, suppose we have a block made up of fragments 8-15 and
4472  * want to free its last two fragments. We are given a request that says:
4473  *     FREEBLK ino=5, blkno=14, lbn=0, frags=2, oldfrags=0
4474  * where frags are the number of fragments to free and oldfrags are the
4475  * number of fragments to keep. To block align it, we have to change it to
4476  * have a valid full-size blkno, so it becomes:
4477  *     FREEBLK ino=5, blkno=8, lbn=0, frags=2, oldfrags=6
4478  */
4479 static void
4480 adjust_newfreework(struct freeblks *freeblks, int frag_offset)
4481 {
4482 	struct jfreeblk *jfreeblk;
4483 
4484 	KASSERT((LIST_FIRST(&freeblks->fb_jblkdephd) != NULL &&
4485 	    LIST_FIRST(&freeblks->fb_jblkdephd)->jb_list.wk_type == D_JFREEBLK),
4486 	    ("adjust_newfreework: Missing freeblks dependency"));
4487 
4488 	jfreeblk = WK_JFREEBLK(LIST_FIRST(&freeblks->fb_jblkdephd));
4489 	jfreeblk->jf_blkno -= frag_offset;
4490 	jfreeblk->jf_frags += frag_offset;
4491 }
4492 
4493 /*
4494  * Allocate a new jtrunc to track a partial truncation.
4495  */
4496 static struct jtrunc *
4497 newjtrunc(struct freeblks *freeblks,
4498 	off_t size,
4499 	int extsize)
4500 {
4501 	struct jtrunc *jtrunc;
4502 
4503 	jtrunc = malloc(sizeof(*jtrunc), M_JTRUNC, M_SOFTDEP_FLAGS);
4504 	workitem_alloc(&jtrunc->jt_dep.jb_list, D_JTRUNC,
4505 	    freeblks->fb_list.wk_mp);
4506 	jtrunc->jt_dep.jb_jsegdep = newjsegdep(&jtrunc->jt_dep.jb_list);
4507 	jtrunc->jt_dep.jb_freeblks = freeblks;
4508 	jtrunc->jt_ino = freeblks->fb_inum;
4509 	jtrunc->jt_size = size;
4510 	jtrunc->jt_extsize = extsize;
4511 	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jtrunc->jt_dep, jb_deps);
4512 
4513 	return (jtrunc);
4514 }
4515 
4516 /*
4517  * If we're canceling a new bitmap we have to search for another ref
4518  * to move into the bmsafemap dep.  This might be better expressed
4519  * with another structure.
4520  */
4521 static void
4522 move_newblock_dep(struct jaddref *jaddref, struct inodedep *inodedep)
4523 {
4524 	struct inoref *inoref;
4525 	struct jaddref *jaddrefn;
4526 
4527 	jaddrefn = NULL;
4528 	for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4529 	    inoref = TAILQ_NEXT(inoref, if_deps)) {
4530 		if ((jaddref->ja_state & NEWBLOCK) &&
4531 		    inoref->if_list.wk_type == D_JADDREF) {
4532 			jaddrefn = (struct jaddref *)inoref;
4533 			break;
4534 		}
4535 	}
4536 	if (jaddrefn == NULL)
4537 		return;
4538 	jaddrefn->ja_state &= ~(ATTACHED | UNDONE);
4539 	jaddrefn->ja_state |= jaddref->ja_state &
4540 	    (ATTACHED | UNDONE | NEWBLOCK);
4541 	jaddref->ja_state &= ~(ATTACHED | UNDONE | NEWBLOCK);
4542 	jaddref->ja_state |= ATTACHED;
4543 	LIST_REMOVE(jaddref, ja_bmdeps);
4544 	LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_jaddrefhd, jaddrefn,
4545 	    ja_bmdeps);
4546 }
4547 
4548 /*
4549  * Cancel a jaddref either before it has been written or while it is being
4550  * written.  This happens when a link is removed before the add reaches
4551  * the disk.  The jaddref dependency is kept linked into the bmsafemap
4552  * and inode to prevent the link count or bitmap from reaching the disk
4553  * until handle_workitem_remove() re-adjusts the counts and bitmaps as
4554  * required.
4555  *
4556  * Returns 1 if the canceled addref requires journaling of the remove and
4557  * 0 otherwise.
4558  */
4559 static int
4560 cancel_jaddref(struct jaddref *jaddref,
4561 	struct inodedep *inodedep,
4562 	struct workhead *wkhd)
4563 {
4564 	struct inoref *inoref;
4565 	struct jsegdep *jsegdep;
4566 	int needsj;
4567 
4568 	KASSERT((jaddref->ja_state & COMPLETE) == 0,
4569 	    ("cancel_jaddref: Canceling complete jaddref"));
4570 	if (jaddref->ja_state & (INPROGRESS | COMPLETE))
4571 		needsj = 1;
4572 	else
4573 		needsj = 0;
4574 	if (inodedep == NULL)
4575 		if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
4576 		    0, &inodedep) == 0)
4577 			panic("cancel_jaddref: Lost inodedep");
4578 	/*
4579 	 * We must adjust the nlink of any reference operation that follows
4580 	 * us so that it is consistent with the in-memory reference.  This
4581 	 * ensures that inode nlink rollbacks always have the correct link.
4582 	 */
4583 	if (needsj == 0) {
4584 		for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4585 		    inoref = TAILQ_NEXT(inoref, if_deps)) {
4586 			if (inoref->if_state & GOINGAWAY)
4587 				break;
4588 			inoref->if_nlink--;
4589 		}
4590 	}
4591 	jsegdep = inoref_jseg(&jaddref->ja_ref);
4592 	if (jaddref->ja_state & NEWBLOCK)
4593 		move_newblock_dep(jaddref, inodedep);
4594 	wake_worklist(&jaddref->ja_list);
4595 	jaddref->ja_mkdir = NULL;
4596 	if (jaddref->ja_state & INPROGRESS) {
4597 		jaddref->ja_state &= ~INPROGRESS;
4598 		WORKLIST_REMOVE(&jaddref->ja_list);
4599 		jwork_insert(wkhd, jsegdep);
4600 	} else {
4601 		free_jsegdep(jsegdep);
4602 		if (jaddref->ja_state & DEPCOMPLETE)
4603 			remove_from_journal(&jaddref->ja_list);
4604 	}
4605 	jaddref->ja_state |= (GOINGAWAY | DEPCOMPLETE);
4606 	/*
4607 	 * Leave NEWBLOCK jaddrefs on the inodedep so handle_workitem_remove
4608 	 * can arrange for them to be freed with the bitmap.  Otherwise we
4609 	 * no longer need this addref attached to the inoreflst and it
4610 	 * will incorrectly adjust nlink if we leave it.
4611 	 */
4612 	if ((jaddref->ja_state & NEWBLOCK) == 0) {
4613 		TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
4614 		    if_deps);
4615 		jaddref->ja_state |= COMPLETE;
4616 		free_jaddref(jaddref);
4617 		return (needsj);
4618 	}
4619 	/*
4620 	 * Leave the head of the list for jsegdeps for fast merging.
4621 	 */
4622 	if (LIST_FIRST(wkhd) != NULL) {
4623 		jaddref->ja_state |= ONWORKLIST;
4624 		LIST_INSERT_AFTER(LIST_FIRST(wkhd), &jaddref->ja_list, wk_list);
4625 	} else
4626 		WORKLIST_INSERT(wkhd, &jaddref->ja_list);
4627 
4628 	return (needsj);
4629 }
4630 
4631 /*
4632  * Attempt to free a jaddref structure when some work completes.  This
4633  * should only succeed once the entry is written and all dependencies have
4634  * been notified.
4635  */
4636 static void
4637 free_jaddref(struct jaddref *jaddref)
4638 {
4639 
4640 	if ((jaddref->ja_state & ALLCOMPLETE) != ALLCOMPLETE)
4641 		return;
4642 	if (jaddref->ja_ref.if_jsegdep)
4643 		panic("free_jaddref: segdep attached to jaddref %p(0x%X)\n",
4644 		    jaddref, jaddref->ja_state);
4645 	if (jaddref->ja_state & NEWBLOCK)
4646 		LIST_REMOVE(jaddref, ja_bmdeps);
4647 	if (jaddref->ja_state & (INPROGRESS | ONWORKLIST))
4648 		panic("free_jaddref: Bad state %p(0x%X)",
4649 		    jaddref, jaddref->ja_state);
4650 	if (jaddref->ja_mkdir != NULL)
4651 		panic("free_jaddref: Work pending, 0x%X\n", jaddref->ja_state);
4652 	WORKITEM_FREE(jaddref, D_JADDREF);
4653 }
4654 
4655 /*
4656  * Free a jremref structure once it has been written or discarded.
4657  */
4658 static void
4659 free_jremref(struct jremref *jremref)
4660 {
4661 
4662 	if (jremref->jr_ref.if_jsegdep)
4663 		free_jsegdep(jremref->jr_ref.if_jsegdep);
4664 	if (jremref->jr_state & INPROGRESS)
4665 		panic("free_jremref: IO still pending");
4666 	WORKITEM_FREE(jremref, D_JREMREF);
4667 }
4668 
4669 /*
4670  * Free a jnewblk structure.
4671  */
4672 static void
4673 free_jnewblk(struct jnewblk *jnewblk)
4674 {
4675 
4676 	if ((jnewblk->jn_state & ALLCOMPLETE) != ALLCOMPLETE)
4677 		return;
4678 	LIST_REMOVE(jnewblk, jn_deps);
4679 	if (jnewblk->jn_dep != NULL)
4680 		panic("free_jnewblk: Dependency still attached.");
4681 	WORKITEM_FREE(jnewblk, D_JNEWBLK);
4682 }
4683 
4684 /*
4685  * Cancel a jnewblk which has been been made redundant by frag extension.
4686  */
4687 static void
4688 cancel_jnewblk(struct jnewblk *jnewblk, struct workhead *wkhd)
4689 {
4690 	struct jsegdep *jsegdep;
4691 
4692 	CTR1(KTR_SUJ, "cancel_jnewblk: blkno %jd", jnewblk->jn_blkno);
4693 	jsegdep = jnewblk->jn_jsegdep;
4694 	if (jnewblk->jn_jsegdep == NULL || jnewblk->jn_dep == NULL)
4695 		panic("cancel_jnewblk: Invalid state");
4696 	jnewblk->jn_jsegdep  = NULL;
4697 	jnewblk->jn_dep = NULL;
4698 	jnewblk->jn_state |= GOINGAWAY;
4699 	if (jnewblk->jn_state & INPROGRESS) {
4700 		jnewblk->jn_state &= ~INPROGRESS;
4701 		WORKLIST_REMOVE(&jnewblk->jn_list);
4702 		jwork_insert(wkhd, jsegdep);
4703 	} else {
4704 		free_jsegdep(jsegdep);
4705 		remove_from_journal(&jnewblk->jn_list);
4706 	}
4707 	wake_worklist(&jnewblk->jn_list);
4708 	WORKLIST_INSERT(wkhd, &jnewblk->jn_list);
4709 }
4710 
4711 static void
4712 free_jblkdep(struct jblkdep *jblkdep)
4713 {
4714 
4715 	if (jblkdep->jb_list.wk_type == D_JFREEBLK)
4716 		WORKITEM_FREE(jblkdep, D_JFREEBLK);
4717 	else if (jblkdep->jb_list.wk_type == D_JTRUNC)
4718 		WORKITEM_FREE(jblkdep, D_JTRUNC);
4719 	else
4720 		panic("free_jblkdep: Unexpected type %s",
4721 		    TYPENAME(jblkdep->jb_list.wk_type));
4722 }
4723 
4724 /*
4725  * Free a single jseg once it is no longer referenced in memory or on
4726  * disk.  Reclaim journal blocks and dependencies waiting for the segment
4727  * to disappear.
4728  */
4729 static void
4730 free_jseg(struct jseg *jseg, struct jblocks *jblocks)
4731 {
4732 	struct freework *freework;
4733 
4734 	/*
4735 	 * Free freework structures that were lingering to indicate freed
4736 	 * indirect blocks that forced journal write ordering on reallocate.
4737 	 */
4738 	while ((freework = LIST_FIRST(&jseg->js_indirs)) != NULL)
4739 		indirblk_remove(freework);
4740 	if (jblocks->jb_oldestseg == jseg)
4741 		jblocks->jb_oldestseg = TAILQ_NEXT(jseg, js_next);
4742 	TAILQ_REMOVE(&jblocks->jb_segs, jseg, js_next);
4743 	jblocks_free(jblocks, jseg->js_list.wk_mp, jseg->js_size);
4744 	KASSERT(LIST_EMPTY(&jseg->js_entries),
4745 	    ("free_jseg: Freed jseg has valid entries."));
4746 	WORKITEM_FREE(jseg, D_JSEG);
4747 }
4748 
4749 /*
4750  * Free all jsegs that meet the criteria for being reclaimed and update
4751  * oldestseg.
4752  */
4753 static void
4754 free_jsegs(struct jblocks *jblocks)
4755 {
4756 	struct jseg *jseg;
4757 
4758 	/*
4759 	 * Free only those jsegs which have none allocated before them to
4760 	 * preserve the journal space ordering.
4761 	 */
4762 	while ((jseg = TAILQ_FIRST(&jblocks->jb_segs)) != NULL) {
4763 		/*
4764 		 * Only reclaim space when nothing depends on this journal
4765 		 * set and another set has written that it is no longer
4766 		 * valid.
4767 		 */
4768 		if (jseg->js_refs != 0) {
4769 			jblocks->jb_oldestseg = jseg;
4770 			return;
4771 		}
4772 		if ((jseg->js_state & ALLCOMPLETE) != ALLCOMPLETE)
4773 			break;
4774 		if (jseg->js_seq > jblocks->jb_oldestwrseq)
4775 			break;
4776 		/*
4777 		 * We can free jsegs that didn't write entries when
4778 		 * oldestwrseq == js_seq.
4779 		 */
4780 		if (jseg->js_seq == jblocks->jb_oldestwrseq &&
4781 		    jseg->js_cnt != 0)
4782 			break;
4783 		free_jseg(jseg, jblocks);
4784 	}
4785 	/*
4786 	 * If we exited the loop above we still must discover the
4787 	 * oldest valid segment.
4788 	 */
4789 	if (jseg)
4790 		for (jseg = jblocks->jb_oldestseg; jseg != NULL;
4791 		     jseg = TAILQ_NEXT(jseg, js_next))
4792 			if (jseg->js_refs != 0)
4793 				break;
4794 	jblocks->jb_oldestseg = jseg;
4795 	/*
4796 	 * The journal has no valid records but some jsegs may still be
4797 	 * waiting on oldestwrseq to advance.  We force a small record
4798 	 * out to permit these lingering records to be reclaimed.
4799 	 */
4800 	if (jblocks->jb_oldestseg == NULL && !TAILQ_EMPTY(&jblocks->jb_segs))
4801 		jblocks->jb_needseg = 1;
4802 }
4803 
4804 /*
4805  * Release one reference to a jseg and free it if the count reaches 0.  This
4806  * should eventually reclaim journal space as well.
4807  */
4808 static void
4809 rele_jseg(struct jseg *jseg)
4810 {
4811 
4812 	KASSERT(jseg->js_refs > 0,
4813 	    ("free_jseg: Invalid refcnt %d", jseg->js_refs));
4814 	if (--jseg->js_refs != 0)
4815 		return;
4816 	free_jsegs(jseg->js_jblocks);
4817 }
4818 
4819 /*
4820  * Release a jsegdep and decrement the jseg count.
4821  */
4822 static void
4823 free_jsegdep(struct jsegdep *jsegdep)
4824 {
4825 
4826 	if (jsegdep->jd_seg)
4827 		rele_jseg(jsegdep->jd_seg);
4828 	WORKITEM_FREE(jsegdep, D_JSEGDEP);
4829 }
4830 
4831 /*
4832  * Wait for a journal item to make it to disk.  Initiate journal processing
4833  * if required.
4834  */
4835 static int
4836 jwait(struct worklist *wk, int waitfor)
4837 {
4838 
4839 	LOCK_OWNED(VFSTOUFS(wk->wk_mp));
4840 	/*
4841 	 * Blocking journal waits cause slow synchronous behavior.  Record
4842 	 * stats on the frequency of these blocking operations.
4843 	 */
4844 	if (waitfor == MNT_WAIT) {
4845 		stat_journal_wait++;
4846 		switch (wk->wk_type) {
4847 		case D_JREMREF:
4848 		case D_JMVREF:
4849 			stat_jwait_filepage++;
4850 			break;
4851 		case D_JTRUNC:
4852 		case D_JFREEBLK:
4853 			stat_jwait_freeblks++;
4854 			break;
4855 		case D_JNEWBLK:
4856 			stat_jwait_newblk++;
4857 			break;
4858 		case D_JADDREF:
4859 			stat_jwait_inode++;
4860 			break;
4861 		default:
4862 			break;
4863 		}
4864 	}
4865 	/*
4866 	 * If IO has not started we process the journal.  We can't mark the
4867 	 * worklist item as IOWAITING because we drop the lock while
4868 	 * processing the journal and the worklist entry may be freed after
4869 	 * this point.  The caller may call back in and re-issue the request.
4870 	 */
4871 	if ((wk->wk_state & INPROGRESS) == 0) {
4872 		softdep_process_journal(wk->wk_mp, wk, waitfor);
4873 		if (waitfor != MNT_WAIT)
4874 			return (EBUSY);
4875 		return (0);
4876 	}
4877 	if (waitfor != MNT_WAIT)
4878 		return (EBUSY);
4879 	wait_worklist(wk, "jwait");
4880 	return (0);
4881 }
4882 
4883 /*
4884  * Lookup an inodedep based on an inode pointer and set the nlinkdelta as
4885  * appropriate.  This is a convenience function to reduce duplicate code
4886  * for the setup and revert functions below.
4887  */
4888 static struct inodedep *
4889 inodedep_lookup_ip(struct inode *ip)
4890 {
4891 	struct inodedep *inodedep;
4892 
4893 	KASSERT(ip->i_nlink >= ip->i_effnlink,
4894 	    ("inodedep_lookup_ip: bad delta"));
4895 	(void) inodedep_lookup(ITOVFS(ip), ip->i_number, DEPALLOC,
4896 	    &inodedep);
4897 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
4898 	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
4899 
4900 	return (inodedep);
4901 }
4902 
4903 /*
4904  * Called prior to creating a new inode and linking it to a directory.  The
4905  * jaddref structure must already be allocated by softdep_setup_inomapdep
4906  * and it is discovered here so we can initialize the mode and update
4907  * nlinkdelta.
4908  */
4909 void
4910 softdep_setup_create(struct inode *dp, struct inode *ip)
4911 {
4912 	struct inodedep *inodedep;
4913 	struct jaddref *jaddref __diagused;
4914 	struct vnode *dvp;
4915 
4916 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4917 	    ("softdep_setup_create called on non-softdep filesystem"));
4918 	KASSERT(ip->i_nlink == 1,
4919 	    ("softdep_setup_create: Invalid link count."));
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 != NULL && jaddref->ja_parent == dp->i_number,
4927 		    ("softdep_setup_create: No addref structure present."));
4928 	}
4929 	FREE_LOCK(ITOUMP(dp));
4930 }
4931 
4932 /*
4933  * Create a jaddref structure to track the addition of a DOTDOT link when
4934  * we are reparenting an inode as part of a rename.  This jaddref will be
4935  * found by softdep_setup_directory_change.  Adjusts nlinkdelta for
4936  * non-journaling softdep.
4937  */
4938 void
4939 softdep_setup_dotdot_link(struct inode *dp, struct inode *ip)
4940 {
4941 	struct inodedep *inodedep;
4942 	struct jaddref *jaddref;
4943 	struct vnode *dvp;
4944 
4945 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4946 	    ("softdep_setup_dotdot_link called on non-softdep filesystem"));
4947 	dvp = ITOV(dp);
4948 	jaddref = NULL;
4949 	/*
4950 	 * We don't set MKDIR_PARENT as this is not tied to a mkdir and
4951 	 * is used as a normal link would be.
4952 	 */
4953 	if (DOINGSUJ(dvp))
4954 		jaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4955 		    dp->i_effnlink - 1, dp->i_mode);
4956 	ACQUIRE_LOCK(ITOUMP(dp));
4957 	inodedep = inodedep_lookup_ip(dp);
4958 	if (jaddref)
4959 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4960 		    if_deps);
4961 	FREE_LOCK(ITOUMP(dp));
4962 }
4963 
4964 /*
4965  * Create a jaddref structure to track a new link to an inode.  The directory
4966  * offset is not known until softdep_setup_directory_add or
4967  * softdep_setup_directory_change.  Adjusts nlinkdelta for non-journaling
4968  * softdep.
4969  */
4970 void
4971 softdep_setup_link(struct inode *dp, struct inode *ip)
4972 {
4973 	struct inodedep *inodedep;
4974 	struct jaddref *jaddref;
4975 	struct vnode *dvp;
4976 
4977 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4978 	    ("softdep_setup_link called on non-softdep filesystem"));
4979 	dvp = ITOV(dp);
4980 	jaddref = NULL;
4981 	if (DOINGSUJ(dvp))
4982 		jaddref = newjaddref(dp, ip->i_number, 0, ip->i_effnlink - 1,
4983 		    ip->i_mode);
4984 	ACQUIRE_LOCK(ITOUMP(dp));
4985 	inodedep = inodedep_lookup_ip(ip);
4986 	if (jaddref)
4987 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4988 		    if_deps);
4989 	FREE_LOCK(ITOUMP(dp));
4990 }
4991 
4992 /*
4993  * Called to create the jaddref structures to track . and .. references as
4994  * well as lookup and further initialize the incomplete jaddref created
4995  * by softdep_setup_inomapdep when the inode was allocated.  Adjusts
4996  * nlinkdelta for non-journaling softdep.
4997  */
4998 void
4999 softdep_setup_mkdir(struct inode *dp, struct inode *ip)
5000 {
5001 	struct inodedep *inodedep;
5002 	struct jaddref *dotdotaddref;
5003 	struct jaddref *dotaddref;
5004 	struct jaddref *jaddref;
5005 	struct vnode *dvp;
5006 
5007 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5008 	    ("softdep_setup_mkdir called on non-softdep filesystem"));
5009 	dvp = ITOV(dp);
5010 	dotaddref = dotdotaddref = NULL;
5011 	if (DOINGSUJ(dvp)) {
5012 		dotaddref = newjaddref(ip, ip->i_number, DOT_OFFSET, 1,
5013 		    ip->i_mode);
5014 		dotaddref->ja_state |= MKDIR_BODY;
5015 		dotdotaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
5016 		    dp->i_effnlink - 1, dp->i_mode);
5017 		dotdotaddref->ja_state |= MKDIR_PARENT;
5018 	}
5019 	ACQUIRE_LOCK(ITOUMP(dp));
5020 	inodedep = inodedep_lookup_ip(ip);
5021 	if (DOINGSUJ(dvp)) {
5022 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5023 		    inoreflst);
5024 		KASSERT(jaddref != NULL,
5025 		    ("softdep_setup_mkdir: No addref structure present."));
5026 		KASSERT(jaddref->ja_parent == dp->i_number,
5027 		    ("softdep_setup_mkdir: bad parent %ju",
5028 		    (uintmax_t)jaddref->ja_parent));
5029 		TAILQ_INSERT_BEFORE(&jaddref->ja_ref, &dotaddref->ja_ref,
5030 		    if_deps);
5031 	}
5032 	inodedep = inodedep_lookup_ip(dp);
5033 	if (DOINGSUJ(dvp))
5034 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst,
5035 		    &dotdotaddref->ja_ref, if_deps);
5036 	FREE_LOCK(ITOUMP(dp));
5037 }
5038 
5039 /*
5040  * Called to track nlinkdelta of the inode and parent directories prior to
5041  * unlinking a directory.
5042  */
5043 void
5044 softdep_setup_rmdir(struct inode *dp, struct inode *ip)
5045 {
5046 
5047 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5048 	    ("softdep_setup_rmdir called on non-softdep filesystem"));
5049 	ACQUIRE_LOCK(ITOUMP(dp));
5050 	(void) inodedep_lookup_ip(ip);
5051 	(void) inodedep_lookup_ip(dp);
5052 	FREE_LOCK(ITOUMP(dp));
5053 }
5054 
5055 /*
5056  * Called to track nlinkdelta of the inode and parent directories prior to
5057  * unlink.
5058  */
5059 void
5060 softdep_setup_unlink(struct inode *dp, struct inode *ip)
5061 {
5062 
5063 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5064 	    ("softdep_setup_unlink called on non-softdep filesystem"));
5065 	ACQUIRE_LOCK(ITOUMP(dp));
5066 	(void) inodedep_lookup_ip(ip);
5067 	(void) inodedep_lookup_ip(dp);
5068 	FREE_LOCK(ITOUMP(dp));
5069 }
5070 
5071 /*
5072  * Called to release the journal structures created by a failed non-directory
5073  * creation.  Adjusts nlinkdelta for non-journaling softdep.
5074  */
5075 void
5076 softdep_revert_create(struct inode *dp, struct inode *ip)
5077 {
5078 	struct inodedep *inodedep;
5079 	struct jaddref *jaddref;
5080 	struct vnode *dvp;
5081 
5082 	KASSERT(MOUNTEDSOFTDEP(ITOVFS((dp))) != 0,
5083 	    ("softdep_revert_create called on non-softdep filesystem"));
5084 	dvp = ITOV(dp);
5085 	ACQUIRE_LOCK(ITOUMP(dp));
5086 	inodedep = inodedep_lookup_ip(ip);
5087 	if (DOINGSUJ(dvp)) {
5088 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5089 		    inoreflst);
5090 		KASSERT(jaddref->ja_parent == dp->i_number,
5091 		    ("softdep_revert_create: addref parent mismatch"));
5092 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
5093 	}
5094 	FREE_LOCK(ITOUMP(dp));
5095 }
5096 
5097 /*
5098  * Called to release the journal structures created by a failed link
5099  * addition.  Adjusts nlinkdelta for non-journaling softdep.
5100  */
5101 void
5102 softdep_revert_link(struct inode *dp, struct inode *ip)
5103 {
5104 	struct inodedep *inodedep;
5105 	struct jaddref *jaddref;
5106 	struct vnode *dvp;
5107 
5108 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5109 	    ("softdep_revert_link called on non-softdep filesystem"));
5110 	dvp = ITOV(dp);
5111 	ACQUIRE_LOCK(ITOUMP(dp));
5112 	inodedep = inodedep_lookup_ip(ip);
5113 	if (DOINGSUJ(dvp)) {
5114 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5115 		    inoreflst);
5116 		KASSERT(jaddref->ja_parent == dp->i_number,
5117 		    ("softdep_revert_link: addref parent mismatch"));
5118 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
5119 	}
5120 	FREE_LOCK(ITOUMP(dp));
5121 }
5122 
5123 /*
5124  * Called to release the journal structures created by a failed mkdir
5125  * attempt.  Adjusts nlinkdelta for non-journaling softdep.
5126  */
5127 void
5128 softdep_revert_mkdir(struct inode *dp, struct inode *ip)
5129 {
5130 	struct inodedep *inodedep;
5131 	struct jaddref *jaddref;
5132 	struct jaddref *dotaddref;
5133 	struct vnode *dvp;
5134 
5135 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5136 	    ("softdep_revert_mkdir called on non-softdep filesystem"));
5137 	dvp = ITOV(dp);
5138 
5139 	ACQUIRE_LOCK(ITOUMP(dp));
5140 	inodedep = inodedep_lookup_ip(dp);
5141 	if (DOINGSUJ(dvp)) {
5142 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5143 		    inoreflst);
5144 		KASSERT(jaddref->ja_parent == ip->i_number,
5145 		    ("softdep_revert_mkdir: dotdot addref parent mismatch"));
5146 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
5147 	}
5148 	inodedep = inodedep_lookup_ip(ip);
5149 	if (DOINGSUJ(dvp)) {
5150 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5151 		    inoreflst);
5152 		KASSERT(jaddref->ja_parent == dp->i_number,
5153 		    ("softdep_revert_mkdir: addref parent mismatch"));
5154 		dotaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
5155 		    inoreflst, if_deps);
5156 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
5157 		KASSERT(dotaddref->ja_parent == ip->i_number,
5158 		    ("softdep_revert_mkdir: dot addref parent mismatch"));
5159 		cancel_jaddref(dotaddref, inodedep, &inodedep->id_inowait);
5160 	}
5161 	FREE_LOCK(ITOUMP(dp));
5162 }
5163 
5164 /*
5165  * Called to correct nlinkdelta after a failed rmdir.
5166  */
5167 void
5168 softdep_revert_rmdir(struct inode *dp, struct inode *ip)
5169 {
5170 
5171 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5172 	    ("softdep_revert_rmdir called on non-softdep filesystem"));
5173 	ACQUIRE_LOCK(ITOUMP(dp));
5174 	(void) inodedep_lookup_ip(ip);
5175 	(void) inodedep_lookup_ip(dp);
5176 	FREE_LOCK(ITOUMP(dp));
5177 }
5178 
5179 /*
5180  * Protecting the freemaps (or bitmaps).
5181  *
5182  * To eliminate the need to execute fsck before mounting a filesystem
5183  * after a power failure, one must (conservatively) guarantee that the
5184  * on-disk copy of the bitmaps never indicate that a live inode or block is
5185  * free.  So, when a block or inode is allocated, the bitmap should be
5186  * updated (on disk) before any new pointers.  When a block or inode is
5187  * freed, the bitmap should not be updated until all pointers have been
5188  * reset.  The latter dependency is handled by the delayed de-allocation
5189  * approach described below for block and inode de-allocation.  The former
5190  * dependency is handled by calling the following procedure when a block or
5191  * inode is allocated. When an inode is allocated an "inodedep" is created
5192  * with its DEPCOMPLETE flag cleared until its bitmap is written to disk.
5193  * Each "inodedep" is also inserted into the hash indexing structure so
5194  * that any additional link additions can be made dependent on the inode
5195  * allocation.
5196  *
5197  * The ufs filesystem maintains a number of free block counts (e.g., per
5198  * cylinder group, per cylinder and per <cylinder, rotational position> pair)
5199  * in addition to the bitmaps.  These counts are used to improve efficiency
5200  * during allocation and therefore must be consistent with the bitmaps.
5201  * There is no convenient way to guarantee post-crash consistency of these
5202  * counts with simple update ordering, for two main reasons: (1) The counts
5203  * and bitmaps for a single cylinder group block are not in the same disk
5204  * sector.  If a disk write is interrupted (e.g., by power failure), one may
5205  * be written and the other not.  (2) Some of the counts are located in the
5206  * superblock rather than the cylinder group block. So, we focus our soft
5207  * updates implementation on protecting the bitmaps. When mounting a
5208  * filesystem, we recompute the auxiliary counts from the bitmaps.
5209  */
5210 
5211 /*
5212  * Called just after updating the cylinder group block to allocate an inode.
5213  */
5214 void
5215 softdep_setup_inomapdep(
5216 	struct buf *bp,		/* buffer for cylgroup block with inode map */
5217 	struct inode *ip,	/* inode related to allocation */
5218 	ino_t newinum,		/* new inode number being allocated */
5219 	int mode)
5220 {
5221 	struct inodedep *inodedep;
5222 	struct bmsafemap *bmsafemap;
5223 	struct jaddref *jaddref;
5224 	struct mount *mp;
5225 	struct fs *fs;
5226 
5227 	mp = ITOVFS(ip);
5228 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5229 	    ("softdep_setup_inomapdep called on non-softdep filesystem"));
5230 	fs = VFSTOUFS(mp)->um_fs;
5231 	jaddref = NULL;
5232 
5233 	/*
5234 	 * Allocate the journal reference add structure so that the bitmap
5235 	 * can be dependent on it.
5236 	 */
5237 	if (MOUNTEDSUJ(mp)) {
5238 		jaddref = newjaddref(ip, newinum, 0, 0, mode);
5239 		jaddref->ja_state |= NEWBLOCK;
5240 	}
5241 
5242 	/*
5243 	 * Create a dependency for the newly allocated inode.
5244 	 * Panic if it already exists as something is seriously wrong.
5245 	 * Otherwise add it to the dependency list for the buffer holding
5246 	 * the cylinder group map from which it was allocated.
5247 	 *
5248 	 * We have to preallocate a bmsafemap entry in case it is needed
5249 	 * in bmsafemap_lookup since once we allocate the inodedep, we
5250 	 * have to finish initializing it before we can FREE_LOCK().
5251 	 * By preallocating, we avoid FREE_LOCK() while doing a malloc
5252 	 * in bmsafemap_lookup. We cannot call bmsafemap_lookup before
5253 	 * creating the inodedep as it can be freed during the time
5254 	 * that we FREE_LOCK() while allocating the inodedep. We must
5255 	 * call workitem_alloc() before entering the locked section as
5256 	 * it also acquires the lock and we must avoid trying doing so
5257 	 * recursively.
5258 	 */
5259 	bmsafemap = malloc(sizeof(struct bmsafemap),
5260 	    M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5261 	workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5262 	ACQUIRE_LOCK(ITOUMP(ip));
5263 	if ((inodedep_lookup(mp, newinum, DEPALLOC, &inodedep)))
5264 		panic("softdep_setup_inomapdep: dependency %p for new"
5265 		    "inode already exists", inodedep);
5266 	bmsafemap = bmsafemap_lookup(mp, bp, ino_to_cg(fs, newinum), bmsafemap);
5267 	if (jaddref) {
5268 		LIST_INSERT_HEAD(&bmsafemap->sm_jaddrefhd, jaddref, ja_bmdeps);
5269 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
5270 		    if_deps);
5271 	} else {
5272 		inodedep->id_state |= ONDEPLIST;
5273 		LIST_INSERT_HEAD(&bmsafemap->sm_inodedephd, inodedep, id_deps);
5274 	}
5275 	inodedep->id_bmsafemap = bmsafemap;
5276 	inodedep->id_state &= ~DEPCOMPLETE;
5277 	FREE_LOCK(ITOUMP(ip));
5278 }
5279 
5280 /*
5281  * Called just after updating the cylinder group block to
5282  * allocate block or fragment.
5283  */
5284 void
5285 softdep_setup_blkmapdep(
5286 	struct buf *bp,		/* buffer for cylgroup block with block map */
5287 	struct mount *mp,	/* filesystem doing allocation */
5288 	ufs2_daddr_t newblkno,	/* number of newly allocated block */
5289 	int frags,		/* Number of fragments. */
5290 	int oldfrags)		/* Previous number of fragments for extend. */
5291 {
5292 	struct newblk *newblk;
5293 	struct bmsafemap *bmsafemap;
5294 	struct jnewblk *jnewblk;
5295 	struct ufsmount *ump;
5296 	struct fs *fs;
5297 
5298 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5299 	    ("softdep_setup_blkmapdep called on non-softdep filesystem"));
5300 	ump = VFSTOUFS(mp);
5301 	fs = ump->um_fs;
5302 	jnewblk = NULL;
5303 	/*
5304 	 * Create a dependency for the newly allocated block.
5305 	 * Add it to the dependency list for the buffer holding
5306 	 * the cylinder group map from which it was allocated.
5307 	 */
5308 	if (MOUNTEDSUJ(mp)) {
5309 		jnewblk = malloc(sizeof(*jnewblk), M_JNEWBLK, M_SOFTDEP_FLAGS);
5310 		workitem_alloc(&jnewblk->jn_list, D_JNEWBLK, mp);
5311 		jnewblk->jn_jsegdep = newjsegdep(&jnewblk->jn_list);
5312 		jnewblk->jn_state = ATTACHED;
5313 		jnewblk->jn_blkno = newblkno;
5314 		jnewblk->jn_frags = frags;
5315 		jnewblk->jn_oldfrags = oldfrags;
5316 #ifdef INVARIANTS
5317 		{
5318 			struct cg *cgp;
5319 			uint8_t *blksfree;
5320 			long bno;
5321 			int i;
5322 
5323 			cgp = (struct cg *)bp->b_data;
5324 			blksfree = cg_blksfree(cgp);
5325 			bno = dtogd(fs, jnewblk->jn_blkno);
5326 			for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags;
5327 			    i++) {
5328 				if (isset(blksfree, bno + i))
5329 					panic("softdep_setup_blkmapdep: "
5330 					    "free fragment %d from %d-%d "
5331 					    "state 0x%X dep %p", i,
5332 					    jnewblk->jn_oldfrags,
5333 					    jnewblk->jn_frags,
5334 					    jnewblk->jn_state,
5335 					    jnewblk->jn_dep);
5336 			}
5337 		}
5338 #endif
5339 	}
5340 
5341 	CTR3(KTR_SUJ,
5342 	    "softdep_setup_blkmapdep: blkno %jd frags %d oldfrags %d",
5343 	    newblkno, frags, oldfrags);
5344 	ACQUIRE_LOCK(ump);
5345 	if (newblk_lookup(mp, newblkno, DEPALLOC, &newblk) != 0)
5346 		panic("softdep_setup_blkmapdep: found block");
5347 	newblk->nb_bmsafemap = bmsafemap = bmsafemap_lookup(mp, bp,
5348 	    dtog(fs, newblkno), NULL);
5349 	if (jnewblk) {
5350 		jnewblk->jn_dep = (struct worklist *)newblk;
5351 		LIST_INSERT_HEAD(&bmsafemap->sm_jnewblkhd, jnewblk, jn_deps);
5352 	} else {
5353 		newblk->nb_state |= ONDEPLIST;
5354 		LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
5355 	}
5356 	newblk->nb_bmsafemap = bmsafemap;
5357 	newblk->nb_jnewblk = jnewblk;
5358 	FREE_LOCK(ump);
5359 }
5360 
5361 #define	BMSAFEMAP_HASH(ump, cg) \
5362       (&(ump)->bmsafemap_hashtbl[(cg) & (ump)->bmsafemap_hash_size])
5363 
5364 static int
5365 bmsafemap_find(
5366 	struct bmsafemap_hashhead *bmsafemaphd,
5367 	int cg,
5368 	struct bmsafemap **bmsafemapp)
5369 {
5370 	struct bmsafemap *bmsafemap;
5371 
5372 	LIST_FOREACH(bmsafemap, bmsafemaphd, sm_hash)
5373 		if (bmsafemap->sm_cg == cg)
5374 			break;
5375 	if (bmsafemap) {
5376 		*bmsafemapp = bmsafemap;
5377 		return (1);
5378 	}
5379 	*bmsafemapp = NULL;
5380 
5381 	return (0);
5382 }
5383 
5384 /*
5385  * Find the bmsafemap associated with a cylinder group buffer.
5386  * If none exists, create one. The buffer must be locked when
5387  * this routine is called and this routine must be called with
5388  * the softdep lock held. To avoid giving up the lock while
5389  * allocating a new bmsafemap, a preallocated bmsafemap may be
5390  * provided. If it is provided but not needed, it is freed.
5391  */
5392 static struct bmsafemap *
5393 bmsafemap_lookup(struct mount *mp,
5394 	struct buf *bp,
5395 	int cg,
5396 	struct bmsafemap *newbmsafemap)
5397 {
5398 	struct bmsafemap_hashhead *bmsafemaphd;
5399 	struct bmsafemap *bmsafemap, *collision;
5400 	struct worklist *wk;
5401 	struct ufsmount *ump;
5402 
5403 	ump = VFSTOUFS(mp);
5404 	LOCK_OWNED(ump);
5405 	KASSERT(bp != NULL, ("bmsafemap_lookup: missing buffer"));
5406 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5407 		if (wk->wk_type == D_BMSAFEMAP) {
5408 			if (newbmsafemap)
5409 				WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5410 			return (WK_BMSAFEMAP(wk));
5411 		}
5412 	}
5413 	bmsafemaphd = BMSAFEMAP_HASH(ump, cg);
5414 	if (bmsafemap_find(bmsafemaphd, cg, &bmsafemap) == 1) {
5415 		if (newbmsafemap)
5416 			WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5417 		return (bmsafemap);
5418 	}
5419 	if (newbmsafemap) {
5420 		bmsafemap = newbmsafemap;
5421 	} else {
5422 		FREE_LOCK(ump);
5423 		bmsafemap = malloc(sizeof(struct bmsafemap),
5424 			M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5425 		workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5426 		ACQUIRE_LOCK(ump);
5427 	}
5428 	bmsafemap->sm_buf = bp;
5429 	LIST_INIT(&bmsafemap->sm_inodedephd);
5430 	LIST_INIT(&bmsafemap->sm_inodedepwr);
5431 	LIST_INIT(&bmsafemap->sm_newblkhd);
5432 	LIST_INIT(&bmsafemap->sm_newblkwr);
5433 	LIST_INIT(&bmsafemap->sm_jaddrefhd);
5434 	LIST_INIT(&bmsafemap->sm_jnewblkhd);
5435 	LIST_INIT(&bmsafemap->sm_freehd);
5436 	LIST_INIT(&bmsafemap->sm_freewr);
5437 	if (bmsafemap_find(bmsafemaphd, cg, &collision) == 1) {
5438 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
5439 		return (collision);
5440 	}
5441 	bmsafemap->sm_cg = cg;
5442 	LIST_INSERT_HEAD(bmsafemaphd, bmsafemap, sm_hash);
5443 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
5444 	WORKLIST_INSERT(&bp->b_dep, &bmsafemap->sm_list);
5445 	return (bmsafemap);
5446 }
5447 
5448 /*
5449  * Direct block allocation dependencies.
5450  *
5451  * When a new block is allocated, the corresponding disk locations must be
5452  * initialized (with zeros or new data) before the on-disk inode points to
5453  * them.  Also, the freemap from which the block was allocated must be
5454  * updated (on disk) before the inode's pointer. These two dependencies are
5455  * independent of each other and are needed for all file blocks and indirect
5456  * blocks that are pointed to directly by the inode.  Just before the
5457  * "in-core" version of the inode is updated with a newly allocated block
5458  * number, a procedure (below) is called to setup allocation dependency
5459  * structures.  These structures are removed when the corresponding
5460  * dependencies are satisfied or when the block allocation becomes obsolete
5461  * (i.e., the file is deleted, the block is de-allocated, or the block is a
5462  * fragment that gets upgraded).  All of these cases are handled in
5463  * procedures described later.
5464  *
5465  * When a file extension causes a fragment to be upgraded, either to a larger
5466  * fragment or to a full block, the on-disk location may change (if the
5467  * previous fragment could not simply be extended). In this case, the old
5468  * fragment must be de-allocated, but not until after the inode's pointer has
5469  * been updated. In most cases, this is handled by later procedures, which
5470  * will construct a "freefrag" structure to be added to the workitem queue
5471  * when the inode update is complete (or obsolete).  The main exception to
5472  * this is when an allocation occurs while a pending allocation dependency
5473  * (for the same block pointer) remains.  This case is handled in the main
5474  * allocation dependency setup procedure by immediately freeing the
5475  * unreferenced fragments.
5476  */
5477 void
5478 softdep_setup_allocdirect(
5479 	struct inode *ip,	/* inode to which block is being added */
5480 	ufs_lbn_t off,		/* block pointer within inode */
5481 	ufs2_daddr_t newblkno,	/* disk block number being added */
5482 	ufs2_daddr_t oldblkno,	/* previous block number, 0 unless frag */
5483 	long newsize,		/* size of new block */
5484 	long oldsize,		/* size of new block */
5485 	struct buf *bp)		/* bp for allocated block */
5486 {
5487 	struct allocdirect *adp, *oldadp;
5488 	struct allocdirectlst *adphead;
5489 	struct freefrag *freefrag;
5490 	struct inodedep *inodedep;
5491 	struct pagedep *pagedep;
5492 	struct jnewblk *jnewblk;
5493 	struct newblk *newblk;
5494 	struct mount *mp;
5495 	ufs_lbn_t lbn;
5496 
5497 	lbn = bp->b_lblkno;
5498 	mp = ITOVFS(ip);
5499 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5500 	    ("softdep_setup_allocdirect called on non-softdep filesystem"));
5501 	if (oldblkno && oldblkno != newblkno)
5502 		/*
5503 		 * The usual case is that a smaller fragment that
5504 		 * was just allocated has been replaced with a bigger
5505 		 * fragment or a full-size block. If it is marked as
5506 		 * B_DELWRI, the current contents have not been written
5507 		 * to disk. It is possible that the block was written
5508 		 * earlier, but very uncommon. If the block has never
5509 		 * been written, there is no need to send a BIO_DELETE
5510 		 * for it when it is freed. The gain from avoiding the
5511 		 * TRIMs for the common case of unwritten blocks far
5512 		 * exceeds the cost of the write amplification for the
5513 		 * uncommon case of failing to send a TRIM for a block
5514 		 * that had been written.
5515 		 */
5516 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn,
5517 		    (bp->b_flags & B_DELWRI) != 0 ? NOTRIM_KEY : SINGLETON_KEY);
5518 	else
5519 		freefrag = NULL;
5520 
5521 	CTR6(KTR_SUJ,
5522 	    "softdep_setup_allocdirect: ino %d blkno %jd oldblkno %jd "
5523 	    "off %jd newsize %ld oldsize %d",
5524 	    ip->i_number, newblkno, oldblkno, off, newsize, oldsize);
5525 	ACQUIRE_LOCK(ITOUMP(ip));
5526 	if (off >= UFS_NDADDR) {
5527 		if (lbn > 0)
5528 			panic("softdep_setup_allocdirect: bad lbn %jd, off %jd",
5529 			    lbn, off);
5530 		/* allocating an indirect block */
5531 		if (oldblkno != 0)
5532 			panic("softdep_setup_allocdirect: non-zero indir");
5533 	} else {
5534 		if (off != lbn)
5535 			panic("softdep_setup_allocdirect: lbn %jd != off %jd",
5536 			    lbn, off);
5537 		/*
5538 		 * Allocating a direct block.
5539 		 *
5540 		 * If we are allocating a directory block, then we must
5541 		 * allocate an associated pagedep to track additions and
5542 		 * deletions.
5543 		 */
5544 		if ((ip->i_mode & IFMT) == IFDIR)
5545 			pagedep_lookup(mp, bp, ip->i_number, off, DEPALLOC,
5546 			    &pagedep);
5547 	}
5548 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5549 		panic("softdep_setup_allocdirect: lost block");
5550 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5551 	    ("softdep_setup_allocdirect: newblk already initialized"));
5552 	/*
5553 	 * Convert the newblk to an allocdirect.
5554 	 */
5555 	WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5556 	adp = (struct allocdirect *)newblk;
5557 	newblk->nb_freefrag = freefrag;
5558 	adp->ad_offset = off;
5559 	adp->ad_oldblkno = oldblkno;
5560 	adp->ad_newsize = newsize;
5561 	adp->ad_oldsize = oldsize;
5562 
5563 	/*
5564 	 * Finish initializing the journal.
5565 	 */
5566 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5567 		jnewblk->jn_ino = ip->i_number;
5568 		jnewblk->jn_lbn = lbn;
5569 		add_to_journal(&jnewblk->jn_list);
5570 	}
5571 	if (freefrag && freefrag->ff_jdep != NULL &&
5572 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5573 		add_to_journal(freefrag->ff_jdep);
5574 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5575 	adp->ad_inodedep = inodedep;
5576 
5577 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5578 	/*
5579 	 * The list of allocdirects must be kept in sorted and ascending
5580 	 * order so that the rollback routines can quickly determine the
5581 	 * first uncommitted block (the size of the file stored on disk
5582 	 * ends at the end of the lowest committed fragment, or if there
5583 	 * are no fragments, at the end of the highest committed block).
5584 	 * Since files generally grow, the typical case is that the new
5585 	 * block is to be added at the end of the list. We speed this
5586 	 * special case by checking against the last allocdirect in the
5587 	 * list before laboriously traversing the list looking for the
5588 	 * insertion point.
5589 	 */
5590 	adphead = &inodedep->id_newinoupdt;
5591 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
5592 	if (oldadp == NULL || oldadp->ad_offset <= off) {
5593 		/* insert at end of list */
5594 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5595 		if (oldadp != NULL && oldadp->ad_offset == off)
5596 			allocdirect_merge(adphead, adp, oldadp);
5597 		FREE_LOCK(ITOUMP(ip));
5598 		return;
5599 	}
5600 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
5601 		if (oldadp->ad_offset >= off)
5602 			break;
5603 	}
5604 	if (oldadp == NULL)
5605 		panic("softdep_setup_allocdirect: lost entry");
5606 	/* insert in middle of list */
5607 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5608 	if (oldadp->ad_offset == off)
5609 		allocdirect_merge(adphead, adp, oldadp);
5610 
5611 	FREE_LOCK(ITOUMP(ip));
5612 }
5613 
5614 /*
5615  * Merge a newer and older journal record to be stored either in a
5616  * newblock or freefrag.  This handles aggregating journal records for
5617  * fragment allocation into a second record as well as replacing a
5618  * journal free with an aborted journal allocation.  A segment for the
5619  * oldest record will be placed on wkhd if it has been written.  If not
5620  * the segment for the newer record will suffice.
5621  */
5622 static struct worklist *
5623 jnewblk_merge(struct worklist *new,
5624 	struct worklist *old,
5625 	struct workhead *wkhd)
5626 {
5627 	struct jnewblk *njnewblk;
5628 	struct jnewblk *jnewblk;
5629 
5630 	/* Handle NULLs to simplify callers. */
5631 	if (new == NULL)
5632 		return (old);
5633 	if (old == NULL)
5634 		return (new);
5635 	/* Replace a jfreefrag with a jnewblk. */
5636 	if (new->wk_type == D_JFREEFRAG) {
5637 		if (WK_JNEWBLK(old)->jn_blkno != WK_JFREEFRAG(new)->fr_blkno)
5638 			panic("jnewblk_merge: blkno mismatch: %p, %p",
5639 			    old, new);
5640 		cancel_jfreefrag(WK_JFREEFRAG(new));
5641 		return (old);
5642 	}
5643 	if (old->wk_type != D_JNEWBLK || new->wk_type != D_JNEWBLK)
5644 		panic("jnewblk_merge: Bad type: old %d new %d\n",
5645 		    old->wk_type, new->wk_type);
5646 	/*
5647 	 * Handle merging of two jnewblk records that describe
5648 	 * different sets of fragments in the same block.
5649 	 */
5650 	jnewblk = WK_JNEWBLK(old);
5651 	njnewblk = WK_JNEWBLK(new);
5652 	if (jnewblk->jn_blkno != njnewblk->jn_blkno)
5653 		panic("jnewblk_merge: Merging disparate blocks.");
5654 	/*
5655 	 * The record may be rolled back in the cg.
5656 	 */
5657 	if (jnewblk->jn_state & UNDONE) {
5658 		jnewblk->jn_state &= ~UNDONE;
5659 		njnewblk->jn_state |= UNDONE;
5660 		njnewblk->jn_state &= ~ATTACHED;
5661 	}
5662 	/*
5663 	 * We modify the newer addref and free the older so that if neither
5664 	 * has been written the most up-to-date copy will be on disk.  If
5665 	 * both have been written but rolled back we only temporarily need
5666 	 * one of them to fix the bits when the cg write completes.
5667 	 */
5668 	jnewblk->jn_state |= ATTACHED | COMPLETE;
5669 	njnewblk->jn_oldfrags = jnewblk->jn_oldfrags;
5670 	cancel_jnewblk(jnewblk, wkhd);
5671 	WORKLIST_REMOVE(&jnewblk->jn_list);
5672 	free_jnewblk(jnewblk);
5673 	return (new);
5674 }
5675 
5676 /*
5677  * Replace an old allocdirect dependency with a newer one.
5678  */
5679 static void
5680 allocdirect_merge(
5681 	struct allocdirectlst *adphead,	/* head of list holding allocdirects */
5682 	struct allocdirect *newadp,	/* allocdirect being added */
5683 	struct allocdirect *oldadp)	/* existing allocdirect being checked */
5684 {
5685 	struct worklist *wk;
5686 	struct freefrag *freefrag;
5687 
5688 	freefrag = NULL;
5689 	LOCK_OWNED(VFSTOUFS(newadp->ad_list.wk_mp));
5690 	if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
5691 	    newadp->ad_oldsize != oldadp->ad_newsize ||
5692 	    newadp->ad_offset >= UFS_NDADDR)
5693 		panic("%s %jd != new %jd || old size %ld != new %ld",
5694 		    "allocdirect_merge: old blkno",
5695 		    (intmax_t)newadp->ad_oldblkno,
5696 		    (intmax_t)oldadp->ad_newblkno,
5697 		    newadp->ad_oldsize, oldadp->ad_newsize);
5698 	newadp->ad_oldblkno = oldadp->ad_oldblkno;
5699 	newadp->ad_oldsize = oldadp->ad_oldsize;
5700 	/*
5701 	 * If the old dependency had a fragment to free or had never
5702 	 * previously had a block allocated, then the new dependency
5703 	 * can immediately post its freefrag and adopt the old freefrag.
5704 	 * This action is done by swapping the freefrag dependencies.
5705 	 * The new dependency gains the old one's freefrag, and the
5706 	 * old one gets the new one and then immediately puts it on
5707 	 * the worklist when it is freed by free_newblk. It is
5708 	 * not possible to do this swap when the old dependency had a
5709 	 * non-zero size but no previous fragment to free. This condition
5710 	 * arises when the new block is an extension of the old block.
5711 	 * Here, the first part of the fragment allocated to the new
5712 	 * dependency is part of the block currently claimed on disk by
5713 	 * the old dependency, so cannot legitimately be freed until the
5714 	 * conditions for the new dependency are fulfilled.
5715 	 */
5716 	freefrag = newadp->ad_freefrag;
5717 	if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
5718 		newadp->ad_freefrag = oldadp->ad_freefrag;
5719 		oldadp->ad_freefrag = freefrag;
5720 	}
5721 	/*
5722 	 * If we are tracking a new directory-block allocation,
5723 	 * move it from the old allocdirect to the new allocdirect.
5724 	 */
5725 	if ((wk = LIST_FIRST(&oldadp->ad_newdirblk)) != NULL) {
5726 		WORKLIST_REMOVE(wk);
5727 		if (!LIST_EMPTY(&oldadp->ad_newdirblk))
5728 			panic("allocdirect_merge: extra newdirblk");
5729 		WORKLIST_INSERT(&newadp->ad_newdirblk, wk);
5730 	}
5731 	TAILQ_REMOVE(adphead, oldadp, ad_next);
5732 	/*
5733 	 * We need to move any journal dependencies over to the freefrag
5734 	 * that releases this block if it exists.  Otherwise we are
5735 	 * extending an existing block and we'll wait until that is
5736 	 * complete to release the journal space and extend the
5737 	 * new journal to cover this old space as well.
5738 	 */
5739 	if (freefrag == NULL) {
5740 		if (oldadp->ad_newblkno != newadp->ad_newblkno)
5741 			panic("allocdirect_merge: %jd != %jd",
5742 			    oldadp->ad_newblkno, newadp->ad_newblkno);
5743 		newadp->ad_block.nb_jnewblk = (struct jnewblk *)
5744 		    jnewblk_merge(&newadp->ad_block.nb_jnewblk->jn_list,
5745 		    &oldadp->ad_block.nb_jnewblk->jn_list,
5746 		    &newadp->ad_block.nb_jwork);
5747 		oldadp->ad_block.nb_jnewblk = NULL;
5748 		cancel_newblk(&oldadp->ad_block, NULL,
5749 		    &newadp->ad_block.nb_jwork);
5750 	} else {
5751 		wk = (struct worklist *) cancel_newblk(&oldadp->ad_block,
5752 		    &freefrag->ff_list, &freefrag->ff_jwork);
5753 		freefrag->ff_jdep = jnewblk_merge(freefrag->ff_jdep, wk,
5754 		    &freefrag->ff_jwork);
5755 	}
5756 	free_newblk(&oldadp->ad_block);
5757 }
5758 
5759 /*
5760  * Allocate a jfreefrag structure to journal a single block free.
5761  */
5762 static struct jfreefrag *
5763 newjfreefrag(struct freefrag *freefrag,
5764 	struct inode *ip,
5765 	ufs2_daddr_t blkno,
5766 	long size,
5767 	ufs_lbn_t lbn)
5768 {
5769 	struct jfreefrag *jfreefrag;
5770 	struct fs *fs;
5771 
5772 	fs = ITOFS(ip);
5773 	jfreefrag = malloc(sizeof(struct jfreefrag), M_JFREEFRAG,
5774 	    M_SOFTDEP_FLAGS);
5775 	workitem_alloc(&jfreefrag->fr_list, D_JFREEFRAG, ITOVFS(ip));
5776 	jfreefrag->fr_jsegdep = newjsegdep(&jfreefrag->fr_list);
5777 	jfreefrag->fr_state = ATTACHED | DEPCOMPLETE;
5778 	jfreefrag->fr_ino = ip->i_number;
5779 	jfreefrag->fr_lbn = lbn;
5780 	jfreefrag->fr_blkno = blkno;
5781 	jfreefrag->fr_frags = numfrags(fs, size);
5782 	jfreefrag->fr_freefrag = freefrag;
5783 
5784 	return (jfreefrag);
5785 }
5786 
5787 /*
5788  * Allocate a new freefrag structure.
5789  */
5790 static struct freefrag *
5791 newfreefrag(struct inode *ip,
5792 	ufs2_daddr_t blkno,
5793 	long size,
5794 	ufs_lbn_t lbn,
5795 	u_long key)
5796 {
5797 	struct freefrag *freefrag;
5798 	struct ufsmount *ump;
5799 	struct fs *fs;
5800 
5801 	CTR4(KTR_SUJ, "newfreefrag: ino %d blkno %jd size %ld lbn %jd",
5802 	    ip->i_number, blkno, size, lbn);
5803 	ump = ITOUMP(ip);
5804 	fs = ump->um_fs;
5805 	if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
5806 		panic("newfreefrag: frag size");
5807 	freefrag = malloc(sizeof(struct freefrag),
5808 	    M_FREEFRAG, M_SOFTDEP_FLAGS);
5809 	workitem_alloc(&freefrag->ff_list, D_FREEFRAG, UFSTOVFS(ump));
5810 	freefrag->ff_state = ATTACHED;
5811 	LIST_INIT(&freefrag->ff_jwork);
5812 	freefrag->ff_inum = ip->i_number;
5813 	freefrag->ff_vtype = ITOV(ip)->v_type;
5814 	freefrag->ff_blkno = blkno;
5815 	freefrag->ff_fragsize = size;
5816 	freefrag->ff_key = key;
5817 
5818 	if (MOUNTEDSUJ(UFSTOVFS(ump))) {
5819 		freefrag->ff_jdep = (struct worklist *)
5820 		    newjfreefrag(freefrag, ip, blkno, size, lbn);
5821 	} else {
5822 		freefrag->ff_state |= DEPCOMPLETE;
5823 		freefrag->ff_jdep = NULL;
5824 	}
5825 
5826 	return (freefrag);
5827 }
5828 
5829 /*
5830  * This workitem de-allocates fragments that were replaced during
5831  * file block allocation.
5832  */
5833 static void
5834 handle_workitem_freefrag(struct freefrag *freefrag)
5835 {
5836 	struct ufsmount *ump = VFSTOUFS(freefrag->ff_list.wk_mp);
5837 	struct workhead wkhd;
5838 
5839 	CTR3(KTR_SUJ,
5840 	    "handle_workitem_freefrag: ino %d blkno %jd size %ld",
5841 	    freefrag->ff_inum, freefrag->ff_blkno, freefrag->ff_fragsize);
5842 	/*
5843 	 * It would be illegal to add new completion items to the
5844 	 * freefrag after it was schedule to be done so it must be
5845 	 * safe to modify the list head here.
5846 	 */
5847 	LIST_INIT(&wkhd);
5848 	ACQUIRE_LOCK(ump);
5849 	LIST_SWAP(&freefrag->ff_jwork, &wkhd, worklist, wk_list);
5850 	/*
5851 	 * If the journal has not been written we must cancel it here.
5852 	 */
5853 	if (freefrag->ff_jdep) {
5854 		if (freefrag->ff_jdep->wk_type != D_JNEWBLK)
5855 			panic("handle_workitem_freefrag: Unexpected type %d\n",
5856 			    freefrag->ff_jdep->wk_type);
5857 		cancel_jnewblk(WK_JNEWBLK(freefrag->ff_jdep), &wkhd);
5858 	}
5859 	FREE_LOCK(ump);
5860 	ffs_blkfree(ump, ump->um_fs, ump->um_devvp, freefrag->ff_blkno,
5861 	   freefrag->ff_fragsize, freefrag->ff_inum, freefrag->ff_vtype,
5862 	   &wkhd, freefrag->ff_key);
5863 	ACQUIRE_LOCK(ump);
5864 	WORKITEM_FREE(freefrag, D_FREEFRAG);
5865 	FREE_LOCK(ump);
5866 }
5867 
5868 /*
5869  * Set up a dependency structure for an external attributes data block.
5870  * This routine follows much of the structure of softdep_setup_allocdirect.
5871  * See the description of softdep_setup_allocdirect above for details.
5872  */
5873 void
5874 softdep_setup_allocext(
5875 	struct inode *ip,
5876 	ufs_lbn_t off,
5877 	ufs2_daddr_t newblkno,
5878 	ufs2_daddr_t oldblkno,
5879 	long newsize,
5880 	long oldsize,
5881 	struct buf *bp)
5882 {
5883 	struct allocdirect *adp, *oldadp;
5884 	struct allocdirectlst *adphead;
5885 	struct freefrag *freefrag;
5886 	struct inodedep *inodedep;
5887 	struct jnewblk *jnewblk;
5888 	struct newblk *newblk;
5889 	struct mount *mp;
5890 	struct ufsmount *ump;
5891 	ufs_lbn_t lbn;
5892 
5893 	mp = ITOVFS(ip);
5894 	ump = VFSTOUFS(mp);
5895 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5896 	    ("softdep_setup_allocext called on non-softdep filesystem"));
5897 	KASSERT(off < UFS_NXADDR,
5898 	    ("softdep_setup_allocext: lbn %lld > UFS_NXADDR", (long long)off));
5899 
5900 	lbn = bp->b_lblkno;
5901 	if (oldblkno && oldblkno != newblkno)
5902 		/*
5903 		 * The usual case is that a smaller fragment that
5904 		 * was just allocated has been replaced with a bigger
5905 		 * fragment or a full-size block. If it is marked as
5906 		 * B_DELWRI, the current contents have not been written
5907 		 * to disk. It is possible that the block was written
5908 		 * earlier, but very uncommon. If the block has never
5909 		 * been written, there is no need to send a BIO_DELETE
5910 		 * for it when it is freed. The gain from avoiding the
5911 		 * TRIMs for the common case of unwritten blocks far
5912 		 * exceeds the cost of the write amplification for the
5913 		 * uncommon case of failing to send a TRIM for a block
5914 		 * that had been written.
5915 		 */
5916 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn,
5917 		    (bp->b_flags & B_DELWRI) != 0 ? NOTRIM_KEY : SINGLETON_KEY);
5918 	else
5919 		freefrag = NULL;
5920 
5921 	ACQUIRE_LOCK(ump);
5922 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5923 		panic("softdep_setup_allocext: lost block");
5924 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5925 	    ("softdep_setup_allocext: newblk already initialized"));
5926 	/*
5927 	 * Convert the newblk to an allocdirect.
5928 	 */
5929 	WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5930 	adp = (struct allocdirect *)newblk;
5931 	newblk->nb_freefrag = freefrag;
5932 	adp->ad_offset = off;
5933 	adp->ad_oldblkno = oldblkno;
5934 	adp->ad_newsize = newsize;
5935 	adp->ad_oldsize = oldsize;
5936 	adp->ad_state |=  EXTDATA;
5937 
5938 	/*
5939 	 * Finish initializing the journal.
5940 	 */
5941 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5942 		jnewblk->jn_ino = ip->i_number;
5943 		jnewblk->jn_lbn = lbn;
5944 		add_to_journal(&jnewblk->jn_list);
5945 	}
5946 	if (freefrag && freefrag->ff_jdep != NULL &&
5947 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5948 		add_to_journal(freefrag->ff_jdep);
5949 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5950 	adp->ad_inodedep = inodedep;
5951 
5952 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5953 	/*
5954 	 * The list of allocdirects must be kept in sorted and ascending
5955 	 * order so that the rollback routines can quickly determine the
5956 	 * first uncommitted block (the size of the file stored on disk
5957 	 * ends at the end of the lowest committed fragment, or if there
5958 	 * are no fragments, at the end of the highest committed block).
5959 	 * Since files generally grow, the typical case is that the new
5960 	 * block is to be added at the end of the list. We speed this
5961 	 * special case by checking against the last allocdirect in the
5962 	 * list before laboriously traversing the list looking for the
5963 	 * insertion point.
5964 	 */
5965 	adphead = &inodedep->id_newextupdt;
5966 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
5967 	if (oldadp == NULL || oldadp->ad_offset <= off) {
5968 		/* insert at end of list */
5969 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5970 		if (oldadp != NULL && oldadp->ad_offset == off)
5971 			allocdirect_merge(adphead, adp, oldadp);
5972 		FREE_LOCK(ump);
5973 		return;
5974 	}
5975 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
5976 		if (oldadp->ad_offset >= off)
5977 			break;
5978 	}
5979 	if (oldadp == NULL)
5980 		panic("softdep_setup_allocext: lost entry");
5981 	/* insert in middle of list */
5982 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5983 	if (oldadp->ad_offset == off)
5984 		allocdirect_merge(adphead, adp, oldadp);
5985 	FREE_LOCK(ump);
5986 }
5987 
5988 /*
5989  * Indirect block allocation dependencies.
5990  *
5991  * The same dependencies that exist for a direct block also exist when
5992  * a new block is allocated and pointed to by an entry in a block of
5993  * indirect pointers. The undo/redo states described above are also
5994  * used here. Because an indirect block contains many pointers that
5995  * may have dependencies, a second copy of the entire in-memory indirect
5996  * block is kept. The buffer cache copy is always completely up-to-date.
5997  * The second copy, which is used only as a source for disk writes,
5998  * contains only the safe pointers (i.e., those that have no remaining
5999  * update dependencies). The second copy is freed when all pointers
6000  * are safe. The cache is not allowed to replace indirect blocks with
6001  * pending update dependencies. If a buffer containing an indirect
6002  * block with dependencies is written, these routines will mark it
6003  * dirty again. It can only be successfully written once all the
6004  * dependencies are removed. The ffs_fsync routine in conjunction with
6005  * softdep_sync_metadata work together to get all the dependencies
6006  * removed so that a file can be successfully written to disk. Three
6007  * procedures are used when setting up indirect block pointer
6008  * dependencies. The division is necessary because of the organization
6009  * of the "balloc" routine and because of the distinction between file
6010  * pages and file metadata blocks.
6011  */
6012 
6013 /*
6014  * Allocate a new allocindir structure.
6015  */
6016 static struct allocindir *
6017 newallocindir(
6018 	struct inode *ip,	/* inode for file being extended */
6019 	int ptrno,		/* offset of pointer in indirect block */
6020 	ufs2_daddr_t newblkno,	/* disk block number being added */
6021 	ufs2_daddr_t oldblkno,	/* previous block number, 0 if none */
6022 	ufs_lbn_t lbn)
6023 {
6024 	struct newblk *newblk;
6025 	struct allocindir *aip;
6026 	struct freefrag *freefrag;
6027 	struct jnewblk *jnewblk;
6028 
6029 	if (oldblkno)
6030 		freefrag = newfreefrag(ip, oldblkno, ITOFS(ip)->fs_bsize, lbn,
6031 		    SINGLETON_KEY);
6032 	else
6033 		freefrag = NULL;
6034 	ACQUIRE_LOCK(ITOUMP(ip));
6035 	if (newblk_lookup(ITOVFS(ip), newblkno, 0, &newblk) == 0)
6036 		panic("new_allocindir: lost block");
6037 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
6038 	    ("newallocindir: newblk already initialized"));
6039 	WORKITEM_REASSIGN(newblk, D_ALLOCINDIR);
6040 	newblk->nb_freefrag = freefrag;
6041 	aip = (struct allocindir *)newblk;
6042 	aip->ai_offset = ptrno;
6043 	aip->ai_oldblkno = oldblkno;
6044 	aip->ai_lbn = lbn;
6045 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
6046 		jnewblk->jn_ino = ip->i_number;
6047 		jnewblk->jn_lbn = lbn;
6048 		add_to_journal(&jnewblk->jn_list);
6049 	}
6050 	if (freefrag && freefrag->ff_jdep != NULL &&
6051 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
6052 		add_to_journal(freefrag->ff_jdep);
6053 	return (aip);
6054 }
6055 
6056 /*
6057  * Called just before setting an indirect block pointer
6058  * to a newly allocated file page.
6059  */
6060 void
6061 softdep_setup_allocindir_page(
6062 	struct inode *ip,	/* inode for file being extended */
6063 	ufs_lbn_t lbn,		/* allocated block number within file */
6064 	struct buf *bp,		/* buffer with indirect blk referencing page */
6065 	int ptrno,		/* offset of pointer in indirect block */
6066 	ufs2_daddr_t newblkno,	/* disk block number being added */
6067 	ufs2_daddr_t oldblkno,	/* previous block number, 0 if none */
6068 	struct buf *nbp)	/* buffer holding allocated page */
6069 {
6070 	struct inodedep *inodedep;
6071 	struct freefrag *freefrag;
6072 	struct allocindir *aip;
6073 	struct pagedep *pagedep;
6074 	struct mount *mp;
6075 	struct ufsmount *ump;
6076 
6077 	mp = ITOVFS(ip);
6078 	ump = VFSTOUFS(mp);
6079 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6080 	    ("softdep_setup_allocindir_page called on non-softdep filesystem"));
6081 	KASSERT(lbn == nbp->b_lblkno,
6082 	    ("softdep_setup_allocindir_page: lbn %jd != lblkno %jd",
6083 	    lbn, bp->b_lblkno));
6084 	CTR4(KTR_SUJ,
6085 	    "softdep_setup_allocindir_page: ino %d blkno %jd oldblkno %jd "
6086 	    "lbn %jd", ip->i_number, newblkno, oldblkno, lbn);
6087 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_page");
6088 	aip = newallocindir(ip, ptrno, newblkno, oldblkno, lbn);
6089 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6090 	/*
6091 	 * If we are allocating a directory page, then we must
6092 	 * allocate an associated pagedep to track additions and
6093 	 * deletions.
6094 	 */
6095 	if ((ip->i_mode & IFMT) == IFDIR)
6096 		pagedep_lookup(mp, nbp, ip->i_number, lbn, DEPALLOC, &pagedep);
6097 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
6098 	freefrag = setup_allocindir_phase2(bp, ip, inodedep, aip, lbn);
6099 	FREE_LOCK(ump);
6100 	if (freefrag)
6101 		handle_workitem_freefrag(freefrag);
6102 }
6103 
6104 /*
6105  * Called just before setting an indirect block pointer to a
6106  * newly allocated indirect block.
6107  */
6108 void
6109 softdep_setup_allocindir_meta(
6110 	struct buf *nbp,	/* newly allocated indirect block */
6111 	struct inode *ip,	/* inode for file being extended */
6112 	struct buf *bp,		/* indirect block referencing allocated block */
6113 	int ptrno,		/* offset of pointer in indirect block */
6114 	ufs2_daddr_t newblkno)	/* disk block number being added */
6115 {
6116 	struct inodedep *inodedep;
6117 	struct allocindir *aip;
6118 	struct ufsmount *ump;
6119 	ufs_lbn_t lbn;
6120 
6121 	ump = ITOUMP(ip);
6122 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
6123 	    ("softdep_setup_allocindir_meta called on non-softdep filesystem"));
6124 	CTR3(KTR_SUJ,
6125 	    "softdep_setup_allocindir_meta: ino %d blkno %jd ptrno %d",
6126 	    ip->i_number, newblkno, ptrno);
6127 	lbn = nbp->b_lblkno;
6128 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_meta");
6129 	aip = newallocindir(ip, ptrno, newblkno, 0, lbn);
6130 	inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
6131 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
6132 	if (setup_allocindir_phase2(bp, ip, inodedep, aip, lbn))
6133 		panic("softdep_setup_allocindir_meta: Block already existed");
6134 	FREE_LOCK(ump);
6135 }
6136 
6137 static void
6138 indirdep_complete(struct indirdep *indirdep)
6139 {
6140 	struct allocindir *aip;
6141 
6142 	LIST_REMOVE(indirdep, ir_next);
6143 	indirdep->ir_state |= DEPCOMPLETE;
6144 
6145 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL) {
6146 		LIST_REMOVE(aip, ai_next);
6147 		free_newblk(&aip->ai_block);
6148 	}
6149 	/*
6150 	 * If this indirdep is not attached to a buf it was simply waiting
6151 	 * on completion to clear completehd.  free_indirdep() asserts
6152 	 * that nothing is dangling.
6153 	 */
6154 	if ((indirdep->ir_state & ONWORKLIST) == 0)
6155 		free_indirdep(indirdep);
6156 }
6157 
6158 static struct indirdep *
6159 indirdep_lookup(struct mount *mp,
6160 	struct inode *ip,
6161 	struct buf *bp)
6162 {
6163 	struct indirdep *indirdep, *newindirdep;
6164 	struct newblk *newblk;
6165 	struct ufsmount *ump;
6166 	struct worklist *wk;
6167 	struct fs *fs;
6168 	ufs2_daddr_t blkno;
6169 
6170 	ump = VFSTOUFS(mp);
6171 	LOCK_OWNED(ump);
6172 	indirdep = NULL;
6173 	newindirdep = NULL;
6174 	fs = ump->um_fs;
6175 	for (;;) {
6176 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
6177 			if (wk->wk_type != D_INDIRDEP)
6178 				continue;
6179 			indirdep = WK_INDIRDEP(wk);
6180 			break;
6181 		}
6182 		/* Found on the buffer worklist, no new structure to free. */
6183 		if (indirdep != NULL && newindirdep == NULL)
6184 			return (indirdep);
6185 		if (indirdep != NULL && newindirdep != NULL)
6186 			panic("indirdep_lookup: simultaneous create");
6187 		/* None found on the buffer and a new structure is ready. */
6188 		if (indirdep == NULL && newindirdep != NULL)
6189 			break;
6190 		/* None found and no new structure available. */
6191 		FREE_LOCK(ump);
6192 		newindirdep = malloc(sizeof(struct indirdep),
6193 		    M_INDIRDEP, M_SOFTDEP_FLAGS);
6194 		workitem_alloc(&newindirdep->ir_list, D_INDIRDEP, mp);
6195 		newindirdep->ir_state = ATTACHED;
6196 		if (I_IS_UFS1(ip))
6197 			newindirdep->ir_state |= UFS1FMT;
6198 		TAILQ_INIT(&newindirdep->ir_trunc);
6199 		newindirdep->ir_saveddata = NULL;
6200 		LIST_INIT(&newindirdep->ir_deplisthd);
6201 		LIST_INIT(&newindirdep->ir_donehd);
6202 		LIST_INIT(&newindirdep->ir_writehd);
6203 		LIST_INIT(&newindirdep->ir_completehd);
6204 		if (bp->b_blkno == bp->b_lblkno) {
6205 			ufs_bmaparray(bp->b_vp, bp->b_lblkno, &blkno, bp,
6206 			    NULL, NULL);
6207 			bp->b_blkno = blkno;
6208 		}
6209 		newindirdep->ir_freeblks = NULL;
6210 		newindirdep->ir_savebp =
6211 		    getblk(ump->um_devvp, bp->b_blkno, bp->b_bcount, 0, 0, 0);
6212 		newindirdep->ir_bp = bp;
6213 		BUF_KERNPROC(newindirdep->ir_savebp);
6214 		bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
6215 		ACQUIRE_LOCK(ump);
6216 	}
6217 	indirdep = newindirdep;
6218 	WORKLIST_INSERT(&bp->b_dep, &indirdep->ir_list);
6219 	/*
6220 	 * If the block is not yet allocated we don't set DEPCOMPLETE so
6221 	 * that we don't free dependencies until the pointers are valid.
6222 	 * This could search b_dep for D_ALLOCDIRECT/D_ALLOCINDIR rather
6223 	 * than using the hash.
6224 	 */
6225 	if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk))
6226 		LIST_INSERT_HEAD(&newblk->nb_indirdeps, indirdep, ir_next);
6227 	else
6228 		indirdep->ir_state |= DEPCOMPLETE;
6229 	return (indirdep);
6230 }
6231 
6232 /*
6233  * Called to finish the allocation of the "aip" allocated
6234  * by one of the two routines above.
6235  */
6236 static struct freefrag *
6237 setup_allocindir_phase2(
6238 	struct buf *bp,		/* in-memory copy of the indirect block */
6239 	struct inode *ip,	/* inode for file being extended */
6240 	struct inodedep *inodedep, /* Inodedep for ip */
6241 	struct allocindir *aip,	/* allocindir allocated by the above routines */
6242 	ufs_lbn_t lbn)		/* Logical block number for this block. */
6243 {
6244 	struct fs *fs __diagused;
6245 	struct indirdep *indirdep;
6246 	struct allocindir *oldaip;
6247 	struct freefrag *freefrag;
6248 	struct mount *mp;
6249 	struct ufsmount *ump;
6250 
6251 	mp = ITOVFS(ip);
6252 	ump = VFSTOUFS(mp);
6253 	LOCK_OWNED(ump);
6254 	fs = ump->um_fs;
6255 	if (bp->b_lblkno >= 0)
6256 		panic("setup_allocindir_phase2: not indir blk");
6257 	KASSERT(aip->ai_offset >= 0 && aip->ai_offset < NINDIR(fs),
6258 	    ("setup_allocindir_phase2: Bad offset %d", aip->ai_offset));
6259 	indirdep = indirdep_lookup(mp, ip, bp);
6260 	KASSERT(indirdep->ir_savebp != NULL,
6261 	    ("setup_allocindir_phase2 NULL ir_savebp"));
6262 	aip->ai_indirdep = indirdep;
6263 	/*
6264 	 * Check for an unwritten dependency for this indirect offset.  If
6265 	 * there is, merge the old dependency into the new one.  This happens
6266 	 * as a result of reallocblk only.
6267 	 */
6268 	freefrag = NULL;
6269 	if (aip->ai_oldblkno != 0) {
6270 		LIST_FOREACH(oldaip, &indirdep->ir_deplisthd, ai_next) {
6271 			if (oldaip->ai_offset == aip->ai_offset) {
6272 				freefrag = allocindir_merge(aip, oldaip);
6273 				goto done;
6274 			}
6275 		}
6276 		LIST_FOREACH(oldaip, &indirdep->ir_donehd, ai_next) {
6277 			if (oldaip->ai_offset == aip->ai_offset) {
6278 				freefrag = allocindir_merge(aip, oldaip);
6279 				goto done;
6280 			}
6281 		}
6282 	}
6283 done:
6284 	LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
6285 	return (freefrag);
6286 }
6287 
6288 /*
6289  * Merge two allocindirs which refer to the same block.  Move newblock
6290  * dependencies and setup the freefrags appropriately.
6291  */
6292 static struct freefrag *
6293 allocindir_merge(
6294 	struct allocindir *aip,
6295 	struct allocindir *oldaip)
6296 {
6297 	struct freefrag *freefrag;
6298 	struct worklist *wk;
6299 
6300 	if (oldaip->ai_newblkno != aip->ai_oldblkno)
6301 		panic("allocindir_merge: blkno");
6302 	aip->ai_oldblkno = oldaip->ai_oldblkno;
6303 	freefrag = aip->ai_freefrag;
6304 	aip->ai_freefrag = oldaip->ai_freefrag;
6305 	oldaip->ai_freefrag = NULL;
6306 	KASSERT(freefrag != NULL, ("setup_allocindir_phase2: No freefrag"));
6307 	/*
6308 	 * If we are tracking a new directory-block allocation,
6309 	 * move it from the old allocindir to the new allocindir.
6310 	 */
6311 	if ((wk = LIST_FIRST(&oldaip->ai_newdirblk)) != NULL) {
6312 		WORKLIST_REMOVE(wk);
6313 		if (!LIST_EMPTY(&oldaip->ai_newdirblk))
6314 			panic("allocindir_merge: extra newdirblk");
6315 		WORKLIST_INSERT(&aip->ai_newdirblk, wk);
6316 	}
6317 	/*
6318 	 * We can skip journaling for this freefrag and just complete
6319 	 * any pending journal work for the allocindir that is being
6320 	 * removed after the freefrag completes.
6321 	 */
6322 	if (freefrag->ff_jdep)
6323 		cancel_jfreefrag(WK_JFREEFRAG(freefrag->ff_jdep));
6324 	LIST_REMOVE(oldaip, ai_next);
6325 	freefrag->ff_jdep = (struct worklist *)cancel_newblk(&oldaip->ai_block,
6326 	    &freefrag->ff_list, &freefrag->ff_jwork);
6327 	free_newblk(&oldaip->ai_block);
6328 
6329 	return (freefrag);
6330 }
6331 
6332 static inline void
6333 setup_freedirect(
6334 	struct freeblks *freeblks,
6335 	struct inode *ip,
6336 	int i,
6337 	int needj)
6338 {
6339 	struct ufsmount *ump;
6340 	ufs2_daddr_t blkno;
6341 	int frags;
6342 
6343 	blkno = DIP(ip, i_db[i]);
6344 	if (blkno == 0)
6345 		return;
6346 	DIP_SET(ip, i_db[i], 0);
6347 	ump = ITOUMP(ip);
6348 	frags = sblksize(ump->um_fs, ip->i_size, i);
6349 	frags = numfrags(ump->um_fs, frags);
6350 	newfreework(ump, freeblks, NULL, i, blkno, frags, 0, needj);
6351 }
6352 
6353 static inline void
6354 setup_freeext(
6355 	struct freeblks *freeblks,
6356 	struct inode *ip,
6357 	int i,
6358 	int needj)
6359 {
6360 	struct ufsmount *ump;
6361 	ufs2_daddr_t blkno;
6362 	int frags;
6363 
6364 	blkno = ip->i_din2->di_extb[i];
6365 	if (blkno == 0)
6366 		return;
6367 	ip->i_din2->di_extb[i] = 0;
6368 	ump = ITOUMP(ip);
6369 	frags = sblksize(ump->um_fs, ip->i_din2->di_extsize, i);
6370 	frags = numfrags(ump->um_fs, frags);
6371 	newfreework(ump, freeblks, NULL, -1 - i, blkno, frags, 0, needj);
6372 }
6373 
6374 static inline void
6375 setup_freeindir(
6376 	struct freeblks *freeblks,
6377 	struct inode *ip,
6378 	int i,
6379 	ufs_lbn_t lbn,
6380 	int needj)
6381 {
6382 	struct ufsmount *ump;
6383 	ufs2_daddr_t blkno;
6384 
6385 	blkno = DIP(ip, i_ib[i]);
6386 	if (blkno == 0)
6387 		return;
6388 	DIP_SET(ip, i_ib[i], 0);
6389 	ump = ITOUMP(ip);
6390 	newfreework(ump, freeblks, NULL, lbn, blkno, ump->um_fs->fs_frag,
6391 	    0, needj);
6392 }
6393 
6394 static inline struct freeblks *
6395 newfreeblks(struct mount *mp, struct inode *ip)
6396 {
6397 	struct freeblks *freeblks;
6398 
6399 	freeblks = malloc(sizeof(struct freeblks),
6400 		M_FREEBLKS, M_SOFTDEP_FLAGS|M_ZERO);
6401 	workitem_alloc(&freeblks->fb_list, D_FREEBLKS, mp);
6402 	LIST_INIT(&freeblks->fb_jblkdephd);
6403 	LIST_INIT(&freeblks->fb_jwork);
6404 	freeblks->fb_ref = 0;
6405 	freeblks->fb_cgwait = 0;
6406 	freeblks->fb_state = ATTACHED;
6407 	freeblks->fb_uid = ip->i_uid;
6408 	freeblks->fb_inum = ip->i_number;
6409 	freeblks->fb_vtype = ITOV(ip)->v_type;
6410 	freeblks->fb_modrev = DIP(ip, i_modrev);
6411 	freeblks->fb_devvp = ITODEVVP(ip);
6412 	freeblks->fb_chkcnt = 0;
6413 	freeblks->fb_len = 0;
6414 
6415 	return (freeblks);
6416 }
6417 
6418 static void
6419 trunc_indirdep(
6420 	struct indirdep *indirdep,
6421 	struct freeblks *freeblks,
6422 	struct buf *bp,
6423 	int off)
6424 {
6425 	struct allocindir *aip, *aipn;
6426 
6427 	/*
6428 	 * The first set of allocindirs won't be in savedbp.
6429 	 */
6430 	LIST_FOREACH_SAFE(aip, &indirdep->ir_deplisthd, ai_next, aipn)
6431 		if (aip->ai_offset > off)
6432 			cancel_allocindir(aip, bp, freeblks, 1);
6433 	LIST_FOREACH_SAFE(aip, &indirdep->ir_donehd, ai_next, aipn)
6434 		if (aip->ai_offset > off)
6435 			cancel_allocindir(aip, bp, freeblks, 1);
6436 	/*
6437 	 * These will exist in savedbp.
6438 	 */
6439 	LIST_FOREACH_SAFE(aip, &indirdep->ir_writehd, ai_next, aipn)
6440 		if (aip->ai_offset > off)
6441 			cancel_allocindir(aip, NULL, freeblks, 0);
6442 	LIST_FOREACH_SAFE(aip, &indirdep->ir_completehd, ai_next, aipn)
6443 		if (aip->ai_offset > off)
6444 			cancel_allocindir(aip, NULL, freeblks, 0);
6445 }
6446 
6447 /*
6448  * Follow the chain of indirects down to lastlbn creating a freework
6449  * structure for each.  This will be used to start indir_trunc() at
6450  * the right offset and create the journal records for the parrtial
6451  * truncation.  A second step will handle the truncated dependencies.
6452  */
6453 static int
6454 setup_trunc_indir(
6455 	struct freeblks *freeblks,
6456 	struct inode *ip,
6457 	ufs_lbn_t lbn,
6458 	ufs_lbn_t lastlbn,
6459 	ufs2_daddr_t blkno)
6460 {
6461 	struct indirdep *indirdep;
6462 	struct indirdep *indirn;
6463 	struct freework *freework;
6464 	struct newblk *newblk;
6465 	struct mount *mp;
6466 	struct ufsmount *ump;
6467 	struct buf *bp;
6468 	uint8_t *start;
6469 	uint8_t *end;
6470 	ufs_lbn_t lbnadd;
6471 	int level;
6472 	int error;
6473 	int off;
6474 
6475 	freework = NULL;
6476 	if (blkno == 0)
6477 		return (0);
6478 	mp = freeblks->fb_list.wk_mp;
6479 	ump = VFSTOUFS(mp);
6480 	/*
6481 	 * Here, calls to VOP_BMAP() will fail.  However, we already have
6482 	 * the on-disk address, so we just pass it to bread() instead of
6483 	 * having bread() attempt to calculate it using VOP_BMAP().
6484 	 */
6485 	error = ffs_breadz(ump, ITOV(ip), lbn, blkptrtodb(ump, blkno),
6486 	    (int)mp->mnt_stat.f_iosize, NULL, NULL, 0, NOCRED, 0, NULL, &bp);
6487 	if (error)
6488 		return (error);
6489 	level = lbn_level(lbn);
6490 	lbnadd = lbn_offset(ump->um_fs, level);
6491 	/*
6492 	 * Compute the offset of the last block we want to keep.  Store
6493 	 * in the freework the first block we want to completely free.
6494 	 */
6495 	off = (lastlbn - -(lbn + level)) / lbnadd;
6496 	if (off + 1 == NINDIR(ump->um_fs))
6497 		goto nowork;
6498 	freework = newfreework(ump, freeblks, NULL, lbn, blkno, 0, off + 1, 0);
6499 	/*
6500 	 * Link the freework into the indirdep.  This will prevent any new
6501 	 * allocations from proceeding until we are finished with the
6502 	 * truncate and the block is written.
6503 	 */
6504 	ACQUIRE_LOCK(ump);
6505 	indirdep = indirdep_lookup(mp, ip, bp);
6506 	if (indirdep->ir_freeblks)
6507 		panic("setup_trunc_indir: indirdep already truncated.");
6508 	TAILQ_INSERT_TAIL(&indirdep->ir_trunc, freework, fw_next);
6509 	freework->fw_indir = indirdep;
6510 	/*
6511 	 * Cancel any allocindirs that will not make it to disk.
6512 	 * We have to do this for all copies of the indirdep that
6513 	 * live on this newblk.
6514 	 */
6515 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
6516 		if (newblk_lookup(mp, dbtofsb(ump->um_fs, bp->b_blkno), 0,
6517 		    &newblk) == 0)
6518 			panic("setup_trunc_indir: lost block");
6519 		LIST_FOREACH(indirn, &newblk->nb_indirdeps, ir_next)
6520 			trunc_indirdep(indirn, freeblks, bp, off);
6521 	} else
6522 		trunc_indirdep(indirdep, freeblks, bp, off);
6523 	FREE_LOCK(ump);
6524 	/*
6525 	 * Creation is protected by the buf lock. The saveddata is only
6526 	 * needed if a full truncation follows a partial truncation but it
6527 	 * is difficult to allocate in that case so we fetch it anyway.
6528 	 */
6529 	if (indirdep->ir_saveddata == NULL)
6530 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
6531 		    M_SOFTDEP_FLAGS);
6532 nowork:
6533 	/* Fetch the blkno of the child and the zero start offset. */
6534 	if (I_IS_UFS1(ip)) {
6535 		blkno = ((ufs1_daddr_t *)bp->b_data)[off];
6536 		start = (uint8_t *)&((ufs1_daddr_t *)bp->b_data)[off+1];
6537 	} else {
6538 		blkno = ((ufs2_daddr_t *)bp->b_data)[off];
6539 		start = (uint8_t *)&((ufs2_daddr_t *)bp->b_data)[off+1];
6540 	}
6541 	if (freework) {
6542 		/* Zero the truncated pointers. */
6543 		end = bp->b_data + bp->b_bcount;
6544 		bzero(start, end - start);
6545 		bdwrite(bp);
6546 	} else
6547 		bqrelse(bp);
6548 	if (level == 0)
6549 		return (0);
6550 	lbn++; /* adjust level */
6551 	lbn -= (off * lbnadd);
6552 	return setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno);
6553 }
6554 
6555 /*
6556  * Complete the partial truncation of an indirect block setup by
6557  * setup_trunc_indir().  This zeros the truncated pointers in the saved
6558  * copy and writes them to disk before the freeblks is allowed to complete.
6559  */
6560 static void
6561 complete_trunc_indir(struct freework *freework)
6562 {
6563 	struct freework *fwn;
6564 	struct indirdep *indirdep;
6565 	struct ufsmount *ump;
6566 	struct buf *bp;
6567 	uintptr_t start;
6568 	int count;
6569 
6570 	ump = VFSTOUFS(freework->fw_list.wk_mp);
6571 	LOCK_OWNED(ump);
6572 	indirdep = freework->fw_indir;
6573 	for (;;) {
6574 		bp = indirdep->ir_bp;
6575 		/* See if the block was discarded. */
6576 		if (bp == NULL)
6577 			break;
6578 		/* Inline part of getdirtybuf().  We dont want bremfree. */
6579 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) == 0)
6580 			break;
6581 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
6582 		    LOCK_PTR(ump)) == 0)
6583 			BUF_UNLOCK(bp);
6584 		ACQUIRE_LOCK(ump);
6585 	}
6586 	freework->fw_state |= DEPCOMPLETE;
6587 	TAILQ_REMOVE(&indirdep->ir_trunc, freework, fw_next);
6588 	/*
6589 	 * Zero the pointers in the saved copy.
6590 	 */
6591 	if (indirdep->ir_state & UFS1FMT)
6592 		start = sizeof(ufs1_daddr_t);
6593 	else
6594 		start = sizeof(ufs2_daddr_t);
6595 	start *= freework->fw_start;
6596 	count = indirdep->ir_savebp->b_bcount - start;
6597 	start += (uintptr_t)indirdep->ir_savebp->b_data;
6598 	bzero((char *)start, count);
6599 	/*
6600 	 * We need to start the next truncation in the list if it has not
6601 	 * been started yet.
6602 	 */
6603 	fwn = TAILQ_FIRST(&indirdep->ir_trunc);
6604 	if (fwn != NULL) {
6605 		if (fwn->fw_freeblks == indirdep->ir_freeblks)
6606 			TAILQ_REMOVE(&indirdep->ir_trunc, fwn, fw_next);
6607 		if ((fwn->fw_state & ONWORKLIST) == 0)
6608 			freework_enqueue(fwn);
6609 	}
6610 	/*
6611 	 * If bp is NULL the block was fully truncated, restore
6612 	 * the saved block list otherwise free it if it is no
6613 	 * longer needed.
6614 	 */
6615 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
6616 		if (bp == NULL)
6617 			bcopy(indirdep->ir_saveddata,
6618 			    indirdep->ir_savebp->b_data,
6619 			    indirdep->ir_savebp->b_bcount);
6620 		free(indirdep->ir_saveddata, M_INDIRDEP);
6621 		indirdep->ir_saveddata = NULL;
6622 	}
6623 	/*
6624 	 * When bp is NULL there is a full truncation pending.  We
6625 	 * must wait for this full truncation to be journaled before
6626 	 * we can release this freework because the disk pointers will
6627 	 * never be written as zero.
6628 	 */
6629 	if (bp == NULL)  {
6630 		if (LIST_EMPTY(&indirdep->ir_freeblks->fb_jblkdephd))
6631 			handle_written_freework(freework);
6632 		else
6633 			WORKLIST_INSERT(&indirdep->ir_freeblks->fb_freeworkhd,
6634 			   &freework->fw_list);
6635 		if (fwn == NULL) {
6636 			freework->fw_indir = (void *)0x0000deadbeef0000;
6637 			bp = indirdep->ir_savebp;
6638 			indirdep->ir_savebp = NULL;
6639 			free_indirdep(indirdep);
6640 			FREE_LOCK(ump);
6641 			brelse(bp);
6642 			ACQUIRE_LOCK(ump);
6643 		}
6644 	} else {
6645 		/* Complete when the real copy is written. */
6646 		WORKLIST_INSERT(&bp->b_dep, &freework->fw_list);
6647 		BUF_UNLOCK(bp);
6648 	}
6649 }
6650 
6651 /*
6652  * Calculate the number of blocks we are going to release where datablocks
6653  * is the current total and length is the new file size.
6654  */
6655 static ufs2_daddr_t
6656 blkcount(struct fs *fs,
6657 	ufs2_daddr_t datablocks,
6658 	off_t length)
6659 {
6660 	off_t totblks, numblks;
6661 
6662 	totblks = 0;
6663 	numblks = howmany(length, fs->fs_bsize);
6664 	if (numblks <= UFS_NDADDR) {
6665 		totblks = howmany(length, fs->fs_fsize);
6666 		goto out;
6667 	}
6668         totblks = blkstofrags(fs, numblks);
6669 	numblks -= UFS_NDADDR;
6670 	/*
6671 	 * Count all single, then double, then triple indirects required.
6672 	 * Subtracting one indirects worth of blocks for each pass
6673 	 * acknowledges one of each pointed to by the inode.
6674 	 */
6675 	for (;;) {
6676 		totblks += blkstofrags(fs, howmany(numblks, NINDIR(fs)));
6677 		numblks -= NINDIR(fs);
6678 		if (numblks <= 0)
6679 			break;
6680 		numblks = howmany(numblks, NINDIR(fs));
6681 	}
6682 out:
6683 	totblks = fsbtodb(fs, totblks);
6684 	/*
6685 	 * Handle sparse files.  We can't reclaim more blocks than the inode
6686 	 * references.  We will correct it later in handle_complete_freeblks()
6687 	 * when we know the real count.
6688 	 */
6689 	if (totblks > datablocks)
6690 		return (0);
6691 	return (datablocks - totblks);
6692 }
6693 
6694 /*
6695  * Handle freeblocks for journaled softupdate filesystems.
6696  *
6697  * Contrary to normal softupdates, we must preserve the block pointers in
6698  * indirects until their subordinates are free.  This is to avoid journaling
6699  * every block that is freed which may consume more space than the journal
6700  * itself.  The recovery program will see the free block journals at the
6701  * base of the truncated area and traverse them to reclaim space.  The
6702  * pointers in the inode may be cleared immediately after the journal
6703  * records are written because each direct and indirect pointer in the
6704  * inode is recorded in a journal.  This permits full truncation to proceed
6705  * asynchronously.  The write order is journal -> inode -> cgs -> indirects.
6706  *
6707  * The algorithm is as follows:
6708  * 1) Traverse the in-memory state and create journal entries to release
6709  *    the relevant blocks and full indirect trees.
6710  * 2) Traverse the indirect block chain adding partial truncation freework
6711  *    records to indirects in the path to lastlbn.  The freework will
6712  *    prevent new allocation dependencies from being satisfied in this
6713  *    indirect until the truncation completes.
6714  * 3) Read and lock the inode block, performing an update with the new size
6715  *    and pointers.  This prevents truncated data from becoming valid on
6716  *    disk through step 4.
6717  * 4) Reap unsatisfied dependencies that are beyond the truncated area,
6718  *    eliminate journal work for those records that do not require it.
6719  * 5) Schedule the journal records to be written followed by the inode block.
6720  * 6) Allocate any necessary frags for the end of file.
6721  * 7) Zero any partially truncated blocks.
6722  *
6723  * From this truncation proceeds asynchronously using the freework and
6724  * indir_trunc machinery.  The file will not be extended again into a
6725  * partially truncated indirect block until all work is completed but
6726  * the normal dependency mechanism ensures that it is rolled back/forward
6727  * as appropriate.  Further truncation may occur without delay and is
6728  * serialized in indir_trunc().
6729  */
6730 void
6731 softdep_journal_freeblocks(
6732 	struct inode *ip,	/* The inode whose length is to be reduced */
6733 	struct ucred *cred,
6734 	off_t length,		/* The new length for the file */
6735 	int flags)		/* IO_EXT and/or IO_NORMAL */
6736 {
6737 	struct freeblks *freeblks, *fbn;
6738 	struct worklist *wk, *wkn;
6739 	struct inodedep *inodedep;
6740 	struct jblkdep *jblkdep;
6741 	struct allocdirect *adp, *adpn;
6742 	struct ufsmount *ump;
6743 	struct fs *fs;
6744 	struct buf *bp;
6745 	struct vnode *vp;
6746 	struct mount *mp;
6747 	daddr_t dbn;
6748 	ufs2_daddr_t extblocks, datablocks;
6749 	ufs_lbn_t tmpval, lbn, lastlbn;
6750 	int frags, lastoff, iboff, allocblock, needj, error, i;
6751 
6752 	ump = ITOUMP(ip);
6753 	mp = UFSTOVFS(ump);
6754 	fs = ump->um_fs;
6755 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6756 	    ("softdep_journal_freeblocks called on non-softdep filesystem"));
6757 	vp = ITOV(ip);
6758 	needj = 1;
6759 	iboff = -1;
6760 	allocblock = 0;
6761 	extblocks = 0;
6762 	datablocks = 0;
6763 	frags = 0;
6764 	freeblks = newfreeblks(mp, ip);
6765 	ACQUIRE_LOCK(ump);
6766 	/*
6767 	 * If we're truncating a removed file that will never be written
6768 	 * we don't need to journal the block frees.  The canceled journals
6769 	 * for the allocations will suffice.
6770 	 */
6771 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6772 	if ((inodedep->id_state & (UNLINKED | DEPCOMPLETE)) == UNLINKED &&
6773 	    length == 0)
6774 		needj = 0;
6775 	CTR3(KTR_SUJ, "softdep_journal_freeblks: ip %d length %ld needj %d",
6776 	    ip->i_number, length, needj);
6777 	FREE_LOCK(ump);
6778 	/*
6779 	 * Calculate the lbn that we are truncating to.  This results in -1
6780 	 * if we're truncating the 0 bytes.  So it is the last lbn we want
6781 	 * to keep, not the first lbn we want to truncate.
6782 	 */
6783 	lastlbn = lblkno(fs, length + fs->fs_bsize - 1) - 1;
6784 	lastoff = blkoff(fs, length);
6785 	/*
6786 	 * Compute frags we are keeping in lastlbn.  0 means all.
6787 	 */
6788 	if (lastlbn >= 0 && lastlbn < UFS_NDADDR) {
6789 		frags = fragroundup(fs, lastoff);
6790 		/* adp offset of last valid allocdirect. */
6791 		iboff = lastlbn;
6792 	} else if (lastlbn > 0)
6793 		iboff = UFS_NDADDR;
6794 	if (fs->fs_magic == FS_UFS2_MAGIC)
6795 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6796 	/*
6797 	 * Handle normal data blocks and indirects.  This section saves
6798 	 * values used after the inode update to complete frag and indirect
6799 	 * truncation.
6800 	 */
6801 	if ((flags & IO_NORMAL) != 0) {
6802 		/*
6803 		 * Handle truncation of whole direct and indirect blocks.
6804 		 */
6805 		for (i = iboff + 1; i < UFS_NDADDR; i++)
6806 			setup_freedirect(freeblks, ip, i, needj);
6807 		for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
6808 		    i < UFS_NIADDR;
6809 		    i++, lbn += tmpval, tmpval *= NINDIR(fs)) {
6810 			/* Release a whole indirect tree. */
6811 			if (lbn > lastlbn) {
6812 				setup_freeindir(freeblks, ip, i, -lbn -i,
6813 				    needj);
6814 				continue;
6815 			}
6816 			iboff = i + UFS_NDADDR;
6817 			/*
6818 			 * Traverse partially truncated indirect tree.
6819 			 */
6820 			if (lbn <= lastlbn && lbn + tmpval - 1 > lastlbn)
6821 				setup_trunc_indir(freeblks, ip, -lbn - i,
6822 				    lastlbn, DIP(ip, i_ib[i]));
6823 		}
6824 		/*
6825 		 * Handle partial truncation to a frag boundary.
6826 		 */
6827 		if (frags) {
6828 			ufs2_daddr_t blkno;
6829 			long oldfrags;
6830 
6831 			oldfrags = blksize(fs, ip, lastlbn);
6832 			blkno = DIP(ip, i_db[lastlbn]);
6833 			if (blkno && oldfrags != frags) {
6834 				oldfrags -= frags;
6835 				oldfrags = numfrags(fs, oldfrags);
6836 				blkno += numfrags(fs, frags);
6837 				newfreework(ump, freeblks, NULL, lastlbn,
6838 				    blkno, oldfrags, 0, needj);
6839 				if (needj)
6840 					adjust_newfreework(freeblks,
6841 					    numfrags(fs, frags));
6842 			} else if (blkno == 0)
6843 				allocblock = 1;
6844 		}
6845 		/*
6846 		 * Add a journal record for partial truncate if we are
6847 		 * handling indirect blocks.  Non-indirects need no extra
6848 		 * journaling.
6849 		 */
6850 		if (length != 0 && lastlbn >= UFS_NDADDR) {
6851 			UFS_INODE_SET_FLAG(ip, IN_TRUNCATED);
6852 			newjtrunc(freeblks, length, 0);
6853 		}
6854 		ip->i_size = length;
6855 		DIP_SET(ip, i_size, ip->i_size);
6856 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE);
6857 		datablocks = DIP(ip, i_blocks) - extblocks;
6858 		if (length != 0)
6859 			datablocks = blkcount(fs, datablocks, length);
6860 		freeblks->fb_len = length;
6861 	}
6862 	if ((flags & IO_EXT) != 0) {
6863 		for (i = 0; i < UFS_NXADDR; i++)
6864 			setup_freeext(freeblks, ip, i, needj);
6865 		ip->i_din2->di_extsize = 0;
6866 		datablocks += extblocks;
6867 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE);
6868 	}
6869 #ifdef QUOTA
6870 	/* Reference the quotas in case the block count is wrong in the end. */
6871 	quotaref(vp, freeblks->fb_quota);
6872 	(void) chkdq(ip, -datablocks, NOCRED, FORCE);
6873 #endif
6874 	freeblks->fb_chkcnt = -datablocks;
6875 	UFS_LOCK(ump);
6876 	fs->fs_pendingblocks += datablocks;
6877 	UFS_UNLOCK(ump);
6878 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6879 	/*
6880 	 * Handle truncation of incomplete alloc direct dependencies.  We
6881 	 * hold the inode block locked to prevent incomplete dependencies
6882 	 * from reaching the disk while we are eliminating those that
6883 	 * have been truncated.  This is a partially inlined ffs_update().
6884 	 */
6885 	ufs_itimes(vp);
6886 	ip->i_flag &= ~(IN_LAZYACCESS | IN_LAZYMOD | IN_MODIFIED);
6887 	dbn = fsbtodb(fs, ino_to_fsba(fs, ip->i_number));
6888 	error = ffs_breadz(ump, ump->um_devvp, dbn, dbn, (int)fs->fs_bsize,
6889 	    NULL, NULL, 0, cred, 0, NULL, &bp);
6890 	if (error) {
6891 		softdep_error("softdep_journal_freeblocks", error);
6892 		return;
6893 	}
6894 	if (bp->b_bufsize == fs->fs_bsize)
6895 		bp->b_flags |= B_CLUSTEROK;
6896 	softdep_update_inodeblock(ip, bp, 0);
6897 	if (ump->um_fstype == UFS1) {
6898 		*((struct ufs1_dinode *)bp->b_data +
6899 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din1;
6900 	} else {
6901 		ffs_update_dinode_ckhash(fs, ip->i_din2);
6902 		*((struct ufs2_dinode *)bp->b_data +
6903 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din2;
6904 	}
6905 	ACQUIRE_LOCK(ump);
6906 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6907 	if ((inodedep->id_state & IOSTARTED) != 0)
6908 		panic("softdep_setup_freeblocks: inode busy");
6909 	/*
6910 	 * Add the freeblks structure to the list of operations that
6911 	 * must await the zero'ed inode being written to disk. If we
6912 	 * still have a bitmap dependency (needj), then the inode
6913 	 * has never been written to disk, so we can process the
6914 	 * freeblks below once we have deleted the dependencies.
6915 	 */
6916 	if (needj)
6917 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6918 	else
6919 		freeblks->fb_state |= COMPLETE;
6920 	if ((flags & IO_NORMAL) != 0) {
6921 		TAILQ_FOREACH_SAFE(adp, &inodedep->id_inoupdt, ad_next, adpn) {
6922 			if (adp->ad_offset > iboff)
6923 				cancel_allocdirect(&inodedep->id_inoupdt, adp,
6924 				    freeblks);
6925 			/*
6926 			 * Truncate the allocdirect.  We could eliminate
6927 			 * or modify journal records as well.
6928 			 */
6929 			else if (adp->ad_offset == iboff && frags)
6930 				adp->ad_newsize = frags;
6931 		}
6932 	}
6933 	if ((flags & IO_EXT) != 0)
6934 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
6935 			cancel_allocdirect(&inodedep->id_extupdt, adp,
6936 			    freeblks);
6937 	/*
6938 	 * Scan the bufwait list for newblock dependencies that will never
6939 	 * make it to disk.
6940 	 */
6941 	LIST_FOREACH_SAFE(wk, &inodedep->id_bufwait, wk_list, wkn) {
6942 		if (wk->wk_type != D_ALLOCDIRECT)
6943 			continue;
6944 		adp = WK_ALLOCDIRECT(wk);
6945 		if (((flags & IO_NORMAL) != 0 && (adp->ad_offset > iboff)) ||
6946 		    ((flags & IO_EXT) != 0 && (adp->ad_state & EXTDATA))) {
6947 			cancel_jfreeblk(freeblks, adp->ad_newblkno);
6948 			cancel_newblk(WK_NEWBLK(wk), NULL, &freeblks->fb_jwork);
6949 			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
6950 		}
6951 	}
6952 	/*
6953 	 * Add journal work.
6954 	 */
6955 	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps)
6956 		add_to_journal(&jblkdep->jb_list);
6957 	FREE_LOCK(ump);
6958 	bdwrite(bp);
6959 	/*
6960 	 * Truncate dependency structures beyond length.
6961 	 */
6962 	trunc_dependencies(ip, freeblks, lastlbn, frags, flags);
6963 	/*
6964 	 * This is only set when we need to allocate a fragment because
6965 	 * none existed at the end of a frag-sized file.  It handles only
6966 	 * allocating a new, zero filled block.
6967 	 */
6968 	if (allocblock) {
6969 		ip->i_size = length - lastoff;
6970 		DIP_SET(ip, i_size, ip->i_size);
6971 		error = UFS_BALLOC(vp, length - 1, 1, cred, BA_CLRBUF, &bp);
6972 		if (error != 0) {
6973 			softdep_error("softdep_journal_freeblks", error);
6974 			return;
6975 		}
6976 		ip->i_size = length;
6977 		DIP_SET(ip, i_size, length);
6978 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE | IN_UPDATE);
6979 		allocbuf(bp, frags);
6980 		ffs_update(vp, 0);
6981 		bawrite(bp);
6982 	} else if (lastoff != 0 && vp->v_type != VDIR) {
6983 		int size;
6984 
6985 		/*
6986 		 * Zero the end of a truncated frag or block.
6987 		 */
6988 		size = sblksize(fs, length, lastlbn);
6989 		error = bread(vp, lastlbn, size, cred, &bp);
6990 		if (error == 0) {
6991 			bzero((char *)bp->b_data + lastoff, size - lastoff);
6992 			bawrite(bp);
6993 		} else if (!ffs_fsfail_cleanup(ump, error)) {
6994 			softdep_error("softdep_journal_freeblks", error);
6995 			return;
6996 		}
6997 	}
6998 	ACQUIRE_LOCK(ump);
6999 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
7000 	TAILQ_INSERT_TAIL(&inodedep->id_freeblklst, freeblks, fb_next);
7001 	freeblks->fb_state |= DEPCOMPLETE | ONDEPLIST;
7002 	/*
7003 	 * We zero earlier truncations so they don't erroneously
7004 	 * update i_blocks.
7005 	 */
7006 	if (freeblks->fb_len == 0 && (flags & IO_NORMAL) != 0)
7007 		TAILQ_FOREACH(fbn, &inodedep->id_freeblklst, fb_next)
7008 			fbn->fb_len = 0;
7009 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE &&
7010 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
7011 		freeblks->fb_state |= INPROGRESS;
7012 	else
7013 		freeblks = NULL;
7014 	FREE_LOCK(ump);
7015 	if (freeblks)
7016 		handle_workitem_freeblocks(freeblks, 0);
7017 	trunc_pages(ip, length, extblocks, flags);
7018 
7019 }
7020 
7021 /*
7022  * Flush a JOP_SYNC to the journal.
7023  */
7024 void
7025 softdep_journal_fsync(struct inode *ip)
7026 {
7027 	struct jfsync *jfsync;
7028 	struct ufsmount *ump;
7029 
7030 	ump = ITOUMP(ip);
7031 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
7032 	    ("softdep_journal_fsync called on non-softdep filesystem"));
7033 	if ((ip->i_flag & IN_TRUNCATED) == 0)
7034 		return;
7035 	ip->i_flag &= ~IN_TRUNCATED;
7036 	jfsync = malloc(sizeof(*jfsync), M_JFSYNC, M_SOFTDEP_FLAGS | M_ZERO);
7037 	workitem_alloc(&jfsync->jfs_list, D_JFSYNC, UFSTOVFS(ump));
7038 	jfsync->jfs_size = ip->i_size;
7039 	jfsync->jfs_ino = ip->i_number;
7040 	ACQUIRE_LOCK(ump);
7041 	add_to_journal(&jfsync->jfs_list);
7042 	jwait(&jfsync->jfs_list, MNT_WAIT);
7043 	FREE_LOCK(ump);
7044 }
7045 
7046 /*
7047  * Block de-allocation dependencies.
7048  *
7049  * When blocks are de-allocated, the on-disk pointers must be nullified before
7050  * the blocks are made available for use by other files.  (The true
7051  * requirement is that old pointers must be nullified before new on-disk
7052  * pointers are set.  We chose this slightly more stringent requirement to
7053  * reduce complexity.) Our implementation handles this dependency by updating
7054  * the inode (or indirect block) appropriately but delaying the actual block
7055  * de-allocation (i.e., freemap and free space count manipulation) until
7056  * after the updated versions reach stable storage.  After the disk is
7057  * updated, the blocks can be safely de-allocated whenever it is convenient.
7058  * This implementation handles only the common case of reducing a file's
7059  * length to zero. Other cases are handled by the conventional synchronous
7060  * write approach.
7061  *
7062  * The ffs implementation with which we worked double-checks
7063  * the state of the block pointers and file size as it reduces
7064  * a file's length.  Some of this code is replicated here in our
7065  * soft updates implementation.  The freeblks->fb_chkcnt field is
7066  * used to transfer a part of this information to the procedure
7067  * that eventually de-allocates the blocks.
7068  *
7069  * This routine should be called from the routine that shortens
7070  * a file's length, before the inode's size or block pointers
7071  * are modified. It will save the block pointer information for
7072  * later release and zero the inode so that the calling routine
7073  * can release it.
7074  */
7075 void
7076 softdep_setup_freeblocks(
7077 	struct inode *ip,	/* The inode whose length is to be reduced */
7078 	off_t length,		/* The new length for the file */
7079 	int flags)		/* IO_EXT and/or IO_NORMAL */
7080 {
7081 	struct ufs1_dinode *dp1;
7082 	struct ufs2_dinode *dp2;
7083 	struct freeblks *freeblks;
7084 	struct inodedep *inodedep;
7085 	struct allocdirect *adp;
7086 	struct ufsmount *ump;
7087 	struct buf *bp;
7088 	struct fs *fs;
7089 	ufs2_daddr_t extblocks, datablocks;
7090 	struct mount *mp;
7091 	int i, delay, error;
7092 	ufs_lbn_t tmpval;
7093 	ufs_lbn_t lbn;
7094 
7095 	ump = ITOUMP(ip);
7096 	mp = UFSTOVFS(ump);
7097 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
7098 	    ("softdep_setup_freeblocks called on non-softdep filesystem"));
7099 	CTR2(KTR_SUJ, "softdep_setup_freeblks: ip %d length %ld",
7100 	    ip->i_number, length);
7101 	KASSERT(length == 0, ("softdep_setup_freeblocks: non-zero length"));
7102 	fs = ump->um_fs;
7103 	if ((error = bread(ump->um_devvp,
7104 	    fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
7105 	    (int)fs->fs_bsize, NOCRED, &bp)) != 0) {
7106 		if (!ffs_fsfail_cleanup(ump, error))
7107 			softdep_error("softdep_setup_freeblocks", error);
7108 		return;
7109 	}
7110 	freeblks = newfreeblks(mp, ip);
7111 	extblocks = 0;
7112 	datablocks = 0;
7113 	if (fs->fs_magic == FS_UFS2_MAGIC)
7114 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
7115 	if ((flags & IO_NORMAL) != 0) {
7116 		for (i = 0; i < UFS_NDADDR; i++)
7117 			setup_freedirect(freeblks, ip, i, 0);
7118 		for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
7119 		    i < UFS_NIADDR;
7120 		    i++, lbn += tmpval, tmpval *= NINDIR(fs))
7121 			setup_freeindir(freeblks, ip, i, -lbn -i, 0);
7122 		ip->i_size = 0;
7123 		DIP_SET(ip, i_size, 0);
7124 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE);
7125 		datablocks = DIP(ip, i_blocks) - extblocks;
7126 	}
7127 	if ((flags & IO_EXT) != 0) {
7128 		for (i = 0; i < UFS_NXADDR; i++)
7129 			setup_freeext(freeblks, ip, i, 0);
7130 		ip->i_din2->di_extsize = 0;
7131 		datablocks += extblocks;
7132 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE);
7133 	}
7134 #ifdef QUOTA
7135 	/* Reference the quotas in case the block count is wrong in the end. */
7136 	quotaref(ITOV(ip), freeblks->fb_quota);
7137 	(void) chkdq(ip, -datablocks, NOCRED, FORCE);
7138 #endif
7139 	freeblks->fb_chkcnt = -datablocks;
7140 	UFS_LOCK(ump);
7141 	fs->fs_pendingblocks += datablocks;
7142 	UFS_UNLOCK(ump);
7143 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
7144 	/*
7145 	 * Push the zero'ed inode to its disk buffer so that we are free
7146 	 * to delete its dependencies below. Once the dependencies are gone
7147 	 * the buffer can be safely released.
7148 	 */
7149 	if (ump->um_fstype == UFS1) {
7150 		dp1 = ((struct ufs1_dinode *)bp->b_data +
7151 		    ino_to_fsbo(fs, ip->i_number));
7152 		ip->i_din1->di_freelink = dp1->di_freelink;
7153 		*dp1 = *ip->i_din1;
7154 	} else {
7155 		dp2 = ((struct ufs2_dinode *)bp->b_data +
7156 		    ino_to_fsbo(fs, ip->i_number));
7157 		ip->i_din2->di_freelink = dp2->di_freelink;
7158 		ffs_update_dinode_ckhash(fs, ip->i_din2);
7159 		*dp2 = *ip->i_din2;
7160 	}
7161 	/*
7162 	 * Find and eliminate any inode dependencies.
7163 	 */
7164 	ACQUIRE_LOCK(ump);
7165 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
7166 	if ((inodedep->id_state & IOSTARTED) != 0)
7167 		panic("softdep_setup_freeblocks: inode busy");
7168 	/*
7169 	 * Add the freeblks structure to the list of operations that
7170 	 * must await the zero'ed inode being written to disk. If we
7171 	 * still have a bitmap dependency (delay == 0), then the inode
7172 	 * has never been written to disk, so we can process the
7173 	 * freeblks below once we have deleted the dependencies.
7174 	 */
7175 	delay = (inodedep->id_state & DEPCOMPLETE);
7176 	if (delay)
7177 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
7178 	else
7179 		freeblks->fb_state |= COMPLETE;
7180 	/*
7181 	 * Because the file length has been truncated to zero, any
7182 	 * pending block allocation dependency structures associated
7183 	 * with this inode are obsolete and can simply be de-allocated.
7184 	 * We must first merge the two dependency lists to get rid of
7185 	 * any duplicate freefrag structures, then purge the merged list.
7186 	 * If we still have a bitmap dependency, then the inode has never
7187 	 * been written to disk, so we can free any fragments without delay.
7188 	 */
7189 	if (flags & IO_NORMAL) {
7190 		merge_inode_lists(&inodedep->id_newinoupdt,
7191 		    &inodedep->id_inoupdt);
7192 		while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
7193 			cancel_allocdirect(&inodedep->id_inoupdt, adp,
7194 			    freeblks);
7195 	}
7196 	if (flags & IO_EXT) {
7197 		merge_inode_lists(&inodedep->id_newextupdt,
7198 		    &inodedep->id_extupdt);
7199 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
7200 			cancel_allocdirect(&inodedep->id_extupdt, adp,
7201 			    freeblks);
7202 	}
7203 	FREE_LOCK(ump);
7204 	bdwrite(bp);
7205 	trunc_dependencies(ip, freeblks, -1, 0, flags);
7206 	ACQUIRE_LOCK(ump);
7207 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
7208 		(void) free_inodedep(inodedep);
7209 	freeblks->fb_state |= DEPCOMPLETE;
7210 	/*
7211 	 * If the inode with zeroed block pointers is now on disk
7212 	 * we can start freeing blocks.
7213 	 */
7214 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
7215 		freeblks->fb_state |= INPROGRESS;
7216 	else
7217 		freeblks = NULL;
7218 	FREE_LOCK(ump);
7219 	if (freeblks)
7220 		handle_workitem_freeblocks(freeblks, 0);
7221 	trunc_pages(ip, length, extblocks, flags);
7222 }
7223 
7224 /*
7225  * Eliminate pages from the page cache that back parts of this inode and
7226  * adjust the vnode pager's idea of our size.  This prevents stale data
7227  * from hanging around in the page cache.
7228  */
7229 static void
7230 trunc_pages(
7231 	struct inode *ip,
7232 	off_t length,
7233 	ufs2_daddr_t extblocks,
7234 	int flags)
7235 {
7236 	struct vnode *vp;
7237 	struct fs *fs;
7238 	ufs_lbn_t lbn;
7239 	off_t end, extend;
7240 
7241 	vp = ITOV(ip);
7242 	fs = ITOFS(ip);
7243 	extend = OFF_TO_IDX(lblktosize(fs, -extblocks));
7244 	if ((flags & IO_EXT) != 0)
7245 		vn_pages_remove(vp, extend, 0);
7246 	if ((flags & IO_NORMAL) == 0)
7247 		return;
7248 	BO_LOCK(&vp->v_bufobj);
7249 	drain_output(vp);
7250 	BO_UNLOCK(&vp->v_bufobj);
7251 	/*
7252 	 * The vnode pager eliminates file pages we eliminate indirects
7253 	 * below.
7254 	 */
7255 	vnode_pager_setsize(vp, length);
7256 	/*
7257 	 * Calculate the end based on the last indirect we want to keep.  If
7258 	 * the block extends into indirects we can just use the negative of
7259 	 * its lbn.  Doubles and triples exist at lower numbers so we must
7260 	 * be careful not to remove those, if they exist.  double and triple
7261 	 * indirect lbns do not overlap with others so it is not important
7262 	 * to verify how many levels are required.
7263 	 */
7264 	lbn = lblkno(fs, length);
7265 	if (lbn >= UFS_NDADDR) {
7266 		/* Calculate the virtual lbn of the triple indirect. */
7267 		lbn = -lbn - (UFS_NIADDR - 1);
7268 		end = OFF_TO_IDX(lblktosize(fs, lbn));
7269 	} else
7270 		end = extend;
7271 	vn_pages_remove(vp, OFF_TO_IDX(OFF_MAX), end);
7272 }
7273 
7274 /*
7275  * See if the buf bp is in the range eliminated by truncation.
7276  */
7277 static int
7278 trunc_check_buf(
7279 	struct buf *bp,
7280 	int *blkoffp,
7281 	ufs_lbn_t lastlbn,
7282 	int lastoff,
7283 	int flags)
7284 {
7285 	ufs_lbn_t lbn;
7286 
7287 	*blkoffp = 0;
7288 	/* Only match ext/normal blocks as appropriate. */
7289 	if (((flags & IO_EXT) == 0 && (bp->b_xflags & BX_ALTDATA)) ||
7290 	    ((flags & IO_NORMAL) == 0 && (bp->b_xflags & BX_ALTDATA) == 0))
7291 		return (0);
7292 	/* ALTDATA is always a full truncation. */
7293 	if ((bp->b_xflags & BX_ALTDATA) != 0)
7294 		return (1);
7295 	/* -1 is full truncation. */
7296 	if (lastlbn == -1)
7297 		return (1);
7298 	/*
7299 	 * If this is a partial truncate we only want those
7300 	 * blocks and indirect blocks that cover the range
7301 	 * we're after.
7302 	 */
7303 	lbn = bp->b_lblkno;
7304 	if (lbn < 0)
7305 		lbn = -(lbn + lbn_level(lbn));
7306 	if (lbn < lastlbn)
7307 		return (0);
7308 	/* Here we only truncate lblkno if it's partial. */
7309 	if (lbn == lastlbn) {
7310 		if (lastoff == 0)
7311 			return (0);
7312 		*blkoffp = lastoff;
7313 	}
7314 	return (1);
7315 }
7316 
7317 /*
7318  * Eliminate any dependencies that exist in memory beyond lblkno:off
7319  */
7320 static void
7321 trunc_dependencies(
7322 	struct inode *ip,
7323 	struct freeblks *freeblks,
7324 	ufs_lbn_t lastlbn,
7325 	int lastoff,
7326 	int flags)
7327 {
7328 	struct bufobj *bo;
7329 	struct vnode *vp;
7330 	struct buf *bp;
7331 	int blkoff;
7332 
7333 	/*
7334 	 * We must wait for any I/O in progress to finish so that
7335 	 * all potential buffers on the dirty list will be visible.
7336 	 * Once they are all there, walk the list and get rid of
7337 	 * any dependencies.
7338 	 */
7339 	vp = ITOV(ip);
7340 	bo = &vp->v_bufobj;
7341 	BO_LOCK(bo);
7342 	drain_output(vp);
7343 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs)
7344 		bp->b_vflags &= ~BV_SCANNED;
7345 restart:
7346 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) {
7347 		if (bp->b_vflags & BV_SCANNED)
7348 			continue;
7349 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7350 			bp->b_vflags |= BV_SCANNED;
7351 			continue;
7352 		}
7353 		KASSERT(bp->b_bufobj == bo, ("Wrong object in buffer"));
7354 		if ((bp = getdirtybuf(bp, BO_LOCKPTR(bo), MNT_WAIT)) == NULL)
7355 			goto restart;
7356 		BO_UNLOCK(bo);
7357 		if (deallocate_dependencies(bp, freeblks, blkoff))
7358 			bqrelse(bp);
7359 		else
7360 			brelse(bp);
7361 		BO_LOCK(bo);
7362 		goto restart;
7363 	}
7364 	/*
7365 	 * Now do the work of vtruncbuf while also matching indirect blocks.
7366 	 */
7367 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs)
7368 		bp->b_vflags &= ~BV_SCANNED;
7369 cleanrestart:
7370 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs) {
7371 		if (bp->b_vflags & BV_SCANNED)
7372 			continue;
7373 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7374 			bp->b_vflags |= BV_SCANNED;
7375 			continue;
7376 		}
7377 		if (BUF_LOCK(bp,
7378 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
7379 		    BO_LOCKPTR(bo)) == ENOLCK) {
7380 			BO_LOCK(bo);
7381 			goto cleanrestart;
7382 		}
7383 		BO_LOCK(bo);
7384 		bp->b_vflags |= BV_SCANNED;
7385 		BO_UNLOCK(bo);
7386 		bremfree(bp);
7387 		if (blkoff != 0) {
7388 			allocbuf(bp, blkoff);
7389 			bqrelse(bp);
7390 		} else {
7391 			bp->b_flags |= B_INVAL | B_NOCACHE | B_RELBUF;
7392 			brelse(bp);
7393 		}
7394 		BO_LOCK(bo);
7395 		goto cleanrestart;
7396 	}
7397 	drain_output(vp);
7398 	BO_UNLOCK(bo);
7399 }
7400 
7401 static int
7402 cancel_pagedep(
7403 	struct pagedep *pagedep,
7404 	struct freeblks *freeblks,
7405 	int blkoff)
7406 {
7407 	struct jremref *jremref;
7408 	struct jmvref *jmvref;
7409 	struct dirrem *dirrem, *tmp;
7410 	int i;
7411 
7412 	/*
7413 	 * Copy any directory remove dependencies to the list
7414 	 * to be processed after the freeblks proceeds.  If
7415 	 * directory entry never made it to disk they
7416 	 * can be dumped directly onto the work list.
7417 	 */
7418 	LIST_FOREACH_SAFE(dirrem, &pagedep->pd_dirremhd, dm_next, tmp) {
7419 		/* Skip this directory removal if it is intended to remain. */
7420 		if (dirrem->dm_offset < blkoff)
7421 			continue;
7422 		/*
7423 		 * If there are any dirrems we wait for the journal write
7424 		 * to complete and then restart the buf scan as the lock
7425 		 * has been dropped.
7426 		 */
7427 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL) {
7428 			jwait(&jremref->jr_list, MNT_WAIT);
7429 			return (ERESTART);
7430 		}
7431 		LIST_REMOVE(dirrem, dm_next);
7432 		dirrem->dm_dirinum = pagedep->pd_ino;
7433 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &dirrem->dm_list);
7434 	}
7435 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL) {
7436 		jwait(&jmvref->jm_list, MNT_WAIT);
7437 		return (ERESTART);
7438 	}
7439 	/*
7440 	 * When we're partially truncating a pagedep we just want to flush
7441 	 * journal entries and return.  There can not be any adds in the
7442 	 * truncated portion of the directory and newblk must remain if
7443 	 * part of the block remains.
7444 	 */
7445 	if (blkoff != 0) {
7446 		struct diradd *dap;
7447 
7448 		LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
7449 			if (dap->da_offset > blkoff)
7450 				panic("cancel_pagedep: diradd %p off %d > %d",
7451 				    dap, dap->da_offset, blkoff);
7452 		for (i = 0; i < DAHASHSZ; i++)
7453 			LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist)
7454 				if (dap->da_offset > blkoff)
7455 					panic("cancel_pagedep: diradd %p off %d > %d",
7456 					    dap, dap->da_offset, blkoff);
7457 		return (0);
7458 	}
7459 	/*
7460 	 * There should be no directory add dependencies present
7461 	 * as the directory could not be truncated until all
7462 	 * children were removed.
7463 	 */
7464 	KASSERT(LIST_FIRST(&pagedep->pd_pendinghd) == NULL,
7465 	    ("deallocate_dependencies: pendinghd != NULL"));
7466 	for (i = 0; i < DAHASHSZ; i++)
7467 		KASSERT(LIST_FIRST(&pagedep->pd_diraddhd[i]) == NULL,
7468 		    ("deallocate_dependencies: diraddhd != NULL"));
7469 	if ((pagedep->pd_state & NEWBLOCK) != 0)
7470 		free_newdirblk(pagedep->pd_newdirblk);
7471 	if (free_pagedep(pagedep) == 0)
7472 		panic("Failed to free pagedep %p", pagedep);
7473 	return (0);
7474 }
7475 
7476 /*
7477  * Reclaim any dependency structures from a buffer that is about to
7478  * be reallocated to a new vnode. The buffer must be locked, thus,
7479  * no I/O completion operations can occur while we are manipulating
7480  * its associated dependencies. The mutex is held so that other I/O's
7481  * associated with related dependencies do not occur.
7482  */
7483 static int
7484 deallocate_dependencies(
7485 	struct buf *bp,
7486 	struct freeblks *freeblks,
7487 	int off)
7488 {
7489 	struct indirdep *indirdep;
7490 	struct pagedep *pagedep;
7491 	struct worklist *wk, *wkn;
7492 	struct ufsmount *ump;
7493 
7494 	ump = softdep_bp_to_mp(bp);
7495 	if (ump == NULL)
7496 		goto done;
7497 	ACQUIRE_LOCK(ump);
7498 	LIST_FOREACH_SAFE(wk, &bp->b_dep, wk_list, wkn) {
7499 		switch (wk->wk_type) {
7500 		case D_INDIRDEP:
7501 			indirdep = WK_INDIRDEP(wk);
7502 			if (bp->b_lblkno >= 0 ||
7503 			    bp->b_blkno != indirdep->ir_savebp->b_lblkno)
7504 				panic("deallocate_dependencies: not indir");
7505 			cancel_indirdep(indirdep, bp, freeblks);
7506 			continue;
7507 
7508 		case D_PAGEDEP:
7509 			pagedep = WK_PAGEDEP(wk);
7510 			if (cancel_pagedep(pagedep, freeblks, off)) {
7511 				FREE_LOCK(ump);
7512 				return (ERESTART);
7513 			}
7514 			continue;
7515 
7516 		case D_ALLOCINDIR:
7517 			/*
7518 			 * Simply remove the allocindir, we'll find it via
7519 			 * the indirdep where we can clear pointers if
7520 			 * needed.
7521 			 */
7522 			WORKLIST_REMOVE(wk);
7523 			continue;
7524 
7525 		case D_FREEWORK:
7526 			/*
7527 			 * A truncation is waiting for the zero'd pointers
7528 			 * to be written.  It can be freed when the freeblks
7529 			 * is journaled.
7530 			 */
7531 			WORKLIST_REMOVE(wk);
7532 			wk->wk_state |= ONDEPLIST;
7533 			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
7534 			break;
7535 
7536 		case D_ALLOCDIRECT:
7537 			if (off != 0)
7538 				continue;
7539 			/* FALLTHROUGH */
7540 		default:
7541 			panic("deallocate_dependencies: Unexpected type %s",
7542 			    TYPENAME(wk->wk_type));
7543 			/* NOTREACHED */
7544 		}
7545 	}
7546 	FREE_LOCK(ump);
7547 done:
7548 	/*
7549 	 * Don't throw away this buf, we were partially truncating and
7550 	 * some deps may always remain.
7551 	 */
7552 	if (off) {
7553 		allocbuf(bp, off);
7554 		bp->b_vflags |= BV_SCANNED;
7555 		return (EBUSY);
7556 	}
7557 	bp->b_flags |= B_INVAL | B_NOCACHE;
7558 
7559 	return (0);
7560 }
7561 
7562 /*
7563  * An allocdirect is being canceled due to a truncate.  We must make sure
7564  * the journal entry is released in concert with the blkfree that releases
7565  * the storage.  Completed journal entries must not be released until the
7566  * space is no longer pointed to by the inode or in the bitmap.
7567  */
7568 static void
7569 cancel_allocdirect(
7570 	struct allocdirectlst *adphead,
7571 	struct allocdirect *adp,
7572 	struct freeblks *freeblks)
7573 {
7574 	struct freework *freework;
7575 	struct newblk *newblk;
7576 	struct worklist *wk;
7577 
7578 	TAILQ_REMOVE(adphead, adp, ad_next);
7579 	newblk = (struct newblk *)adp;
7580 	freework = NULL;
7581 	/*
7582 	 * Find the correct freework structure.
7583 	 */
7584 	LIST_FOREACH(wk, &freeblks->fb_freeworkhd, wk_list) {
7585 		if (wk->wk_type != D_FREEWORK)
7586 			continue;
7587 		freework = WK_FREEWORK(wk);
7588 		if (freework->fw_blkno == newblk->nb_newblkno)
7589 			break;
7590 	}
7591 	if (freework == NULL)
7592 		panic("cancel_allocdirect: Freework not found");
7593 	/*
7594 	 * If a newblk exists at all we still have the journal entry that
7595 	 * initiated the allocation so we do not need to journal the free.
7596 	 */
7597 	cancel_jfreeblk(freeblks, freework->fw_blkno);
7598 	/*
7599 	 * If the journal hasn't been written the jnewblk must be passed
7600 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
7601 	 * this by linking the journal dependency into the freework to be
7602 	 * freed when freework_freeblock() is called.  If the journal has
7603 	 * been written we can simply reclaim the journal space when the
7604 	 * freeblks work is complete.
7605 	 */
7606 	freework->fw_jnewblk = cancel_newblk(newblk, &freework->fw_list,
7607 	    &freeblks->fb_jwork);
7608 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
7609 }
7610 
7611 /*
7612  * Cancel a new block allocation.  May be an indirect or direct block.  We
7613  * remove it from various lists and return any journal record that needs to
7614  * be resolved by the caller.
7615  *
7616  * A special consideration is made for indirects which were never pointed
7617  * at on disk and will never be found once this block is released.
7618  */
7619 static struct jnewblk *
7620 cancel_newblk(
7621 	struct newblk *newblk,
7622 	struct worklist *wk,
7623 	struct workhead *wkhd)
7624 {
7625 	struct jnewblk *jnewblk;
7626 
7627 	CTR1(KTR_SUJ, "cancel_newblk: blkno %jd", newblk->nb_newblkno);
7628 
7629 	newblk->nb_state |= GOINGAWAY;
7630 	/*
7631 	 * Previously we traversed the completedhd on each indirdep
7632 	 * attached to this newblk to cancel them and gather journal
7633 	 * work.  Since we need only the oldest journal segment and
7634 	 * the lowest point on the tree will always have the oldest
7635 	 * journal segment we are free to release the segments
7636 	 * of any subordinates and may leave the indirdep list to
7637 	 * indirdep_complete() when this newblk is freed.
7638 	 */
7639 	if (newblk->nb_state & ONDEPLIST) {
7640 		newblk->nb_state &= ~ONDEPLIST;
7641 		LIST_REMOVE(newblk, nb_deps);
7642 	}
7643 	if (newblk->nb_state & ONWORKLIST)
7644 		WORKLIST_REMOVE(&newblk->nb_list);
7645 	/*
7646 	 * If the journal entry hasn't been written we save a pointer to
7647 	 * the dependency that frees it until it is written or the
7648 	 * superseding operation completes.
7649 	 */
7650 	jnewblk = newblk->nb_jnewblk;
7651 	if (jnewblk != NULL && wk != NULL) {
7652 		newblk->nb_jnewblk = NULL;
7653 		jnewblk->jn_dep = wk;
7654 	}
7655 	if (!LIST_EMPTY(&newblk->nb_jwork))
7656 		jwork_move(wkhd, &newblk->nb_jwork);
7657 	/*
7658 	 * When truncating we must free the newdirblk early to remove
7659 	 * the pagedep from the hash before returning.
7660 	 */
7661 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7662 		free_newdirblk(WK_NEWDIRBLK(wk));
7663 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7664 		panic("cancel_newblk: extra newdirblk");
7665 
7666 	return (jnewblk);
7667 }
7668 
7669 /*
7670  * Schedule the freefrag associated with a newblk to be released once
7671  * the pointers are written and the previous block is no longer needed.
7672  */
7673 static void
7674 newblk_freefrag(struct newblk *newblk)
7675 {
7676 	struct freefrag *freefrag;
7677 
7678 	if (newblk->nb_freefrag == NULL)
7679 		return;
7680 	freefrag = newblk->nb_freefrag;
7681 	newblk->nb_freefrag = NULL;
7682 	freefrag->ff_state |= COMPLETE;
7683 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
7684 		add_to_worklist(&freefrag->ff_list, 0);
7685 }
7686 
7687 /*
7688  * Free a newblk. Generate a new freefrag work request if appropriate.
7689  * This must be called after the inode pointer and any direct block pointers
7690  * are valid or fully removed via truncate or frag extension.
7691  */
7692 static void
7693 free_newblk(struct newblk *newblk)
7694 {
7695 	struct indirdep *indirdep;
7696 	struct worklist *wk;
7697 
7698 	KASSERT(newblk->nb_jnewblk == NULL,
7699 	    ("free_newblk: jnewblk %p still attached", newblk->nb_jnewblk));
7700 	KASSERT(newblk->nb_list.wk_type != D_NEWBLK,
7701 	    ("free_newblk: unclaimed newblk"));
7702 	LOCK_OWNED(VFSTOUFS(newblk->nb_list.wk_mp));
7703 	newblk_freefrag(newblk);
7704 	if (newblk->nb_state & ONDEPLIST)
7705 		LIST_REMOVE(newblk, nb_deps);
7706 	if (newblk->nb_state & ONWORKLIST)
7707 		WORKLIST_REMOVE(&newblk->nb_list);
7708 	LIST_REMOVE(newblk, nb_hash);
7709 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7710 		free_newdirblk(WK_NEWDIRBLK(wk));
7711 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7712 		panic("free_newblk: extra newdirblk");
7713 	while ((indirdep = LIST_FIRST(&newblk->nb_indirdeps)) != NULL)
7714 		indirdep_complete(indirdep);
7715 	handle_jwork(&newblk->nb_jwork);
7716 	WORKITEM_FREE(newblk, D_NEWBLK);
7717 }
7718 
7719 /*
7720  * Free a newdirblk. Clear the NEWBLOCK flag on its associated pagedep.
7721  */
7722 static void
7723 free_newdirblk(struct newdirblk *newdirblk)
7724 {
7725 	struct pagedep *pagedep;
7726 	struct diradd *dap;
7727 	struct worklist *wk;
7728 
7729 	LOCK_OWNED(VFSTOUFS(newdirblk->db_list.wk_mp));
7730 	WORKLIST_REMOVE(&newdirblk->db_list);
7731 	/*
7732 	 * If the pagedep is still linked onto the directory buffer
7733 	 * dependency chain, then some of the entries on the
7734 	 * pd_pendinghd list may not be committed to disk yet. In
7735 	 * this case, we will simply clear the NEWBLOCK flag and
7736 	 * let the pd_pendinghd list be processed when the pagedep
7737 	 * is next written. If the pagedep is no longer on the buffer
7738 	 * dependency chain, then all the entries on the pd_pending
7739 	 * list are committed to disk and we can free them here.
7740 	 */
7741 	pagedep = newdirblk->db_pagedep;
7742 	pagedep->pd_state &= ~NEWBLOCK;
7743 	if ((pagedep->pd_state & ONWORKLIST) == 0) {
7744 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
7745 			free_diradd(dap, NULL);
7746 		/*
7747 		 * If no dependencies remain, the pagedep will be freed.
7748 		 */
7749 		free_pagedep(pagedep);
7750 	}
7751 	/* Should only ever be one item in the list. */
7752 	while ((wk = LIST_FIRST(&newdirblk->db_mkdir)) != NULL) {
7753 		WORKLIST_REMOVE(wk);
7754 		handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
7755 	}
7756 	WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
7757 }
7758 
7759 /*
7760  * Prepare an inode to be freed. The actual free operation is not
7761  * done until the zero'ed inode has been written to disk.
7762  */
7763 void
7764 softdep_freefile(
7765 	struct vnode *pvp,
7766 	ino_t ino,
7767 	int mode)
7768 {
7769 	struct inode *ip = VTOI(pvp);
7770 	struct inodedep *inodedep;
7771 	struct freefile *freefile;
7772 	struct freeblks *freeblks;
7773 	struct ufsmount *ump;
7774 
7775 	ump = ITOUMP(ip);
7776 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
7777 	    ("softdep_freefile called on non-softdep filesystem"));
7778 	/*
7779 	 * This sets up the inode de-allocation dependency.
7780 	 */
7781 	freefile = malloc(sizeof(struct freefile),
7782 		M_FREEFILE, M_SOFTDEP_FLAGS);
7783 	workitem_alloc(&freefile->fx_list, D_FREEFILE, pvp->v_mount);
7784 	freefile->fx_mode = mode;
7785 	freefile->fx_oldinum = ino;
7786 	freefile->fx_devvp = ump->um_devvp;
7787 	LIST_INIT(&freefile->fx_jwork);
7788 	UFS_LOCK(ump);
7789 	ump->um_fs->fs_pendinginodes += 1;
7790 	UFS_UNLOCK(ump);
7791 
7792 	/*
7793 	 * If the inodedep does not exist, then the zero'ed inode has
7794 	 * been written to disk. If the allocated inode has never been
7795 	 * written to disk, then the on-disk inode is zero'ed. In either
7796 	 * case we can free the file immediately.  If the journal was
7797 	 * canceled before being written the inode will never make it to
7798 	 * disk and we must send the canceled journal entrys to
7799 	 * ffs_freefile() to be cleared in conjunction with the bitmap.
7800 	 * Any blocks waiting on the inode to write can be safely freed
7801 	 * here as it will never been written.
7802 	 */
7803 	ACQUIRE_LOCK(ump);
7804 	inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7805 	if (inodedep) {
7806 		/*
7807 		 * Clear out freeblks that no longer need to reference
7808 		 * this inode.
7809 		 */
7810 		while ((freeblks =
7811 		    TAILQ_FIRST(&inodedep->id_freeblklst)) != NULL) {
7812 			TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks,
7813 			    fb_next);
7814 			freeblks->fb_state &= ~ONDEPLIST;
7815 		}
7816 		/*
7817 		 * Remove this inode from the unlinked list.
7818 		 */
7819 		if (inodedep->id_state & UNLINKED) {
7820 			/*
7821 			 * Save the journal work to be freed with the bitmap
7822 			 * before we clear UNLINKED.  Otherwise it can be lost
7823 			 * if the inode block is written.
7824 			 */
7825 			handle_bufwait(inodedep, &freefile->fx_jwork);
7826 			clear_unlinked_inodedep(inodedep);
7827 			/*
7828 			 * Re-acquire inodedep as we've dropped the
7829 			 * per-filesystem lock in clear_unlinked_inodedep().
7830 			 */
7831 			inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7832 		}
7833 	}
7834 	if (inodedep == NULL || check_inode_unwritten(inodedep)) {
7835 		FREE_LOCK(ump);
7836 		handle_workitem_freefile(freefile);
7837 		return;
7838 	}
7839 	if ((inodedep->id_state & DEPCOMPLETE) == 0)
7840 		inodedep->id_state |= GOINGAWAY;
7841 	WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
7842 	FREE_LOCK(ump);
7843 	if (ip->i_number == ino)
7844 		UFS_INODE_SET_FLAG(ip, IN_MODIFIED);
7845 }
7846 
7847 /*
7848  * Check to see if an inode has never been written to disk. If
7849  * so free the inodedep and return success, otherwise return failure.
7850  *
7851  * If we still have a bitmap dependency, then the inode has never
7852  * been written to disk. Drop the dependency as it is no longer
7853  * necessary since the inode is being deallocated. We set the
7854  * ALLCOMPLETE flags since the bitmap now properly shows that the
7855  * inode is not allocated. Even if the inode is actively being
7856  * written, it has been rolled back to its zero'ed state, so we
7857  * are ensured that a zero inode is what is on the disk. For short
7858  * lived files, this change will usually result in removing all the
7859  * dependencies from the inode so that it can be freed immediately.
7860  */
7861 static int
7862 check_inode_unwritten(struct inodedep *inodedep)
7863 {
7864 
7865 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7866 
7867 	if ((inodedep->id_state & (DEPCOMPLETE | UNLINKED)) != 0 ||
7868 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
7869 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
7870 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
7871 	    !LIST_EMPTY(&inodedep->id_inowait) ||
7872 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7873 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7874 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7875 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7876 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7877 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7878 	    inodedep->id_mkdiradd != NULL ||
7879 	    inodedep->id_nlinkdelta != 0)
7880 		return (0);
7881 	/*
7882 	 * Another process might be in initiate_write_inodeblock_ufs[12]
7883 	 * trying to allocate memory without holding "Softdep Lock".
7884 	 */
7885 	if ((inodedep->id_state & IOSTARTED) != 0 &&
7886 	    inodedep->id_savedino1 == NULL)
7887 		return (0);
7888 
7889 	if (inodedep->id_state & ONDEPLIST)
7890 		LIST_REMOVE(inodedep, id_deps);
7891 	inodedep->id_state &= ~ONDEPLIST;
7892 	inodedep->id_state |= ALLCOMPLETE;
7893 	inodedep->id_bmsafemap = NULL;
7894 	if (inodedep->id_state & ONWORKLIST)
7895 		WORKLIST_REMOVE(&inodedep->id_list);
7896 	if (inodedep->id_savedino1 != NULL) {
7897 		free(inodedep->id_savedino1, M_SAVEDINO);
7898 		inodedep->id_savedino1 = NULL;
7899 	}
7900 	if (free_inodedep(inodedep) == 0)
7901 		panic("check_inode_unwritten: busy inode");
7902 	return (1);
7903 }
7904 
7905 static int
7906 check_inodedep_free(struct inodedep *inodedep)
7907 {
7908 
7909 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7910 	if ((inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
7911 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
7912 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
7913 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
7914 	    !LIST_EMPTY(&inodedep->id_inowait) ||
7915 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7916 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7917 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7918 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7919 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7920 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7921 	    inodedep->id_mkdiradd != NULL ||
7922 	    inodedep->id_nlinkdelta != 0 ||
7923 	    inodedep->id_savedino1 != NULL)
7924 		return (0);
7925 	return (1);
7926 }
7927 
7928 /*
7929  * Try to free an inodedep structure. Return 1 if it could be freed.
7930  */
7931 static int
7932 free_inodedep(struct inodedep *inodedep)
7933 {
7934 
7935 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7936 	if ((inodedep->id_state & (ONWORKLIST | UNLINKED)) != 0 ||
7937 	    !check_inodedep_free(inodedep))
7938 		return (0);
7939 	if (inodedep->id_state & ONDEPLIST)
7940 		LIST_REMOVE(inodedep, id_deps);
7941 	LIST_REMOVE(inodedep, id_hash);
7942 	WORKITEM_FREE(inodedep, D_INODEDEP);
7943 	return (1);
7944 }
7945 
7946 /*
7947  * Free the block referenced by a freework structure.  The parent freeblks
7948  * structure is released and completed when the final cg bitmap reaches
7949  * the disk.  This routine may be freeing a jnewblk which never made it to
7950  * disk in which case we do not have to wait as the operation is undone
7951  * in memory immediately.
7952  */
7953 static void
7954 freework_freeblock(struct freework *freework, u_long key)
7955 {
7956 	struct freeblks *freeblks;
7957 	struct jnewblk *jnewblk;
7958 	struct ufsmount *ump;
7959 	struct workhead wkhd;
7960 	struct fs *fs;
7961 	int bsize;
7962 	int needj;
7963 
7964 	ump = VFSTOUFS(freework->fw_list.wk_mp);
7965 	LOCK_OWNED(ump);
7966 	/*
7967 	 * Handle partial truncate separately.
7968 	 */
7969 	if (freework->fw_indir) {
7970 		complete_trunc_indir(freework);
7971 		return;
7972 	}
7973 	freeblks = freework->fw_freeblks;
7974 	fs = ump->um_fs;
7975 	needj = MOUNTEDSUJ(freeblks->fb_list.wk_mp) != 0;
7976 	bsize = lfragtosize(fs, freework->fw_frags);
7977 	LIST_INIT(&wkhd);
7978 	/*
7979 	 * DEPCOMPLETE is cleared in indirblk_insert() if the block lives
7980 	 * on the indirblk hashtable and prevents premature freeing.
7981 	 */
7982 	freework->fw_state |= DEPCOMPLETE;
7983 	/*
7984 	 * SUJ needs to wait for the segment referencing freed indirect
7985 	 * blocks to expire so that we know the checker will not confuse
7986 	 * a re-allocated indirect block with its old contents.
7987 	 */
7988 	if (needj && freework->fw_lbn <= -UFS_NDADDR)
7989 		indirblk_insert(freework);
7990 	/*
7991 	 * If we are canceling an existing jnewblk pass it to the free
7992 	 * routine, otherwise pass the freeblk which will ultimately
7993 	 * release the freeblks.  If we're not journaling, we can just
7994 	 * free the freeblks immediately.
7995 	 */
7996 	jnewblk = freework->fw_jnewblk;
7997 	if (jnewblk != NULL) {
7998 		cancel_jnewblk(jnewblk, &wkhd);
7999 		needj = 0;
8000 	} else if (needj) {
8001 		freework->fw_state |= DELAYEDFREE;
8002 		freeblks->fb_cgwait++;
8003 		WORKLIST_INSERT(&wkhd, &freework->fw_list);
8004 	}
8005 	FREE_LOCK(ump);
8006 	freeblks_free(ump, freeblks, btodb(bsize));
8007 	CTR4(KTR_SUJ,
8008 	    "freework_freeblock: ino %jd blkno %jd lbn %jd size %d",
8009 	    freeblks->fb_inum, freework->fw_blkno, freework->fw_lbn, bsize);
8010 	ffs_blkfree(ump, fs, freeblks->fb_devvp, freework->fw_blkno, bsize,
8011 	    freeblks->fb_inum, freeblks->fb_vtype, &wkhd, key);
8012 	ACQUIRE_LOCK(ump);
8013 	/*
8014 	 * The jnewblk will be discarded and the bits in the map never
8015 	 * made it to disk.  We can immediately free the freeblk.
8016 	 */
8017 	if (needj == 0)
8018 		handle_written_freework(freework);
8019 }
8020 
8021 /*
8022  * We enqueue freework items that need processing back on the freeblks and
8023  * add the freeblks to the worklist.  This makes it easier to find all work
8024  * required to flush a truncation in process_truncates().
8025  */
8026 static void
8027 freework_enqueue(struct freework *freework)
8028 {
8029 	struct freeblks *freeblks;
8030 
8031 	freeblks = freework->fw_freeblks;
8032 	if ((freework->fw_state & INPROGRESS) == 0)
8033 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
8034 	if ((freeblks->fb_state &
8035 	    (ONWORKLIST | INPROGRESS | ALLCOMPLETE)) == ALLCOMPLETE &&
8036 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
8037 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
8038 }
8039 
8040 /*
8041  * Start, continue, or finish the process of freeing an indirect block tree.
8042  * The free operation may be paused at any point with fw_off containing the
8043  * offset to restart from.  This enables us to implement some flow control
8044  * for large truncates which may fan out and generate a huge number of
8045  * dependencies.
8046  */
8047 static void
8048 handle_workitem_indirblk(struct freework *freework)
8049 {
8050 	struct freeblks *freeblks;
8051 	struct ufsmount *ump;
8052 	struct fs *fs;
8053 
8054 	freeblks = freework->fw_freeblks;
8055 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8056 	fs = ump->um_fs;
8057 	if (freework->fw_state & DEPCOMPLETE) {
8058 		handle_written_freework(freework);
8059 		return;
8060 	}
8061 	if (freework->fw_off == NINDIR(fs)) {
8062 		freework_freeblock(freework, SINGLETON_KEY);
8063 		return;
8064 	}
8065 	freework->fw_state |= INPROGRESS;
8066 	FREE_LOCK(ump);
8067 	indir_trunc(freework, fsbtodb(fs, freework->fw_blkno),
8068 	    freework->fw_lbn);
8069 	ACQUIRE_LOCK(ump);
8070 }
8071 
8072 /*
8073  * Called when a freework structure attached to a cg buf is written.  The
8074  * ref on either the parent or the freeblks structure is released and
8075  * the freeblks is added back to the worklist if there is more work to do.
8076  */
8077 static void
8078 handle_written_freework(struct freework *freework)
8079 {
8080 	struct freeblks *freeblks;
8081 	struct freework *parent;
8082 
8083 	freeblks = freework->fw_freeblks;
8084 	parent = freework->fw_parent;
8085 	if (freework->fw_state & DELAYEDFREE)
8086 		freeblks->fb_cgwait--;
8087 	freework->fw_state |= COMPLETE;
8088 	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
8089 		WORKITEM_FREE(freework, D_FREEWORK);
8090 	if (parent) {
8091 		if (--parent->fw_ref == 0)
8092 			freework_enqueue(parent);
8093 		return;
8094 	}
8095 	if (--freeblks->fb_ref != 0)
8096 		return;
8097 	if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST | INPROGRESS)) ==
8098 	    ALLCOMPLETE && LIST_EMPTY(&freeblks->fb_jblkdephd))
8099 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
8100 }
8101 
8102 /*
8103  * This workitem routine performs the block de-allocation.
8104  * The workitem is added to the pending list after the updated
8105  * inode block has been written to disk.  As mentioned above,
8106  * checks regarding the number of blocks de-allocated (compared
8107  * to the number of blocks allocated for the file) are also
8108  * performed in this function.
8109  */
8110 static int
8111 handle_workitem_freeblocks(struct freeblks *freeblks, int flags)
8112 {
8113 	struct freework *freework;
8114 	struct newblk *newblk;
8115 	struct allocindir *aip;
8116 	struct ufsmount *ump;
8117 	struct worklist *wk;
8118 	u_long key;
8119 
8120 	KASSERT(LIST_EMPTY(&freeblks->fb_jblkdephd),
8121 	    ("handle_workitem_freeblocks: Journal entries not written."));
8122 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8123 	key = ffs_blkrelease_start(ump, freeblks->fb_devvp, freeblks->fb_inum);
8124 	ACQUIRE_LOCK(ump);
8125 	while ((wk = LIST_FIRST(&freeblks->fb_freeworkhd)) != NULL) {
8126 		WORKLIST_REMOVE(wk);
8127 		switch (wk->wk_type) {
8128 		case D_DIRREM:
8129 			wk->wk_state |= COMPLETE;
8130 			add_to_worklist(wk, 0);
8131 			continue;
8132 
8133 		case D_ALLOCDIRECT:
8134 			free_newblk(WK_NEWBLK(wk));
8135 			continue;
8136 
8137 		case D_ALLOCINDIR:
8138 			aip = WK_ALLOCINDIR(wk);
8139 			freework = NULL;
8140 			if (aip->ai_state & DELAYEDFREE) {
8141 				FREE_LOCK(ump);
8142 				freework = newfreework(ump, freeblks, NULL,
8143 				    aip->ai_lbn, aip->ai_newblkno,
8144 				    ump->um_fs->fs_frag, 0, 0);
8145 				ACQUIRE_LOCK(ump);
8146 			}
8147 			newblk = WK_NEWBLK(wk);
8148 			if (newblk->nb_jnewblk) {
8149 				freework->fw_jnewblk = newblk->nb_jnewblk;
8150 				newblk->nb_jnewblk->jn_dep = &freework->fw_list;
8151 				newblk->nb_jnewblk = NULL;
8152 			}
8153 			free_newblk(newblk);
8154 			continue;
8155 
8156 		case D_FREEWORK:
8157 			freework = WK_FREEWORK(wk);
8158 			if (freework->fw_lbn <= -UFS_NDADDR)
8159 				handle_workitem_indirblk(freework);
8160 			else
8161 				freework_freeblock(freework, key);
8162 			continue;
8163 		default:
8164 			panic("handle_workitem_freeblocks: Unknown type %s",
8165 			    TYPENAME(wk->wk_type));
8166 		}
8167 	}
8168 	if (freeblks->fb_ref != 0) {
8169 		freeblks->fb_state &= ~INPROGRESS;
8170 		wake_worklist(&freeblks->fb_list);
8171 		freeblks = NULL;
8172 	}
8173 	FREE_LOCK(ump);
8174 	ffs_blkrelease_finish(ump, key);
8175 	if (freeblks)
8176 		return handle_complete_freeblocks(freeblks, flags);
8177 	return (0);
8178 }
8179 
8180 /*
8181  * Handle completion of block free via truncate.  This allows fs_pending
8182  * to track the actual free block count more closely than if we only updated
8183  * it at the end.  We must be careful to handle cases where the block count
8184  * on free was incorrect.
8185  */
8186 static void
8187 freeblks_free(struct ufsmount *ump,
8188 	struct freeblks *freeblks,
8189 	int blocks)
8190 {
8191 	struct fs *fs;
8192 	ufs2_daddr_t remain;
8193 
8194 	UFS_LOCK(ump);
8195 	remain = -freeblks->fb_chkcnt;
8196 	freeblks->fb_chkcnt += blocks;
8197 	if (remain > 0) {
8198 		if (remain < blocks)
8199 			blocks = remain;
8200 		fs = ump->um_fs;
8201 		fs->fs_pendingblocks -= blocks;
8202 	}
8203 	UFS_UNLOCK(ump);
8204 }
8205 
8206 /*
8207  * Once all of the freework workitems are complete we can retire the
8208  * freeblocks dependency and any journal work awaiting completion.  This
8209  * can not be called until all other dependencies are stable on disk.
8210  */
8211 static int
8212 handle_complete_freeblocks(struct freeblks *freeblks, int flags)
8213 {
8214 	struct inodedep *inodedep;
8215 	struct inode *ip;
8216 	struct vnode *vp;
8217 	struct fs *fs;
8218 	struct ufsmount *ump;
8219 	ufs2_daddr_t spare;
8220 
8221 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8222 	fs = ump->um_fs;
8223 	flags = LK_EXCLUSIVE | flags;
8224 	spare = freeblks->fb_chkcnt;
8225 
8226 	/*
8227 	 * If we did not release the expected number of blocks we may have
8228 	 * to adjust the inode block count here.  Only do so if it wasn't
8229 	 * a truncation to zero and the modrev still matches.
8230 	 */
8231 	if (spare && freeblks->fb_len != 0) {
8232 		if (ffs_vgetf(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8233 		    flags, &vp, FFSV_FORCEINSMQ | FFSV_FORCEINODEDEP) != 0)
8234 			return (EBUSY);
8235 		ip = VTOI(vp);
8236 		if (ip->i_mode == 0) {
8237 			vgone(vp);
8238 		} else if (DIP(ip, i_modrev) == freeblks->fb_modrev) {
8239 			DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - spare);
8240 			UFS_INODE_SET_FLAG(ip, IN_CHANGE);
8241 			/*
8242 			 * We must wait so this happens before the
8243 			 * journal is reclaimed.
8244 			 */
8245 			ffs_update(vp, 1);
8246 		}
8247 		vput(vp);
8248 	}
8249 	if (spare < 0) {
8250 		UFS_LOCK(ump);
8251 		fs->fs_pendingblocks += spare;
8252 		UFS_UNLOCK(ump);
8253 	}
8254 #ifdef QUOTA
8255 	/* Handle spare. */
8256 	if (spare)
8257 		quotaadj(freeblks->fb_quota, ump, -spare);
8258 	quotarele(freeblks->fb_quota);
8259 #endif
8260 	ACQUIRE_LOCK(ump);
8261 	if (freeblks->fb_state & ONDEPLIST) {
8262 		inodedep_lookup(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8263 		    0, &inodedep);
8264 		TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks, fb_next);
8265 		freeblks->fb_state &= ~ONDEPLIST;
8266 		if (TAILQ_EMPTY(&inodedep->id_freeblklst))
8267 			free_inodedep(inodedep);
8268 	}
8269 	/*
8270 	 * All of the freeblock deps must be complete prior to this call
8271 	 * so it's now safe to complete earlier outstanding journal entries.
8272 	 */
8273 	handle_jwork(&freeblks->fb_jwork);
8274 	WORKITEM_FREE(freeblks, D_FREEBLKS);
8275 	FREE_LOCK(ump);
8276 	return (0);
8277 }
8278 
8279 /*
8280  * Release blocks associated with the freeblks and stored in the indirect
8281  * block dbn. If level is greater than SINGLE, the block is an indirect block
8282  * and recursive calls to indirtrunc must be used to cleanse other indirect
8283  * blocks.
8284  *
8285  * This handles partial and complete truncation of blocks.  Partial is noted
8286  * with goingaway == 0.  In this case the freework is completed after the
8287  * zero'd indirects are written to disk.  For full truncation the freework
8288  * is completed after the block is freed.
8289  */
8290 static void
8291 indir_trunc(struct freework *freework,
8292 	ufs2_daddr_t dbn,
8293 	ufs_lbn_t lbn)
8294 {
8295 	struct freework *nfreework;
8296 	struct workhead wkhd;
8297 	struct freeblks *freeblks;
8298 	struct buf *bp;
8299 	struct fs *fs;
8300 	struct indirdep *indirdep;
8301 	struct mount *mp;
8302 	struct ufsmount *ump;
8303 	ufs1_daddr_t *bap1;
8304 	ufs2_daddr_t nb, nnb, *bap2;
8305 	ufs_lbn_t lbnadd, nlbn;
8306 	u_long key;
8307 	int nblocks, ufs1fmt, freedblocks;
8308 	int goingaway, freedeps, needj, level, cnt, i, error;
8309 
8310 	freeblks = freework->fw_freeblks;
8311 	mp = freeblks->fb_list.wk_mp;
8312 	ump = VFSTOUFS(mp);
8313 	fs = ump->um_fs;
8314 	/*
8315 	 * Get buffer of block pointers to be freed.  There are three cases:
8316 	 *
8317 	 * 1) Partial truncate caches the indirdep pointer in the freework
8318 	 *    which provides us a back copy to the save bp which holds the
8319 	 *    pointers we want to clear.  When this completes the zero
8320 	 *    pointers are written to the real copy.
8321 	 * 2) The indirect is being completely truncated, cancel_indirdep()
8322 	 *    eliminated the real copy and placed the indirdep on the saved
8323 	 *    copy.  The indirdep and buf are discarded when this completes.
8324 	 * 3) The indirect was not in memory, we read a copy off of the disk
8325 	 *    using the devvp and drop and invalidate the buffer when we're
8326 	 *    done.
8327 	 */
8328 	goingaway = 1;
8329 	indirdep = NULL;
8330 	if (freework->fw_indir != NULL) {
8331 		goingaway = 0;
8332 		indirdep = freework->fw_indir;
8333 		bp = indirdep->ir_savebp;
8334 		if (bp == NULL || bp->b_blkno != dbn)
8335 			panic("indir_trunc: Bad saved buf %p blkno %jd",
8336 			    bp, (intmax_t)dbn);
8337 	} else if ((bp = incore(&freeblks->fb_devvp->v_bufobj, dbn)) != NULL) {
8338 		/*
8339 		 * The lock prevents the buf dep list from changing and
8340 	 	 * indirects on devvp should only ever have one dependency.
8341 		 */
8342 		indirdep = WK_INDIRDEP(LIST_FIRST(&bp->b_dep));
8343 		if (indirdep == NULL || (indirdep->ir_state & GOINGAWAY) == 0)
8344 			panic("indir_trunc: Bad indirdep %p from buf %p",
8345 			    indirdep, bp);
8346 	} else {
8347 		error = ffs_breadz(ump, freeblks->fb_devvp, dbn, dbn,
8348 		    (int)fs->fs_bsize, NULL, NULL, 0, NOCRED, 0, NULL, &bp);
8349 		if (error)
8350 			return;
8351 	}
8352 	ACQUIRE_LOCK(ump);
8353 	/* Protects against a race with complete_trunc_indir(). */
8354 	freework->fw_state &= ~INPROGRESS;
8355 	/*
8356 	 * If we have an indirdep we need to enforce the truncation order
8357 	 * and discard it when it is complete.
8358 	 */
8359 	if (indirdep) {
8360 		if (freework != TAILQ_FIRST(&indirdep->ir_trunc) &&
8361 		    !TAILQ_EMPTY(&indirdep->ir_trunc)) {
8362 			/*
8363 			 * Add the complete truncate to the list on the
8364 			 * indirdep to enforce in-order processing.
8365 			 */
8366 			if (freework->fw_indir == NULL)
8367 				TAILQ_INSERT_TAIL(&indirdep->ir_trunc,
8368 				    freework, fw_next);
8369 			FREE_LOCK(ump);
8370 			return;
8371 		}
8372 		/*
8373 		 * If we're goingaway, free the indirdep.  Otherwise it will
8374 		 * linger until the write completes.
8375 		 */
8376 		if (goingaway) {
8377 			KASSERT(indirdep->ir_savebp == bp,
8378 			    ("indir_trunc: losing ir_savebp %p",
8379 			    indirdep->ir_savebp));
8380 			indirdep->ir_savebp = NULL;
8381 			free_indirdep(indirdep);
8382 		}
8383 	}
8384 	FREE_LOCK(ump);
8385 	/* Initialize pointers depending on block size. */
8386 	if (ump->um_fstype == UFS1) {
8387 		bap1 = (ufs1_daddr_t *)bp->b_data;
8388 		nb = bap1[freework->fw_off];
8389 		ufs1fmt = 1;
8390 		bap2 = NULL;
8391 	} else {
8392 		bap2 = (ufs2_daddr_t *)bp->b_data;
8393 		nb = bap2[freework->fw_off];
8394 		ufs1fmt = 0;
8395 		bap1 = NULL;
8396 	}
8397 	level = lbn_level(lbn);
8398 	needj = MOUNTEDSUJ(UFSTOVFS(ump)) != 0;
8399 	lbnadd = lbn_offset(fs, level);
8400 	nblocks = btodb(fs->fs_bsize);
8401 	nfreework = freework;
8402 	freedeps = 0;
8403 	cnt = 0;
8404 	/*
8405 	 * Reclaim blocks.  Traverses into nested indirect levels and
8406 	 * arranges for the current level to be freed when subordinates
8407 	 * are free when journaling.
8408 	 */
8409 	key = ffs_blkrelease_start(ump, freeblks->fb_devvp, freeblks->fb_inum);
8410 	for (i = freework->fw_off; i < NINDIR(fs); i++, nb = nnb) {
8411 		if (UFS_CHECK_BLKNO(mp, freeblks->fb_inum, nb,
8412 		    fs->fs_bsize) != 0)
8413 			nb = 0;
8414 		if (i != NINDIR(fs) - 1) {
8415 			if (ufs1fmt)
8416 				nnb = bap1[i+1];
8417 			else
8418 				nnb = bap2[i+1];
8419 		} else
8420 			nnb = 0;
8421 		if (nb == 0)
8422 			continue;
8423 		cnt++;
8424 		if (level != 0) {
8425 			nlbn = (lbn + 1) - (i * lbnadd);
8426 			if (needj != 0) {
8427 				nfreework = newfreework(ump, freeblks, freework,
8428 				    nlbn, nb, fs->fs_frag, 0, 0);
8429 				freedeps++;
8430 			}
8431 			indir_trunc(nfreework, fsbtodb(fs, nb), nlbn);
8432 		} else {
8433 			struct freedep *freedep;
8434 
8435 			/*
8436 			 * Attempt to aggregate freedep dependencies for
8437 			 * all blocks being released to the same CG.
8438 			 */
8439 			LIST_INIT(&wkhd);
8440 			if (needj != 0 &&
8441 			    (nnb == 0 || (dtog(fs, nb) != dtog(fs, nnb)))) {
8442 				freedep = newfreedep(freework);
8443 				WORKLIST_INSERT_UNLOCKED(&wkhd,
8444 				    &freedep->fd_list);
8445 				freedeps++;
8446 			}
8447 			CTR3(KTR_SUJ,
8448 			    "indir_trunc: ino %jd blkno %jd size %d",
8449 			    freeblks->fb_inum, nb, fs->fs_bsize);
8450 			ffs_blkfree(ump, fs, freeblks->fb_devvp, nb,
8451 			    fs->fs_bsize, freeblks->fb_inum,
8452 			    freeblks->fb_vtype, &wkhd, key);
8453 		}
8454 	}
8455 	ffs_blkrelease_finish(ump, key);
8456 	if (goingaway) {
8457 		bp->b_flags |= B_INVAL | B_NOCACHE;
8458 		brelse(bp);
8459 	}
8460 	freedblocks = 0;
8461 	if (level == 0)
8462 		freedblocks = (nblocks * cnt);
8463 	if (needj == 0)
8464 		freedblocks += nblocks;
8465 	freeblks_free(ump, freeblks, freedblocks);
8466 	/*
8467 	 * If we are journaling set up the ref counts and offset so this
8468 	 * indirect can be completed when its children are free.
8469 	 */
8470 	if (needj) {
8471 		ACQUIRE_LOCK(ump);
8472 		freework->fw_off = i;
8473 		freework->fw_ref += freedeps;
8474 		freework->fw_ref -= NINDIR(fs) + 1;
8475 		if (level == 0)
8476 			freeblks->fb_cgwait += freedeps;
8477 		if (freework->fw_ref == 0)
8478 			freework_freeblock(freework, SINGLETON_KEY);
8479 		FREE_LOCK(ump);
8480 		return;
8481 	}
8482 	/*
8483 	 * If we're not journaling we can free the indirect now.
8484 	 */
8485 	dbn = dbtofsb(fs, dbn);
8486 	CTR3(KTR_SUJ,
8487 	    "indir_trunc 2: ino %jd blkno %jd size %d",
8488 	    freeblks->fb_inum, dbn, fs->fs_bsize);
8489 	ffs_blkfree(ump, fs, freeblks->fb_devvp, dbn, fs->fs_bsize,
8490 	    freeblks->fb_inum, freeblks->fb_vtype, NULL, SINGLETON_KEY);
8491 	/* Non SUJ softdep does single-threaded truncations. */
8492 	if (freework->fw_blkno == dbn) {
8493 		freework->fw_state |= ALLCOMPLETE;
8494 		ACQUIRE_LOCK(ump);
8495 		handle_written_freework(freework);
8496 		FREE_LOCK(ump);
8497 	}
8498 	return;
8499 }
8500 
8501 /*
8502  * Cancel an allocindir when it is removed via truncation.  When bp is not
8503  * NULL the indirect never appeared on disk and is scheduled to be freed
8504  * independently of the indir so we can more easily track journal work.
8505  */
8506 static void
8507 cancel_allocindir(
8508 	struct allocindir *aip,
8509 	struct buf *bp,
8510 	struct freeblks *freeblks,
8511 	int trunc)
8512 {
8513 	struct indirdep *indirdep;
8514 	struct freefrag *freefrag;
8515 	struct newblk *newblk;
8516 
8517 	newblk = (struct newblk *)aip;
8518 	LIST_REMOVE(aip, ai_next);
8519 	/*
8520 	 * We must eliminate the pointer in bp if it must be freed on its
8521 	 * own due to partial truncate or pending journal work.
8522 	 */
8523 	if (bp && (trunc || newblk->nb_jnewblk)) {
8524 		/*
8525 		 * Clear the pointer and mark the aip to be freed
8526 		 * directly if it never existed on disk.
8527 		 */
8528 		aip->ai_state |= DELAYEDFREE;
8529 		indirdep = aip->ai_indirdep;
8530 		if (indirdep->ir_state & UFS1FMT)
8531 			((ufs1_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8532 		else
8533 			((ufs2_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8534 	}
8535 	/*
8536 	 * When truncating the previous pointer will be freed via
8537 	 * savedbp.  Eliminate the freefrag which would dup free.
8538 	 */
8539 	if (trunc && (freefrag = newblk->nb_freefrag) != NULL) {
8540 		newblk->nb_freefrag = NULL;
8541 		if (freefrag->ff_jdep)
8542 			cancel_jfreefrag(
8543 			    WK_JFREEFRAG(freefrag->ff_jdep));
8544 		jwork_move(&freeblks->fb_jwork, &freefrag->ff_jwork);
8545 		WORKITEM_FREE(freefrag, D_FREEFRAG);
8546 	}
8547 	/*
8548 	 * If the journal hasn't been written the jnewblk must be passed
8549 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
8550 	 * this by leaving the journal dependency on the newblk to be freed
8551 	 * when a freework is created in handle_workitem_freeblocks().
8552 	 */
8553 	cancel_newblk(newblk, NULL, &freeblks->fb_jwork);
8554 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
8555 }
8556 
8557 /*
8558  * Create the mkdir dependencies for . and .. in a new directory.  Link them
8559  * in to a newdirblk so any subsequent additions are tracked properly.  The
8560  * caller is responsible for adding the mkdir1 dependency to the journal
8561  * and updating id_mkdiradd.  This function returns with the per-filesystem
8562  * lock held.
8563  */
8564 static struct mkdir *
8565 setup_newdir(
8566 	struct diradd *dap,
8567 	ino_t newinum,
8568 	ino_t dinum,
8569 	struct buf *newdirbp,
8570 	struct mkdir **mkdirp)
8571 {
8572 	struct newblk *newblk;
8573 	struct pagedep *pagedep;
8574 	struct inodedep *inodedep;
8575 	struct newdirblk *newdirblk;
8576 	struct mkdir *mkdir1, *mkdir2;
8577 	struct worklist *wk;
8578 	struct jaddref *jaddref;
8579 	struct ufsmount *ump;
8580 	struct mount *mp;
8581 
8582 	mp = dap->da_list.wk_mp;
8583 	ump = VFSTOUFS(mp);
8584 	newdirblk = malloc(sizeof(struct newdirblk), M_NEWDIRBLK,
8585 	    M_SOFTDEP_FLAGS);
8586 	workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8587 	LIST_INIT(&newdirblk->db_mkdir);
8588 	mkdir1 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8589 	workitem_alloc(&mkdir1->md_list, D_MKDIR, mp);
8590 	mkdir1->md_state = ATTACHED | MKDIR_BODY;
8591 	mkdir1->md_diradd = dap;
8592 	mkdir1->md_jaddref = NULL;
8593 	mkdir2 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8594 	workitem_alloc(&mkdir2->md_list, D_MKDIR, mp);
8595 	mkdir2->md_state = ATTACHED | MKDIR_PARENT;
8596 	mkdir2->md_diradd = dap;
8597 	mkdir2->md_jaddref = NULL;
8598 	if (MOUNTEDSUJ(mp) == 0) {
8599 		mkdir1->md_state |= DEPCOMPLETE;
8600 		mkdir2->md_state |= DEPCOMPLETE;
8601 	}
8602 	/*
8603 	 * Dependency on "." and ".." being written to disk.
8604 	 */
8605 	mkdir1->md_buf = newdirbp;
8606 	ACQUIRE_LOCK(VFSTOUFS(mp));
8607 	LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir1, md_mkdirs);
8608 	/*
8609 	 * We must link the pagedep, allocdirect, and newdirblk for
8610 	 * the initial file page so the pointer to the new directory
8611 	 * is not written until the directory contents are live and
8612 	 * any subsequent additions are not marked live until the
8613 	 * block is reachable via the inode.
8614 	 */
8615 	if (pagedep_lookup(mp, newdirbp, newinum, 0, 0, &pagedep) == 0)
8616 		panic("setup_newdir: lost pagedep");
8617 	LIST_FOREACH(wk, &newdirbp->b_dep, wk_list)
8618 		if (wk->wk_type == D_ALLOCDIRECT)
8619 			break;
8620 	if (wk == NULL)
8621 		panic("setup_newdir: lost allocdirect");
8622 	if (pagedep->pd_state & NEWBLOCK)
8623 		panic("setup_newdir: NEWBLOCK already set");
8624 	newblk = WK_NEWBLK(wk);
8625 	pagedep->pd_state |= NEWBLOCK;
8626 	pagedep->pd_newdirblk = newdirblk;
8627 	newdirblk->db_pagedep = pagedep;
8628 	WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8629 	WORKLIST_INSERT(&newdirblk->db_mkdir, &mkdir1->md_list);
8630 	/*
8631 	 * Look up the inodedep for the parent directory so that we
8632 	 * can link mkdir2 into the pending dotdot jaddref or
8633 	 * the inode write if there is none.  If the inode is
8634 	 * ALLCOMPLETE and no jaddref is present all dependencies have
8635 	 * been satisfied and mkdir2 can be freed.
8636 	 */
8637 	inodedep_lookup(mp, dinum, 0, &inodedep);
8638 	if (MOUNTEDSUJ(mp)) {
8639 		if (inodedep == NULL)
8640 			panic("setup_newdir: Lost parent.");
8641 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8642 		    inoreflst);
8643 		KASSERT(jaddref != NULL && jaddref->ja_parent == newinum &&
8644 		    (jaddref->ja_state & MKDIR_PARENT),
8645 		    ("setup_newdir: bad dotdot jaddref %p", jaddref));
8646 		LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8647 		mkdir2->md_jaddref = jaddref;
8648 		jaddref->ja_mkdir = mkdir2;
8649 	} else if (inodedep == NULL ||
8650 	    (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
8651 		dap->da_state &= ~MKDIR_PARENT;
8652 		WORKITEM_FREE(mkdir2, D_MKDIR);
8653 		mkdir2 = NULL;
8654 	} else {
8655 		LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8656 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir2->md_list);
8657 	}
8658 	*mkdirp = mkdir2;
8659 
8660 	return (mkdir1);
8661 }
8662 
8663 /*
8664  * Directory entry addition dependencies.
8665  *
8666  * When adding a new directory entry, the inode (with its incremented link
8667  * count) must be written to disk before the directory entry's pointer to it.
8668  * Also, if the inode is newly allocated, the corresponding freemap must be
8669  * updated (on disk) before the directory entry's pointer. These requirements
8670  * are met via undo/redo on the directory entry's pointer, which consists
8671  * simply of the inode number.
8672  *
8673  * As directory entries are added and deleted, the free space within a
8674  * directory block can become fragmented.  The ufs filesystem will compact
8675  * a fragmented directory block to make space for a new entry. When this
8676  * occurs, the offsets of previously added entries change. Any "diradd"
8677  * dependency structures corresponding to these entries must be updated with
8678  * the new offsets.
8679  */
8680 
8681 /*
8682  * This routine is called after the in-memory inode's link
8683  * count has been incremented, but before the directory entry's
8684  * pointer to the inode has been set.
8685  */
8686 int
8687 softdep_setup_directory_add(
8688 	struct buf *bp,		/* buffer containing directory block */
8689 	struct inode *dp,	/* inode for directory */
8690 	off_t diroffset,	/* offset of new entry in directory */
8691 	ino_t newinum,		/* inode referenced by new directory entry */
8692 	struct buf *newdirbp,	/* non-NULL => contents of new mkdir */
8693 	int isnewblk)		/* entry is in a newly allocated block */
8694 {
8695 	int offset;		/* offset of new entry within directory block */
8696 	ufs_lbn_t lbn;		/* block in directory containing new entry */
8697 	struct fs *fs;
8698 	struct diradd *dap;
8699 	struct newblk *newblk;
8700 	struct pagedep *pagedep;
8701 	struct inodedep *inodedep;
8702 	struct newdirblk *newdirblk;
8703 	struct mkdir *mkdir1, *mkdir2;
8704 	struct jaddref *jaddref;
8705 	struct ufsmount *ump;
8706 	struct mount *mp;
8707 	int isindir;
8708 
8709 	mp = ITOVFS(dp);
8710 	ump = VFSTOUFS(mp);
8711 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8712 	    ("softdep_setup_directory_add called on non-softdep filesystem"));
8713 	/*
8714 	 * Whiteouts have no dependencies.
8715 	 */
8716 	if (newinum == UFS_WINO) {
8717 		if (newdirbp != NULL)
8718 			bdwrite(newdirbp);
8719 		return (0);
8720 	}
8721 	jaddref = NULL;
8722 	mkdir1 = mkdir2 = NULL;
8723 	fs = ump->um_fs;
8724 	lbn = lblkno(fs, diroffset);
8725 	offset = blkoff(fs, diroffset);
8726 	dap = malloc(sizeof(struct diradd), M_DIRADD,
8727 		M_SOFTDEP_FLAGS|M_ZERO);
8728 	workitem_alloc(&dap->da_list, D_DIRADD, mp);
8729 	dap->da_offset = offset;
8730 	dap->da_newinum = newinum;
8731 	dap->da_state = ATTACHED;
8732 	LIST_INIT(&dap->da_jwork);
8733 	isindir = bp->b_lblkno >= UFS_NDADDR;
8734 	newdirblk = NULL;
8735 	if (isnewblk &&
8736 	    (isindir ? blkoff(fs, diroffset) : fragoff(fs, diroffset)) == 0) {
8737 		newdirblk = malloc(sizeof(struct newdirblk),
8738 		    M_NEWDIRBLK, M_SOFTDEP_FLAGS);
8739 		workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8740 		LIST_INIT(&newdirblk->db_mkdir);
8741 	}
8742 	/*
8743 	 * If we're creating a new directory setup the dependencies and set
8744 	 * the dap state to wait for them.  Otherwise it's COMPLETE and
8745 	 * we can move on.
8746 	 */
8747 	if (newdirbp == NULL) {
8748 		dap->da_state |= DEPCOMPLETE;
8749 		ACQUIRE_LOCK(ump);
8750 	} else {
8751 		dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
8752 		mkdir1 = setup_newdir(dap, newinum, dp->i_number, newdirbp,
8753 		    &mkdir2);
8754 	}
8755 	/*
8756 	 * Link into parent directory pagedep to await its being written.
8757 	 */
8758 	pagedep_lookup(mp, bp, dp->i_number, lbn, DEPALLOC, &pagedep);
8759 #ifdef INVARIANTS
8760 	if (diradd_lookup(pagedep, offset) != NULL)
8761 		panic("softdep_setup_directory_add: %p already at off %d\n",
8762 		    diradd_lookup(pagedep, offset), offset);
8763 #endif
8764 	dap->da_pagedep = pagedep;
8765 	LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
8766 	    da_pdlist);
8767 	inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
8768 	/*
8769 	 * If we're journaling, link the diradd into the jaddref so it
8770 	 * may be completed after the journal entry is written.  Otherwise,
8771 	 * link the diradd into its inodedep.  If the inode is not yet
8772 	 * written place it on the bufwait list, otherwise do the post-inode
8773 	 * write processing to put it on the id_pendinghd list.
8774 	 */
8775 	if (MOUNTEDSUJ(mp)) {
8776 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8777 		    inoreflst);
8778 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
8779 		    ("softdep_setup_directory_add: bad jaddref %p", jaddref));
8780 		jaddref->ja_diroff = diroffset;
8781 		jaddref->ja_diradd = dap;
8782 		add_to_journal(&jaddref->ja_list);
8783 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
8784 		diradd_inode_written(dap, inodedep);
8785 	else
8786 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
8787 	/*
8788 	 * Add the journal entries for . and .. links now that the primary
8789 	 * link is written.
8790 	 */
8791 	if (mkdir1 != NULL && MOUNTEDSUJ(mp)) {
8792 		jaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
8793 		    inoreflst, if_deps);
8794 		KASSERT(jaddref != NULL &&
8795 		    jaddref->ja_ino == jaddref->ja_parent &&
8796 		    (jaddref->ja_state & MKDIR_BODY),
8797 		    ("softdep_setup_directory_add: bad dot jaddref %p",
8798 		    jaddref));
8799 		mkdir1->md_jaddref = jaddref;
8800 		jaddref->ja_mkdir = mkdir1;
8801 		/*
8802 		 * It is important that the dotdot journal entry
8803 		 * is added prior to the dot entry since dot writes
8804 		 * both the dot and dotdot links.  These both must
8805 		 * be added after the primary link for the journal
8806 		 * to remain consistent.
8807 		 */
8808 		add_to_journal(&mkdir2->md_jaddref->ja_list);
8809 		add_to_journal(&jaddref->ja_list);
8810 	}
8811 	/*
8812 	 * If we are adding a new directory remember this diradd so that if
8813 	 * we rename it we can keep the dot and dotdot dependencies.  If
8814 	 * we are adding a new name for an inode that has a mkdiradd we
8815 	 * must be in rename and we have to move the dot and dotdot
8816 	 * dependencies to this new name.  The old name is being orphaned
8817 	 * soon.
8818 	 */
8819 	if (mkdir1 != NULL) {
8820 		if (inodedep->id_mkdiradd != NULL)
8821 			panic("softdep_setup_directory_add: Existing mkdir");
8822 		inodedep->id_mkdiradd = dap;
8823 	} else if (inodedep->id_mkdiradd)
8824 		merge_diradd(inodedep, dap);
8825 	if (newdirblk != NULL) {
8826 		/*
8827 		 * There is nothing to do if we are already tracking
8828 		 * this block.
8829 		 */
8830 		if ((pagedep->pd_state & NEWBLOCK) != 0) {
8831 			WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
8832 			FREE_LOCK(ump);
8833 			return (0);
8834 		}
8835 		if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk)
8836 		    == 0)
8837 			panic("softdep_setup_directory_add: lost entry");
8838 		WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8839 		pagedep->pd_state |= NEWBLOCK;
8840 		pagedep->pd_newdirblk = newdirblk;
8841 		newdirblk->db_pagedep = pagedep;
8842 		FREE_LOCK(ump);
8843 		/*
8844 		 * If we extended into an indirect signal direnter to sync.
8845 		 */
8846 		if (isindir)
8847 			return (1);
8848 		return (0);
8849 	}
8850 	FREE_LOCK(ump);
8851 	return (0);
8852 }
8853 
8854 /*
8855  * This procedure is called to change the offset of a directory
8856  * entry when compacting a directory block which must be owned
8857  * exclusively by the caller. Note that the actual entry movement
8858  * must be done in this procedure to ensure that no I/O completions
8859  * occur while the move is in progress.
8860  */
8861 void
8862 softdep_change_directoryentry_offset(
8863 	struct buf *bp,		/* Buffer holding directory block. */
8864 	struct inode *dp,	/* inode for directory */
8865 	caddr_t base,		/* address of dp->i_offset */
8866 	caddr_t oldloc,		/* address of old directory location */
8867 	caddr_t newloc,		/* address of new directory location */
8868 	int entrysize)		/* size of directory entry */
8869 {
8870 	int offset, oldoffset, newoffset;
8871 	struct pagedep *pagedep;
8872 	struct jmvref *jmvref;
8873 	struct diradd *dap;
8874 	struct direct *de;
8875 	struct mount *mp;
8876 	struct ufsmount *ump;
8877 	ufs_lbn_t lbn;
8878 	int flags;
8879 
8880 	mp = ITOVFS(dp);
8881 	ump = VFSTOUFS(mp);
8882 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8883 	    ("softdep_change_directoryentry_offset called on "
8884 	     "non-softdep filesystem"));
8885 	de = (struct direct *)oldloc;
8886 	jmvref = NULL;
8887 	flags = 0;
8888 	/*
8889 	 * Moves are always journaled as it would be too complex to
8890 	 * determine if any affected adds or removes are present in the
8891 	 * journal.
8892 	 */
8893 	if (MOUNTEDSUJ(mp)) {
8894 		flags = DEPALLOC;
8895 		jmvref = newjmvref(dp, de->d_ino,
8896 		    I_OFFSET(dp) + (oldloc - base),
8897 		    I_OFFSET(dp) + (newloc - base));
8898 	}
8899 	lbn = lblkno(ump->um_fs, I_OFFSET(dp));
8900 	offset = blkoff(ump->um_fs, I_OFFSET(dp));
8901 	oldoffset = offset + (oldloc - base);
8902 	newoffset = offset + (newloc - base);
8903 	ACQUIRE_LOCK(ump);
8904 	if (pagedep_lookup(mp, bp, dp->i_number, lbn, flags, &pagedep) == 0)
8905 		goto done;
8906 	dap = diradd_lookup(pagedep, oldoffset);
8907 	if (dap) {
8908 		dap->da_offset = newoffset;
8909 		newoffset = DIRADDHASH(newoffset);
8910 		oldoffset = DIRADDHASH(oldoffset);
8911 		if ((dap->da_state & ALLCOMPLETE) != ALLCOMPLETE &&
8912 		    newoffset != oldoffset) {
8913 			LIST_REMOVE(dap, da_pdlist);
8914 			LIST_INSERT_HEAD(&pagedep->pd_diraddhd[newoffset],
8915 			    dap, da_pdlist);
8916 		}
8917 	}
8918 done:
8919 	if (jmvref) {
8920 		jmvref->jm_pagedep = pagedep;
8921 		LIST_INSERT_HEAD(&pagedep->pd_jmvrefhd, jmvref, jm_deps);
8922 		add_to_journal(&jmvref->jm_list);
8923 	}
8924 	bcopy(oldloc, newloc, entrysize);
8925 	FREE_LOCK(ump);
8926 }
8927 
8928 /*
8929  * Move the mkdir dependencies and journal work from one diradd to another
8930  * when renaming a directory.  The new name must depend on the mkdir deps
8931  * completing as the old name did.  Directories can only have one valid link
8932  * at a time so one must be canonical.
8933  */
8934 static void
8935 merge_diradd(struct inodedep *inodedep, struct diradd *newdap)
8936 {
8937 	struct diradd *olddap;
8938 	struct mkdir *mkdir, *nextmd;
8939 	struct ufsmount *ump;
8940 	short state;
8941 
8942 	olddap = inodedep->id_mkdiradd;
8943 	inodedep->id_mkdiradd = newdap;
8944 	if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8945 		newdap->da_state &= ~DEPCOMPLETE;
8946 		ump = VFSTOUFS(inodedep->id_list.wk_mp);
8947 		for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
8948 		     mkdir = nextmd) {
8949 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
8950 			if (mkdir->md_diradd != olddap)
8951 				continue;
8952 			mkdir->md_diradd = newdap;
8953 			state = mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY);
8954 			newdap->da_state |= state;
8955 			olddap->da_state &= ~state;
8956 			if ((olddap->da_state &
8957 			    (MKDIR_PARENT | MKDIR_BODY)) == 0)
8958 				break;
8959 		}
8960 		if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8961 			panic("merge_diradd: unfound ref");
8962 	}
8963 	/*
8964 	 * Any mkdir related journal items are not safe to be freed until
8965 	 * the new name is stable.
8966 	 */
8967 	jwork_move(&newdap->da_jwork, &olddap->da_jwork);
8968 	olddap->da_state |= DEPCOMPLETE;
8969 	complete_diradd(olddap);
8970 }
8971 
8972 /*
8973  * Move the diradd to the pending list when all diradd dependencies are
8974  * complete.
8975  */
8976 static void
8977 complete_diradd(struct diradd *dap)
8978 {
8979 	struct pagedep *pagedep;
8980 
8981 	if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
8982 		if (dap->da_state & DIRCHG)
8983 			pagedep = dap->da_previous->dm_pagedep;
8984 		else
8985 			pagedep = dap->da_pagedep;
8986 		LIST_REMOVE(dap, da_pdlist);
8987 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
8988 	}
8989 }
8990 
8991 /*
8992  * Cancel a diradd when a dirrem overlaps with it.  We must cancel the journal
8993  * add entries and conditionally journal the remove.
8994  */
8995 static void
8996 cancel_diradd(
8997 	struct diradd *dap,
8998 	struct dirrem *dirrem,
8999 	struct jremref *jremref,
9000 	struct jremref *dotremref,
9001 	struct jremref *dotdotremref)
9002 {
9003 	struct inodedep *inodedep;
9004 	struct jaddref *jaddref;
9005 	struct inoref *inoref;
9006 	struct ufsmount *ump;
9007 	struct mkdir *mkdir;
9008 
9009 	/*
9010 	 * If no remove references were allocated we're on a non-journaled
9011 	 * filesystem and can skip the cancel step.
9012 	 */
9013 	if (jremref == NULL) {
9014 		free_diradd(dap, NULL);
9015 		return;
9016 	}
9017 	/*
9018 	 * Cancel the primary name an free it if it does not require
9019 	 * journaling.
9020 	 */
9021 	if (inodedep_lookup(dap->da_list.wk_mp, dap->da_newinum,
9022 	    0, &inodedep) != 0) {
9023 		/* Abort the addref that reference this diradd.  */
9024 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
9025 			if (inoref->if_list.wk_type != D_JADDREF)
9026 				continue;
9027 			jaddref = (struct jaddref *)inoref;
9028 			if (jaddref->ja_diradd != dap)
9029 				continue;
9030 			if (cancel_jaddref(jaddref, inodedep,
9031 			    &dirrem->dm_jwork) == 0) {
9032 				free_jremref(jremref);
9033 				jremref = NULL;
9034 			}
9035 			break;
9036 		}
9037 	}
9038 	/*
9039 	 * Cancel subordinate names and free them if they do not require
9040 	 * journaling.
9041 	 */
9042 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
9043 		ump = VFSTOUFS(dap->da_list.wk_mp);
9044 		LIST_FOREACH(mkdir, &ump->softdep_mkdirlisthd, md_mkdirs) {
9045 			if (mkdir->md_diradd != dap)
9046 				continue;
9047 			if ((jaddref = mkdir->md_jaddref) == NULL)
9048 				continue;
9049 			mkdir->md_jaddref = NULL;
9050 			if (mkdir->md_state & MKDIR_PARENT) {
9051 				if (cancel_jaddref(jaddref, NULL,
9052 				    &dirrem->dm_jwork) == 0) {
9053 					free_jremref(dotdotremref);
9054 					dotdotremref = NULL;
9055 				}
9056 			} else {
9057 				if (cancel_jaddref(jaddref, inodedep,
9058 				    &dirrem->dm_jwork) == 0) {
9059 					free_jremref(dotremref);
9060 					dotremref = NULL;
9061 				}
9062 			}
9063 		}
9064 	}
9065 
9066 	if (jremref)
9067 		journal_jremref(dirrem, jremref, inodedep);
9068 	if (dotremref)
9069 		journal_jremref(dirrem, dotremref, inodedep);
9070 	if (dotdotremref)
9071 		journal_jremref(dirrem, dotdotremref, NULL);
9072 	jwork_move(&dirrem->dm_jwork, &dap->da_jwork);
9073 	free_diradd(dap, &dirrem->dm_jwork);
9074 }
9075 
9076 /*
9077  * Free a diradd dependency structure.
9078  */
9079 static void
9080 free_diradd(struct diradd *dap, struct workhead *wkhd)
9081 {
9082 	struct dirrem *dirrem;
9083 	struct pagedep *pagedep;
9084 	struct inodedep *inodedep;
9085 	struct mkdir *mkdir, *nextmd;
9086 	struct ufsmount *ump;
9087 
9088 	ump = VFSTOUFS(dap->da_list.wk_mp);
9089 	LOCK_OWNED(ump);
9090 	LIST_REMOVE(dap, da_pdlist);
9091 	if (dap->da_state & ONWORKLIST)
9092 		WORKLIST_REMOVE(&dap->da_list);
9093 	if ((dap->da_state & DIRCHG) == 0) {
9094 		pagedep = dap->da_pagedep;
9095 	} else {
9096 		dirrem = dap->da_previous;
9097 		pagedep = dirrem->dm_pagedep;
9098 		dirrem->dm_dirinum = pagedep->pd_ino;
9099 		dirrem->dm_state |= COMPLETE;
9100 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9101 			add_to_worklist(&dirrem->dm_list, 0);
9102 	}
9103 	if (inodedep_lookup(pagedep->pd_list.wk_mp, dap->da_newinum,
9104 	    0, &inodedep) != 0)
9105 		if (inodedep->id_mkdiradd == dap)
9106 			inodedep->id_mkdiradd = NULL;
9107 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
9108 		for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
9109 		     mkdir = nextmd) {
9110 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
9111 			if (mkdir->md_diradd != dap)
9112 				continue;
9113 			dap->da_state &=
9114 			    ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
9115 			LIST_REMOVE(mkdir, md_mkdirs);
9116 			if (mkdir->md_state & ONWORKLIST)
9117 				WORKLIST_REMOVE(&mkdir->md_list);
9118 			if (mkdir->md_jaddref != NULL)
9119 				panic("free_diradd: Unexpected jaddref");
9120 			WORKITEM_FREE(mkdir, D_MKDIR);
9121 			if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
9122 				break;
9123 		}
9124 		if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
9125 			panic("free_diradd: unfound ref");
9126 	}
9127 	if (inodedep)
9128 		free_inodedep(inodedep);
9129 	/*
9130 	 * Free any journal segments waiting for the directory write.
9131 	 */
9132 	handle_jwork(&dap->da_jwork);
9133 	WORKITEM_FREE(dap, D_DIRADD);
9134 }
9135 
9136 /*
9137  * Directory entry removal dependencies.
9138  *
9139  * When removing a directory entry, the entry's inode pointer must be
9140  * zero'ed on disk before the corresponding inode's link count is decremented
9141  * (possibly freeing the inode for re-use). This dependency is handled by
9142  * updating the directory entry but delaying the inode count reduction until
9143  * after the directory block has been written to disk. After this point, the
9144  * inode count can be decremented whenever it is convenient.
9145  */
9146 
9147 /*
9148  * This routine should be called immediately after removing
9149  * a directory entry.  The inode's link count should not be
9150  * decremented by the calling procedure -- the soft updates
9151  * code will do this task when it is safe.
9152  */
9153 void
9154 softdep_setup_remove(
9155 	struct buf *bp,		/* buffer containing directory block */
9156 	struct inode *dp,	/* inode for the directory being modified */
9157 	struct inode *ip,	/* inode for directory entry being removed */
9158 	int isrmdir)		/* indicates if doing RMDIR */
9159 {
9160 	struct dirrem *dirrem, *prevdirrem;
9161 	struct inodedep *inodedep;
9162 	struct ufsmount *ump;
9163 	int direct;
9164 
9165 	ump = ITOUMP(ip);
9166 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9167 	    ("softdep_setup_remove called on non-softdep filesystem"));
9168 	/*
9169 	 * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.  We want
9170 	 * newdirrem() to setup the full directory remove which requires
9171 	 * isrmdir > 1.
9172 	 */
9173 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9174 	/*
9175 	 * Add the dirrem to the inodedep's pending remove list for quick
9176 	 * discovery later.
9177 	 */
9178 	if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0)
9179 		panic("softdep_setup_remove: Lost inodedep.");
9180 	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
9181 	dirrem->dm_state |= ONDEPLIST;
9182 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9183 
9184 	/*
9185 	 * If the COMPLETE flag is clear, then there were no active
9186 	 * entries and we want to roll back to a zeroed entry until
9187 	 * the new inode is committed to disk. If the COMPLETE flag is
9188 	 * set then we have deleted an entry that never made it to
9189 	 * disk. If the entry we deleted resulted from a name change,
9190 	 * then the old name still resides on disk. We cannot delete
9191 	 * its inode (returned to us in prevdirrem) until the zeroed
9192 	 * directory entry gets to disk. The new inode has never been
9193 	 * referenced on the disk, so can be deleted immediately.
9194 	 */
9195 	if ((dirrem->dm_state & COMPLETE) == 0) {
9196 		LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
9197 		    dm_next);
9198 		FREE_LOCK(ump);
9199 	} else {
9200 		if (prevdirrem != NULL)
9201 			LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
9202 			    prevdirrem, dm_next);
9203 		dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
9204 		direct = LIST_EMPTY(&dirrem->dm_jremrefhd);
9205 		FREE_LOCK(ump);
9206 		if (direct)
9207 			handle_workitem_remove(dirrem, 0);
9208 	}
9209 }
9210 
9211 /*
9212  * Check for an entry matching 'offset' on both the pd_dirraddhd list and the
9213  * pd_pendinghd list of a pagedep.
9214  */
9215 static struct diradd *
9216 diradd_lookup(struct pagedep *pagedep, int offset)
9217 {
9218 	struct diradd *dap;
9219 
9220 	LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
9221 		if (dap->da_offset == offset)
9222 			return (dap);
9223 	LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
9224 		if (dap->da_offset == offset)
9225 			return (dap);
9226 	return (NULL);
9227 }
9228 
9229 /*
9230  * Search for a .. diradd dependency in a directory that is being removed.
9231  * If the directory was renamed to a new parent we have a diradd rather
9232  * than a mkdir for the .. entry.  We need to cancel it now before
9233  * it is found in truncate().
9234  */
9235 static struct jremref *
9236 cancel_diradd_dotdot(struct inode *ip,
9237 	struct dirrem *dirrem,
9238 	struct jremref *jremref)
9239 {
9240 	struct pagedep *pagedep;
9241 	struct diradd *dap;
9242 	struct worklist *wk;
9243 
9244 	if (pagedep_lookup(ITOVFS(ip), NULL, ip->i_number, 0, 0, &pagedep) == 0)
9245 		return (jremref);
9246 	dap = diradd_lookup(pagedep, DOTDOT_OFFSET);
9247 	if (dap == NULL)
9248 		return (jremref);
9249 	cancel_diradd(dap, dirrem, jremref, NULL, NULL);
9250 	/*
9251 	 * Mark any journal work as belonging to the parent so it is freed
9252 	 * with the .. reference.
9253 	 */
9254 	LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9255 		wk->wk_state |= MKDIR_PARENT;
9256 	return (NULL);
9257 }
9258 
9259 /*
9260  * Cancel the MKDIR_PARENT mkdir component of a diradd when we're going to
9261  * replace it with a dirrem/diradd pair as a result of re-parenting a
9262  * directory.  This ensures that we don't simultaneously have a mkdir and
9263  * a diradd for the same .. entry.
9264  */
9265 static struct jremref *
9266 cancel_mkdir_dotdot(struct inode *ip,
9267 	struct dirrem *dirrem,
9268 	struct jremref *jremref)
9269 {
9270 	struct inodedep *inodedep;
9271 	struct jaddref *jaddref;
9272 	struct ufsmount *ump;
9273 	struct mkdir *mkdir;
9274 	struct diradd *dap;
9275 	struct mount *mp;
9276 
9277 	mp = ITOVFS(ip);
9278 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9279 		return (jremref);
9280 	dap = inodedep->id_mkdiradd;
9281 	if (dap == NULL || (dap->da_state & MKDIR_PARENT) == 0)
9282 		return (jremref);
9283 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
9284 	for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
9285 	    mkdir = LIST_NEXT(mkdir, md_mkdirs))
9286 		if (mkdir->md_diradd == dap && mkdir->md_state & MKDIR_PARENT)
9287 			break;
9288 	if (mkdir == NULL)
9289 		panic("cancel_mkdir_dotdot: Unable to find mkdir\n");
9290 	if ((jaddref = mkdir->md_jaddref) != NULL) {
9291 		mkdir->md_jaddref = NULL;
9292 		jaddref->ja_state &= ~MKDIR_PARENT;
9293 		if (inodedep_lookup(mp, jaddref->ja_ino, 0, &inodedep) == 0)
9294 			panic("cancel_mkdir_dotdot: Lost parent inodedep");
9295 		if (cancel_jaddref(jaddref, inodedep, &dirrem->dm_jwork)) {
9296 			journal_jremref(dirrem, jremref, inodedep);
9297 			jremref = NULL;
9298 		}
9299 	}
9300 	if (mkdir->md_state & ONWORKLIST)
9301 		WORKLIST_REMOVE(&mkdir->md_list);
9302 	mkdir->md_state |= ALLCOMPLETE;
9303 	complete_mkdir(mkdir);
9304 	return (jremref);
9305 }
9306 
9307 static void
9308 journal_jremref(struct dirrem *dirrem,
9309 	struct jremref *jremref,
9310 	struct inodedep *inodedep)
9311 {
9312 
9313 	if (inodedep == NULL)
9314 		if (inodedep_lookup(jremref->jr_list.wk_mp,
9315 		    jremref->jr_ref.if_ino, 0, &inodedep) == 0)
9316 			panic("journal_jremref: Lost inodedep");
9317 	LIST_INSERT_HEAD(&dirrem->dm_jremrefhd, jremref, jr_deps);
9318 	TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
9319 	add_to_journal(&jremref->jr_list);
9320 }
9321 
9322 static void
9323 dirrem_journal(
9324 	struct dirrem *dirrem,
9325 	struct jremref *jremref,
9326 	struct jremref *dotremref,
9327 	struct jremref *dotdotremref)
9328 {
9329 	struct inodedep *inodedep;
9330 
9331 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino, 0,
9332 	    &inodedep) == 0)
9333 		panic("dirrem_journal: Lost inodedep");
9334 	journal_jremref(dirrem, jremref, inodedep);
9335 	if (dotremref)
9336 		journal_jremref(dirrem, dotremref, inodedep);
9337 	if (dotdotremref)
9338 		journal_jremref(dirrem, dotdotremref, NULL);
9339 }
9340 
9341 /*
9342  * Allocate a new dirrem if appropriate and return it along with
9343  * its associated pagedep. Called without a lock, returns with lock.
9344  */
9345 static struct dirrem *
9346 newdirrem(
9347 	struct buf *bp,		/* buffer containing directory block */
9348 	struct inode *dp,	/* inode for the directory being modified */
9349 	struct inode *ip,	/* inode for directory entry being removed */
9350 	int isrmdir,		/* indicates if doing RMDIR */
9351 	struct dirrem **prevdirremp) /* previously referenced inode, if any */
9352 {
9353 	int offset;
9354 	ufs_lbn_t lbn;
9355 	struct diradd *dap;
9356 	struct dirrem *dirrem;
9357 	struct pagedep *pagedep;
9358 	struct jremref *jremref;
9359 	struct jremref *dotremref;
9360 	struct jremref *dotdotremref;
9361 	struct vnode *dvp;
9362 	struct ufsmount *ump;
9363 
9364 	/*
9365 	 * Whiteouts have no deletion dependencies.
9366 	 */
9367 	if (ip == NULL)
9368 		panic("newdirrem: whiteout");
9369 	dvp = ITOV(dp);
9370 	ump = ITOUMP(dp);
9371 
9372 	/*
9373 	 * If the system is over its limit and our filesystem is
9374 	 * responsible for more than our share of that usage and
9375 	 * we are not a snapshot, request some inodedep cleanup.
9376 	 * Limiting the number of dirrem structures will also limit
9377 	 * the number of freefile and freeblks structures.
9378 	 */
9379 	ACQUIRE_LOCK(ump);
9380 	if (!IS_SNAPSHOT(ip) && softdep_excess_items(ump, D_DIRREM))
9381 		schedule_cleanup(UFSTOVFS(ump));
9382 	else
9383 		FREE_LOCK(ump);
9384 	dirrem = malloc(sizeof(struct dirrem), M_DIRREM, M_SOFTDEP_FLAGS |
9385 	    M_ZERO);
9386 	workitem_alloc(&dirrem->dm_list, D_DIRREM, dvp->v_mount);
9387 	LIST_INIT(&dirrem->dm_jremrefhd);
9388 	LIST_INIT(&dirrem->dm_jwork);
9389 	dirrem->dm_state = isrmdir ? RMDIR : 0;
9390 	dirrem->dm_oldinum = ip->i_number;
9391 	*prevdirremp = NULL;
9392 	/*
9393 	 * Allocate remove reference structures to track journal write
9394 	 * dependencies.  We will always have one for the link and
9395 	 * when doing directories we will always have one more for dot.
9396 	 * When renaming a directory we skip the dotdot link change so
9397 	 * this is not needed.
9398 	 */
9399 	jremref = dotremref = dotdotremref = NULL;
9400 	if (DOINGSUJ(dvp)) {
9401 		if (isrmdir) {
9402 			jremref = newjremref(dirrem, dp, ip, I_OFFSET(dp),
9403 			    ip->i_effnlink + 2);
9404 			dotremref = newjremref(dirrem, ip, ip, DOT_OFFSET,
9405 			    ip->i_effnlink + 1);
9406 			dotdotremref = newjremref(dirrem, ip, dp, DOTDOT_OFFSET,
9407 			    dp->i_effnlink + 1);
9408 			dotdotremref->jr_state |= MKDIR_PARENT;
9409 		} else
9410 			jremref = newjremref(dirrem, dp, ip, I_OFFSET(dp),
9411 			    ip->i_effnlink + 1);
9412 	}
9413 	ACQUIRE_LOCK(ump);
9414 	lbn = lblkno(ump->um_fs, I_OFFSET(dp));
9415 	offset = blkoff(ump->um_fs, I_OFFSET(dp));
9416 	pagedep_lookup(UFSTOVFS(ump), bp, dp->i_number, lbn, DEPALLOC,
9417 	    &pagedep);
9418 	dirrem->dm_pagedep = pagedep;
9419 	dirrem->dm_offset = offset;
9420 	/*
9421 	 * If we're renaming a .. link to a new directory, cancel any
9422 	 * existing MKDIR_PARENT mkdir.  If it has already been canceled
9423 	 * the jremref is preserved for any potential diradd in this
9424 	 * location.  This can not coincide with a rmdir.
9425 	 */
9426 	if (I_OFFSET(dp) == DOTDOT_OFFSET) {
9427 		if (isrmdir)
9428 			panic("newdirrem: .. directory change during remove?");
9429 		jremref = cancel_mkdir_dotdot(dp, dirrem, jremref);
9430 	}
9431 	/*
9432 	 * If we're removing a directory search for the .. dependency now and
9433 	 * cancel it.  Any pending journal work will be added to the dirrem
9434 	 * to be completed when the workitem remove completes.
9435 	 */
9436 	if (isrmdir)
9437 		dotdotremref = cancel_diradd_dotdot(ip, dirrem, dotdotremref);
9438 	/*
9439 	 * Check for a diradd dependency for the same directory entry.
9440 	 * If present, then both dependencies become obsolete and can
9441 	 * be de-allocated.
9442 	 */
9443 	dap = diradd_lookup(pagedep, offset);
9444 	if (dap == NULL) {
9445 		/*
9446 		 * Link the jremref structures into the dirrem so they are
9447 		 * written prior to the pagedep.
9448 		 */
9449 		if (jremref)
9450 			dirrem_journal(dirrem, jremref, dotremref,
9451 			    dotdotremref);
9452 		return (dirrem);
9453 	}
9454 	/*
9455 	 * Must be ATTACHED at this point.
9456 	 */
9457 	if ((dap->da_state & ATTACHED) == 0)
9458 		panic("newdirrem: not ATTACHED");
9459 	if (dap->da_newinum != ip->i_number)
9460 		panic("newdirrem: inum %ju should be %ju",
9461 		    (uintmax_t)ip->i_number, (uintmax_t)dap->da_newinum);
9462 	/*
9463 	 * If we are deleting a changed name that never made it to disk,
9464 	 * then return the dirrem describing the previous inode (which
9465 	 * represents the inode currently referenced from this entry on disk).
9466 	 */
9467 	if ((dap->da_state & DIRCHG) != 0) {
9468 		*prevdirremp = dap->da_previous;
9469 		dap->da_state &= ~DIRCHG;
9470 		dap->da_pagedep = pagedep;
9471 	}
9472 	/*
9473 	 * We are deleting an entry that never made it to disk.
9474 	 * Mark it COMPLETE so we can delete its inode immediately.
9475 	 */
9476 	dirrem->dm_state |= COMPLETE;
9477 	cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref);
9478 #ifdef INVARIANTS
9479 	if (isrmdir == 0) {
9480 		struct worklist *wk;
9481 
9482 		LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9483 			if (wk->wk_state & (MKDIR_BODY | MKDIR_PARENT))
9484 				panic("bad wk %p (0x%X)\n", wk, wk->wk_state);
9485 	}
9486 #endif
9487 
9488 	return (dirrem);
9489 }
9490 
9491 /*
9492  * Directory entry change dependencies.
9493  *
9494  * Changing an existing directory entry requires that an add operation
9495  * be completed first followed by a deletion. The semantics for the addition
9496  * are identical to the description of adding a new entry above except
9497  * that the rollback is to the old inode number rather than zero. Once
9498  * the addition dependency is completed, the removal is done as described
9499  * in the removal routine above.
9500  */
9501 
9502 /*
9503  * This routine should be called immediately after changing
9504  * a directory entry.  The inode's link count should not be
9505  * decremented by the calling procedure -- the soft updates
9506  * code will perform this task when it is safe.
9507  */
9508 void
9509 softdep_setup_directory_change(
9510 	struct buf *bp,		/* buffer containing directory block */
9511 	struct inode *dp,	/* inode for the directory being modified */
9512 	struct inode *ip,	/* inode for directory entry being removed */
9513 	ino_t newinum,		/* new inode number for changed entry */
9514 	int isrmdir)		/* indicates if doing RMDIR */
9515 {
9516 	int offset;
9517 	struct diradd *dap = NULL;
9518 	struct dirrem *dirrem, *prevdirrem;
9519 	struct pagedep *pagedep;
9520 	struct inodedep *inodedep;
9521 	struct jaddref *jaddref;
9522 	struct mount *mp;
9523 	struct ufsmount *ump;
9524 
9525 	mp = ITOVFS(dp);
9526 	ump = VFSTOUFS(mp);
9527 	offset = blkoff(ump->um_fs, I_OFFSET(dp));
9528 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
9529 	   ("softdep_setup_directory_change called on non-softdep filesystem"));
9530 
9531 	/*
9532 	 * Whiteouts do not need diradd dependencies.
9533 	 */
9534 	if (newinum != UFS_WINO) {
9535 		dap = malloc(sizeof(struct diradd),
9536 		    M_DIRADD, M_SOFTDEP_FLAGS|M_ZERO);
9537 		workitem_alloc(&dap->da_list, D_DIRADD, mp);
9538 		dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
9539 		dap->da_offset = offset;
9540 		dap->da_newinum = newinum;
9541 		LIST_INIT(&dap->da_jwork);
9542 	}
9543 
9544 	/*
9545 	 * Allocate a new dirrem and ACQUIRE_LOCK.
9546 	 */
9547 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9548 	pagedep = dirrem->dm_pagedep;
9549 	/*
9550 	 * The possible values for isrmdir:
9551 	 *	0 - non-directory file rename
9552 	 *	1 - directory rename within same directory
9553 	 *   inum - directory rename to new directory of given inode number
9554 	 * When renaming to a new directory, we are both deleting and
9555 	 * creating a new directory entry, so the link count on the new
9556 	 * directory should not change. Thus we do not need the followup
9557 	 * dirrem which is usually done in handle_workitem_remove. We set
9558 	 * the DIRCHG flag to tell handle_workitem_remove to skip the
9559 	 * followup dirrem.
9560 	 */
9561 	if (isrmdir > 1)
9562 		dirrem->dm_state |= DIRCHG;
9563 
9564 	/*
9565 	 * Whiteouts have no additional dependencies,
9566 	 * so just put the dirrem on the correct list.
9567 	 */
9568 	if (newinum == UFS_WINO) {
9569 		if ((dirrem->dm_state & COMPLETE) == 0) {
9570 			LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
9571 			    dm_next);
9572 		} else {
9573 			dirrem->dm_dirinum = pagedep->pd_ino;
9574 			if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9575 				add_to_worklist(&dirrem->dm_list, 0);
9576 		}
9577 		FREE_LOCK(ump);
9578 		return;
9579 	}
9580 	/*
9581 	 * Add the dirrem to the inodedep's pending remove list for quick
9582 	 * discovery later.  A valid nlinkdelta ensures that this lookup
9583 	 * will not fail.
9584 	 */
9585 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9586 		panic("softdep_setup_directory_change: Lost inodedep.");
9587 	dirrem->dm_state |= ONDEPLIST;
9588 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9589 
9590 	/*
9591 	 * If the COMPLETE flag is clear, then there were no active
9592 	 * entries and we want to roll back to the previous inode until
9593 	 * the new inode is committed to disk. If the COMPLETE flag is
9594 	 * set, then we have deleted an entry that never made it to disk.
9595 	 * If the entry we deleted resulted from a name change, then the old
9596 	 * inode reference still resides on disk. Any rollback that we do
9597 	 * needs to be to that old inode (returned to us in prevdirrem). If
9598 	 * the entry we deleted resulted from a create, then there is
9599 	 * no entry on the disk, so we want to roll back to zero rather
9600 	 * than the uncommitted inode. In either of the COMPLETE cases we
9601 	 * want to immediately free the unwritten and unreferenced inode.
9602 	 */
9603 	if ((dirrem->dm_state & COMPLETE) == 0) {
9604 		dap->da_previous = dirrem;
9605 	} else {
9606 		if (prevdirrem != NULL) {
9607 			dap->da_previous = prevdirrem;
9608 		} else {
9609 			dap->da_state &= ~DIRCHG;
9610 			dap->da_pagedep = pagedep;
9611 		}
9612 		dirrem->dm_dirinum = pagedep->pd_ino;
9613 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9614 			add_to_worklist(&dirrem->dm_list, 0);
9615 	}
9616 	/*
9617 	 * Lookup the jaddref for this journal entry.  We must finish
9618 	 * initializing it and make the diradd write dependent on it.
9619 	 * If we're not journaling, put it on the id_bufwait list if the
9620 	 * inode is not yet written. If it is written, do the post-inode
9621 	 * write processing to put it on the id_pendinghd list.
9622 	 */
9623 	inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
9624 	if (MOUNTEDSUJ(mp)) {
9625 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
9626 		    inoreflst);
9627 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
9628 		    ("softdep_setup_directory_change: bad jaddref %p",
9629 		    jaddref));
9630 		jaddref->ja_diroff = I_OFFSET(dp);
9631 		jaddref->ja_diradd = dap;
9632 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9633 		    dap, da_pdlist);
9634 		add_to_journal(&jaddref->ja_list);
9635 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
9636 		dap->da_state |= COMPLETE;
9637 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
9638 		WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
9639 	} else {
9640 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9641 		    dap, da_pdlist);
9642 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
9643 	}
9644 	/*
9645 	 * If we're making a new name for a directory that has not been
9646 	 * committed when need to move the dot and dotdot references to
9647 	 * this new name.
9648 	 */
9649 	if (inodedep->id_mkdiradd && I_OFFSET(dp) != DOTDOT_OFFSET)
9650 		merge_diradd(inodedep, dap);
9651 	FREE_LOCK(ump);
9652 }
9653 
9654 /*
9655  * Called whenever the link count on an inode is changed.
9656  * It creates an inode dependency so that the new reference(s)
9657  * to the inode cannot be committed to disk until the updated
9658  * inode has been written.
9659  */
9660 void
9661 softdep_change_linkcnt(
9662 	struct inode *ip)	/* the inode with the increased link count */
9663 {
9664 	struct inodedep *inodedep;
9665 	struct ufsmount *ump;
9666 
9667 	ump = ITOUMP(ip);
9668 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9669 	    ("softdep_change_linkcnt called on non-softdep filesystem"));
9670 	ACQUIRE_LOCK(ump);
9671 	inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
9672 	if (ip->i_nlink < ip->i_effnlink)
9673 		panic("softdep_change_linkcnt: bad delta");
9674 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9675 	FREE_LOCK(ump);
9676 }
9677 
9678 /*
9679  * Attach a sbdep dependency to the superblock buf so that we can keep
9680  * track of the head of the linked list of referenced but unlinked inodes.
9681  */
9682 void
9683 softdep_setup_sbupdate(
9684 	struct ufsmount *ump,
9685 	struct fs *fs,
9686 	struct buf *bp)
9687 {
9688 	struct sbdep *sbdep;
9689 	struct worklist *wk;
9690 
9691 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9692 	    ("softdep_setup_sbupdate called on non-softdep filesystem"));
9693 	LIST_FOREACH(wk, &bp->b_dep, wk_list)
9694 		if (wk->wk_type == D_SBDEP)
9695 			break;
9696 	if (wk != NULL)
9697 		return;
9698 	sbdep = malloc(sizeof(struct sbdep), M_SBDEP, M_SOFTDEP_FLAGS);
9699 	workitem_alloc(&sbdep->sb_list, D_SBDEP, UFSTOVFS(ump));
9700 	sbdep->sb_fs = fs;
9701 	sbdep->sb_ump = ump;
9702 	ACQUIRE_LOCK(ump);
9703 	WORKLIST_INSERT(&bp->b_dep, &sbdep->sb_list);
9704 	FREE_LOCK(ump);
9705 }
9706 
9707 /*
9708  * Return the first unlinked inodedep which is ready to be the head of the
9709  * list.  The inodedep and all those after it must have valid next pointers.
9710  */
9711 static struct inodedep *
9712 first_unlinked_inodedep(struct ufsmount *ump)
9713 {
9714 	struct inodedep *inodedep;
9715 	struct inodedep *idp;
9716 
9717 	LOCK_OWNED(ump);
9718 	for (inodedep = TAILQ_LAST(&ump->softdep_unlinked, inodedeplst);
9719 	    inodedep; inodedep = idp) {
9720 		if ((inodedep->id_state & UNLINKNEXT) == 0)
9721 			return (NULL);
9722 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9723 		if (idp == NULL || (idp->id_state & UNLINKNEXT) == 0)
9724 			break;
9725 		if ((inodedep->id_state & UNLINKPREV) == 0)
9726 			break;
9727 	}
9728 	return (inodedep);
9729 }
9730 
9731 /*
9732  * Set the sujfree unlinked head pointer prior to writing a superblock.
9733  */
9734 static void
9735 initiate_write_sbdep(struct sbdep *sbdep)
9736 {
9737 	struct inodedep *inodedep;
9738 	struct fs *bpfs;
9739 	struct fs *fs;
9740 
9741 	bpfs = sbdep->sb_fs;
9742 	fs = sbdep->sb_ump->um_fs;
9743 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9744 	if (inodedep) {
9745 		fs->fs_sujfree = inodedep->id_ino;
9746 		inodedep->id_state |= UNLINKPREV;
9747 	} else
9748 		fs->fs_sujfree = 0;
9749 	bpfs->fs_sujfree = fs->fs_sujfree;
9750 	/*
9751 	 * Because we have made changes to the superblock, we need to
9752 	 * recompute its check-hash.
9753 	 */
9754 	bpfs->fs_ckhash = ffs_calc_sbhash(bpfs);
9755 }
9756 
9757 /*
9758  * After a superblock is written determine whether it must be written again
9759  * due to a changing unlinked list head.
9760  */
9761 static int
9762 handle_written_sbdep(struct sbdep *sbdep, struct buf *bp)
9763 {
9764 	struct inodedep *inodedep;
9765 	struct fs *fs;
9766 
9767 	LOCK_OWNED(sbdep->sb_ump);
9768 	fs = sbdep->sb_fs;
9769 	/*
9770 	 * If the superblock doesn't match the in-memory list start over.
9771 	 */
9772 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9773 	if ((inodedep && fs->fs_sujfree != inodedep->id_ino) ||
9774 	    (inodedep == NULL && fs->fs_sujfree != 0)) {
9775 		bdirty(bp);
9776 		return (1);
9777 	}
9778 	WORKITEM_FREE(sbdep, D_SBDEP);
9779 	if (fs->fs_sujfree == 0)
9780 		return (0);
9781 	/*
9782 	 * Now that we have a record of this inode in stable store allow it
9783 	 * to be written to free up pending work.  Inodes may see a lot of
9784 	 * write activity after they are unlinked which we must not hold up.
9785 	 */
9786 	for (; inodedep != NULL; inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
9787 		if ((inodedep->id_state & UNLINKLINKS) != UNLINKLINKS)
9788 			panic("handle_written_sbdep: Bad inodedep %p (0x%X)",
9789 			    inodedep, inodedep->id_state);
9790 		if (inodedep->id_state & UNLINKONLIST)
9791 			break;
9792 		inodedep->id_state |= DEPCOMPLETE | UNLINKONLIST;
9793 	}
9794 
9795 	return (0);
9796 }
9797 
9798 /*
9799  * Mark an inodedep as unlinked and insert it into the in-memory unlinked list.
9800  */
9801 static void
9802 unlinked_inodedep( struct mount *mp, struct inodedep *inodedep)
9803 {
9804 	struct ufsmount *ump;
9805 
9806 	ump = VFSTOUFS(mp);
9807 	LOCK_OWNED(ump);
9808 	if (MOUNTEDSUJ(mp) == 0)
9809 		return;
9810 	ump->um_fs->fs_fmod = 1;
9811 	if (inodedep->id_state & UNLINKED)
9812 		panic("unlinked_inodedep: %p already unlinked\n", inodedep);
9813 	inodedep->id_state |= UNLINKED;
9814 	TAILQ_INSERT_HEAD(&ump->softdep_unlinked, inodedep, id_unlinked);
9815 }
9816 
9817 /*
9818  * Remove an inodedep from the unlinked inodedep list.  This may require
9819  * disk writes if the inode has made it that far.
9820  */
9821 static void
9822 clear_unlinked_inodedep( struct inodedep *inodedep)
9823 {
9824 	struct ufs2_dinode *dip;
9825 	struct ufsmount *ump;
9826 	struct inodedep *idp;
9827 	struct inodedep *idn;
9828 	struct fs *fs, *bpfs;
9829 	struct buf *bp;
9830 	daddr_t dbn;
9831 	ino_t ino;
9832 	ino_t nino;
9833 	ino_t pino;
9834 	int error;
9835 
9836 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
9837 	fs = ump->um_fs;
9838 	ino = inodedep->id_ino;
9839 	error = 0;
9840 	for (;;) {
9841 		LOCK_OWNED(ump);
9842 		KASSERT((inodedep->id_state & UNLINKED) != 0,
9843 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
9844 		    inodedep));
9845 		/*
9846 		 * If nothing has yet been written simply remove us from
9847 		 * the in memory list and return.  This is the most common
9848 		 * case where handle_workitem_remove() loses the final
9849 		 * reference.
9850 		 */
9851 		if ((inodedep->id_state & UNLINKLINKS) == 0)
9852 			break;
9853 		/*
9854 		 * If we have a NEXT pointer and no PREV pointer we can simply
9855 		 * clear NEXT's PREV and remove ourselves from the list.  Be
9856 		 * careful not to clear PREV if the superblock points at
9857 		 * next as well.
9858 		 */
9859 		idn = TAILQ_NEXT(inodedep, id_unlinked);
9860 		if ((inodedep->id_state & UNLINKLINKS) == UNLINKNEXT) {
9861 			if (idn && fs->fs_sujfree != idn->id_ino)
9862 				idn->id_state &= ~UNLINKPREV;
9863 			break;
9864 		}
9865 		/*
9866 		 * Here we have an inodedep which is actually linked into
9867 		 * the list.  We must remove it by forcing a write to the
9868 		 * link before us, whether it be the superblock or an inode.
9869 		 * Unfortunately the list may change while we're waiting
9870 		 * on the buf lock for either resource so we must loop until
9871 		 * we lock the right one.  If both the superblock and an
9872 		 * inode point to this inode we must clear the inode first
9873 		 * followed by the superblock.
9874 		 */
9875 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9876 		pino = 0;
9877 		if (idp && (idp->id_state & UNLINKNEXT))
9878 			pino = idp->id_ino;
9879 		FREE_LOCK(ump);
9880 		if (pino == 0) {
9881 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9882 			    (int)fs->fs_sbsize, 0, 0, 0);
9883 		} else {
9884 			dbn = fsbtodb(fs, ino_to_fsba(fs, pino));
9885 			error = ffs_breadz(ump, ump->um_devvp, dbn, dbn,
9886 			    (int)fs->fs_bsize, NULL, NULL, 0, NOCRED, 0, NULL,
9887 			    &bp);
9888 		}
9889 		ACQUIRE_LOCK(ump);
9890 		if (error)
9891 			break;
9892 		/* If the list has changed restart the loop. */
9893 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9894 		nino = 0;
9895 		if (idp && (idp->id_state & UNLINKNEXT))
9896 			nino = idp->id_ino;
9897 		if (nino != pino ||
9898 		    (inodedep->id_state & UNLINKPREV) != UNLINKPREV) {
9899 			FREE_LOCK(ump);
9900 			brelse(bp);
9901 			ACQUIRE_LOCK(ump);
9902 			continue;
9903 		}
9904 		nino = 0;
9905 		idn = TAILQ_NEXT(inodedep, id_unlinked);
9906 		if (idn)
9907 			nino = idn->id_ino;
9908 		/*
9909 		 * Remove us from the in memory list.  After this we cannot
9910 		 * access the inodedep.
9911 		 */
9912 		KASSERT((inodedep->id_state & UNLINKED) != 0,
9913 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
9914 		    inodedep));
9915 		inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9916 		TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9917 		FREE_LOCK(ump);
9918 		/*
9919 		 * The predecessor's next pointer is manually updated here
9920 		 * so that the NEXT flag is never cleared for an element
9921 		 * that is in the list.
9922 		 */
9923 		if (pino == 0) {
9924 			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9925 			bpfs = (struct fs *)bp->b_data;
9926 			ffs_oldfscompat_write(bpfs, ump);
9927 			softdep_setup_sbupdate(ump, bpfs, bp);
9928 			/*
9929 			 * Because we may have made changes to the superblock,
9930 			 * we need to recompute its check-hash.
9931 			 */
9932 			bpfs->fs_ckhash = ffs_calc_sbhash(bpfs);
9933 		} else if (fs->fs_magic == FS_UFS1_MAGIC) {
9934 			((struct ufs1_dinode *)bp->b_data +
9935 			    ino_to_fsbo(fs, pino))->di_freelink = nino;
9936 		} else {
9937 			dip = (struct ufs2_dinode *)bp->b_data +
9938 			    ino_to_fsbo(fs, pino);
9939 			dip->di_freelink = nino;
9940 			ffs_update_dinode_ckhash(fs, dip);
9941 		}
9942 		/*
9943 		 * If the bwrite fails we have no recourse to recover.  The
9944 		 * filesystem is corrupted already.
9945 		 */
9946 		bwrite(bp);
9947 		ACQUIRE_LOCK(ump);
9948 		/*
9949 		 * If the superblock pointer still needs to be cleared force
9950 		 * a write here.
9951 		 */
9952 		if (fs->fs_sujfree == ino) {
9953 			FREE_LOCK(ump);
9954 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9955 			    (int)fs->fs_sbsize, 0, 0, 0);
9956 			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9957 			bpfs = (struct fs *)bp->b_data;
9958 			ffs_oldfscompat_write(bpfs, ump);
9959 			softdep_setup_sbupdate(ump, bpfs, bp);
9960 			/*
9961 			 * Because we may have made changes to the superblock,
9962 			 * we need to recompute its check-hash.
9963 			 */
9964 			bpfs->fs_ckhash = ffs_calc_sbhash(bpfs);
9965 			bwrite(bp);
9966 			ACQUIRE_LOCK(ump);
9967 		}
9968 
9969 		if (fs->fs_sujfree != ino)
9970 			return;
9971 		panic("clear_unlinked_inodedep: Failed to clear free head");
9972 	}
9973 	if (inodedep->id_ino == fs->fs_sujfree)
9974 		panic("clear_unlinked_inodedep: Freeing head of free list");
9975 	inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9976 	TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9977 	return;
9978 }
9979 
9980 /*
9981  * This workitem decrements the inode's link count.
9982  * If the link count reaches zero, the file is removed.
9983  */
9984 static int
9985 handle_workitem_remove(struct dirrem *dirrem, int flags)
9986 {
9987 	struct inodedep *inodedep;
9988 	struct workhead dotdotwk;
9989 	struct worklist *wk;
9990 	struct ufsmount *ump;
9991 	struct mount *mp;
9992 	struct vnode *vp;
9993 	struct inode *ip;
9994 	ino_t oldinum;
9995 
9996 	if (dirrem->dm_state & ONWORKLIST)
9997 		panic("handle_workitem_remove: dirrem %p still on worklist",
9998 		    dirrem);
9999 	oldinum = dirrem->dm_oldinum;
10000 	mp = dirrem->dm_list.wk_mp;
10001 	ump = VFSTOUFS(mp);
10002 	flags |= LK_EXCLUSIVE;
10003 	if (ffs_vgetf(mp, oldinum, flags, &vp, FFSV_FORCEINSMQ |
10004 	    FFSV_FORCEINODEDEP) != 0)
10005 		return (EBUSY);
10006 	ip = VTOI(vp);
10007 	MPASS(ip->i_mode != 0);
10008 	ACQUIRE_LOCK(ump);
10009 	if ((inodedep_lookup(mp, oldinum, 0, &inodedep)) == 0)
10010 		panic("handle_workitem_remove: lost inodedep");
10011 	if (dirrem->dm_state & ONDEPLIST)
10012 		LIST_REMOVE(dirrem, dm_inonext);
10013 	KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
10014 	    ("handle_workitem_remove:  Journal entries not written."));
10015 
10016 	/*
10017 	 * Move all dependencies waiting on the remove to complete
10018 	 * from the dirrem to the inode inowait list to be completed
10019 	 * after the inode has been updated and written to disk.
10020 	 *
10021 	 * Any marked MKDIR_PARENT are saved to be completed when the
10022 	 * dotdot ref is removed unless DIRCHG is specified.  For
10023 	 * directory change operations there will be no further
10024 	 * directory writes and the jsegdeps need to be moved along
10025 	 * with the rest to be completed when the inode is free or
10026 	 * stable in the inode free list.
10027 	 */
10028 	LIST_INIT(&dotdotwk);
10029 	while ((wk = LIST_FIRST(&dirrem->dm_jwork)) != NULL) {
10030 		WORKLIST_REMOVE(wk);
10031 		if ((dirrem->dm_state & DIRCHG) == 0 &&
10032 		    wk->wk_state & MKDIR_PARENT) {
10033 			wk->wk_state &= ~MKDIR_PARENT;
10034 			WORKLIST_INSERT(&dotdotwk, wk);
10035 			continue;
10036 		}
10037 		WORKLIST_INSERT(&inodedep->id_inowait, wk);
10038 	}
10039 	LIST_SWAP(&dirrem->dm_jwork, &dotdotwk, worklist, wk_list);
10040 	/*
10041 	 * Normal file deletion.
10042 	 */
10043 	if ((dirrem->dm_state & RMDIR) == 0) {
10044 		ip->i_nlink--;
10045 		KASSERT(ip->i_nlink >= 0, ("handle_workitem_remove: file ino "
10046 		    "%ju negative i_nlink %d", (intmax_t)ip->i_number,
10047 		    ip->i_nlink));
10048 		DIP_SET(ip, i_nlink, ip->i_nlink);
10049 		UFS_INODE_SET_FLAG(ip, IN_CHANGE);
10050 		if (ip->i_nlink < ip->i_effnlink)
10051 			panic("handle_workitem_remove: bad file delta");
10052 		if (ip->i_nlink == 0)
10053 			unlinked_inodedep(mp, inodedep);
10054 		inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
10055 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
10056 		    ("handle_workitem_remove: worklist not empty. %s",
10057 		    TYPENAME(LIST_FIRST(&dirrem->dm_jwork)->wk_type)));
10058 		WORKITEM_FREE(dirrem, D_DIRREM);
10059 		FREE_LOCK(ump);
10060 		goto out;
10061 	}
10062 	/*
10063 	 * Directory deletion. Decrement reference count for both the
10064 	 * just deleted parent directory entry and the reference for ".".
10065 	 * Arrange to have the reference count on the parent decremented
10066 	 * to account for the loss of "..".
10067 	 */
10068 	ip->i_nlink -= 2;
10069 	KASSERT(ip->i_nlink >= 0, ("handle_workitem_remove: directory ino "
10070 	    "%ju negative i_nlink %d", (intmax_t)ip->i_number, ip->i_nlink));
10071 	DIP_SET(ip, i_nlink, ip->i_nlink);
10072 	UFS_INODE_SET_FLAG(ip, IN_CHANGE);
10073 	if (ip->i_nlink < ip->i_effnlink)
10074 		panic("handle_workitem_remove: bad dir delta");
10075 	if (ip->i_nlink == 0)
10076 		unlinked_inodedep(mp, inodedep);
10077 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
10078 	/*
10079 	 * Rename a directory to a new parent. Since, we are both deleting
10080 	 * and creating a new directory entry, the link count on the new
10081 	 * directory should not change. Thus we skip the followup dirrem.
10082 	 */
10083 	if (dirrem->dm_state & DIRCHG) {
10084 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
10085 		    ("handle_workitem_remove: DIRCHG and worklist not empty."));
10086 		WORKITEM_FREE(dirrem, D_DIRREM);
10087 		FREE_LOCK(ump);
10088 		goto out;
10089 	}
10090 	dirrem->dm_state = ONDEPLIST;
10091 	dirrem->dm_oldinum = dirrem->dm_dirinum;
10092 	/*
10093 	 * Place the dirrem on the parent's diremhd list.
10094 	 */
10095 	if (inodedep_lookup(mp, dirrem->dm_oldinum, 0, &inodedep) == 0)
10096 		panic("handle_workitem_remove: lost dir inodedep");
10097 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
10098 	/*
10099 	 * If the allocated inode has never been written to disk, then
10100 	 * the on-disk inode is zero'ed and we can remove the file
10101 	 * immediately.  When journaling if the inode has been marked
10102 	 * unlinked and not DEPCOMPLETE we know it can never be written.
10103 	 */
10104 	inodedep_lookup(mp, oldinum, 0, &inodedep);
10105 	if (inodedep == NULL ||
10106 	    (inodedep->id_state & (DEPCOMPLETE | UNLINKED)) == UNLINKED ||
10107 	    check_inode_unwritten(inodedep)) {
10108 		FREE_LOCK(ump);
10109 		vput(vp);
10110 		return handle_workitem_remove(dirrem, flags);
10111 	}
10112 	WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
10113 	FREE_LOCK(ump);
10114 	UFS_INODE_SET_FLAG(ip, IN_CHANGE);
10115 out:
10116 	ffs_update(vp, 0);
10117 	vput(vp);
10118 	return (0);
10119 }
10120 
10121 /*
10122  * Inode de-allocation dependencies.
10123  *
10124  * When an inode's link count is reduced to zero, it can be de-allocated. We
10125  * found it convenient to postpone de-allocation until after the inode is
10126  * written to disk with its new link count (zero).  At this point, all of the
10127  * on-disk inode's block pointers are nullified and, with careful dependency
10128  * list ordering, all dependencies related to the inode will be satisfied and
10129  * the corresponding dependency structures de-allocated.  So, if/when the
10130  * inode is reused, there will be no mixing of old dependencies with new
10131  * ones.  This artificial dependency is set up by the block de-allocation
10132  * procedure above (softdep_setup_freeblocks) and completed by the
10133  * following procedure.
10134  */
10135 static void
10136 handle_workitem_freefile(struct freefile *freefile)
10137 {
10138 	struct workhead wkhd;
10139 	struct fs *fs;
10140 	struct ufsmount *ump;
10141 	int error;
10142 #ifdef INVARIANTS
10143 	struct inodedep *idp;
10144 #endif
10145 
10146 	ump = VFSTOUFS(freefile->fx_list.wk_mp);
10147 	fs = ump->um_fs;
10148 #ifdef INVARIANTS
10149 	ACQUIRE_LOCK(ump);
10150 	error = inodedep_lookup(UFSTOVFS(ump), freefile->fx_oldinum, 0, &idp);
10151 	FREE_LOCK(ump);
10152 	if (error)
10153 		panic("handle_workitem_freefile: inodedep %p survived", idp);
10154 #endif
10155 	UFS_LOCK(ump);
10156 	fs->fs_pendinginodes -= 1;
10157 	UFS_UNLOCK(ump);
10158 	LIST_INIT(&wkhd);
10159 	LIST_SWAP(&freefile->fx_jwork, &wkhd, worklist, wk_list);
10160 	if ((error = ffs_freefile(ump, fs, freefile->fx_devvp,
10161 	    freefile->fx_oldinum, freefile->fx_mode, &wkhd)) != 0)
10162 		softdep_error("handle_workitem_freefile", error);
10163 	ACQUIRE_LOCK(ump);
10164 	WORKITEM_FREE(freefile, D_FREEFILE);
10165 	FREE_LOCK(ump);
10166 }
10167 
10168 /*
10169  * Helper function which unlinks marker element from work list and returns
10170  * the next element on the list.
10171  */
10172 static __inline struct worklist *
10173 markernext(struct worklist *marker)
10174 {
10175 	struct worklist *next;
10176 
10177 	next = LIST_NEXT(marker, wk_list);
10178 	LIST_REMOVE(marker, wk_list);
10179 	return next;
10180 }
10181 
10182 /*
10183  * Disk writes.
10184  *
10185  * The dependency structures constructed above are most actively used when file
10186  * system blocks are written to disk.  No constraints are placed on when a
10187  * block can be written, but unsatisfied update dependencies are made safe by
10188  * modifying (or replacing) the source memory for the duration of the disk
10189  * write.  When the disk write completes, the memory block is again brought
10190  * up-to-date.
10191  *
10192  * In-core inode structure reclamation.
10193  *
10194  * Because there are a finite number of "in-core" inode structures, they are
10195  * reused regularly.  By transferring all inode-related dependencies to the
10196  * in-memory inode block and indexing them separately (via "inodedep"s), we
10197  * can allow "in-core" inode structures to be reused at any time and avoid
10198  * any increase in contention.
10199  *
10200  * Called just before entering the device driver to initiate a new disk I/O.
10201  * The buffer must be locked, thus, no I/O completion operations can occur
10202  * while we are manipulating its associated dependencies.
10203  */
10204 static void
10205 softdep_disk_io_initiation(
10206 	struct buf *bp)		/* structure describing disk write to occur */
10207 {
10208 	struct worklist *wk;
10209 	struct worklist marker;
10210 	struct inodedep *inodedep;
10211 	struct freeblks *freeblks;
10212 	struct jblkdep *jblkdep;
10213 	struct newblk *newblk;
10214 	struct ufsmount *ump;
10215 
10216 	/*
10217 	 * We only care about write operations. There should never
10218 	 * be dependencies for reads.
10219 	 */
10220 	if (bp->b_iocmd != BIO_WRITE)
10221 		panic("softdep_disk_io_initiation: not write");
10222 
10223 	if (bp->b_vflags & BV_BKGRDINPROG)
10224 		panic("softdep_disk_io_initiation: Writing buffer with "
10225 		    "background write in progress: %p", bp);
10226 
10227 	ump = softdep_bp_to_mp(bp);
10228 	if (ump == NULL)
10229 		return;
10230 
10231 	marker.wk_type = D_LAST + 1;	/* Not a normal workitem */
10232 	PHOLD(curproc);			/* Don't swap out kernel stack */
10233 	ACQUIRE_LOCK(ump);
10234 	/*
10235 	 * Do any necessary pre-I/O processing.
10236 	 */
10237 	for (wk = LIST_FIRST(&bp->b_dep); wk != NULL;
10238 	     wk = markernext(&marker)) {
10239 		LIST_INSERT_AFTER(wk, &marker, wk_list);
10240 		switch (wk->wk_type) {
10241 		case D_PAGEDEP:
10242 			initiate_write_filepage(WK_PAGEDEP(wk), bp);
10243 			continue;
10244 
10245 		case D_INODEDEP:
10246 			inodedep = WK_INODEDEP(wk);
10247 			if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC)
10248 				initiate_write_inodeblock_ufs1(inodedep, bp);
10249 			else
10250 				initiate_write_inodeblock_ufs2(inodedep, bp);
10251 			continue;
10252 
10253 		case D_INDIRDEP:
10254 			initiate_write_indirdep(WK_INDIRDEP(wk), bp);
10255 			continue;
10256 
10257 		case D_BMSAFEMAP:
10258 			initiate_write_bmsafemap(WK_BMSAFEMAP(wk), bp);
10259 			continue;
10260 
10261 		case D_JSEG:
10262 			WK_JSEG(wk)->js_buf = NULL;
10263 			continue;
10264 
10265 		case D_FREEBLKS:
10266 			freeblks = WK_FREEBLKS(wk);
10267 			jblkdep = LIST_FIRST(&freeblks->fb_jblkdephd);
10268 			/*
10269 			 * We have to wait for the freeblks to be journaled
10270 			 * before we can write an inodeblock with updated
10271 			 * pointers.  Be careful to arrange the marker so
10272 			 * we revisit the freeblks if it's not removed by
10273 			 * the first jwait().
10274 			 */
10275 			if (jblkdep != NULL) {
10276 				LIST_REMOVE(&marker, wk_list);
10277 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
10278 				jwait(&jblkdep->jb_list, MNT_WAIT);
10279 			}
10280 			continue;
10281 		case D_ALLOCDIRECT:
10282 		case D_ALLOCINDIR:
10283 			/*
10284 			 * We have to wait for the jnewblk to be journaled
10285 			 * before we can write to a block if the contents
10286 			 * may be confused with an earlier file's indirect
10287 			 * at recovery time.  Handle the marker as described
10288 			 * above.
10289 			 */
10290 			newblk = WK_NEWBLK(wk);
10291 			if (newblk->nb_jnewblk != NULL &&
10292 			    indirblk_lookup(newblk->nb_list.wk_mp,
10293 			    newblk->nb_newblkno)) {
10294 				LIST_REMOVE(&marker, wk_list);
10295 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
10296 				jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
10297 			}
10298 			continue;
10299 
10300 		case D_SBDEP:
10301 			initiate_write_sbdep(WK_SBDEP(wk));
10302 			continue;
10303 
10304 		case D_MKDIR:
10305 		case D_FREEWORK:
10306 		case D_FREEDEP:
10307 		case D_JSEGDEP:
10308 			continue;
10309 
10310 		default:
10311 			panic("handle_disk_io_initiation: Unexpected type %s",
10312 			    TYPENAME(wk->wk_type));
10313 			/* NOTREACHED */
10314 		}
10315 	}
10316 	FREE_LOCK(ump);
10317 	PRELE(curproc);			/* Allow swapout of kernel stack */
10318 }
10319 
10320 /*
10321  * Called from within the procedure above to deal with unsatisfied
10322  * allocation dependencies in a directory. The buffer must be locked,
10323  * thus, no I/O completion operations can occur while we are
10324  * manipulating its associated dependencies.
10325  */
10326 static void
10327 initiate_write_filepage(struct pagedep *pagedep, struct buf *bp)
10328 {
10329 	struct jremref *jremref;
10330 	struct jmvref *jmvref;
10331 	struct dirrem *dirrem;
10332 	struct diradd *dap;
10333 	struct direct *ep;
10334 	int i;
10335 
10336 	if (pagedep->pd_state & IOSTARTED) {
10337 		/*
10338 		 * This can only happen if there is a driver that does not
10339 		 * understand chaining. Here biodone will reissue the call
10340 		 * to strategy for the incomplete buffers.
10341 		 */
10342 		printf("initiate_write_filepage: already started\n");
10343 		return;
10344 	}
10345 	pagedep->pd_state |= IOSTARTED;
10346 	/*
10347 	 * Wait for all journal remove dependencies to hit the disk.
10348 	 * We can not allow any potentially conflicting directory adds
10349 	 * to be visible before removes and rollback is too difficult.
10350 	 * The per-filesystem lock may be dropped and re-acquired, however
10351 	 * we hold the buf locked so the dependency can not go away.
10352 	 */
10353 	LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next)
10354 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL)
10355 			jwait(&jremref->jr_list, MNT_WAIT);
10356 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL)
10357 		jwait(&jmvref->jm_list, MNT_WAIT);
10358 	for (i = 0; i < DAHASHSZ; i++) {
10359 		LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
10360 			ep = (struct direct *)
10361 			    ((char *)bp->b_data + dap->da_offset);
10362 			if (ep->d_ino != dap->da_newinum)
10363 				panic("%s: dir inum %ju != new %ju",
10364 				    "initiate_write_filepage",
10365 				    (uintmax_t)ep->d_ino,
10366 				    (uintmax_t)dap->da_newinum);
10367 			if (dap->da_state & DIRCHG)
10368 				ep->d_ino = dap->da_previous->dm_oldinum;
10369 			else
10370 				ep->d_ino = 0;
10371 			dap->da_state &= ~ATTACHED;
10372 			dap->da_state |= UNDONE;
10373 		}
10374 	}
10375 }
10376 
10377 /*
10378  * Version of initiate_write_inodeblock that handles UFS1 dinodes.
10379  * Note that any bug fixes made to this routine must be done in the
10380  * version found below.
10381  *
10382  * Called from within the procedure above to deal with unsatisfied
10383  * allocation dependencies in an inodeblock. The buffer must be
10384  * locked, thus, no I/O completion operations can occur while we
10385  * are manipulating its associated dependencies.
10386  */
10387 static void
10388 initiate_write_inodeblock_ufs1(
10389 	struct inodedep *inodedep,
10390 	struct buf *bp)			/* The inode block */
10391 {
10392 	struct allocdirect *adp, *lastadp;
10393 	struct ufs1_dinode *dp;
10394 	struct ufs1_dinode *sip;
10395 	struct inoref *inoref;
10396 	struct ufsmount *ump;
10397 	struct fs *fs;
10398 	ufs_lbn_t i;
10399 #ifdef INVARIANTS
10400 	ufs_lbn_t prevlbn = 0;
10401 #endif
10402 	int deplist __diagused;
10403 
10404 	if (inodedep->id_state & IOSTARTED)
10405 		panic("initiate_write_inodeblock_ufs1: already started");
10406 	inodedep->id_state |= IOSTARTED;
10407 	fs = inodedep->id_fs;
10408 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10409 	LOCK_OWNED(ump);
10410 	dp = (struct ufs1_dinode *)bp->b_data +
10411 	    ino_to_fsbo(fs, inodedep->id_ino);
10412 
10413 	/*
10414 	 * If we're on the unlinked list but have not yet written our
10415 	 * next pointer initialize it here.
10416 	 */
10417 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10418 		struct inodedep *inon;
10419 
10420 		inon = TAILQ_NEXT(inodedep, id_unlinked);
10421 		dp->di_freelink = inon ? inon->id_ino : 0;
10422 	}
10423 	/*
10424 	 * If the bitmap is not yet written, then the allocated
10425 	 * inode cannot be written to disk.
10426 	 */
10427 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10428 		if (inodedep->id_savedino1 != NULL)
10429 			panic("initiate_write_inodeblock_ufs1: I/O underway");
10430 		FREE_LOCK(ump);
10431 		sip = malloc(sizeof(struct ufs1_dinode),
10432 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
10433 		ACQUIRE_LOCK(ump);
10434 		inodedep->id_savedino1 = sip;
10435 		*inodedep->id_savedino1 = *dp;
10436 		bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
10437 		dp->di_gen = inodedep->id_savedino1->di_gen;
10438 		dp->di_freelink = inodedep->id_savedino1->di_freelink;
10439 		return;
10440 	}
10441 	/*
10442 	 * If no dependencies, then there is nothing to roll back.
10443 	 */
10444 	inodedep->id_savedsize = dp->di_size;
10445 	inodedep->id_savedextsize = 0;
10446 	inodedep->id_savednlink = dp->di_nlink;
10447 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10448 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
10449 		return;
10450 	/*
10451 	 * Revert the link count to that of the first unwritten journal entry.
10452 	 */
10453 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10454 	if (inoref)
10455 		dp->di_nlink = inoref->if_nlink;
10456 	/*
10457 	 * Set the dependencies to busy.
10458 	 */
10459 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10460 	     adp = TAILQ_NEXT(adp, ad_next)) {
10461 #ifdef INVARIANTS
10462 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10463 			panic("softdep_write_inodeblock: lbn order");
10464 		prevlbn = adp->ad_offset;
10465 		if (adp->ad_offset < UFS_NDADDR &&
10466 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10467 			panic("initiate_write_inodeblock_ufs1: "
10468 			    "direct pointer #%jd mismatch %d != %jd",
10469 			    (intmax_t)adp->ad_offset,
10470 			    dp->di_db[adp->ad_offset],
10471 			    (intmax_t)adp->ad_newblkno);
10472 		if (adp->ad_offset >= UFS_NDADDR &&
10473 		    dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10474 			panic("initiate_write_inodeblock_ufs1: "
10475 			    "indirect pointer #%jd mismatch %d != %jd",
10476 			    (intmax_t)adp->ad_offset - UFS_NDADDR,
10477 			    dp->di_ib[adp->ad_offset - UFS_NDADDR],
10478 			    (intmax_t)adp->ad_newblkno);
10479 		deplist |= 1 << adp->ad_offset;
10480 		if ((adp->ad_state & ATTACHED) == 0)
10481 			panic("initiate_write_inodeblock_ufs1: "
10482 			    "Unknown state 0x%x", adp->ad_state);
10483 #endif /* INVARIANTS */
10484 		adp->ad_state &= ~ATTACHED;
10485 		adp->ad_state |= UNDONE;
10486 	}
10487 	/*
10488 	 * The on-disk inode cannot claim to be any larger than the last
10489 	 * fragment that has been written. Otherwise, the on-disk inode
10490 	 * might have fragments that were not the last block in the file
10491 	 * which would corrupt the filesystem.
10492 	 */
10493 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10494 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10495 		if (adp->ad_offset >= UFS_NDADDR)
10496 			break;
10497 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10498 		/* keep going until hitting a rollback to a frag */
10499 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10500 			continue;
10501 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10502 		for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10503 #ifdef INVARIANTS
10504 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10505 				panic("initiate_write_inodeblock_ufs1: "
10506 				    "lost dep1");
10507 #endif /* INVARIANTS */
10508 			dp->di_db[i] = 0;
10509 		}
10510 		for (i = 0; i < UFS_NIADDR; i++) {
10511 #ifdef INVARIANTS
10512 			if (dp->di_ib[i] != 0 &&
10513 			    (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10514 				panic("initiate_write_inodeblock_ufs1: "
10515 				    "lost dep2");
10516 #endif /* INVARIANTS */
10517 			dp->di_ib[i] = 0;
10518 		}
10519 		return;
10520 	}
10521 	/*
10522 	 * If we have zero'ed out the last allocated block of the file,
10523 	 * roll back the size to the last currently allocated block.
10524 	 * We know that this last allocated block is a full-sized as
10525 	 * we already checked for fragments in the loop above.
10526 	 */
10527 	if (lastadp != NULL &&
10528 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10529 		for (i = lastadp->ad_offset; i >= 0; i--)
10530 			if (dp->di_db[i] != 0)
10531 				break;
10532 		dp->di_size = (i + 1) * fs->fs_bsize;
10533 	}
10534 	/*
10535 	 * The only dependencies are for indirect blocks.
10536 	 *
10537 	 * The file size for indirect block additions is not guaranteed.
10538 	 * Such a guarantee would be non-trivial to achieve. The conventional
10539 	 * synchronous write implementation also does not make this guarantee.
10540 	 * Fsck should catch and fix discrepancies. Arguably, the file size
10541 	 * can be over-estimated without destroying integrity when the file
10542 	 * moves into the indirect blocks (i.e., is large). If we want to
10543 	 * postpone fsck, we are stuck with this argument.
10544 	 */
10545 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10546 		dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10547 }
10548 
10549 /*
10550  * Version of initiate_write_inodeblock that handles UFS2 dinodes.
10551  * Note that any bug fixes made to this routine must be done in the
10552  * version found above.
10553  *
10554  * Called from within the procedure above to deal with unsatisfied
10555  * allocation dependencies in an inodeblock. The buffer must be
10556  * locked, thus, no I/O completion operations can occur while we
10557  * are manipulating its associated dependencies.
10558  */
10559 static void
10560 initiate_write_inodeblock_ufs2(
10561 	struct inodedep *inodedep,
10562 	struct buf *bp)			/* The inode block */
10563 {
10564 	struct allocdirect *adp, *lastadp;
10565 	struct ufs2_dinode *dp;
10566 	struct ufs2_dinode *sip;
10567 	struct inoref *inoref;
10568 	struct ufsmount *ump;
10569 	struct fs *fs;
10570 	ufs_lbn_t i;
10571 #ifdef INVARIANTS
10572 	ufs_lbn_t prevlbn = 0;
10573 #endif
10574 	int deplist __diagused;
10575 
10576 	if (inodedep->id_state & IOSTARTED)
10577 		panic("initiate_write_inodeblock_ufs2: already started");
10578 	inodedep->id_state |= IOSTARTED;
10579 	fs = inodedep->id_fs;
10580 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10581 	LOCK_OWNED(ump);
10582 	dp = (struct ufs2_dinode *)bp->b_data +
10583 	    ino_to_fsbo(fs, inodedep->id_ino);
10584 
10585 	/*
10586 	 * If we're on the unlinked list but have not yet written our
10587 	 * next pointer initialize it here.
10588 	 */
10589 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10590 		struct inodedep *inon;
10591 
10592 		inon = TAILQ_NEXT(inodedep, id_unlinked);
10593 		dp->di_freelink = inon ? inon->id_ino : 0;
10594 		ffs_update_dinode_ckhash(fs, dp);
10595 	}
10596 	/*
10597 	 * If the bitmap is not yet written, then the allocated
10598 	 * inode cannot be written to disk.
10599 	 */
10600 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10601 		if (inodedep->id_savedino2 != NULL)
10602 			panic("initiate_write_inodeblock_ufs2: I/O underway");
10603 		FREE_LOCK(ump);
10604 		sip = malloc(sizeof(struct ufs2_dinode),
10605 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
10606 		ACQUIRE_LOCK(ump);
10607 		inodedep->id_savedino2 = sip;
10608 		*inodedep->id_savedino2 = *dp;
10609 		bzero((caddr_t)dp, sizeof(struct ufs2_dinode));
10610 		dp->di_gen = inodedep->id_savedino2->di_gen;
10611 		dp->di_freelink = inodedep->id_savedino2->di_freelink;
10612 		return;
10613 	}
10614 	/*
10615 	 * If no dependencies, then there is nothing to roll back.
10616 	 */
10617 	inodedep->id_savedsize = dp->di_size;
10618 	inodedep->id_savedextsize = dp->di_extsize;
10619 	inodedep->id_savednlink = dp->di_nlink;
10620 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10621 	    TAILQ_EMPTY(&inodedep->id_extupdt) &&
10622 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
10623 		return;
10624 	/*
10625 	 * Revert the link count to that of the first unwritten journal entry.
10626 	 */
10627 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10628 	if (inoref)
10629 		dp->di_nlink = inoref->if_nlink;
10630 
10631 	/*
10632 	 * Set the ext data dependencies to busy.
10633 	 */
10634 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10635 	     adp = TAILQ_NEXT(adp, ad_next)) {
10636 #ifdef INVARIANTS
10637 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10638 			panic("initiate_write_inodeblock_ufs2: lbn order");
10639 		prevlbn = adp->ad_offset;
10640 		if (dp->di_extb[adp->ad_offset] != adp->ad_newblkno)
10641 			panic("initiate_write_inodeblock_ufs2: "
10642 			    "ext pointer #%jd mismatch %jd != %jd",
10643 			    (intmax_t)adp->ad_offset,
10644 			    (intmax_t)dp->di_extb[adp->ad_offset],
10645 			    (intmax_t)adp->ad_newblkno);
10646 		deplist |= 1 << adp->ad_offset;
10647 		if ((adp->ad_state & ATTACHED) == 0)
10648 			panic("initiate_write_inodeblock_ufs2: Unknown "
10649 			    "state 0x%x", adp->ad_state);
10650 #endif /* INVARIANTS */
10651 		adp->ad_state &= ~ATTACHED;
10652 		adp->ad_state |= UNDONE;
10653 	}
10654 	/*
10655 	 * The on-disk inode cannot claim to be any larger than the last
10656 	 * fragment that has been written. Otherwise, the on-disk inode
10657 	 * might have fragments that were not the last block in the ext
10658 	 * data which would corrupt the filesystem.
10659 	 */
10660 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10661 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10662 		dp->di_extb[adp->ad_offset] = adp->ad_oldblkno;
10663 		/* keep going until hitting a rollback to a frag */
10664 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10665 			continue;
10666 		dp->di_extsize = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10667 		for (i = adp->ad_offset + 1; i < UFS_NXADDR; i++) {
10668 #ifdef INVARIANTS
10669 			if (dp->di_extb[i] != 0 && (deplist & (1 << i)) == 0)
10670 				panic("initiate_write_inodeblock_ufs2: "
10671 				    "lost dep1");
10672 #endif /* INVARIANTS */
10673 			dp->di_extb[i] = 0;
10674 		}
10675 		lastadp = NULL;
10676 		break;
10677 	}
10678 	/*
10679 	 * If we have zero'ed out the last allocated block of the ext
10680 	 * data, roll back the size to the last currently allocated block.
10681 	 * We know that this last allocated block is a full-sized as
10682 	 * we already checked for fragments in the loop above.
10683 	 */
10684 	if (lastadp != NULL &&
10685 	    dp->di_extsize <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10686 		for (i = lastadp->ad_offset; i >= 0; i--)
10687 			if (dp->di_extb[i] != 0)
10688 				break;
10689 		dp->di_extsize = (i + 1) * fs->fs_bsize;
10690 	}
10691 	/*
10692 	 * Set the file data dependencies to busy.
10693 	 */
10694 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10695 	     adp = TAILQ_NEXT(adp, ad_next)) {
10696 #ifdef INVARIANTS
10697 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10698 			panic("softdep_write_inodeblock: lbn order");
10699 		if ((adp->ad_state & ATTACHED) == 0)
10700 			panic("inodedep %p and adp %p not attached", inodedep, adp);
10701 		prevlbn = adp->ad_offset;
10702 		if (!ffs_fsfail_cleanup(ump, 0) &&
10703 		    adp->ad_offset < UFS_NDADDR &&
10704 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10705 			panic("initiate_write_inodeblock_ufs2: "
10706 			    "direct pointer #%jd mismatch %jd != %jd",
10707 			    (intmax_t)adp->ad_offset,
10708 			    (intmax_t)dp->di_db[adp->ad_offset],
10709 			    (intmax_t)adp->ad_newblkno);
10710 		if (!ffs_fsfail_cleanup(ump, 0) &&
10711 		    adp->ad_offset >= UFS_NDADDR &&
10712 		    dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10713 			panic("initiate_write_inodeblock_ufs2: "
10714 			    "indirect pointer #%jd mismatch %jd != %jd",
10715 			    (intmax_t)adp->ad_offset - UFS_NDADDR,
10716 			    (intmax_t)dp->di_ib[adp->ad_offset - UFS_NDADDR],
10717 			    (intmax_t)adp->ad_newblkno);
10718 		deplist |= 1 << adp->ad_offset;
10719 		if ((adp->ad_state & ATTACHED) == 0)
10720 			panic("initiate_write_inodeblock_ufs2: Unknown "
10721 			     "state 0x%x", adp->ad_state);
10722 #endif /* INVARIANTS */
10723 		adp->ad_state &= ~ATTACHED;
10724 		adp->ad_state |= UNDONE;
10725 	}
10726 	/*
10727 	 * The on-disk inode cannot claim to be any larger than the last
10728 	 * fragment that has been written. Otherwise, the on-disk inode
10729 	 * might have fragments that were not the last block in the file
10730 	 * which would corrupt the filesystem.
10731 	 */
10732 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10733 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10734 		if (adp->ad_offset >= UFS_NDADDR)
10735 			break;
10736 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10737 		/* keep going until hitting a rollback to a frag */
10738 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10739 			continue;
10740 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10741 		for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10742 #ifdef INVARIANTS
10743 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10744 				panic("initiate_write_inodeblock_ufs2: "
10745 				    "lost dep2");
10746 #endif /* INVARIANTS */
10747 			dp->di_db[i] = 0;
10748 		}
10749 		for (i = 0; i < UFS_NIADDR; i++) {
10750 #ifdef INVARIANTS
10751 			if (dp->di_ib[i] != 0 &&
10752 			    (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10753 				panic("initiate_write_inodeblock_ufs2: "
10754 				    "lost dep3");
10755 #endif /* INVARIANTS */
10756 			dp->di_ib[i] = 0;
10757 		}
10758 		ffs_update_dinode_ckhash(fs, dp);
10759 		return;
10760 	}
10761 	/*
10762 	 * If we have zero'ed out the last allocated block of the file,
10763 	 * roll back the size to the last currently allocated block.
10764 	 * We know that this last allocated block is a full-sized as
10765 	 * we already checked for fragments in the loop above.
10766 	 */
10767 	if (lastadp != NULL &&
10768 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10769 		for (i = lastadp->ad_offset; i >= 0; i--)
10770 			if (dp->di_db[i] != 0)
10771 				break;
10772 		dp->di_size = (i + 1) * fs->fs_bsize;
10773 	}
10774 	/*
10775 	 * The only dependencies are for indirect blocks.
10776 	 *
10777 	 * The file size for indirect block additions is not guaranteed.
10778 	 * Such a guarantee would be non-trivial to achieve. The conventional
10779 	 * synchronous write implementation also does not make this guarantee.
10780 	 * Fsck should catch and fix discrepancies. Arguably, the file size
10781 	 * can be over-estimated without destroying integrity when the file
10782 	 * moves into the indirect blocks (i.e., is large). If we want to
10783 	 * postpone fsck, we are stuck with this argument.
10784 	 */
10785 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10786 		dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10787 	ffs_update_dinode_ckhash(fs, dp);
10788 }
10789 
10790 /*
10791  * Cancel an indirdep as a result of truncation.  Release all of the
10792  * children allocindirs and place their journal work on the appropriate
10793  * list.
10794  */
10795 static void
10796 cancel_indirdep(
10797 	struct indirdep *indirdep,
10798 	struct buf *bp,
10799 	struct freeblks *freeblks)
10800 {
10801 	struct allocindir *aip;
10802 
10803 	/*
10804 	 * None of the indirect pointers will ever be visible,
10805 	 * so they can simply be tossed. GOINGAWAY ensures
10806 	 * that allocated pointers will be saved in the buffer
10807 	 * cache until they are freed. Note that they will
10808 	 * only be able to be found by their physical address
10809 	 * since the inode mapping the logical address will
10810 	 * be gone. The save buffer used for the safe copy
10811 	 * was allocated in setup_allocindir_phase2 using
10812 	 * the physical address so it could be used for this
10813 	 * purpose. Hence we swap the safe copy with the real
10814 	 * copy, allowing the safe copy to be freed and holding
10815 	 * on to the real copy for later use in indir_trunc.
10816 	 */
10817 	if (indirdep->ir_state & GOINGAWAY)
10818 		panic("cancel_indirdep: already gone");
10819 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
10820 		indirdep->ir_state |= DEPCOMPLETE;
10821 		LIST_REMOVE(indirdep, ir_next);
10822 	}
10823 	indirdep->ir_state |= GOINGAWAY;
10824 	/*
10825 	 * Pass in bp for blocks still have journal writes
10826 	 * pending so we can cancel them on their own.
10827 	 */
10828 	while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != NULL)
10829 		cancel_allocindir(aip, bp, freeblks, 0);
10830 	while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL)
10831 		cancel_allocindir(aip, NULL, freeblks, 0);
10832 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL)
10833 		cancel_allocindir(aip, NULL, freeblks, 0);
10834 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL)
10835 		cancel_allocindir(aip, NULL, freeblks, 0);
10836 	/*
10837 	 * If there are pending partial truncations we need to keep the
10838 	 * old block copy around until they complete.  This is because
10839 	 * the current b_data is not a perfect superset of the available
10840 	 * blocks.
10841 	 */
10842 	if (TAILQ_EMPTY(&indirdep->ir_trunc))
10843 		bcopy(bp->b_data, indirdep->ir_savebp->b_data, bp->b_bcount);
10844 	else
10845 		bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10846 	WORKLIST_REMOVE(&indirdep->ir_list);
10847 	WORKLIST_INSERT(&indirdep->ir_savebp->b_dep, &indirdep->ir_list);
10848 	indirdep->ir_bp = NULL;
10849 	indirdep->ir_freeblks = freeblks;
10850 }
10851 
10852 /*
10853  * Free an indirdep once it no longer has new pointers to track.
10854  */
10855 static void
10856 free_indirdep(struct indirdep *indirdep)
10857 {
10858 
10859 	KASSERT(TAILQ_EMPTY(&indirdep->ir_trunc),
10860 	    ("free_indirdep: Indir trunc list not empty."));
10861 	KASSERT(LIST_EMPTY(&indirdep->ir_completehd),
10862 	    ("free_indirdep: Complete head not empty."));
10863 	KASSERT(LIST_EMPTY(&indirdep->ir_writehd),
10864 	    ("free_indirdep: write head not empty."));
10865 	KASSERT(LIST_EMPTY(&indirdep->ir_donehd),
10866 	    ("free_indirdep: done head not empty."));
10867 	KASSERT(LIST_EMPTY(&indirdep->ir_deplisthd),
10868 	    ("free_indirdep: deplist head not empty."));
10869 	KASSERT((indirdep->ir_state & DEPCOMPLETE),
10870 	    ("free_indirdep: %p still on newblk list.", indirdep));
10871 	KASSERT(indirdep->ir_saveddata == NULL,
10872 	    ("free_indirdep: %p still has saved data.", indirdep));
10873 	KASSERT(indirdep->ir_savebp == NULL,
10874 	    ("free_indirdep: %p still has savebp buffer.", indirdep));
10875 	if (indirdep->ir_state & ONWORKLIST)
10876 		WORKLIST_REMOVE(&indirdep->ir_list);
10877 	WORKITEM_FREE(indirdep, D_INDIRDEP);
10878 }
10879 
10880 /*
10881  * Called before a write to an indirdep.  This routine is responsible for
10882  * rolling back pointers to a safe state which includes only those
10883  * allocindirs which have been completed.
10884  */
10885 static void
10886 initiate_write_indirdep(struct indirdep *indirdep, struct buf *bp)
10887 {
10888 	struct ufsmount *ump;
10889 
10890 	indirdep->ir_state |= IOSTARTED;
10891 	if (indirdep->ir_state & GOINGAWAY)
10892 		panic("disk_io_initiation: indirdep gone");
10893 	/*
10894 	 * If there are no remaining dependencies, this will be writing
10895 	 * the real pointers.
10896 	 */
10897 	if (LIST_EMPTY(&indirdep->ir_deplisthd) &&
10898 	    TAILQ_EMPTY(&indirdep->ir_trunc))
10899 		return;
10900 	/*
10901 	 * Replace up-to-date version with safe version.
10902 	 */
10903 	if (indirdep->ir_saveddata == NULL) {
10904 		ump = VFSTOUFS(indirdep->ir_list.wk_mp);
10905 		LOCK_OWNED(ump);
10906 		FREE_LOCK(ump);
10907 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
10908 		    M_SOFTDEP_FLAGS);
10909 		ACQUIRE_LOCK(ump);
10910 	}
10911 	indirdep->ir_state &= ~ATTACHED;
10912 	indirdep->ir_state |= UNDONE;
10913 	bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10914 	bcopy(indirdep->ir_savebp->b_data, bp->b_data,
10915 	    bp->b_bcount);
10916 }
10917 
10918 /*
10919  * Called when an inode has been cleared in a cg bitmap.  This finally
10920  * eliminates any canceled jaddrefs
10921  */
10922 void
10923 softdep_setup_inofree(struct mount *mp,
10924 	struct buf *bp,
10925 	ino_t ino,
10926 	struct workhead *wkhd)
10927 {
10928 	struct worklist *wk, *wkn;
10929 	struct inodedep *inodedep;
10930 	struct ufsmount *ump;
10931 	uint8_t *inosused;
10932 	struct cg *cgp;
10933 	struct fs *fs;
10934 
10935 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
10936 	    ("softdep_setup_inofree called on non-softdep filesystem"));
10937 	ump = VFSTOUFS(mp);
10938 	ACQUIRE_LOCK(ump);
10939 	if (!ffs_fsfail_cleanup(ump, 0)) {
10940 		fs = ump->um_fs;
10941 		cgp = (struct cg *)bp->b_data;
10942 		inosused = cg_inosused(cgp);
10943 		if (isset(inosused, ino % fs->fs_ipg))
10944 			panic("softdep_setup_inofree: inode %ju not freed.",
10945 			    (uintmax_t)ino);
10946 	}
10947 	if (inodedep_lookup(mp, ino, 0, &inodedep))
10948 		panic("softdep_setup_inofree: ino %ju has existing inodedep %p",
10949 		    (uintmax_t)ino, inodedep);
10950 	if (wkhd) {
10951 		LIST_FOREACH_SAFE(wk, wkhd, wk_list, wkn) {
10952 			if (wk->wk_type != D_JADDREF)
10953 				continue;
10954 			WORKLIST_REMOVE(wk);
10955 			/*
10956 			 * We can free immediately even if the jaddref
10957 			 * isn't attached in a background write as now
10958 			 * the bitmaps are reconciled.
10959 			 */
10960 			wk->wk_state |= COMPLETE | ATTACHED;
10961 			free_jaddref(WK_JADDREF(wk));
10962 		}
10963 		jwork_move(&bp->b_dep, wkhd);
10964 	}
10965 	FREE_LOCK(ump);
10966 }
10967 
10968 /*
10969  * Called via ffs_blkfree() after a set of frags has been cleared from a cg
10970  * map.  Any dependencies waiting for the write to clear are added to the
10971  * buf's list and any jnewblks that are being canceled are discarded
10972  * immediately.
10973  */
10974 void
10975 softdep_setup_blkfree(
10976 	struct mount *mp,
10977 	struct buf *bp,
10978 	ufs2_daddr_t blkno,
10979 	int frags,
10980 	struct workhead *wkhd)
10981 {
10982 	struct bmsafemap *bmsafemap;
10983 	struct jnewblk *jnewblk;
10984 	struct ufsmount *ump;
10985 	struct worklist *wk;
10986 	struct fs *fs;
10987 #ifdef INVARIANTS
10988 	uint8_t *blksfree;
10989 	struct cg *cgp;
10990 	ufs2_daddr_t jstart;
10991 	ufs2_daddr_t jend;
10992 	ufs2_daddr_t end;
10993 	long bno;
10994 	int i;
10995 #endif
10996 
10997 	CTR3(KTR_SUJ,
10998 	    "softdep_setup_blkfree: blkno %jd frags %d wk head %p",
10999 	    blkno, frags, wkhd);
11000 
11001 	ump = VFSTOUFS(mp);
11002 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
11003 	    ("softdep_setup_blkfree called on non-softdep filesystem"));
11004 	ACQUIRE_LOCK(ump);
11005 	/* Lookup the bmsafemap so we track when it is dirty. */
11006 	fs = ump->um_fs;
11007 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
11008 	/*
11009 	 * Detach any jnewblks which have been canceled.  They must linger
11010 	 * until the bitmap is cleared again by ffs_blkfree() to prevent
11011 	 * an unjournaled allocation from hitting the disk.
11012 	 */
11013 	if (wkhd) {
11014 		while ((wk = LIST_FIRST(wkhd)) != NULL) {
11015 			CTR2(KTR_SUJ,
11016 			    "softdep_setup_blkfree: blkno %jd wk type %d",
11017 			    blkno, wk->wk_type);
11018 			WORKLIST_REMOVE(wk);
11019 			if (wk->wk_type != D_JNEWBLK) {
11020 				WORKLIST_INSERT(&bmsafemap->sm_freehd, wk);
11021 				continue;
11022 			}
11023 			jnewblk = WK_JNEWBLK(wk);
11024 			KASSERT(jnewblk->jn_state & GOINGAWAY,
11025 			    ("softdep_setup_blkfree: jnewblk not canceled."));
11026 #ifdef INVARIANTS
11027 			/*
11028 			 * Assert that this block is free in the bitmap
11029 			 * before we discard the jnewblk.
11030 			 */
11031 			cgp = (struct cg *)bp->b_data;
11032 			blksfree = cg_blksfree(cgp);
11033 			bno = dtogd(fs, jnewblk->jn_blkno);
11034 			for (i = jnewblk->jn_oldfrags;
11035 			    i < jnewblk->jn_frags; i++) {
11036 				if (isset(blksfree, bno + i))
11037 					continue;
11038 				panic("softdep_setup_blkfree: not free");
11039 			}
11040 #endif
11041 			/*
11042 			 * Even if it's not attached we can free immediately
11043 			 * as the new bitmap is correct.
11044 			 */
11045 			wk->wk_state |= COMPLETE | ATTACHED;
11046 			free_jnewblk(jnewblk);
11047 		}
11048 	}
11049 
11050 #ifdef INVARIANTS
11051 	/*
11052 	 * Assert that we are not freeing a block which has an outstanding
11053 	 * allocation dependency.
11054 	 */
11055 	fs = VFSTOUFS(mp)->um_fs;
11056 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
11057 	end = blkno + frags;
11058 	LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
11059 		/*
11060 		 * Don't match against blocks that will be freed when the
11061 		 * background write is done.
11062 		 */
11063 		if ((jnewblk->jn_state & (ATTACHED | COMPLETE | DEPCOMPLETE)) ==
11064 		    (COMPLETE | DEPCOMPLETE))
11065 			continue;
11066 		jstart = jnewblk->jn_blkno + jnewblk->jn_oldfrags;
11067 		jend = jnewblk->jn_blkno + jnewblk->jn_frags;
11068 		if ((blkno >= jstart && blkno < jend) ||
11069 		    (end > jstart && end <= jend)) {
11070 			printf("state 0x%X %jd - %d %d dep %p\n",
11071 			    jnewblk->jn_state, jnewblk->jn_blkno,
11072 			    jnewblk->jn_oldfrags, jnewblk->jn_frags,
11073 			    jnewblk->jn_dep);
11074 			panic("softdep_setup_blkfree: "
11075 			    "%jd-%jd(%d) overlaps with %jd-%jd",
11076 			    blkno, end, frags, jstart, jend);
11077 		}
11078 	}
11079 #endif
11080 	FREE_LOCK(ump);
11081 }
11082 
11083 /*
11084  * Revert a block allocation when the journal record that describes it
11085  * is not yet written.
11086  */
11087 static int
11088 jnewblk_rollback(
11089 	struct jnewblk *jnewblk,
11090 	struct fs *fs,
11091 	struct cg *cgp,
11092 	uint8_t *blksfree)
11093 {
11094 	ufs1_daddr_t fragno;
11095 	long cgbno, bbase;
11096 	int frags, blk;
11097 	int i;
11098 
11099 	frags = 0;
11100 	cgbno = dtogd(fs, jnewblk->jn_blkno);
11101 	/*
11102 	 * We have to test which frags need to be rolled back.  We may
11103 	 * be operating on a stale copy when doing background writes.
11104 	 */
11105 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++)
11106 		if (isclr(blksfree, cgbno + i))
11107 			frags++;
11108 	if (frags == 0)
11109 		return (0);
11110 	/*
11111 	 * This is mostly ffs_blkfree() sans some validation and
11112 	 * superblock updates.
11113 	 */
11114 	if (frags == fs->fs_frag) {
11115 		fragno = fragstoblks(fs, cgbno);
11116 		ffs_setblock(fs, blksfree, fragno);
11117 		ffs_clusteracct(fs, cgp, fragno, 1);
11118 		cgp->cg_cs.cs_nbfree++;
11119 	} else {
11120 		cgbno += jnewblk->jn_oldfrags;
11121 		bbase = cgbno - fragnum(fs, cgbno);
11122 		/* Decrement the old frags.  */
11123 		blk = blkmap(fs, blksfree, bbase);
11124 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
11125 		/* Deallocate the fragment */
11126 		for (i = 0; i < frags; i++)
11127 			setbit(blksfree, cgbno + i);
11128 		cgp->cg_cs.cs_nffree += frags;
11129 		/* Add back in counts associated with the new frags */
11130 		blk = blkmap(fs, blksfree, bbase);
11131 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
11132 		/* If a complete block has been reassembled, account for it. */
11133 		fragno = fragstoblks(fs, bbase);
11134 		if (ffs_isblock(fs, blksfree, fragno)) {
11135 			cgp->cg_cs.cs_nffree -= fs->fs_frag;
11136 			ffs_clusteracct(fs, cgp, fragno, 1);
11137 			cgp->cg_cs.cs_nbfree++;
11138 		}
11139 	}
11140 	stat_jnewblk++;
11141 	jnewblk->jn_state &= ~ATTACHED;
11142 	jnewblk->jn_state |= UNDONE;
11143 
11144 	return (frags);
11145 }
11146 
11147 static void
11148 initiate_write_bmsafemap(
11149 	struct bmsafemap *bmsafemap,
11150 	struct buf *bp)			/* The cg block. */
11151 {
11152 	struct jaddref *jaddref;
11153 	struct jnewblk *jnewblk;
11154 	uint8_t *inosused;
11155 	uint8_t *blksfree;
11156 	struct cg *cgp;
11157 	struct fs *fs;
11158 	ino_t ino;
11159 
11160 	/*
11161 	 * If this is a background write, we did this at the time that
11162 	 * the copy was made, so do not need to do it again.
11163 	 */
11164 	if (bmsafemap->sm_state & IOSTARTED)
11165 		return;
11166 	bmsafemap->sm_state |= IOSTARTED;
11167 	/*
11168 	 * Clear any inode allocations which are pending journal writes.
11169 	 */
11170 	if (LIST_FIRST(&bmsafemap->sm_jaddrefhd) != NULL) {
11171 		cgp = (struct cg *)bp->b_data;
11172 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11173 		inosused = cg_inosused(cgp);
11174 		LIST_FOREACH(jaddref, &bmsafemap->sm_jaddrefhd, ja_bmdeps) {
11175 			ino = jaddref->ja_ino % fs->fs_ipg;
11176 			if (isset(inosused, ino)) {
11177 				if ((jaddref->ja_mode & IFMT) == IFDIR)
11178 					cgp->cg_cs.cs_ndir--;
11179 				cgp->cg_cs.cs_nifree++;
11180 				clrbit(inosused, ino);
11181 				jaddref->ja_state &= ~ATTACHED;
11182 				jaddref->ja_state |= UNDONE;
11183 				stat_jaddref++;
11184 			} else
11185 				panic("initiate_write_bmsafemap: inode %ju "
11186 				    "marked free", (uintmax_t)jaddref->ja_ino);
11187 		}
11188 	}
11189 	/*
11190 	 * Clear any block allocations which are pending journal writes.
11191 	 */
11192 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
11193 		cgp = (struct cg *)bp->b_data;
11194 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11195 		blksfree = cg_blksfree(cgp);
11196 		LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
11197 			if (jnewblk_rollback(jnewblk, fs, cgp, blksfree))
11198 				continue;
11199 			panic("initiate_write_bmsafemap: block %jd "
11200 			    "marked free", jnewblk->jn_blkno);
11201 		}
11202 	}
11203 	/*
11204 	 * Move allocation lists to the written lists so they can be
11205 	 * cleared once the block write is complete.
11206 	 */
11207 	LIST_SWAP(&bmsafemap->sm_inodedephd, &bmsafemap->sm_inodedepwr,
11208 	    inodedep, id_deps);
11209 	LIST_SWAP(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
11210 	    newblk, nb_deps);
11211 	LIST_SWAP(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr, worklist,
11212 	    wk_list);
11213 }
11214 
11215 void
11216 softdep_handle_error(struct buf *bp)
11217 {
11218 	struct ufsmount *ump;
11219 
11220 	ump = softdep_bp_to_mp(bp);
11221 	if (ump == NULL)
11222 		return;
11223 
11224 	if (ffs_fsfail_cleanup(ump, bp->b_error)) {
11225 		/*
11226 		 * No future writes will succeed, so the on-disk image is safe.
11227 		 * Pretend that this write succeeded so that the softdep state
11228 		 * will be cleaned up naturally.
11229 		 */
11230 		bp->b_ioflags &= ~BIO_ERROR;
11231 		bp->b_error = 0;
11232 	}
11233 }
11234 
11235 /*
11236  * This routine is called during the completion interrupt
11237  * service routine for a disk write (from the procedure called
11238  * by the device driver to inform the filesystem caches of
11239  * a request completion).  It should be called early in this
11240  * procedure, before the block is made available to other
11241  * processes or other routines are called.
11242  *
11243  */
11244 static void
11245 softdep_disk_write_complete(
11246 	struct buf *bp)		/* describes the completed disk write */
11247 {
11248 	struct worklist *wk;
11249 	struct worklist *owk;
11250 	struct ufsmount *ump;
11251 	struct workhead reattach;
11252 	struct freeblks *freeblks;
11253 	struct buf *sbp;
11254 
11255 	ump = softdep_bp_to_mp(bp);
11256 	KASSERT(LIST_EMPTY(&bp->b_dep) || ump != NULL,
11257 	    ("softdep_disk_write_complete: softdep_bp_to_mp returned NULL "
11258 	     "with outstanding dependencies for buffer %p", bp));
11259 	if (ump == NULL)
11260 		return;
11261 	if ((bp->b_ioflags & BIO_ERROR) != 0)
11262 		softdep_handle_error(bp);
11263 	/*
11264 	 * If an error occurred while doing the write, then the data
11265 	 * has not hit the disk and the dependencies cannot be processed.
11266 	 * But we do have to go through and roll forward any dependencies
11267 	 * that were rolled back before the disk write.
11268 	 */
11269 	sbp = NULL;
11270 	ACQUIRE_LOCK(ump);
11271 	if ((bp->b_ioflags & BIO_ERROR) != 0 && (bp->b_flags & B_INVAL) == 0) {
11272 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
11273 			switch (wk->wk_type) {
11274 			case D_PAGEDEP:
11275 				handle_written_filepage(WK_PAGEDEP(wk), bp, 0);
11276 				continue;
11277 
11278 			case D_INODEDEP:
11279 				handle_written_inodeblock(WK_INODEDEP(wk),
11280 				    bp, 0);
11281 				continue;
11282 
11283 			case D_BMSAFEMAP:
11284 				handle_written_bmsafemap(WK_BMSAFEMAP(wk),
11285 				    bp, 0);
11286 				continue;
11287 
11288 			case D_INDIRDEP:
11289 				handle_written_indirdep(WK_INDIRDEP(wk),
11290 				    bp, &sbp, 0);
11291 				continue;
11292 			default:
11293 				/* nothing to roll forward */
11294 				continue;
11295 			}
11296 		}
11297 		FREE_LOCK(ump);
11298 		if (sbp)
11299 			brelse(sbp);
11300 		return;
11301 	}
11302 	LIST_INIT(&reattach);
11303 
11304 	/*
11305 	 * Ump SU lock must not be released anywhere in this code segment.
11306 	 */
11307 	owk = NULL;
11308 	while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
11309 		WORKLIST_REMOVE(wk);
11310 		atomic_add_long(&dep_write[wk->wk_type], 1);
11311 		if (wk == owk)
11312 			panic("duplicate worklist: %p\n", wk);
11313 		owk = wk;
11314 		switch (wk->wk_type) {
11315 		case D_PAGEDEP:
11316 			if (handle_written_filepage(WK_PAGEDEP(wk), bp,
11317 			    WRITESUCCEEDED))
11318 				WORKLIST_INSERT(&reattach, wk);
11319 			continue;
11320 
11321 		case D_INODEDEP:
11322 			if (handle_written_inodeblock(WK_INODEDEP(wk), bp,
11323 			    WRITESUCCEEDED))
11324 				WORKLIST_INSERT(&reattach, wk);
11325 			continue;
11326 
11327 		case D_BMSAFEMAP:
11328 			if (handle_written_bmsafemap(WK_BMSAFEMAP(wk), bp,
11329 			    WRITESUCCEEDED))
11330 				WORKLIST_INSERT(&reattach, wk);
11331 			continue;
11332 
11333 		case D_MKDIR:
11334 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
11335 			continue;
11336 
11337 		case D_ALLOCDIRECT:
11338 			wk->wk_state |= COMPLETE;
11339 			handle_allocdirect_partdone(WK_ALLOCDIRECT(wk), NULL);
11340 			continue;
11341 
11342 		case D_ALLOCINDIR:
11343 			wk->wk_state |= COMPLETE;
11344 			handle_allocindir_partdone(WK_ALLOCINDIR(wk));
11345 			continue;
11346 
11347 		case D_INDIRDEP:
11348 			if (handle_written_indirdep(WK_INDIRDEP(wk), bp, &sbp,
11349 			    WRITESUCCEEDED))
11350 				WORKLIST_INSERT(&reattach, wk);
11351 			continue;
11352 
11353 		case D_FREEBLKS:
11354 			wk->wk_state |= COMPLETE;
11355 			freeblks = WK_FREEBLKS(wk);
11356 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE &&
11357 			    LIST_EMPTY(&freeblks->fb_jblkdephd))
11358 				add_to_worklist(wk, WK_NODELAY);
11359 			continue;
11360 
11361 		case D_FREEWORK:
11362 			handle_written_freework(WK_FREEWORK(wk));
11363 			break;
11364 
11365 		case D_JSEGDEP:
11366 			free_jsegdep(WK_JSEGDEP(wk));
11367 			continue;
11368 
11369 		case D_JSEG:
11370 			handle_written_jseg(WK_JSEG(wk), bp);
11371 			continue;
11372 
11373 		case D_SBDEP:
11374 			if (handle_written_sbdep(WK_SBDEP(wk), bp))
11375 				WORKLIST_INSERT(&reattach, wk);
11376 			continue;
11377 
11378 		case D_FREEDEP:
11379 			free_freedep(WK_FREEDEP(wk));
11380 			continue;
11381 
11382 		default:
11383 			panic("handle_disk_write_complete: Unknown type %s",
11384 			    TYPENAME(wk->wk_type));
11385 			/* NOTREACHED */
11386 		}
11387 	}
11388 	/*
11389 	 * Reattach any requests that must be redone.
11390 	 */
11391 	while ((wk = LIST_FIRST(&reattach)) != NULL) {
11392 		WORKLIST_REMOVE(wk);
11393 		WORKLIST_INSERT(&bp->b_dep, wk);
11394 	}
11395 	FREE_LOCK(ump);
11396 	if (sbp)
11397 		brelse(sbp);
11398 }
11399 
11400 /*
11401  * Called from within softdep_disk_write_complete above.
11402  */
11403 static void
11404 handle_allocdirect_partdone(
11405 	struct allocdirect *adp,	/* the completed allocdirect */
11406 	struct workhead *wkhd)		/* Work to do when inode is writtne. */
11407 {
11408 	struct allocdirectlst *listhead;
11409 	struct allocdirect *listadp;
11410 	struct inodedep *inodedep;
11411 	long bsize;
11412 
11413 	LOCK_OWNED(VFSTOUFS(adp->ad_block.nb_list.wk_mp));
11414 	if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11415 		return;
11416 	/*
11417 	 * The on-disk inode cannot claim to be any larger than the last
11418 	 * fragment that has been written. Otherwise, the on-disk inode
11419 	 * might have fragments that were not the last block in the file
11420 	 * which would corrupt the filesystem. Thus, we cannot free any
11421 	 * allocdirects after one whose ad_oldblkno claims a fragment as
11422 	 * these blocks must be rolled back to zero before writing the inode.
11423 	 * We check the currently active set of allocdirects in id_inoupdt
11424 	 * or id_extupdt as appropriate.
11425 	 */
11426 	inodedep = adp->ad_inodedep;
11427 	bsize = inodedep->id_fs->fs_bsize;
11428 	if (adp->ad_state & EXTDATA)
11429 		listhead = &inodedep->id_extupdt;
11430 	else
11431 		listhead = &inodedep->id_inoupdt;
11432 	TAILQ_FOREACH(listadp, listhead, ad_next) {
11433 		/* found our block */
11434 		if (listadp == adp)
11435 			break;
11436 		/* continue if ad_oldlbn is not a fragment */
11437 		if (listadp->ad_oldsize == 0 ||
11438 		    listadp->ad_oldsize == bsize)
11439 			continue;
11440 		/* hit a fragment */
11441 		return;
11442 	}
11443 	/*
11444 	 * If we have reached the end of the current list without
11445 	 * finding the just finished dependency, then it must be
11446 	 * on the future dependency list. Future dependencies cannot
11447 	 * be freed until they are moved to the current list.
11448 	 */
11449 	if (listadp == NULL) {
11450 #ifdef INVARIANTS
11451 		if (adp->ad_state & EXTDATA)
11452 			listhead = &inodedep->id_newextupdt;
11453 		else
11454 			listhead = &inodedep->id_newinoupdt;
11455 		TAILQ_FOREACH(listadp, listhead, ad_next)
11456 			/* found our block */
11457 			if (listadp == adp)
11458 				break;
11459 		if (listadp == NULL)
11460 			panic("handle_allocdirect_partdone: lost dep");
11461 #endif /* INVARIANTS */
11462 		return;
11463 	}
11464 	/*
11465 	 * If we have found the just finished dependency, then queue
11466 	 * it along with anything that follows it that is complete.
11467 	 * Since the pointer has not yet been written in the inode
11468 	 * as the dependency prevents it, place the allocdirect on the
11469 	 * bufwait list where it will be freed once the pointer is
11470 	 * valid.
11471 	 */
11472 	if (wkhd == NULL)
11473 		wkhd = &inodedep->id_bufwait;
11474 	for (; adp; adp = listadp) {
11475 		listadp = TAILQ_NEXT(adp, ad_next);
11476 		if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11477 			return;
11478 		TAILQ_REMOVE(listhead, adp, ad_next);
11479 		WORKLIST_INSERT(wkhd, &adp->ad_block.nb_list);
11480 	}
11481 }
11482 
11483 /*
11484  * Called from within softdep_disk_write_complete above.  This routine
11485  * completes successfully written allocindirs.
11486  */
11487 static void
11488 handle_allocindir_partdone(
11489 	struct allocindir *aip)		/* the completed allocindir */
11490 {
11491 	struct indirdep *indirdep;
11492 
11493 	if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
11494 		return;
11495 	indirdep = aip->ai_indirdep;
11496 	LIST_REMOVE(aip, ai_next);
11497 	/*
11498 	 * Don't set a pointer while the buffer is undergoing IO or while
11499 	 * we have active truncations.
11500 	 */
11501 	if (indirdep->ir_state & UNDONE || !TAILQ_EMPTY(&indirdep->ir_trunc)) {
11502 		LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
11503 		return;
11504 	}
11505 	if (indirdep->ir_state & UFS1FMT)
11506 		((ufs1_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11507 		    aip->ai_newblkno;
11508 	else
11509 		((ufs2_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11510 		    aip->ai_newblkno;
11511 	/*
11512 	 * Await the pointer write before freeing the allocindir.
11513 	 */
11514 	LIST_INSERT_HEAD(&indirdep->ir_writehd, aip, ai_next);
11515 }
11516 
11517 /*
11518  * Release segments held on a jwork list.
11519  */
11520 static void
11521 handle_jwork(struct workhead *wkhd)
11522 {
11523 	struct worklist *wk;
11524 
11525 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
11526 		WORKLIST_REMOVE(wk);
11527 		switch (wk->wk_type) {
11528 		case D_JSEGDEP:
11529 			free_jsegdep(WK_JSEGDEP(wk));
11530 			continue;
11531 		case D_FREEDEP:
11532 			free_freedep(WK_FREEDEP(wk));
11533 			continue;
11534 		case D_FREEFRAG:
11535 			rele_jseg(WK_JSEG(WK_FREEFRAG(wk)->ff_jdep));
11536 			WORKITEM_FREE(wk, D_FREEFRAG);
11537 			continue;
11538 		case D_FREEWORK:
11539 			handle_written_freework(WK_FREEWORK(wk));
11540 			continue;
11541 		default:
11542 			panic("handle_jwork: Unknown type %s\n",
11543 			    TYPENAME(wk->wk_type));
11544 		}
11545 	}
11546 }
11547 
11548 /*
11549  * Handle the bufwait list on an inode when it is safe to release items
11550  * held there.  This normally happens after an inode block is written but
11551  * may be delayed and handled later if there are pending journal items that
11552  * are not yet safe to be released.
11553  */
11554 static struct freefile *
11555 handle_bufwait(
11556 	struct inodedep *inodedep,
11557 	struct workhead *refhd)
11558 {
11559 	struct jaddref *jaddref;
11560 	struct freefile *freefile;
11561 	struct worklist *wk;
11562 
11563 	freefile = NULL;
11564 	while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
11565 		WORKLIST_REMOVE(wk);
11566 		switch (wk->wk_type) {
11567 		case D_FREEFILE:
11568 			/*
11569 			 * We defer adding freefile to the worklist
11570 			 * until all other additions have been made to
11571 			 * ensure that it will be done after all the
11572 			 * old blocks have been freed.
11573 			 */
11574 			if (freefile != NULL)
11575 				panic("handle_bufwait: freefile");
11576 			freefile = WK_FREEFILE(wk);
11577 			continue;
11578 
11579 		case D_MKDIR:
11580 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
11581 			continue;
11582 
11583 		case D_DIRADD:
11584 			diradd_inode_written(WK_DIRADD(wk), inodedep);
11585 			continue;
11586 
11587 		case D_FREEFRAG:
11588 			wk->wk_state |= COMPLETE;
11589 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE)
11590 				add_to_worklist(wk, 0);
11591 			continue;
11592 
11593 		case D_DIRREM:
11594 			wk->wk_state |= COMPLETE;
11595 			add_to_worklist(wk, 0);
11596 			continue;
11597 
11598 		case D_ALLOCDIRECT:
11599 		case D_ALLOCINDIR:
11600 			free_newblk(WK_NEWBLK(wk));
11601 			continue;
11602 
11603 		case D_JNEWBLK:
11604 			wk->wk_state |= COMPLETE;
11605 			free_jnewblk(WK_JNEWBLK(wk));
11606 			continue;
11607 
11608 		/*
11609 		 * Save freed journal segments and add references on
11610 		 * the supplied list which will delay their release
11611 		 * until the cg bitmap is cleared on disk.
11612 		 */
11613 		case D_JSEGDEP:
11614 			if (refhd == NULL)
11615 				free_jsegdep(WK_JSEGDEP(wk));
11616 			else
11617 				WORKLIST_INSERT(refhd, wk);
11618 			continue;
11619 
11620 		case D_JADDREF:
11621 			jaddref = WK_JADDREF(wk);
11622 			TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
11623 			    if_deps);
11624 			/*
11625 			 * Transfer any jaddrefs to the list to be freed with
11626 			 * the bitmap if we're handling a removed file.
11627 			 */
11628 			if (refhd == NULL) {
11629 				wk->wk_state |= COMPLETE;
11630 				free_jaddref(jaddref);
11631 			} else
11632 				WORKLIST_INSERT(refhd, wk);
11633 			continue;
11634 
11635 		default:
11636 			panic("handle_bufwait: Unknown type %p(%s)",
11637 			    wk, TYPENAME(wk->wk_type));
11638 			/* NOTREACHED */
11639 		}
11640 	}
11641 	return (freefile);
11642 }
11643 /*
11644  * Called from within softdep_disk_write_complete above to restore
11645  * in-memory inode block contents to their most up-to-date state. Note
11646  * that this routine is always called from interrupt level with further
11647  * interrupts from this device blocked.
11648  *
11649  * If the write did not succeed, we will do all the roll-forward
11650  * operations, but we will not take the actions that will allow its
11651  * dependencies to be processed.
11652  */
11653 static int
11654 handle_written_inodeblock(
11655 	struct inodedep *inodedep,
11656 	struct buf *bp,		/* buffer containing the inode block */
11657 	int flags)
11658 {
11659 	struct freefile *freefile;
11660 	struct allocdirect *adp, *nextadp;
11661 	struct ufs1_dinode *dp1 = NULL;
11662 	struct ufs2_dinode *dp2 = NULL;
11663 	struct workhead wkhd;
11664 	int hadchanges, fstype;
11665 	ino_t freelink;
11666 
11667 	LIST_INIT(&wkhd);
11668 	hadchanges = 0;
11669 	freefile = NULL;
11670 	if ((inodedep->id_state & IOSTARTED) == 0)
11671 		panic("handle_written_inodeblock: not started");
11672 	inodedep->id_state &= ~IOSTARTED;
11673 	if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC) {
11674 		fstype = UFS1;
11675 		dp1 = (struct ufs1_dinode *)bp->b_data +
11676 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11677 		freelink = dp1->di_freelink;
11678 	} else {
11679 		fstype = UFS2;
11680 		dp2 = (struct ufs2_dinode *)bp->b_data +
11681 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11682 		freelink = dp2->di_freelink;
11683 	}
11684 	/*
11685 	 * Leave this inodeblock dirty until it's in the list.
11686 	 */
11687 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) == UNLINKED &&
11688 	    (flags & WRITESUCCEEDED)) {
11689 		struct inodedep *inon;
11690 
11691 		inon = TAILQ_NEXT(inodedep, id_unlinked);
11692 		if ((inon == NULL && freelink == 0) ||
11693 		    (inon && inon->id_ino == freelink)) {
11694 			if (inon)
11695 				inon->id_state |= UNLINKPREV;
11696 			inodedep->id_state |= UNLINKNEXT;
11697 		}
11698 		hadchanges = 1;
11699 	}
11700 	/*
11701 	 * If we had to rollback the inode allocation because of
11702 	 * bitmaps being incomplete, then simply restore it.
11703 	 * Keep the block dirty so that it will not be reclaimed until
11704 	 * all associated dependencies have been cleared and the
11705 	 * corresponding updates written to disk.
11706 	 */
11707 	if (inodedep->id_savedino1 != NULL) {
11708 		hadchanges = 1;
11709 		if (fstype == UFS1)
11710 			*dp1 = *inodedep->id_savedino1;
11711 		else
11712 			*dp2 = *inodedep->id_savedino2;
11713 		free(inodedep->id_savedino1, M_SAVEDINO);
11714 		inodedep->id_savedino1 = NULL;
11715 		if ((bp->b_flags & B_DELWRI) == 0)
11716 			stat_inode_bitmap++;
11717 		bdirty(bp);
11718 		/*
11719 		 * If the inode is clear here and GOINGAWAY it will never
11720 		 * be written.  Process the bufwait and clear any pending
11721 		 * work which may include the freefile.
11722 		 */
11723 		if (inodedep->id_state & GOINGAWAY)
11724 			goto bufwait;
11725 		return (1);
11726 	}
11727 	if (flags & WRITESUCCEEDED)
11728 		inodedep->id_state |= COMPLETE;
11729 	/*
11730 	 * Roll forward anything that had to be rolled back before
11731 	 * the inode could be updated.
11732 	 */
11733 	for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
11734 		nextadp = TAILQ_NEXT(adp, ad_next);
11735 		if (adp->ad_state & ATTACHED)
11736 			panic("handle_written_inodeblock: new entry");
11737 		if (fstype == UFS1) {
11738 			if (adp->ad_offset < UFS_NDADDR) {
11739 				if (dp1->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11740 					panic("%s %s #%jd mismatch %d != %jd",
11741 					    "handle_written_inodeblock:",
11742 					    "direct pointer",
11743 					    (intmax_t)adp->ad_offset,
11744 					    dp1->di_db[adp->ad_offset],
11745 					    (intmax_t)adp->ad_oldblkno);
11746 				dp1->di_db[adp->ad_offset] = adp->ad_newblkno;
11747 			} else {
11748 				if (dp1->di_ib[adp->ad_offset - UFS_NDADDR] !=
11749 				    0)
11750 					panic("%s: %s #%jd allocated as %d",
11751 					    "handle_written_inodeblock",
11752 					    "indirect pointer",
11753 					    (intmax_t)adp->ad_offset -
11754 					    UFS_NDADDR,
11755 					    dp1->di_ib[adp->ad_offset -
11756 					    UFS_NDADDR]);
11757 				dp1->di_ib[adp->ad_offset - UFS_NDADDR] =
11758 				    adp->ad_newblkno;
11759 			}
11760 		} else {
11761 			if (adp->ad_offset < UFS_NDADDR) {
11762 				if (dp2->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11763 					panic("%s: %s #%jd %s %jd != %jd",
11764 					    "handle_written_inodeblock",
11765 					    "direct pointer",
11766 					    (intmax_t)adp->ad_offset, "mismatch",
11767 					    (intmax_t)dp2->di_db[adp->ad_offset],
11768 					    (intmax_t)adp->ad_oldblkno);
11769 				dp2->di_db[adp->ad_offset] = adp->ad_newblkno;
11770 			} else {
11771 				if (dp2->di_ib[adp->ad_offset - UFS_NDADDR] !=
11772 				    0)
11773 					panic("%s: %s #%jd allocated as %jd",
11774 					    "handle_written_inodeblock",
11775 					    "indirect pointer",
11776 					    (intmax_t)adp->ad_offset -
11777 					    UFS_NDADDR,
11778 					    (intmax_t)
11779 					    dp2->di_ib[adp->ad_offset -
11780 					    UFS_NDADDR]);
11781 				dp2->di_ib[adp->ad_offset - UFS_NDADDR] =
11782 				    adp->ad_newblkno;
11783 			}
11784 		}
11785 		adp->ad_state &= ~UNDONE;
11786 		adp->ad_state |= ATTACHED;
11787 		hadchanges = 1;
11788 	}
11789 	for (adp = TAILQ_FIRST(&inodedep->id_extupdt); adp; adp = nextadp) {
11790 		nextadp = TAILQ_NEXT(adp, ad_next);
11791 		if (adp->ad_state & ATTACHED)
11792 			panic("handle_written_inodeblock: new entry");
11793 		if (dp2->di_extb[adp->ad_offset] != adp->ad_oldblkno)
11794 			panic("%s: direct pointers #%jd %s %jd != %jd",
11795 			    "handle_written_inodeblock",
11796 			    (intmax_t)adp->ad_offset, "mismatch",
11797 			    (intmax_t)dp2->di_extb[adp->ad_offset],
11798 			    (intmax_t)adp->ad_oldblkno);
11799 		dp2->di_extb[adp->ad_offset] = adp->ad_newblkno;
11800 		adp->ad_state &= ~UNDONE;
11801 		adp->ad_state |= ATTACHED;
11802 		hadchanges = 1;
11803 	}
11804 	if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
11805 		stat_direct_blk_ptrs++;
11806 	/*
11807 	 * Reset the file size to its most up-to-date value.
11808 	 */
11809 	if (inodedep->id_savedsize == -1 || inodedep->id_savedextsize == -1)
11810 		panic("handle_written_inodeblock: bad size");
11811 	if (inodedep->id_savednlink > UFS_LINK_MAX)
11812 		panic("handle_written_inodeblock: Invalid link count "
11813 		    "%jd for inodedep %p", (uintmax_t)inodedep->id_savednlink,
11814 		    inodedep);
11815 	if (fstype == UFS1) {
11816 		if (dp1->di_nlink != inodedep->id_savednlink) {
11817 			dp1->di_nlink = inodedep->id_savednlink;
11818 			hadchanges = 1;
11819 		}
11820 		if (dp1->di_size != inodedep->id_savedsize) {
11821 			dp1->di_size = inodedep->id_savedsize;
11822 			hadchanges = 1;
11823 		}
11824 	} else {
11825 		if (dp2->di_nlink != inodedep->id_savednlink) {
11826 			dp2->di_nlink = inodedep->id_savednlink;
11827 			hadchanges = 1;
11828 		}
11829 		if (dp2->di_size != inodedep->id_savedsize) {
11830 			dp2->di_size = inodedep->id_savedsize;
11831 			hadchanges = 1;
11832 		}
11833 		if (dp2->di_extsize != inodedep->id_savedextsize) {
11834 			dp2->di_extsize = inodedep->id_savedextsize;
11835 			hadchanges = 1;
11836 		}
11837 	}
11838 	inodedep->id_savedsize = -1;
11839 	inodedep->id_savedextsize = -1;
11840 	inodedep->id_savednlink = -1;
11841 	/*
11842 	 * If there were any rollbacks in the inode block, then it must be
11843 	 * marked dirty so that its will eventually get written back in
11844 	 * its correct form.
11845 	 */
11846 	if (hadchanges) {
11847 		if (fstype == UFS2)
11848 			ffs_update_dinode_ckhash(inodedep->id_fs, dp2);
11849 		bdirty(bp);
11850 	}
11851 bufwait:
11852 	/*
11853 	 * If the write did not succeed, we have done all the roll-forward
11854 	 * operations, but we cannot take the actions that will allow its
11855 	 * dependencies to be processed.
11856 	 */
11857 	if ((flags & WRITESUCCEEDED) == 0)
11858 		return (hadchanges);
11859 	/*
11860 	 * Process any allocdirects that completed during the update.
11861 	 */
11862 	if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
11863 		handle_allocdirect_partdone(adp, &wkhd);
11864 	if ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
11865 		handle_allocdirect_partdone(adp, &wkhd);
11866 	/*
11867 	 * Process deallocations that were held pending until the
11868 	 * inode had been written to disk. Freeing of the inode
11869 	 * is delayed until after all blocks have been freed to
11870 	 * avoid creation of new <vfsid, inum, lbn> triples
11871 	 * before the old ones have been deleted.  Completely
11872 	 * unlinked inodes are not processed until the unlinked
11873 	 * inode list is written or the last reference is removed.
11874 	 */
11875 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) != UNLINKED) {
11876 		freefile = handle_bufwait(inodedep, NULL);
11877 		if (freefile && !LIST_EMPTY(&wkhd)) {
11878 			WORKLIST_INSERT(&wkhd, &freefile->fx_list);
11879 			freefile = NULL;
11880 		}
11881 	}
11882 	/*
11883 	 * Move rolled forward dependency completions to the bufwait list
11884 	 * now that those that were already written have been processed.
11885 	 */
11886 	if (!LIST_EMPTY(&wkhd) && hadchanges == 0)
11887 		panic("handle_written_inodeblock: bufwait but no changes");
11888 	jwork_move(&inodedep->id_bufwait, &wkhd);
11889 
11890 	if (freefile != NULL) {
11891 		/*
11892 		 * If the inode is goingaway it was never written.  Fake up
11893 		 * the state here so free_inodedep() can succeed.
11894 		 */
11895 		if (inodedep->id_state & GOINGAWAY)
11896 			inodedep->id_state |= COMPLETE | DEPCOMPLETE;
11897 		if (free_inodedep(inodedep) == 0)
11898 			panic("handle_written_inodeblock: live inodedep %p",
11899 			    inodedep);
11900 		add_to_worklist(&freefile->fx_list, 0);
11901 		return (0);
11902 	}
11903 
11904 	/*
11905 	 * If no outstanding dependencies, free it.
11906 	 */
11907 	if (free_inodedep(inodedep) ||
11908 	    (TAILQ_FIRST(&inodedep->id_inoreflst) == 0 &&
11909 	     TAILQ_FIRST(&inodedep->id_inoupdt) == 0 &&
11910 	     TAILQ_FIRST(&inodedep->id_extupdt) == 0 &&
11911 	     LIST_FIRST(&inodedep->id_bufwait) == 0))
11912 		return (0);
11913 	return (hadchanges);
11914 }
11915 
11916 /*
11917  * Perform needed roll-forwards and kick off any dependencies that
11918  * can now be processed.
11919  *
11920  * If the write did not succeed, we will do all the roll-forward
11921  * operations, but we will not take the actions that will allow its
11922  * dependencies to be processed.
11923  */
11924 static int
11925 handle_written_indirdep(
11926 	struct indirdep *indirdep,
11927 	struct buf *bp,
11928 	struct buf **bpp,
11929 	int flags)
11930 {
11931 	struct allocindir *aip;
11932 	struct buf *sbp;
11933 	int chgs;
11934 
11935 	if (indirdep->ir_state & GOINGAWAY)
11936 		panic("handle_written_indirdep: indirdep gone");
11937 	if ((indirdep->ir_state & IOSTARTED) == 0)
11938 		panic("handle_written_indirdep: IO not started");
11939 	chgs = 0;
11940 	/*
11941 	 * If there were rollbacks revert them here.
11942 	 */
11943 	if (indirdep->ir_saveddata) {
11944 		bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
11945 		if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11946 			free(indirdep->ir_saveddata, M_INDIRDEP);
11947 			indirdep->ir_saveddata = NULL;
11948 		}
11949 		chgs = 1;
11950 	}
11951 	indirdep->ir_state &= ~(UNDONE | IOSTARTED);
11952 	indirdep->ir_state |= ATTACHED;
11953 	/*
11954 	 * If the write did not succeed, we have done all the roll-forward
11955 	 * operations, but we cannot take the actions that will allow its
11956 	 * dependencies to be processed.
11957 	 */
11958 	if ((flags & WRITESUCCEEDED) == 0) {
11959 		stat_indir_blk_ptrs++;
11960 		bdirty(bp);
11961 		return (1);
11962 	}
11963 	/*
11964 	 * Move allocindirs with written pointers to the completehd if
11965 	 * the indirdep's pointer is not yet written.  Otherwise
11966 	 * free them here.
11967 	 */
11968 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL) {
11969 		LIST_REMOVE(aip, ai_next);
11970 		if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
11971 			LIST_INSERT_HEAD(&indirdep->ir_completehd, aip,
11972 			    ai_next);
11973 			newblk_freefrag(&aip->ai_block);
11974 			continue;
11975 		}
11976 		free_newblk(&aip->ai_block);
11977 	}
11978 	/*
11979 	 * Move allocindirs that have finished dependency processing from
11980 	 * the done list to the write list after updating the pointers.
11981 	 */
11982 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11983 		while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL) {
11984 			handle_allocindir_partdone(aip);
11985 			if (aip == LIST_FIRST(&indirdep->ir_donehd))
11986 				panic("disk_write_complete: not gone");
11987 			chgs = 1;
11988 		}
11989 	}
11990 	/*
11991 	 * Preserve the indirdep if there were any changes or if it is not
11992 	 * yet valid on disk.
11993 	 */
11994 	if (chgs) {
11995 		stat_indir_blk_ptrs++;
11996 		bdirty(bp);
11997 		return (1);
11998 	}
11999 	/*
12000 	 * If there were no changes we can discard the savedbp and detach
12001 	 * ourselves from the buf.  We are only carrying completed pointers
12002 	 * in this case.
12003 	 */
12004 	sbp = indirdep->ir_savebp;
12005 	sbp->b_flags |= B_INVAL | B_NOCACHE;
12006 	indirdep->ir_savebp = NULL;
12007 	indirdep->ir_bp = NULL;
12008 	if (*bpp != NULL)
12009 		panic("handle_written_indirdep: bp already exists.");
12010 	*bpp = sbp;
12011 	/*
12012 	 * The indirdep may not be freed until its parent points at it.
12013 	 */
12014 	if (indirdep->ir_state & DEPCOMPLETE)
12015 		free_indirdep(indirdep);
12016 
12017 	return (0);
12018 }
12019 
12020 /*
12021  * Process a diradd entry after its dependent inode has been written.
12022  */
12023 static void
12024 diradd_inode_written(
12025 	struct diradd *dap,
12026 	struct inodedep *inodedep)
12027 {
12028 
12029 	LOCK_OWNED(VFSTOUFS(dap->da_list.wk_mp));
12030 	dap->da_state |= COMPLETE;
12031 	complete_diradd(dap);
12032 	WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
12033 }
12034 
12035 /*
12036  * Returns true if the bmsafemap will have rollbacks when written.  Must only
12037  * be called with the per-filesystem lock and the buf lock on the cg held.
12038  */
12039 static int
12040 bmsafemap_backgroundwrite(
12041 	struct bmsafemap *bmsafemap,
12042 	struct buf *bp)
12043 {
12044 	int dirty;
12045 
12046 	LOCK_OWNED(VFSTOUFS(bmsafemap->sm_list.wk_mp));
12047 	dirty = !LIST_EMPTY(&bmsafemap->sm_jaddrefhd) |
12048 	    !LIST_EMPTY(&bmsafemap->sm_jnewblkhd);
12049 	/*
12050 	 * If we're initiating a background write we need to process the
12051 	 * rollbacks as they exist now, not as they exist when IO starts.
12052 	 * No other consumers will look at the contents of the shadowed
12053 	 * buf so this is safe to do here.
12054 	 */
12055 	if (bp->b_xflags & BX_BKGRDMARKER)
12056 		initiate_write_bmsafemap(bmsafemap, bp);
12057 
12058 	return (dirty);
12059 }
12060 
12061 /*
12062  * Re-apply an allocation when a cg write is complete.
12063  */
12064 static int
12065 jnewblk_rollforward(
12066 	struct jnewblk *jnewblk,
12067 	struct fs *fs,
12068 	struct cg *cgp,
12069 	uint8_t *blksfree)
12070 {
12071 	ufs1_daddr_t fragno;
12072 	ufs2_daddr_t blkno;
12073 	long cgbno, bbase;
12074 	int frags, blk;
12075 	int i;
12076 
12077 	frags = 0;
12078 	cgbno = dtogd(fs, jnewblk->jn_blkno);
12079 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++) {
12080 		if (isclr(blksfree, cgbno + i))
12081 			panic("jnewblk_rollforward: re-allocated fragment");
12082 		frags++;
12083 	}
12084 	if (frags == fs->fs_frag) {
12085 		blkno = fragstoblks(fs, cgbno);
12086 		ffs_clrblock(fs, blksfree, (long)blkno);
12087 		ffs_clusteracct(fs, cgp, blkno, -1);
12088 		cgp->cg_cs.cs_nbfree--;
12089 	} else {
12090 		bbase = cgbno - fragnum(fs, cgbno);
12091 		cgbno += jnewblk->jn_oldfrags;
12092                 /* If a complete block had been reassembled, account for it. */
12093 		fragno = fragstoblks(fs, bbase);
12094 		if (ffs_isblock(fs, blksfree, fragno)) {
12095 			cgp->cg_cs.cs_nffree += fs->fs_frag;
12096 			ffs_clusteracct(fs, cgp, fragno, -1);
12097 			cgp->cg_cs.cs_nbfree--;
12098 		}
12099 		/* Decrement the old frags.  */
12100 		blk = blkmap(fs, blksfree, bbase);
12101 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
12102 		/* Allocate the fragment */
12103 		for (i = 0; i < frags; i++)
12104 			clrbit(blksfree, cgbno + i);
12105 		cgp->cg_cs.cs_nffree -= frags;
12106 		/* Add back in counts associated with the new frags */
12107 		blk = blkmap(fs, blksfree, bbase);
12108 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
12109 	}
12110 	return (frags);
12111 }
12112 
12113 /*
12114  * Complete a write to a bmsafemap structure.  Roll forward any bitmap
12115  * changes if it's not a background write.  Set all written dependencies
12116  * to DEPCOMPLETE and free the structure if possible.
12117  *
12118  * If the write did not succeed, we will do all the roll-forward
12119  * operations, but we will not take the actions that will allow its
12120  * dependencies to be processed.
12121  */
12122 static int
12123 handle_written_bmsafemap(
12124 	struct bmsafemap *bmsafemap,
12125 	struct buf *bp,
12126 	int flags)
12127 {
12128 	struct newblk *newblk;
12129 	struct inodedep *inodedep;
12130 	struct jaddref *jaddref, *jatmp;
12131 	struct jnewblk *jnewblk, *jntmp;
12132 	struct ufsmount *ump;
12133 	uint8_t *inosused;
12134 	uint8_t *blksfree;
12135 	struct cg *cgp;
12136 	struct fs *fs;
12137 	ino_t ino;
12138 	int foreground;
12139 	int chgs;
12140 
12141 	if ((bmsafemap->sm_state & IOSTARTED) == 0)
12142 		panic("handle_written_bmsafemap: Not started\n");
12143 	ump = VFSTOUFS(bmsafemap->sm_list.wk_mp);
12144 	chgs = 0;
12145 	bmsafemap->sm_state &= ~IOSTARTED;
12146 	foreground = (bp->b_xflags & BX_BKGRDMARKER) == 0;
12147 	/*
12148 	 * If write was successful, release journal work that was waiting
12149 	 * on the write. Otherwise move the work back.
12150 	 */
12151 	if (flags & WRITESUCCEEDED)
12152 		handle_jwork(&bmsafemap->sm_freewr);
12153 	else
12154 		LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
12155 		    worklist, wk_list);
12156 
12157 	/*
12158 	 * Restore unwritten inode allocation pending jaddref writes.
12159 	 */
12160 	if (!LIST_EMPTY(&bmsafemap->sm_jaddrefhd)) {
12161 		cgp = (struct cg *)bp->b_data;
12162 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
12163 		inosused = cg_inosused(cgp);
12164 		LIST_FOREACH_SAFE(jaddref, &bmsafemap->sm_jaddrefhd,
12165 		    ja_bmdeps, jatmp) {
12166 			if ((jaddref->ja_state & UNDONE) == 0)
12167 				continue;
12168 			ino = jaddref->ja_ino % fs->fs_ipg;
12169 			if (isset(inosused, ino))
12170 				panic("handle_written_bmsafemap: "
12171 				    "re-allocated inode");
12172 			/* Do the roll-forward only if it's a real copy. */
12173 			if (foreground) {
12174 				if ((jaddref->ja_mode & IFMT) == IFDIR)
12175 					cgp->cg_cs.cs_ndir++;
12176 				cgp->cg_cs.cs_nifree--;
12177 				setbit(inosused, ino);
12178 				chgs = 1;
12179 			}
12180 			jaddref->ja_state &= ~UNDONE;
12181 			jaddref->ja_state |= ATTACHED;
12182 			free_jaddref(jaddref);
12183 		}
12184 	}
12185 	/*
12186 	 * Restore any block allocations which are pending journal writes.
12187 	 */
12188 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
12189 		cgp = (struct cg *)bp->b_data;
12190 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
12191 		blksfree = cg_blksfree(cgp);
12192 		LIST_FOREACH_SAFE(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps,
12193 		    jntmp) {
12194 			if ((jnewblk->jn_state & UNDONE) == 0)
12195 				continue;
12196 			/* Do the roll-forward only if it's a real copy. */
12197 			if (foreground &&
12198 			    jnewblk_rollforward(jnewblk, fs, cgp, blksfree))
12199 				chgs = 1;
12200 			jnewblk->jn_state &= ~(UNDONE | NEWBLOCK);
12201 			jnewblk->jn_state |= ATTACHED;
12202 			free_jnewblk(jnewblk);
12203 		}
12204 	}
12205 	/*
12206 	 * If the write did not succeed, we have done all the roll-forward
12207 	 * operations, but we cannot take the actions that will allow its
12208 	 * dependencies to be processed.
12209 	 */
12210 	if ((flags & WRITESUCCEEDED) == 0) {
12211 		LIST_CONCAT(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
12212 		    newblk, nb_deps);
12213 		LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
12214 		    worklist, wk_list);
12215 		if (foreground)
12216 			bdirty(bp);
12217 		return (1);
12218 	}
12219 	while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkwr))) {
12220 		newblk->nb_state |= DEPCOMPLETE;
12221 		newblk->nb_state &= ~ONDEPLIST;
12222 		newblk->nb_bmsafemap = NULL;
12223 		LIST_REMOVE(newblk, nb_deps);
12224 		if (newblk->nb_list.wk_type == D_ALLOCDIRECT)
12225 			handle_allocdirect_partdone(
12226 			    WK_ALLOCDIRECT(&newblk->nb_list), NULL);
12227 		else if (newblk->nb_list.wk_type == D_ALLOCINDIR)
12228 			handle_allocindir_partdone(
12229 			    WK_ALLOCINDIR(&newblk->nb_list));
12230 		else if (newblk->nb_list.wk_type != D_NEWBLK)
12231 			panic("handle_written_bmsafemap: Unexpected type: %s",
12232 			    TYPENAME(newblk->nb_list.wk_type));
12233 	}
12234 	while ((inodedep = LIST_FIRST(&bmsafemap->sm_inodedepwr)) != NULL) {
12235 		inodedep->id_state |= DEPCOMPLETE;
12236 		inodedep->id_state &= ~ONDEPLIST;
12237 		LIST_REMOVE(inodedep, id_deps);
12238 		inodedep->id_bmsafemap = NULL;
12239 	}
12240 	LIST_REMOVE(bmsafemap, sm_next);
12241 	if (chgs == 0 && LIST_EMPTY(&bmsafemap->sm_jaddrefhd) &&
12242 	    LIST_EMPTY(&bmsafemap->sm_jnewblkhd) &&
12243 	    LIST_EMPTY(&bmsafemap->sm_newblkhd) &&
12244 	    LIST_EMPTY(&bmsafemap->sm_inodedephd) &&
12245 	    LIST_EMPTY(&bmsafemap->sm_freehd)) {
12246 		LIST_REMOVE(bmsafemap, sm_hash);
12247 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
12248 		return (0);
12249 	}
12250 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
12251 	if (foreground)
12252 		bdirty(bp);
12253 	return (1);
12254 }
12255 
12256 /*
12257  * Try to free a mkdir dependency.
12258  */
12259 static void
12260 complete_mkdir(struct mkdir *mkdir)
12261 {
12262 	struct diradd *dap;
12263 
12264 	if ((mkdir->md_state & ALLCOMPLETE) != ALLCOMPLETE)
12265 		return;
12266 	LIST_REMOVE(mkdir, md_mkdirs);
12267 	dap = mkdir->md_diradd;
12268 	dap->da_state &= ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
12269 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0) {
12270 		dap->da_state |= DEPCOMPLETE;
12271 		complete_diradd(dap);
12272 	}
12273 	WORKITEM_FREE(mkdir, D_MKDIR);
12274 }
12275 
12276 /*
12277  * Handle the completion of a mkdir dependency.
12278  */
12279 static void
12280 handle_written_mkdir(struct mkdir *mkdir, int type)
12281 {
12282 
12283 	if ((mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY)) != type)
12284 		panic("handle_written_mkdir: bad type");
12285 	mkdir->md_state |= COMPLETE;
12286 	complete_mkdir(mkdir);
12287 }
12288 
12289 static int
12290 free_pagedep(struct pagedep *pagedep)
12291 {
12292 	int i;
12293 
12294 	if (pagedep->pd_state & NEWBLOCK)
12295 		return (0);
12296 	if (!LIST_EMPTY(&pagedep->pd_dirremhd))
12297 		return (0);
12298 	for (i = 0; i < DAHASHSZ; i++)
12299 		if (!LIST_EMPTY(&pagedep->pd_diraddhd[i]))
12300 			return (0);
12301 	if (!LIST_EMPTY(&pagedep->pd_pendinghd))
12302 		return (0);
12303 	if (!LIST_EMPTY(&pagedep->pd_jmvrefhd))
12304 		return (0);
12305 	if (pagedep->pd_state & ONWORKLIST)
12306 		WORKLIST_REMOVE(&pagedep->pd_list);
12307 	LIST_REMOVE(pagedep, pd_hash);
12308 	WORKITEM_FREE(pagedep, D_PAGEDEP);
12309 
12310 	return (1);
12311 }
12312 
12313 /*
12314  * Called from within softdep_disk_write_complete above.
12315  * A write operation was just completed. Removed inodes can
12316  * now be freed and associated block pointers may be committed.
12317  * Note that this routine is always called from interrupt level
12318  * with further interrupts from this device blocked.
12319  *
12320  * If the write did not succeed, we will do all the roll-forward
12321  * operations, but we will not take the actions that will allow its
12322  * dependencies to be processed.
12323  */
12324 static int
12325 handle_written_filepage(
12326 	struct pagedep *pagedep,
12327 	struct buf *bp,		/* buffer containing the written page */
12328 	int flags)
12329 {
12330 	struct dirrem *dirrem;
12331 	struct diradd *dap, *nextdap;
12332 	struct direct *ep;
12333 	int i, chgs;
12334 
12335 	if ((pagedep->pd_state & IOSTARTED) == 0)
12336 		panic("handle_written_filepage: not started");
12337 	pagedep->pd_state &= ~IOSTARTED;
12338 	if ((flags & WRITESUCCEEDED) == 0)
12339 		goto rollforward;
12340 	/*
12341 	 * Process any directory removals that have been committed.
12342 	 */
12343 	while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
12344 		LIST_REMOVE(dirrem, dm_next);
12345 		dirrem->dm_state |= COMPLETE;
12346 		dirrem->dm_dirinum = pagedep->pd_ino;
12347 		KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
12348 		    ("handle_written_filepage: Journal entries not written."));
12349 		add_to_worklist(&dirrem->dm_list, 0);
12350 	}
12351 	/*
12352 	 * Free any directory additions that have been committed.
12353 	 * If it is a newly allocated block, we have to wait until
12354 	 * the on-disk directory inode claims the new block.
12355 	 */
12356 	if ((pagedep->pd_state & NEWBLOCK) == 0)
12357 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
12358 			free_diradd(dap, NULL);
12359 rollforward:
12360 	/*
12361 	 * Uncommitted directory entries must be restored.
12362 	 */
12363 	for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
12364 		for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
12365 		     dap = nextdap) {
12366 			nextdap = LIST_NEXT(dap, da_pdlist);
12367 			if (dap->da_state & ATTACHED)
12368 				panic("handle_written_filepage: attached");
12369 			ep = (struct direct *)
12370 			    ((char *)bp->b_data + dap->da_offset);
12371 			ep->d_ino = dap->da_newinum;
12372 			dap->da_state &= ~UNDONE;
12373 			dap->da_state |= ATTACHED;
12374 			chgs = 1;
12375 			/*
12376 			 * If the inode referenced by the directory has
12377 			 * been written out, then the dependency can be
12378 			 * moved to the pending list.
12379 			 */
12380 			if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
12381 				LIST_REMOVE(dap, da_pdlist);
12382 				LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
12383 				    da_pdlist);
12384 			}
12385 		}
12386 	}
12387 	/*
12388 	 * If there were any rollbacks in the directory, then it must be
12389 	 * marked dirty so that its will eventually get written back in
12390 	 * its correct form.
12391 	 */
12392 	if (chgs || (flags & WRITESUCCEEDED) == 0) {
12393 		if ((bp->b_flags & B_DELWRI) == 0)
12394 			stat_dir_entry++;
12395 		bdirty(bp);
12396 		return (1);
12397 	}
12398 	/*
12399 	 * If we are not waiting for a new directory block to be
12400 	 * claimed by its inode, then the pagedep will be freed.
12401 	 * Otherwise it will remain to track any new entries on
12402 	 * the page in case they are fsync'ed.
12403 	 */
12404 	free_pagedep(pagedep);
12405 	return (0);
12406 }
12407 
12408 /*
12409  * Writing back in-core inode structures.
12410  *
12411  * The filesystem only accesses an inode's contents when it occupies an
12412  * "in-core" inode structure.  These "in-core" structures are separate from
12413  * the page frames used to cache inode blocks.  Only the latter are
12414  * transferred to/from the disk.  So, when the updated contents of the
12415  * "in-core" inode structure are copied to the corresponding in-memory inode
12416  * block, the dependencies are also transferred.  The following procedure is
12417  * called when copying a dirty "in-core" inode to a cached inode block.
12418  */
12419 
12420 /*
12421  * Called when an inode is loaded from disk. If the effective link count
12422  * differed from the actual link count when it was last flushed, then we
12423  * need to ensure that the correct effective link count is put back.
12424  */
12425 void
12426 softdep_load_inodeblock(
12427 	struct inode *ip)	/* the "in_core" copy of the inode */
12428 {
12429 	struct inodedep *inodedep;
12430 	struct ufsmount *ump;
12431 
12432 	ump = ITOUMP(ip);
12433 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
12434 	    ("softdep_load_inodeblock called on non-softdep filesystem"));
12435 	/*
12436 	 * Check for alternate nlink count.
12437 	 */
12438 	ip->i_effnlink = ip->i_nlink;
12439 	ACQUIRE_LOCK(ump);
12440 	if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0) {
12441 		FREE_LOCK(ump);
12442 		return;
12443 	}
12444 	if (ip->i_nlink != inodedep->id_nlinkwrote &&
12445 	    inodedep->id_nlinkwrote != -1) {
12446 		KASSERT(ip->i_nlink == 0 &&
12447 		    (ump->um_flags & UM_FSFAIL_CLEANUP) != 0,
12448 		    ("read bad i_nlink value"));
12449 		ip->i_effnlink = ip->i_nlink = inodedep->id_nlinkwrote;
12450 	}
12451 	ip->i_effnlink -= inodedep->id_nlinkdelta;
12452 	KASSERT(ip->i_effnlink >= 0,
12453 	    ("softdep_load_inodeblock: negative i_effnlink"));
12454 	FREE_LOCK(ump);
12455 }
12456 
12457 /*
12458  * This routine is called just before the "in-core" inode
12459  * information is to be copied to the in-memory inode block.
12460  * Recall that an inode block contains several inodes. If
12461  * the force flag is set, then the dependencies will be
12462  * cleared so that the update can always be made. Note that
12463  * the buffer is locked when this routine is called, so we
12464  * will never be in the middle of writing the inode block
12465  * to disk.
12466  */
12467 void
12468 softdep_update_inodeblock(
12469 	struct inode *ip,	/* the "in_core" copy of the inode */
12470 	struct buf *bp,		/* the buffer containing the inode block */
12471 	int waitfor)		/* nonzero => update must be allowed */
12472 {
12473 	struct inodedep *inodedep;
12474 	struct inoref *inoref;
12475 	struct ufsmount *ump;
12476 	struct worklist *wk;
12477 	struct mount *mp;
12478 	struct buf *ibp;
12479 	struct fs *fs;
12480 	int error;
12481 
12482 	ump = ITOUMP(ip);
12483 	mp = UFSTOVFS(ump);
12484 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
12485 	    ("softdep_update_inodeblock called on non-softdep filesystem"));
12486 	fs = ump->um_fs;
12487 	/*
12488 	 * Preserve the freelink that is on disk.  clear_unlinked_inodedep()
12489 	 * does not have access to the in-core ip so must write directly into
12490 	 * the inode block buffer when setting freelink.
12491 	 */
12492 	if (fs->fs_magic == FS_UFS1_MAGIC)
12493 		DIP_SET(ip, i_freelink, ((struct ufs1_dinode *)bp->b_data +
12494 		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
12495 	else
12496 		DIP_SET(ip, i_freelink, ((struct ufs2_dinode *)bp->b_data +
12497 		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
12498 	/*
12499 	 * If the effective link count is not equal to the actual link
12500 	 * count, then we must track the difference in an inodedep while
12501 	 * the inode is (potentially) tossed out of the cache. Otherwise,
12502 	 * if there is no existing inodedep, then there are no dependencies
12503 	 * to track.
12504 	 */
12505 	ACQUIRE_LOCK(ump);
12506 again:
12507 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12508 		FREE_LOCK(ump);
12509 		if (ip->i_effnlink != ip->i_nlink)
12510 			panic("softdep_update_inodeblock: bad link count");
12511 		return;
12512 	}
12513 	KASSERT(ip->i_nlink >= inodedep->id_nlinkdelta,
12514 	    ("softdep_update_inodeblock inconsistent ip %p i_nlink %d "
12515 	    "inodedep %p id_nlinkdelta %jd",
12516 	    ip, ip->i_nlink, inodedep, (intmax_t)inodedep->id_nlinkdelta));
12517 	inodedep->id_nlinkwrote = ip->i_nlink;
12518 	if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink)
12519 		panic("softdep_update_inodeblock: bad delta");
12520 	/*
12521 	 * If we're flushing all dependencies we must also move any waiting
12522 	 * for journal writes onto the bufwait list prior to I/O.
12523 	 */
12524 	if (waitfor) {
12525 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12526 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12527 			    == DEPCOMPLETE) {
12528 				jwait(&inoref->if_list, MNT_WAIT);
12529 				goto again;
12530 			}
12531 		}
12532 	}
12533 	/*
12534 	 * Changes have been initiated. Anything depending on these
12535 	 * changes cannot occur until this inode has been written.
12536 	 */
12537 	inodedep->id_state &= ~COMPLETE;
12538 	if ((inodedep->id_state & ONWORKLIST) == 0)
12539 		WORKLIST_INSERT(&bp->b_dep, &inodedep->id_list);
12540 	/*
12541 	 * Any new dependencies associated with the incore inode must
12542 	 * now be moved to the list associated with the buffer holding
12543 	 * the in-memory copy of the inode. Once merged process any
12544 	 * allocdirects that are completed by the merger.
12545 	 */
12546 	merge_inode_lists(&inodedep->id_newinoupdt, &inodedep->id_inoupdt);
12547 	if (!TAILQ_EMPTY(&inodedep->id_inoupdt))
12548 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt),
12549 		    NULL);
12550 	merge_inode_lists(&inodedep->id_newextupdt, &inodedep->id_extupdt);
12551 	if (!TAILQ_EMPTY(&inodedep->id_extupdt))
12552 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_extupdt),
12553 		    NULL);
12554 	/*
12555 	 * Now that the inode has been pushed into the buffer, the
12556 	 * operations dependent on the inode being written to disk
12557 	 * can be moved to the id_bufwait so that they will be
12558 	 * processed when the buffer I/O completes.
12559 	 */
12560 	while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
12561 		WORKLIST_REMOVE(wk);
12562 		WORKLIST_INSERT(&inodedep->id_bufwait, wk);
12563 	}
12564 	/*
12565 	 * Newly allocated inodes cannot be written until the bitmap
12566 	 * that allocates them have been written (indicated by
12567 	 * DEPCOMPLETE being set in id_state). If we are doing a
12568 	 * forced sync (e.g., an fsync on a file), we force the bitmap
12569 	 * to be written so that the update can be done.
12570 	 */
12571 	if (waitfor == 0) {
12572 		FREE_LOCK(ump);
12573 		return;
12574 	}
12575 retry:
12576 	if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) != 0) {
12577 		FREE_LOCK(ump);
12578 		return;
12579 	}
12580 	ibp = inodedep->id_bmsafemap->sm_buf;
12581 	ibp = getdirtybuf(ibp, LOCK_PTR(ump), MNT_WAIT);
12582 	if (ibp == NULL) {
12583 		/*
12584 		 * If ibp came back as NULL, the dependency could have been
12585 		 * freed while we slept.  Look it up again, and check to see
12586 		 * that it has completed.
12587 		 */
12588 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
12589 			goto retry;
12590 		FREE_LOCK(ump);
12591 		return;
12592 	}
12593 	FREE_LOCK(ump);
12594 	if ((error = bwrite(ibp)) != 0)
12595 		softdep_error("softdep_update_inodeblock: bwrite", error);
12596 }
12597 
12598 /*
12599  * Merge the a new inode dependency list (such as id_newinoupdt) into an
12600  * old inode dependency list (such as id_inoupdt).
12601  */
12602 static void
12603 merge_inode_lists(
12604 	struct allocdirectlst *newlisthead,
12605 	struct allocdirectlst *oldlisthead)
12606 {
12607 	struct allocdirect *listadp, *newadp;
12608 
12609 	newadp = TAILQ_FIRST(newlisthead);
12610 	if (newadp != NULL)
12611 		LOCK_OWNED(VFSTOUFS(newadp->ad_block.nb_list.wk_mp));
12612 	for (listadp = TAILQ_FIRST(oldlisthead); listadp && newadp;) {
12613 		if (listadp->ad_offset < newadp->ad_offset) {
12614 			listadp = TAILQ_NEXT(listadp, ad_next);
12615 			continue;
12616 		}
12617 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
12618 		TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
12619 		if (listadp->ad_offset == newadp->ad_offset) {
12620 			allocdirect_merge(oldlisthead, newadp,
12621 			    listadp);
12622 			listadp = newadp;
12623 		}
12624 		newadp = TAILQ_FIRST(newlisthead);
12625 	}
12626 	while ((newadp = TAILQ_FIRST(newlisthead)) != NULL) {
12627 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
12628 		TAILQ_INSERT_TAIL(oldlisthead, newadp, ad_next);
12629 	}
12630 }
12631 
12632 /*
12633  * If we are doing an fsync, then we must ensure that any directory
12634  * entries for the inode have been written after the inode gets to disk.
12635  */
12636 int
12637 softdep_fsync(
12638 	struct vnode *vp)	/* the "in_core" copy of the inode */
12639 {
12640 	struct inodedep *inodedep;
12641 	struct pagedep *pagedep;
12642 	struct inoref *inoref;
12643 	struct ufsmount *ump;
12644 	struct worklist *wk;
12645 	struct diradd *dap;
12646 	struct mount *mp;
12647 	struct vnode *pvp;
12648 	struct inode *ip;
12649 	struct buf *bp;
12650 	struct fs *fs;
12651 	struct thread *td = curthread;
12652 	int error, flushparent, pagedep_new_block;
12653 	ino_t parentino;
12654 	ufs_lbn_t lbn;
12655 
12656 	ip = VTOI(vp);
12657 	mp = vp->v_mount;
12658 	ump = VFSTOUFS(mp);
12659 	fs = ump->um_fs;
12660 	if (MOUNTEDSOFTDEP(mp) == 0)
12661 		return (0);
12662 	ACQUIRE_LOCK(ump);
12663 restart:
12664 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12665 		FREE_LOCK(ump);
12666 		return (0);
12667 	}
12668 	TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12669 		if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12670 		    == DEPCOMPLETE) {
12671 			jwait(&inoref->if_list, MNT_WAIT);
12672 			goto restart;
12673 		}
12674 	}
12675 	if (!LIST_EMPTY(&inodedep->id_inowait) ||
12676 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
12677 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
12678 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
12679 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt))
12680 		panic("softdep_fsync: pending ops %p", inodedep);
12681 	for (error = 0, flushparent = 0; ; ) {
12682 		if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
12683 			break;
12684 		if (wk->wk_type != D_DIRADD)
12685 			panic("softdep_fsync: Unexpected type %s",
12686 			    TYPENAME(wk->wk_type));
12687 		dap = WK_DIRADD(wk);
12688 		/*
12689 		 * Flush our parent if this directory entry has a MKDIR_PARENT
12690 		 * dependency or is contained in a newly allocated block.
12691 		 */
12692 		if (dap->da_state & DIRCHG)
12693 			pagedep = dap->da_previous->dm_pagedep;
12694 		else
12695 			pagedep = dap->da_pagedep;
12696 		parentino = pagedep->pd_ino;
12697 		lbn = pagedep->pd_lbn;
12698 		if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE)
12699 			panic("softdep_fsync: dirty");
12700 		if ((dap->da_state & MKDIR_PARENT) ||
12701 		    (pagedep->pd_state & NEWBLOCK))
12702 			flushparent = 1;
12703 		else
12704 			flushparent = 0;
12705 		/*
12706 		 * If we are being fsync'ed as part of vgone'ing this vnode,
12707 		 * then we will not be able to release and recover the
12708 		 * vnode below, so we just have to give up on writing its
12709 		 * directory entry out. It will eventually be written, just
12710 		 * not now, but then the user was not asking to have it
12711 		 * written, so we are not breaking any promises.
12712 		 */
12713 		if (VN_IS_DOOMED(vp))
12714 			break;
12715 		/*
12716 		 * We prevent deadlock by always fetching inodes from the
12717 		 * root, moving down the directory tree. Thus, when fetching
12718 		 * our parent directory, we first try to get the lock. If
12719 		 * that fails, we must unlock ourselves before requesting
12720 		 * the lock on our parent. See the comment in ufs_lookup
12721 		 * for details on possible races.
12722 		 */
12723 		FREE_LOCK(ump);
12724 		error = get_parent_vp(vp, mp, parentino, NULL, NULL, NULL,
12725 		    &pvp);
12726 		if (error == ERELOOKUP)
12727 			error = 0;
12728 		if (error != 0)
12729 			return (error);
12730 		/*
12731 		 * All MKDIR_PARENT dependencies and all the NEWBLOCK pagedeps
12732 		 * that are contained in direct blocks will be resolved by
12733 		 * doing a ffs_update. Pagedeps contained in indirect blocks
12734 		 * may require a complete sync'ing of the directory. So, we
12735 		 * try the cheap and fast ffs_update first, and if that fails,
12736 		 * then we do the slower ffs_syncvnode of the directory.
12737 		 */
12738 		if (flushparent) {
12739 			int locked;
12740 
12741 			if ((error = ffs_update(pvp, 1)) != 0) {
12742 				vput(pvp);
12743 				return (error);
12744 			}
12745 			ACQUIRE_LOCK(ump);
12746 			locked = 1;
12747 			if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0) {
12748 				if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) != NULL) {
12749 					if (wk->wk_type != D_DIRADD)
12750 						panic("softdep_fsync: Unexpected type %s",
12751 						      TYPENAME(wk->wk_type));
12752 					dap = WK_DIRADD(wk);
12753 					if (dap->da_state & DIRCHG)
12754 						pagedep = dap->da_previous->dm_pagedep;
12755 					else
12756 						pagedep = dap->da_pagedep;
12757 					pagedep_new_block = pagedep->pd_state & NEWBLOCK;
12758 					FREE_LOCK(ump);
12759 					locked = 0;
12760 					if (pagedep_new_block && (error =
12761 					    ffs_syncvnode(pvp, MNT_WAIT, 0))) {
12762 						vput(pvp);
12763 						return (error);
12764 					}
12765 				}
12766 			}
12767 			if (locked)
12768 				FREE_LOCK(ump);
12769 		}
12770 		/*
12771 		 * Flush directory page containing the inode's name.
12772 		 */
12773 		error = bread(pvp, lbn, blksize(fs, VTOI(pvp), lbn), td->td_ucred,
12774 		    &bp);
12775 		if (error == 0)
12776 			error = bwrite(bp);
12777 		else
12778 			brelse(bp);
12779 		vput(pvp);
12780 		if (!ffs_fsfail_cleanup(ump, error))
12781 			return (error);
12782 		ACQUIRE_LOCK(ump);
12783 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
12784 			break;
12785 	}
12786 	FREE_LOCK(ump);
12787 	return (0);
12788 }
12789 
12790 /*
12791  * Flush all the dirty bitmaps associated with the block device
12792  * before flushing the rest of the dirty blocks so as to reduce
12793  * the number of dependencies that will have to be rolled back.
12794  *
12795  * XXX Unused?
12796  */
12797 void
12798 softdep_fsync_mountdev(struct vnode *vp)
12799 {
12800 	struct buf *bp, *nbp;
12801 	struct worklist *wk;
12802 	struct bufobj *bo;
12803 
12804 	if (!vn_isdisk(vp))
12805 		panic("softdep_fsync_mountdev: vnode not a disk");
12806 	bo = &vp->v_bufobj;
12807 restart:
12808 	BO_LOCK(bo);
12809 	TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
12810 		/*
12811 		 * If it is already scheduled, skip to the next buffer.
12812 		 */
12813 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL))
12814 			continue;
12815 
12816 		if ((bp->b_flags & B_DELWRI) == 0)
12817 			panic("softdep_fsync_mountdev: not dirty");
12818 		/*
12819 		 * We are only interested in bitmaps with outstanding
12820 		 * dependencies.
12821 		 */
12822 		if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
12823 		    wk->wk_type != D_BMSAFEMAP ||
12824 		    (bp->b_vflags & BV_BKGRDINPROG)) {
12825 			BUF_UNLOCK(bp);
12826 			continue;
12827 		}
12828 		BO_UNLOCK(bo);
12829 		bremfree(bp);
12830 		(void) bawrite(bp);
12831 		goto restart;
12832 	}
12833 	drain_output(vp);
12834 	BO_UNLOCK(bo);
12835 }
12836 
12837 /*
12838  * Sync all cylinder groups that were dirty at the time this function is
12839  * called.  Newly dirtied cgs will be inserted before the sentinel.  This
12840  * is used to flush freedep activity that may be holding up writes to a
12841  * indirect block.
12842  */
12843 static int
12844 sync_cgs(struct mount *mp, int waitfor)
12845 {
12846 	struct bmsafemap *bmsafemap;
12847 	struct bmsafemap *sentinel;
12848 	struct ufsmount *ump;
12849 	struct buf *bp;
12850 	int error;
12851 
12852 	sentinel = malloc(sizeof(*sentinel), M_BMSAFEMAP, M_ZERO | M_WAITOK);
12853 	sentinel->sm_cg = -1;
12854 	ump = VFSTOUFS(mp);
12855 	error = 0;
12856 	ACQUIRE_LOCK(ump);
12857 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, sentinel, sm_next);
12858 	for (bmsafemap = LIST_NEXT(sentinel, sm_next); bmsafemap != NULL;
12859 	    bmsafemap = LIST_NEXT(sentinel, sm_next)) {
12860 		/* Skip sentinels and cgs with no work to release. */
12861 		if (bmsafemap->sm_cg == -1 ||
12862 		    (LIST_EMPTY(&bmsafemap->sm_freehd) &&
12863 		    LIST_EMPTY(&bmsafemap->sm_freewr))) {
12864 			LIST_REMOVE(sentinel, sm_next);
12865 			LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12866 			continue;
12867 		}
12868 		/*
12869 		 * If we don't get the lock and we're waiting try again, if
12870 		 * not move on to the next buf and try to sync it.
12871 		 */
12872 		bp = getdirtybuf(bmsafemap->sm_buf, LOCK_PTR(ump), waitfor);
12873 		if (bp == NULL && waitfor == MNT_WAIT)
12874 			continue;
12875 		LIST_REMOVE(sentinel, sm_next);
12876 		LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12877 		if (bp == NULL)
12878 			continue;
12879 		FREE_LOCK(ump);
12880 		if (waitfor == MNT_NOWAIT)
12881 			bawrite(bp);
12882 		else
12883 			error = bwrite(bp);
12884 		ACQUIRE_LOCK(ump);
12885 		if (error)
12886 			break;
12887 	}
12888 	LIST_REMOVE(sentinel, sm_next);
12889 	FREE_LOCK(ump);
12890 	free(sentinel, M_BMSAFEMAP);
12891 	return (error);
12892 }
12893 
12894 /*
12895  * This routine is called when we are trying to synchronously flush a
12896  * file. This routine must eliminate any filesystem metadata dependencies
12897  * so that the syncing routine can succeed.
12898  */
12899 int
12900 softdep_sync_metadata(struct vnode *vp)
12901 {
12902 	struct inode *ip;
12903 	int error;
12904 
12905 	ip = VTOI(vp);
12906 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12907 	    ("softdep_sync_metadata called on non-softdep filesystem"));
12908 	/*
12909 	 * Ensure that any direct block dependencies have been cleared,
12910 	 * truncations are started, and inode references are journaled.
12911 	 */
12912 	ACQUIRE_LOCK(VFSTOUFS(vp->v_mount));
12913 	/*
12914 	 * Write all journal records to prevent rollbacks on devvp.
12915 	 */
12916 	if (vp->v_type == VCHR)
12917 		softdep_flushjournal(vp->v_mount);
12918 	error = flush_inodedep_deps(vp, vp->v_mount, ip->i_number);
12919 	/*
12920 	 * Ensure that all truncates are written so we won't find deps on
12921 	 * indirect blocks.
12922 	 */
12923 	process_truncates(vp);
12924 	FREE_LOCK(VFSTOUFS(vp->v_mount));
12925 
12926 	return (error);
12927 }
12928 
12929 /*
12930  * This routine is called when we are attempting to sync a buf with
12931  * dependencies.  If waitfor is MNT_NOWAIT it attempts to schedule any
12932  * other IO it can but returns EBUSY if the buffer is not yet able to
12933  * be written.  Dependencies which will not cause rollbacks will always
12934  * return 0.
12935  */
12936 int
12937 softdep_sync_buf(struct vnode *vp,
12938 	struct buf *bp,
12939 	int waitfor)
12940 {
12941 	struct indirdep *indirdep;
12942 	struct pagedep *pagedep;
12943 	struct allocindir *aip;
12944 	struct newblk *newblk;
12945 	struct ufsmount *ump;
12946 	struct buf *nbp;
12947 	struct worklist *wk;
12948 	int i, error;
12949 
12950 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12951 	    ("softdep_sync_buf called on non-softdep filesystem"));
12952 	/*
12953 	 * For VCHR we just don't want to force flush any dependencies that
12954 	 * will cause rollbacks.
12955 	 */
12956 	if (vp->v_type == VCHR) {
12957 		if (waitfor == MNT_NOWAIT && softdep_count_dependencies(bp, 0))
12958 			return (EBUSY);
12959 		return (0);
12960 	}
12961 	ump = VFSTOUFS(vp->v_mount);
12962 	ACQUIRE_LOCK(ump);
12963 	/*
12964 	 * As we hold the buffer locked, none of its dependencies
12965 	 * will disappear.
12966 	 */
12967 	error = 0;
12968 top:
12969 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
12970 		switch (wk->wk_type) {
12971 		case D_ALLOCDIRECT:
12972 		case D_ALLOCINDIR:
12973 			newblk = WK_NEWBLK(wk);
12974 			if (newblk->nb_jnewblk != NULL) {
12975 				if (waitfor == MNT_NOWAIT) {
12976 					error = EBUSY;
12977 					goto out_unlock;
12978 				}
12979 				jwait(&newblk->nb_jnewblk->jn_list, waitfor);
12980 				goto top;
12981 			}
12982 			if (newblk->nb_state & DEPCOMPLETE ||
12983 			    waitfor == MNT_NOWAIT)
12984 				continue;
12985 			nbp = newblk->nb_bmsafemap->sm_buf;
12986 			nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
12987 			if (nbp == NULL)
12988 				goto top;
12989 			FREE_LOCK(ump);
12990 			if ((error = bwrite(nbp)) != 0)
12991 				goto out;
12992 			ACQUIRE_LOCK(ump);
12993 			continue;
12994 
12995 		case D_INDIRDEP:
12996 			indirdep = WK_INDIRDEP(wk);
12997 			if (waitfor == MNT_NOWAIT) {
12998 				if (!TAILQ_EMPTY(&indirdep->ir_trunc) ||
12999 				    !LIST_EMPTY(&indirdep->ir_deplisthd)) {
13000 					error = EBUSY;
13001 					goto out_unlock;
13002 				}
13003 			}
13004 			if (!TAILQ_EMPTY(&indirdep->ir_trunc))
13005 				panic("softdep_sync_buf: truncation pending.");
13006 		restart:
13007 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
13008 				newblk = (struct newblk *)aip;
13009 				if (newblk->nb_jnewblk != NULL) {
13010 					jwait(&newblk->nb_jnewblk->jn_list,
13011 					    waitfor);
13012 					goto restart;
13013 				}
13014 				if (newblk->nb_state & DEPCOMPLETE)
13015 					continue;
13016 				nbp = newblk->nb_bmsafemap->sm_buf;
13017 				nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
13018 				if (nbp == NULL)
13019 					goto restart;
13020 				FREE_LOCK(ump);
13021 				if ((error = bwrite(nbp)) != 0)
13022 					goto out;
13023 				ACQUIRE_LOCK(ump);
13024 				goto restart;
13025 			}
13026 			continue;
13027 
13028 		case D_PAGEDEP:
13029 			/*
13030 			 * Only flush directory entries in synchronous passes.
13031 			 */
13032 			if (waitfor != MNT_WAIT) {
13033 				error = EBUSY;
13034 				goto out_unlock;
13035 			}
13036 			/*
13037 			 * While syncing snapshots, we must allow recursive
13038 			 * lookups.
13039 			 */
13040 			BUF_AREC(bp);
13041 			/*
13042 			 * We are trying to sync a directory that may
13043 			 * have dependencies on both its own metadata
13044 			 * and/or dependencies on the inodes of any
13045 			 * recently allocated files. We walk its diradd
13046 			 * lists pushing out the associated inode.
13047 			 */
13048 			pagedep = WK_PAGEDEP(wk);
13049 			for (i = 0; i < DAHASHSZ; i++) {
13050 				if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
13051 					continue;
13052 				error = flush_pagedep_deps(vp, wk->wk_mp,
13053 				    &pagedep->pd_diraddhd[i], bp);
13054 				if (error != 0) {
13055 					if (error != ERELOOKUP)
13056 						BUF_NOREC(bp);
13057 					goto out_unlock;
13058 				}
13059 			}
13060 			BUF_NOREC(bp);
13061 			continue;
13062 
13063 		case D_FREEWORK:
13064 		case D_FREEDEP:
13065 		case D_JSEGDEP:
13066 		case D_JNEWBLK:
13067 			continue;
13068 
13069 		default:
13070 			panic("softdep_sync_buf: Unknown type %s",
13071 			    TYPENAME(wk->wk_type));
13072 			/* NOTREACHED */
13073 		}
13074 	}
13075 out_unlock:
13076 	FREE_LOCK(ump);
13077 out:
13078 	return (error);
13079 }
13080 
13081 /*
13082  * Flush the dependencies associated with an inodedep.
13083  */
13084 static int
13085 flush_inodedep_deps(
13086 	struct vnode *vp,
13087 	struct mount *mp,
13088 	ino_t ino)
13089 {
13090 	struct inodedep *inodedep;
13091 	struct inoref *inoref;
13092 	struct ufsmount *ump;
13093 	int error, waitfor;
13094 
13095 	/*
13096 	 * This work is done in two passes. The first pass grabs most
13097 	 * of the buffers and begins asynchronously writing them. The
13098 	 * only way to wait for these asynchronous writes is to sleep
13099 	 * on the filesystem vnode which may stay busy for a long time
13100 	 * if the filesystem is active. So, instead, we make a second
13101 	 * pass over the dependencies blocking on each write. In the
13102 	 * usual case we will be blocking against a write that we
13103 	 * initiated, so when it is done the dependency will have been
13104 	 * resolved. Thus the second pass is expected to end quickly.
13105 	 * We give a brief window at the top of the loop to allow
13106 	 * any pending I/O to complete.
13107 	 */
13108 	ump = VFSTOUFS(mp);
13109 	LOCK_OWNED(ump);
13110 	for (error = 0, waitfor = MNT_NOWAIT; ; ) {
13111 		if (error)
13112 			return (error);
13113 		FREE_LOCK(ump);
13114 		ACQUIRE_LOCK(ump);
13115 restart:
13116 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
13117 			return (0);
13118 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
13119 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
13120 			    == DEPCOMPLETE) {
13121 				jwait(&inoref->if_list, MNT_WAIT);
13122 				goto restart;
13123 			}
13124 		}
13125 		if (flush_deplist(&inodedep->id_inoupdt, waitfor, &error) ||
13126 		    flush_deplist(&inodedep->id_newinoupdt, waitfor, &error) ||
13127 		    flush_deplist(&inodedep->id_extupdt, waitfor, &error) ||
13128 		    flush_deplist(&inodedep->id_newextupdt, waitfor, &error))
13129 			continue;
13130 		/*
13131 		 * If pass2, we are done, otherwise do pass 2.
13132 		 */
13133 		if (waitfor == MNT_WAIT)
13134 			break;
13135 		waitfor = MNT_WAIT;
13136 	}
13137 	/*
13138 	 * Try freeing inodedep in case all dependencies have been removed.
13139 	 */
13140 	if (inodedep_lookup(mp, ino, 0, &inodedep) != 0)
13141 		(void) free_inodedep(inodedep);
13142 	return (0);
13143 }
13144 
13145 /*
13146  * Flush an inode dependency list.
13147  */
13148 static int
13149 flush_deplist(
13150 	struct allocdirectlst *listhead,
13151 	int waitfor,
13152 	int *errorp)
13153 {
13154 	struct allocdirect *adp;
13155 	struct newblk *newblk;
13156 	struct ufsmount *ump;
13157 	struct buf *bp;
13158 
13159 	if ((adp = TAILQ_FIRST(listhead)) == NULL)
13160 		return (0);
13161 	ump = VFSTOUFS(adp->ad_list.wk_mp);
13162 	LOCK_OWNED(ump);
13163 	TAILQ_FOREACH(adp, listhead, ad_next) {
13164 		newblk = (struct newblk *)adp;
13165 		if (newblk->nb_jnewblk != NULL) {
13166 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
13167 			return (1);
13168 		}
13169 		if (newblk->nb_state & DEPCOMPLETE)
13170 			continue;
13171 		bp = newblk->nb_bmsafemap->sm_buf;
13172 		bp = getdirtybuf(bp, LOCK_PTR(ump), waitfor);
13173 		if (bp == NULL) {
13174 			if (waitfor == MNT_NOWAIT)
13175 				continue;
13176 			return (1);
13177 		}
13178 		FREE_LOCK(ump);
13179 		if (waitfor == MNT_NOWAIT)
13180 			bawrite(bp);
13181 		else
13182 			*errorp = bwrite(bp);
13183 		ACQUIRE_LOCK(ump);
13184 		return (1);
13185 	}
13186 	return (0);
13187 }
13188 
13189 /*
13190  * Flush dependencies associated with an allocdirect block.
13191  */
13192 static int
13193 flush_newblk_dep(
13194 	struct vnode *vp,
13195 	struct mount *mp,
13196 	ufs_lbn_t lbn)
13197 {
13198 	struct newblk *newblk;
13199 	struct ufsmount *ump;
13200 	struct bufobj *bo;
13201 	struct inode *ip;
13202 	struct buf *bp;
13203 	ufs2_daddr_t blkno;
13204 	int error;
13205 
13206 	error = 0;
13207 	bo = &vp->v_bufobj;
13208 	ip = VTOI(vp);
13209 	blkno = DIP(ip, i_db[lbn]);
13210 	if (blkno == 0)
13211 		panic("flush_newblk_dep: Missing block");
13212 	ump = VFSTOUFS(mp);
13213 	ACQUIRE_LOCK(ump);
13214 	/*
13215 	 * Loop until all dependencies related to this block are satisfied.
13216 	 * We must be careful to restart after each sleep in case a write
13217 	 * completes some part of this process for us.
13218 	 */
13219 	for (;;) {
13220 		if (newblk_lookup(mp, blkno, 0, &newblk) == 0) {
13221 			FREE_LOCK(ump);
13222 			break;
13223 		}
13224 		if (newblk->nb_list.wk_type != D_ALLOCDIRECT)
13225 			panic("flush_newblk_dep: Bad newblk %p", newblk);
13226 		/*
13227 		 * Flush the journal.
13228 		 */
13229 		if (newblk->nb_jnewblk != NULL) {
13230 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
13231 			continue;
13232 		}
13233 		/*
13234 		 * Write the bitmap dependency.
13235 		 */
13236 		if ((newblk->nb_state & DEPCOMPLETE) == 0) {
13237 			bp = newblk->nb_bmsafemap->sm_buf;
13238 			bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13239 			if (bp == NULL)
13240 				continue;
13241 			FREE_LOCK(ump);
13242 			error = bwrite(bp);
13243 			if (error)
13244 				break;
13245 			ACQUIRE_LOCK(ump);
13246 			continue;
13247 		}
13248 		/*
13249 		 * Write the buffer.
13250 		 */
13251 		FREE_LOCK(ump);
13252 		BO_LOCK(bo);
13253 		bp = gbincore(bo, lbn);
13254 		if (bp != NULL) {
13255 			error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
13256 			    LK_INTERLOCK, BO_LOCKPTR(bo));
13257 			if (error == ENOLCK) {
13258 				ACQUIRE_LOCK(ump);
13259 				error = 0;
13260 				continue; /* Slept, retry */
13261 			}
13262 			if (error != 0)
13263 				break;	/* Failed */
13264 			if (bp->b_flags & B_DELWRI) {
13265 				bremfree(bp);
13266 				error = bwrite(bp);
13267 				if (error)
13268 					break;
13269 			} else
13270 				BUF_UNLOCK(bp);
13271 		} else
13272 			BO_UNLOCK(bo);
13273 		/*
13274 		 * We have to wait for the direct pointers to
13275 		 * point at the newdirblk before the dependency
13276 		 * will go away.
13277 		 */
13278 		error = ffs_update(vp, 1);
13279 		if (error)
13280 			break;
13281 		ACQUIRE_LOCK(ump);
13282 	}
13283 	return (error);
13284 }
13285 
13286 /*
13287  * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
13288  */
13289 static int
13290 flush_pagedep_deps(
13291 	struct vnode *pvp,
13292 	struct mount *mp,
13293 	struct diraddhd *diraddhdp,
13294 	struct buf *locked_bp)
13295 {
13296 	struct inodedep *inodedep;
13297 	struct inoref *inoref;
13298 	struct ufsmount *ump;
13299 	struct diradd *dap;
13300 	struct vnode *vp;
13301 	int error = 0;
13302 	struct buf *bp;
13303 	ino_t inum;
13304 	struct diraddhd unfinished;
13305 
13306 	LIST_INIT(&unfinished);
13307 	ump = VFSTOUFS(mp);
13308 	LOCK_OWNED(ump);
13309 restart:
13310 	while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
13311 		/*
13312 		 * Flush ourselves if this directory entry
13313 		 * has a MKDIR_PARENT dependency.
13314 		 */
13315 		if (dap->da_state & MKDIR_PARENT) {
13316 			FREE_LOCK(ump);
13317 			if ((error = ffs_update(pvp, 1)) != 0)
13318 				break;
13319 			ACQUIRE_LOCK(ump);
13320 			/*
13321 			 * If that cleared dependencies, go on to next.
13322 			 */
13323 			if (dap != LIST_FIRST(diraddhdp))
13324 				continue;
13325 			/*
13326 			 * All MKDIR_PARENT dependencies and all the
13327 			 * NEWBLOCK pagedeps that are contained in direct
13328 			 * blocks were resolved by doing above ffs_update.
13329 			 * Pagedeps contained in indirect blocks may
13330 			 * require a complete sync'ing of the directory.
13331 			 * We are in the midst of doing a complete sync,
13332 			 * so if they are not resolved in this pass we
13333 			 * defer them for now as they will be sync'ed by
13334 			 * our caller shortly.
13335 			 */
13336 			LIST_REMOVE(dap, da_pdlist);
13337 			LIST_INSERT_HEAD(&unfinished, dap, da_pdlist);
13338 			continue;
13339 		}
13340 		/*
13341 		 * A newly allocated directory must have its "." and
13342 		 * ".." entries written out before its name can be
13343 		 * committed in its parent.
13344 		 */
13345 		inum = dap->da_newinum;
13346 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13347 			panic("flush_pagedep_deps: lost inode1");
13348 		/*
13349 		 * Wait for any pending journal adds to complete so we don't
13350 		 * cause rollbacks while syncing.
13351 		 */
13352 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
13353 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
13354 			    == DEPCOMPLETE) {
13355 				jwait(&inoref->if_list, MNT_WAIT);
13356 				goto restart;
13357 			}
13358 		}
13359 		if (dap->da_state & MKDIR_BODY) {
13360 			FREE_LOCK(ump);
13361 			error = get_parent_vp(pvp, mp, inum, locked_bp,
13362 			    diraddhdp, &unfinished, &vp);
13363 			if (error != 0)
13364 				break;
13365 			error = flush_newblk_dep(vp, mp, 0);
13366 			/*
13367 			 * If we still have the dependency we might need to
13368 			 * update the vnode to sync the new link count to
13369 			 * disk.
13370 			 */
13371 			if (error == 0 && dap == LIST_FIRST(diraddhdp))
13372 				error = ffs_update(vp, 1);
13373 			vput(vp);
13374 			if (error != 0)
13375 				break;
13376 			ACQUIRE_LOCK(ump);
13377 			/*
13378 			 * If that cleared dependencies, go on to next.
13379 			 */
13380 			if (dap != LIST_FIRST(diraddhdp))
13381 				continue;
13382 			if (dap->da_state & MKDIR_BODY) {
13383 				inodedep_lookup(UFSTOVFS(ump), inum, 0,
13384 				    &inodedep);
13385 				panic("flush_pagedep_deps: MKDIR_BODY "
13386 				    "inodedep %p dap %p vp %p",
13387 				    inodedep, dap, vp);
13388 			}
13389 		}
13390 		/*
13391 		 * Flush the inode on which the directory entry depends.
13392 		 * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
13393 		 * the only remaining dependency is that the updated inode
13394 		 * count must get pushed to disk. The inode has already
13395 		 * been pushed into its inode buffer (via VOP_UPDATE) at
13396 		 * the time of the reference count change. So we need only
13397 		 * locate that buffer, ensure that there will be no rollback
13398 		 * caused by a bitmap dependency, then write the inode buffer.
13399 		 */
13400 retry:
13401 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13402 			panic("flush_pagedep_deps: lost inode");
13403 		/*
13404 		 * If the inode still has bitmap dependencies,
13405 		 * push them to disk.
13406 		 */
13407 		if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) == 0) {
13408 			bp = inodedep->id_bmsafemap->sm_buf;
13409 			bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13410 			if (bp == NULL)
13411 				goto retry;
13412 			FREE_LOCK(ump);
13413 			if ((error = bwrite(bp)) != 0)
13414 				break;
13415 			ACQUIRE_LOCK(ump);
13416 			if (dap != LIST_FIRST(diraddhdp))
13417 				continue;
13418 		}
13419 		/*
13420 		 * If the inode is still sitting in a buffer waiting
13421 		 * to be written or waiting for the link count to be
13422 		 * adjusted update it here to flush it to disk.
13423 		 */
13424 		if (dap == LIST_FIRST(diraddhdp)) {
13425 			FREE_LOCK(ump);
13426 			error = get_parent_vp(pvp, mp, inum, locked_bp,
13427 			    diraddhdp, &unfinished, &vp);
13428 			if (error != 0)
13429 				break;
13430 			error = ffs_update(vp, 1);
13431 			vput(vp);
13432 			if (error)
13433 				break;
13434 			ACQUIRE_LOCK(ump);
13435 		}
13436 		/*
13437 		 * If we have failed to get rid of all the dependencies
13438 		 * then something is seriously wrong.
13439 		 */
13440 		if (dap == LIST_FIRST(diraddhdp)) {
13441 			inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep);
13442 			panic("flush_pagedep_deps: failed to flush "
13443 			    "inodedep %p ino %ju dap %p",
13444 			    inodedep, (uintmax_t)inum, dap);
13445 		}
13446 	}
13447 	if (error)
13448 		ACQUIRE_LOCK(ump);
13449 	while ((dap = LIST_FIRST(&unfinished)) != NULL) {
13450 		LIST_REMOVE(dap, da_pdlist);
13451 		LIST_INSERT_HEAD(diraddhdp, dap, da_pdlist);
13452 	}
13453 	return (error);
13454 }
13455 
13456 /*
13457  * A large burst of file addition or deletion activity can drive the
13458  * memory load excessively high. First attempt to slow things down
13459  * using the techniques below. If that fails, this routine requests
13460  * the offending operations to fall back to running synchronously
13461  * until the memory load returns to a reasonable level.
13462  */
13463 int
13464 softdep_slowdown(struct vnode *vp)
13465 {
13466 	struct ufsmount *ump;
13467 	int jlow;
13468 	int max_softdeps_hard;
13469 
13470 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
13471 	    ("softdep_slowdown called on non-softdep filesystem"));
13472 	ump = VFSTOUFS(vp->v_mount);
13473 	ACQUIRE_LOCK(ump);
13474 	jlow = 0;
13475 	/*
13476 	 * Check for journal space if needed.
13477 	 */
13478 	if (DOINGSUJ(vp)) {
13479 		if (journal_space(ump, 0) == 0)
13480 			jlow = 1;
13481 	}
13482 	/*
13483 	 * If the system is under its limits and our filesystem is
13484 	 * not responsible for more than our share of the usage and
13485 	 * we are not low on journal space, then no need to slow down.
13486 	 */
13487 	max_softdeps_hard = max_softdeps * 11 / 10;
13488 	if (dep_current[D_DIRREM] < max_softdeps_hard / 2 &&
13489 	    dep_current[D_INODEDEP] < max_softdeps_hard &&
13490 	    dep_current[D_INDIRDEP] < max_softdeps_hard / 1000 &&
13491 	    dep_current[D_FREEBLKS] < max_softdeps_hard && jlow == 0 &&
13492 	    ump->softdep_curdeps[D_DIRREM] <
13493 	    (max_softdeps_hard / 2) / stat_flush_threads &&
13494 	    ump->softdep_curdeps[D_INODEDEP] <
13495 	    max_softdeps_hard / stat_flush_threads &&
13496 	    ump->softdep_curdeps[D_INDIRDEP] <
13497 	    (max_softdeps_hard / 1000) / stat_flush_threads &&
13498 	    ump->softdep_curdeps[D_FREEBLKS] <
13499 	    max_softdeps_hard / stat_flush_threads) {
13500 		FREE_LOCK(ump);
13501   		return (0);
13502 	}
13503 	/*
13504 	 * If the journal is low or our filesystem is over its limit
13505 	 * then speedup the cleanup.
13506 	 */
13507 	if (ump->softdep_curdeps[D_INDIRDEP] <
13508 	    (max_softdeps_hard / 1000) / stat_flush_threads || jlow)
13509 		softdep_speedup(ump);
13510 	stat_sync_limit_hit += 1;
13511 	FREE_LOCK(ump);
13512 	/*
13513 	 * We only slow down the rate at which new dependencies are
13514 	 * generated if we are not using journaling. With journaling,
13515 	 * the cleanup should always be sufficient to keep things
13516 	 * under control.
13517 	 */
13518 	if (DOINGSUJ(vp))
13519 		return (0);
13520 	return (1);
13521 }
13522 
13523 static int
13524 softdep_request_cleanup_filter(struct vnode *vp, void *arg __unused)
13525 {
13526 	return ((vp->v_iflag & VI_OWEINACT) != 0 && vp->v_usecount == 0 &&
13527 	    ((vp->v_vflag & VV_NOSYNC) != 0 || VTOI(vp)->i_effnlink == 0));
13528 }
13529 
13530 static void
13531 softdep_request_cleanup_inactivate(struct mount *mp)
13532 {
13533 	struct vnode *vp, *mvp;
13534 	int error;
13535 
13536 	MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, softdep_request_cleanup_filter,
13537 	    NULL) {
13538 		vholdl(vp);
13539 		vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK | LK_RETRY);
13540 		VI_LOCK(vp);
13541 		if (IS_UFS(vp) && vp->v_usecount == 0) {
13542 			while ((vp->v_iflag & VI_OWEINACT) != 0) {
13543 				error = vinactive(vp);
13544 				if (error != 0 && error != ERELOOKUP)
13545 					break;
13546 			}
13547 			atomic_add_int(&stat_delayed_inact, 1);
13548 		}
13549 		VOP_UNLOCK(vp);
13550 		vdropl(vp);
13551 	}
13552 }
13553 
13554 /*
13555  * Called by the allocation routines when they are about to fail
13556  * in the hope that we can free up the requested resource (inodes
13557  * or disk space).
13558  *
13559  * First check to see if the work list has anything on it. If it has,
13560  * clean up entries until we successfully free the requested resource.
13561  * Because this process holds inodes locked, we cannot handle any remove
13562  * requests that might block on a locked inode as that could lead to
13563  * deadlock. If the worklist yields none of the requested resource,
13564  * start syncing out vnodes to free up the needed space.
13565  */
13566 int
13567 softdep_request_cleanup(
13568 	struct fs *fs,
13569 	struct vnode *vp,
13570 	struct ucred *cred,
13571 	int resource)
13572 {
13573 	struct ufsmount *ump;
13574 	struct mount *mp;
13575 	long starttime;
13576 	ufs2_daddr_t needed;
13577 	int error, failed_vnode;
13578 
13579 	/*
13580 	 * If we are being called because of a process doing a
13581 	 * copy-on-write, then it is not safe to process any
13582 	 * worklist items as we will recurse into the copyonwrite
13583 	 * routine.  This will result in an incoherent snapshot.
13584 	 * If the vnode that we hold is a snapshot, we must avoid
13585 	 * handling other resources that could cause deadlock.
13586 	 */
13587 	if ((curthread->td_pflags & TDP_COWINPROGRESS) || IS_SNAPSHOT(VTOI(vp)))
13588 		return (0);
13589 
13590 	if (resource == FLUSH_BLOCKS_WAIT)
13591 		stat_cleanup_blkrequests += 1;
13592 	else
13593 		stat_cleanup_inorequests += 1;
13594 
13595 	mp = vp->v_mount;
13596 	ump = VFSTOUFS(mp);
13597 	mtx_assert(UFS_MTX(ump), MA_OWNED);
13598 	UFS_UNLOCK(ump);
13599 	error = ffs_update(vp, 1);
13600 	if (error != 0 || MOUNTEDSOFTDEP(mp) == 0) {
13601 		UFS_LOCK(ump);
13602 		return (0);
13603 	}
13604 	/*
13605 	 * If we are in need of resources, start by cleaning up
13606 	 * any block removals associated with our inode.
13607 	 */
13608 	ACQUIRE_LOCK(ump);
13609 	process_removes(vp);
13610 	process_truncates(vp);
13611 	FREE_LOCK(ump);
13612 	/*
13613 	 * Now clean up at least as many resources as we will need.
13614 	 *
13615 	 * When requested to clean up inodes, the number that are needed
13616 	 * is set by the number of simultaneous writers (mnt_writeopcount)
13617 	 * plus a bit of slop (2) in case some more writers show up while
13618 	 * we are cleaning.
13619 	 *
13620 	 * When requested to free up space, the amount of space that
13621 	 * we need is enough blocks to allocate a full-sized segment
13622 	 * (fs_contigsumsize). The number of such segments that will
13623 	 * be needed is set by the number of simultaneous writers
13624 	 * (mnt_writeopcount) plus a bit of slop (2) in case some more
13625 	 * writers show up while we are cleaning.
13626 	 *
13627 	 * Additionally, if we are unpriviledged and allocating space,
13628 	 * we need to ensure that we clean up enough blocks to get the
13629 	 * needed number of blocks over the threshold of the minimum
13630 	 * number of blocks required to be kept free by the filesystem
13631 	 * (fs_minfree).
13632 	 */
13633 	if (resource == FLUSH_INODES_WAIT) {
13634 		needed = vfs_mount_fetch_counter(vp->v_mount,
13635 		    MNT_COUNT_WRITEOPCOUNT) + 2;
13636 	} else if (resource == FLUSH_BLOCKS_WAIT) {
13637 		needed = (vfs_mount_fetch_counter(vp->v_mount,
13638 		    MNT_COUNT_WRITEOPCOUNT) + 2) * fs->fs_contigsumsize;
13639 		if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE))
13640 			needed += fragstoblks(fs,
13641 			    roundup((fs->fs_dsize * fs->fs_minfree / 100) -
13642 			    fs->fs_cstotal.cs_nffree, fs->fs_frag));
13643 	} else {
13644 		printf("softdep_request_cleanup: Unknown resource type %d\n",
13645 		    resource);
13646 		UFS_LOCK(ump);
13647 		return (0);
13648 	}
13649 	starttime = time_second;
13650 retry:
13651 	if (resource == FLUSH_BLOCKS_WAIT &&
13652 	    fs->fs_cstotal.cs_nbfree <= needed)
13653 		softdep_send_speedup(ump, needed * fs->fs_bsize,
13654 		    BIO_SPEEDUP_TRIM);
13655 	if ((resource == FLUSH_BLOCKS_WAIT && ump->softdep_on_worklist > 0 &&
13656 	    fs->fs_cstotal.cs_nbfree <= needed) ||
13657 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13658 	    fs->fs_cstotal.cs_nifree <= needed)) {
13659 		ACQUIRE_LOCK(ump);
13660 		if (ump->softdep_on_worklist > 0 &&
13661 		    process_worklist_item(UFSTOVFS(ump),
13662 		    ump->softdep_on_worklist, LK_NOWAIT) != 0)
13663 			stat_worklist_push += 1;
13664 		FREE_LOCK(ump);
13665 	}
13666 
13667 	/*
13668 	 * Check that there are vnodes pending inactivation.  As they
13669 	 * have been unlinked, inactivating them will free up their
13670 	 * inodes.
13671 	 */
13672 	ACQUIRE_LOCK(ump);
13673 	if (resource == FLUSH_INODES_WAIT &&
13674 	    fs->fs_cstotal.cs_nifree <= needed &&
13675 	    fs->fs_pendinginodes <= needed) {
13676 		if ((ump->um_softdep->sd_flags & FLUSH_DI_ACTIVE) == 0) {
13677 			ump->um_softdep->sd_flags |= FLUSH_DI_ACTIVE;
13678 			FREE_LOCK(ump);
13679 			softdep_request_cleanup_inactivate(mp);
13680 			ACQUIRE_LOCK(ump);
13681 			ump->um_softdep->sd_flags &= ~FLUSH_DI_ACTIVE;
13682 			wakeup(&ump->um_softdep->sd_flags);
13683 		} else {
13684 			while ((ump->um_softdep->sd_flags &
13685 			    FLUSH_DI_ACTIVE) != 0) {
13686 				msleep(&ump->um_softdep->sd_flags,
13687 				    LOCK_PTR(ump), PVM, "ffsvina", hz);
13688 			}
13689 		}
13690 	}
13691 	FREE_LOCK(ump);
13692 
13693 	/*
13694 	 * If we still need resources and there are no more worklist
13695 	 * entries to process to obtain them, we have to start flushing
13696 	 * the dirty vnodes to force the release of additional requests
13697 	 * to the worklist that we can then process to reap addition
13698 	 * resources. We walk the vnodes associated with the mount point
13699 	 * until we get the needed worklist requests that we can reap.
13700 	 *
13701 	 * If there are several threads all needing to clean the same
13702 	 * mount point, only one is allowed to walk the mount list.
13703 	 * When several threads all try to walk the same mount list,
13704 	 * they end up competing with each other and often end up in
13705 	 * livelock. This approach ensures that forward progress is
13706 	 * made at the cost of occational ENOSPC errors being returned
13707 	 * that might otherwise have been avoided.
13708 	 */
13709 	error = 1;
13710 	if ((resource == FLUSH_BLOCKS_WAIT &&
13711 	     fs->fs_cstotal.cs_nbfree <= needed) ||
13712 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13713 	     fs->fs_cstotal.cs_nifree <= needed)) {
13714 		ACQUIRE_LOCK(ump);
13715 		if ((ump->um_softdep->sd_flags & FLUSH_RC_ACTIVE) == 0) {
13716 			ump->um_softdep->sd_flags |= FLUSH_RC_ACTIVE;
13717 			FREE_LOCK(ump);
13718 			failed_vnode = softdep_request_cleanup_flush(mp, ump);
13719 			ACQUIRE_LOCK(ump);
13720 			ump->um_softdep->sd_flags &= ~FLUSH_RC_ACTIVE;
13721 			wakeup(&ump->um_softdep->sd_flags);
13722 			FREE_LOCK(ump);
13723 			if (ump->softdep_on_worklist > 0) {
13724 				stat_cleanup_retries += 1;
13725 				if (!failed_vnode)
13726 					goto retry;
13727 			}
13728 		} else {
13729 			while ((ump->um_softdep->sd_flags &
13730 			    FLUSH_RC_ACTIVE) != 0) {
13731 				msleep(&ump->um_softdep->sd_flags,
13732 				    LOCK_PTR(ump), PVM, "ffsrca", hz);
13733 			}
13734 			FREE_LOCK(ump);
13735 			error = 0;
13736 		}
13737 		stat_cleanup_failures += 1;
13738 	}
13739 	if (time_second - starttime > stat_cleanup_high_delay)
13740 		stat_cleanup_high_delay = time_second - starttime;
13741 	UFS_LOCK(ump);
13742 	return (error);
13743 }
13744 
13745 /*
13746  * Scan the vnodes for the specified mount point flushing out any
13747  * vnodes that can be locked without waiting. Finally, try to flush
13748  * the device associated with the mount point if it can be locked
13749  * without waiting.
13750  *
13751  * We return 0 if we were able to lock every vnode in our scan.
13752  * If we had to skip one or more vnodes, we return 1.
13753  */
13754 static int
13755 softdep_request_cleanup_flush(struct mount *mp, struct ufsmount *ump)
13756 {
13757 	struct thread *td;
13758 	struct vnode *lvp, *mvp;
13759 	int failed_vnode;
13760 
13761 	failed_vnode = 0;
13762 	td = curthread;
13763 	MNT_VNODE_FOREACH_ALL(lvp, mp, mvp) {
13764 		if (TAILQ_FIRST(&lvp->v_bufobj.bo_dirty.bv_hd) == 0) {
13765 			VI_UNLOCK(lvp);
13766 			continue;
13767 		}
13768 		if (vget(lvp, LK_EXCLUSIVE | LK_INTERLOCK | LK_NOWAIT) != 0) {
13769 			failed_vnode = 1;
13770 			continue;
13771 		}
13772 		if (lvp->v_vflag & VV_NOSYNC) {	/* unlinked */
13773 			vput(lvp);
13774 			continue;
13775 		}
13776 		(void) ffs_syncvnode(lvp, MNT_NOWAIT, 0);
13777 		vput(lvp);
13778 	}
13779 	lvp = ump->um_devvp;
13780 	if (vn_lock(lvp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
13781 		VOP_FSYNC(lvp, MNT_NOWAIT, td);
13782 		VOP_UNLOCK(lvp);
13783 	}
13784 	return (failed_vnode);
13785 }
13786 
13787 static bool
13788 softdep_excess_items(struct ufsmount *ump, int item)
13789 {
13790 
13791 	KASSERT(item >= 0 && item < D_LAST, ("item %d", item));
13792 	return (dep_current[item] > max_softdeps &&
13793 	    ump->softdep_curdeps[item] > max_softdeps /
13794 	    stat_flush_threads);
13795 }
13796 
13797 static void
13798 schedule_cleanup(struct mount *mp)
13799 {
13800 	struct ufsmount *ump;
13801 	struct thread *td;
13802 
13803 	ump = VFSTOUFS(mp);
13804 	LOCK_OWNED(ump);
13805 	FREE_LOCK(ump);
13806 	td = curthread;
13807 	if ((td->td_pflags & TDP_KTHREAD) != 0 &&
13808 	    (td->td_proc->p_flag2 & P2_AST_SU) == 0) {
13809 		/*
13810 		 * No ast is delivered to kernel threads, so nobody
13811 		 * would deref the mp.  Some kernel threads
13812 		 * explicitly check for AST, e.g. NFS daemon does
13813 		 * this in the serving loop.
13814 		 */
13815 		return;
13816 	}
13817 	if (td->td_su != NULL)
13818 		vfs_rel(td->td_su);
13819 	vfs_ref(mp);
13820 	td->td_su = mp;
13821 	thread_lock(td);
13822 	td->td_flags |= TDF_ASTPENDING;
13823 	thread_unlock(td);
13824 }
13825 
13826 static void
13827 softdep_ast_cleanup_proc(struct thread *td)
13828 {
13829 	struct mount *mp;
13830 	struct ufsmount *ump;
13831 	int error;
13832 	bool req;
13833 
13834 	while ((mp = td->td_su) != NULL) {
13835 		td->td_su = NULL;
13836 		error = vfs_busy(mp, MBF_NOWAIT);
13837 		vfs_rel(mp);
13838 		if (error != 0)
13839 			return;
13840 		if (ffs_own_mount(mp) && MOUNTEDSOFTDEP(mp)) {
13841 			ump = VFSTOUFS(mp);
13842 			for (;;) {
13843 				req = false;
13844 				ACQUIRE_LOCK(ump);
13845 				if (softdep_excess_items(ump, D_INODEDEP)) {
13846 					req = true;
13847 					request_cleanup(mp, FLUSH_INODES);
13848 				}
13849 				if (softdep_excess_items(ump, D_DIRREM)) {
13850 					req = true;
13851 					request_cleanup(mp, FLUSH_BLOCKS);
13852 				}
13853 				FREE_LOCK(ump);
13854 				if (softdep_excess_items(ump, D_NEWBLK) ||
13855 				    softdep_excess_items(ump, D_ALLOCDIRECT) ||
13856 				    softdep_excess_items(ump, D_ALLOCINDIR)) {
13857 					error = vn_start_write(NULL, &mp,
13858 					    V_WAIT);
13859 					if (error == 0) {
13860 						req = true;
13861 						VFS_SYNC(mp, MNT_WAIT);
13862 						vn_finished_write(mp);
13863 					}
13864 				}
13865 				if ((td->td_pflags & TDP_KTHREAD) != 0 || !req)
13866 					break;
13867 			}
13868 		}
13869 		vfs_unbusy(mp);
13870 	}
13871 	if ((mp = td->td_su) != NULL) {
13872 		td->td_su = NULL;
13873 		vfs_rel(mp);
13874 	}
13875 }
13876 
13877 /*
13878  * If memory utilization has gotten too high, deliberately slow things
13879  * down and speed up the I/O processing.
13880  */
13881 static int
13882 request_cleanup(struct mount *mp, int resource)
13883 {
13884 	struct thread *td = curthread;
13885 	struct ufsmount *ump;
13886 
13887 	ump = VFSTOUFS(mp);
13888 	LOCK_OWNED(ump);
13889 	/*
13890 	 * We never hold up the filesystem syncer or buf daemon.
13891 	 */
13892 	if (td->td_pflags & (TDP_SOFTDEP|TDP_NORUNNINGBUF))
13893 		return (0);
13894 	/*
13895 	 * First check to see if the work list has gotten backlogged.
13896 	 * If it has, co-opt this process to help clean up two entries.
13897 	 * Because this process may hold inodes locked, we cannot
13898 	 * handle any remove requests that might block on a locked
13899 	 * inode as that could lead to deadlock.  We set TDP_SOFTDEP
13900 	 * to avoid recursively processing the worklist.
13901 	 */
13902 	if (ump->softdep_on_worklist > max_softdeps / 10) {
13903 		td->td_pflags |= TDP_SOFTDEP;
13904 		process_worklist_item(mp, 2, LK_NOWAIT);
13905 		td->td_pflags &= ~TDP_SOFTDEP;
13906 		stat_worklist_push += 2;
13907 		return(1);
13908 	}
13909 	/*
13910 	 * Next, we attempt to speed up the syncer process. If that
13911 	 * is successful, then we allow the process to continue.
13912 	 */
13913 	if (softdep_speedup(ump) &&
13914 	    resource != FLUSH_BLOCKS_WAIT &&
13915 	    resource != FLUSH_INODES_WAIT)
13916 		return(0);
13917 	/*
13918 	 * If we are resource constrained on inode dependencies, try
13919 	 * flushing some dirty inodes. Otherwise, we are constrained
13920 	 * by file deletions, so try accelerating flushes of directories
13921 	 * with removal dependencies. We would like to do the cleanup
13922 	 * here, but we probably hold an inode locked at this point and
13923 	 * that might deadlock against one that we try to clean. So,
13924 	 * the best that we can do is request the syncer daemon to do
13925 	 * the cleanup for us.
13926 	 */
13927 	switch (resource) {
13928 	case FLUSH_INODES:
13929 	case FLUSH_INODES_WAIT:
13930 		ACQUIRE_GBLLOCK(&lk);
13931 		stat_ino_limit_push += 1;
13932 		req_clear_inodedeps += 1;
13933 		FREE_GBLLOCK(&lk);
13934 		stat_countp = &stat_ino_limit_hit;
13935 		break;
13936 
13937 	case FLUSH_BLOCKS:
13938 	case FLUSH_BLOCKS_WAIT:
13939 		ACQUIRE_GBLLOCK(&lk);
13940 		stat_blk_limit_push += 1;
13941 		req_clear_remove += 1;
13942 		FREE_GBLLOCK(&lk);
13943 		stat_countp = &stat_blk_limit_hit;
13944 		break;
13945 
13946 	default:
13947 		panic("request_cleanup: unknown type");
13948 	}
13949 	/*
13950 	 * Hopefully the syncer daemon will catch up and awaken us.
13951 	 * We wait at most tickdelay before proceeding in any case.
13952 	 */
13953 	ACQUIRE_GBLLOCK(&lk);
13954 	FREE_LOCK(ump);
13955 	proc_waiting += 1;
13956 	if (callout_pending(&softdep_callout) == FALSE)
13957 		callout_reset(&softdep_callout, tickdelay > 2 ? tickdelay : 2,
13958 		    pause_timer, 0);
13959 
13960 	if ((td->td_pflags & TDP_KTHREAD) == 0)
13961 		msleep((caddr_t)&proc_waiting, &lk, PPAUSE, "softupdate", 0);
13962 	proc_waiting -= 1;
13963 	FREE_GBLLOCK(&lk);
13964 	ACQUIRE_LOCK(ump);
13965 	return (1);
13966 }
13967 
13968 /*
13969  * Awaken processes pausing in request_cleanup and clear proc_waiting
13970  * to indicate that there is no longer a timer running. Pause_timer
13971  * will be called with the global softdep mutex (&lk) locked.
13972  */
13973 static void
13974 pause_timer(void *arg)
13975 {
13976 
13977 	GBLLOCK_OWNED(&lk);
13978 	/*
13979 	 * The callout_ API has acquired mtx and will hold it around this
13980 	 * function call.
13981 	 */
13982 	*stat_countp += proc_waiting;
13983 	wakeup(&proc_waiting);
13984 }
13985 
13986 /*
13987  * If requested, try removing inode or removal dependencies.
13988  */
13989 static void
13990 check_clear_deps(struct mount *mp)
13991 {
13992 	struct ufsmount *ump;
13993 	bool suj_susp;
13994 
13995 	/*
13996 	 * Tell the lower layers that any TRIM or WRITE transactions that have
13997 	 * been delayed for performance reasons should proceed to help alleviate
13998 	 * the shortage faster. The race between checking req_* and the softdep
13999 	 * mutex (lk) is fine since this is an advisory operation that at most
14000 	 * causes deferred work to be done sooner.
14001 	 */
14002 	ump = VFSTOUFS(mp);
14003 	suj_susp = ump->um_softdep->sd_jblocks != NULL &&
14004 	    ump->softdep_jblocks->jb_suspended;
14005 	if (req_clear_remove || req_clear_inodedeps || suj_susp) {
14006 		FREE_LOCK(ump);
14007 		softdep_send_speedup(ump, 0, BIO_SPEEDUP_TRIM | BIO_SPEEDUP_WRITE);
14008 		ACQUIRE_LOCK(ump);
14009 	}
14010 
14011 	/*
14012 	 * If we are suspended, it may be because of our using
14013 	 * too many inodedeps, so help clear them out.
14014 	 */
14015 	if (suj_susp)
14016 		clear_inodedeps(mp);
14017 
14018 	/*
14019 	 * General requests for cleanup of backed up dependencies
14020 	 */
14021 	ACQUIRE_GBLLOCK(&lk);
14022 	if (req_clear_inodedeps) {
14023 		req_clear_inodedeps -= 1;
14024 		FREE_GBLLOCK(&lk);
14025 		clear_inodedeps(mp);
14026 		ACQUIRE_GBLLOCK(&lk);
14027 		wakeup(&proc_waiting);
14028 	}
14029 	if (req_clear_remove) {
14030 		req_clear_remove -= 1;
14031 		FREE_GBLLOCK(&lk);
14032 		clear_remove(mp);
14033 		ACQUIRE_GBLLOCK(&lk);
14034 		wakeup(&proc_waiting);
14035 	}
14036 	FREE_GBLLOCK(&lk);
14037 }
14038 
14039 /*
14040  * Flush out a directory with at least one removal dependency in an effort to
14041  * reduce the number of dirrem, freefile, and freeblks dependency structures.
14042  */
14043 static void
14044 clear_remove(struct mount *mp)
14045 {
14046 	struct pagedep_hashhead *pagedephd;
14047 	struct pagedep *pagedep;
14048 	struct ufsmount *ump;
14049 	struct vnode *vp;
14050 	struct bufobj *bo;
14051 	int error, cnt;
14052 	ino_t ino;
14053 
14054 	ump = VFSTOUFS(mp);
14055 	LOCK_OWNED(ump);
14056 
14057 	for (cnt = 0; cnt <= ump->pagedep_hash_size; cnt++) {
14058 		pagedephd = &ump->pagedep_hashtbl[ump->pagedep_nextclean++];
14059 		if (ump->pagedep_nextclean > ump->pagedep_hash_size)
14060 			ump->pagedep_nextclean = 0;
14061 		LIST_FOREACH(pagedep, pagedephd, pd_hash) {
14062 			if (LIST_EMPTY(&pagedep->pd_dirremhd))
14063 				continue;
14064 			ino = pagedep->pd_ino;
14065 			if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
14066 				continue;
14067 			FREE_LOCK(ump);
14068 
14069 			/*
14070 			 * Let unmount clear deps
14071 			 */
14072 			error = vfs_busy(mp, MBF_NOWAIT);
14073 			if (error != 0)
14074 				goto finish_write;
14075 			error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
14076 			     FFSV_FORCEINSMQ | FFSV_FORCEINODEDEP);
14077 			vfs_unbusy(mp);
14078 			if (error != 0) {
14079 				softdep_error("clear_remove: vget", error);
14080 				goto finish_write;
14081 			}
14082 			MPASS(VTOI(vp)->i_mode != 0);
14083 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
14084 				softdep_error("clear_remove: fsync", error);
14085 			bo = &vp->v_bufobj;
14086 			BO_LOCK(bo);
14087 			drain_output(vp);
14088 			BO_UNLOCK(bo);
14089 			vput(vp);
14090 		finish_write:
14091 			vn_finished_write(mp);
14092 			ACQUIRE_LOCK(ump);
14093 			return;
14094 		}
14095 	}
14096 }
14097 
14098 /*
14099  * Clear out a block of dirty inodes in an effort to reduce
14100  * the number of inodedep dependency structures.
14101  */
14102 static void
14103 clear_inodedeps(struct mount *mp)
14104 {
14105 	struct inodedep_hashhead *inodedephd;
14106 	struct inodedep *inodedep;
14107 	struct ufsmount *ump;
14108 	struct vnode *vp;
14109 	struct fs *fs;
14110 	int error, cnt;
14111 	ino_t firstino, lastino, ino;
14112 
14113 	ump = VFSTOUFS(mp);
14114 	fs = ump->um_fs;
14115 	LOCK_OWNED(ump);
14116 	/*
14117 	 * Pick a random inode dependency to be cleared.
14118 	 * We will then gather up all the inodes in its block
14119 	 * that have dependencies and flush them out.
14120 	 */
14121 	for (cnt = 0; cnt <= ump->inodedep_hash_size; cnt++) {
14122 		inodedephd = &ump->inodedep_hashtbl[ump->inodedep_nextclean++];
14123 		if (ump->inodedep_nextclean > ump->inodedep_hash_size)
14124 			ump->inodedep_nextclean = 0;
14125 		if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
14126 			break;
14127 	}
14128 	if (inodedep == NULL)
14129 		return;
14130 	/*
14131 	 * Find the last inode in the block with dependencies.
14132 	 */
14133 	firstino = rounddown2(inodedep->id_ino, INOPB(fs));
14134 	for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
14135 		if (inodedep_lookup(mp, lastino, 0, &inodedep) != 0)
14136 			break;
14137 	/*
14138 	 * Asynchronously push all but the last inode with dependencies.
14139 	 * Synchronously push the last inode with dependencies to ensure
14140 	 * that the inode block gets written to free up the inodedeps.
14141 	 */
14142 	for (ino = firstino; ino <= lastino; ino++) {
14143 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
14144 			continue;
14145 		if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
14146 			continue;
14147 		FREE_LOCK(ump);
14148 		error = vfs_busy(mp, MBF_NOWAIT); /* Let unmount clear deps */
14149 		if (error != 0) {
14150 			vn_finished_write(mp);
14151 			ACQUIRE_LOCK(ump);
14152 			return;
14153 		}
14154 		if ((error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
14155 		    FFSV_FORCEINSMQ | FFSV_FORCEINODEDEP)) != 0) {
14156 			softdep_error("clear_inodedeps: vget", error);
14157 			vfs_unbusy(mp);
14158 			vn_finished_write(mp);
14159 			ACQUIRE_LOCK(ump);
14160 			return;
14161 		}
14162 		vfs_unbusy(mp);
14163 		if (VTOI(vp)->i_mode == 0) {
14164 			vgone(vp);
14165 		} else if (ino == lastino) {
14166 			do {
14167 				error = ffs_syncvnode(vp, MNT_WAIT, 0);
14168 			} while (error == ERELOOKUP);
14169 			if (error != 0)
14170 				softdep_error("clear_inodedeps: fsync1", error);
14171 		} else {
14172 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
14173 				softdep_error("clear_inodedeps: fsync2", error);
14174 			BO_LOCK(&vp->v_bufobj);
14175 			drain_output(vp);
14176 			BO_UNLOCK(&vp->v_bufobj);
14177 		}
14178 		vput(vp);
14179 		vn_finished_write(mp);
14180 		ACQUIRE_LOCK(ump);
14181 	}
14182 }
14183 
14184 void
14185 softdep_buf_append(struct buf *bp, struct workhead *wkhd)
14186 {
14187 	struct worklist *wk;
14188 	struct ufsmount *ump;
14189 
14190 	if ((wk = LIST_FIRST(wkhd)) == NULL)
14191 		return;
14192 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
14193 	    ("softdep_buf_append called on non-softdep filesystem"));
14194 	ump = VFSTOUFS(wk->wk_mp);
14195 	ACQUIRE_LOCK(ump);
14196 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
14197 		WORKLIST_REMOVE(wk);
14198 		WORKLIST_INSERT(&bp->b_dep, wk);
14199 	}
14200 	FREE_LOCK(ump);
14201 
14202 }
14203 
14204 void
14205 softdep_inode_append(
14206 	struct inode *ip,
14207 	struct ucred *cred,
14208 	struct workhead *wkhd)
14209 {
14210 	struct buf *bp;
14211 	struct fs *fs;
14212 	struct ufsmount *ump;
14213 	int error;
14214 
14215 	ump = ITOUMP(ip);
14216 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
14217 	    ("softdep_inode_append called on non-softdep filesystem"));
14218 	fs = ump->um_fs;
14219 	error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
14220 	    (int)fs->fs_bsize, cred, &bp);
14221 	if (error) {
14222 		bqrelse(bp);
14223 		softdep_freework(wkhd);
14224 		return;
14225 	}
14226 	softdep_buf_append(bp, wkhd);
14227 	bqrelse(bp);
14228 }
14229 
14230 void
14231 softdep_freework(struct workhead *wkhd)
14232 {
14233 	struct worklist *wk;
14234 	struct ufsmount *ump;
14235 
14236 	if ((wk = LIST_FIRST(wkhd)) == NULL)
14237 		return;
14238 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
14239 	    ("softdep_freework called on non-softdep filesystem"));
14240 	ump = VFSTOUFS(wk->wk_mp);
14241 	ACQUIRE_LOCK(ump);
14242 	handle_jwork(wkhd);
14243 	FREE_LOCK(ump);
14244 }
14245 
14246 static struct ufsmount *
14247 softdep_bp_to_mp(struct buf *bp)
14248 {
14249 	struct mount *mp;
14250 	struct vnode *vp;
14251 
14252 	if (LIST_EMPTY(&bp->b_dep))
14253 		return (NULL);
14254 	vp = bp->b_vp;
14255 	KASSERT(vp != NULL,
14256 	    ("%s, buffer with dependencies lacks vnode", __func__));
14257 
14258 	/*
14259 	 * The ump mount point is stable after we get a correct
14260 	 * pointer, since bp is locked and this prevents unmount from
14261 	 * proceeding.  But to get to it, we cannot dereference bp->b_dep
14262 	 * head wk_mp, because we do not yet own SU ump lock and
14263 	 * workitem might be freed while dereferenced.
14264 	 */
14265 retry:
14266 	switch (vp->v_type) {
14267 	case VCHR:
14268 		VI_LOCK(vp);
14269 		mp = vp->v_type == VCHR ? vp->v_rdev->si_mountpt : NULL;
14270 		VI_UNLOCK(vp);
14271 		if (mp == NULL)
14272 			goto retry;
14273 		break;
14274 	case VREG:
14275 	case VDIR:
14276 	case VLNK:
14277 	case VFIFO:
14278 	case VSOCK:
14279 		mp = vp->v_mount;
14280 		break;
14281 	case VBLK:
14282 		vn_printf(vp, "softdep_bp_to_mp: unexpected block device\n");
14283 		/* FALLTHROUGH */
14284 	case VNON:
14285 	case VBAD:
14286 	case VMARKER:
14287 		mp = NULL;
14288 		break;
14289 	default:
14290 		vn_printf(vp, "unknown vnode type");
14291 		mp = NULL;
14292 		break;
14293 	}
14294 	return (VFSTOUFS(mp));
14295 }
14296 
14297 /*
14298  * Function to determine if the buffer has outstanding dependencies
14299  * that will cause a roll-back if the buffer is written. If wantcount
14300  * is set, return number of dependencies, otherwise just yes or no.
14301  */
14302 static int
14303 softdep_count_dependencies(struct buf *bp, int wantcount)
14304 {
14305 	struct worklist *wk;
14306 	struct ufsmount *ump;
14307 	struct bmsafemap *bmsafemap;
14308 	struct freework *freework;
14309 	struct inodedep *inodedep;
14310 	struct indirdep *indirdep;
14311 	struct freeblks *freeblks;
14312 	struct allocindir *aip;
14313 	struct pagedep *pagedep;
14314 	struct dirrem *dirrem;
14315 	struct newblk *newblk;
14316 	struct mkdir *mkdir;
14317 	struct diradd *dap;
14318 	int i, retval;
14319 
14320 	ump = softdep_bp_to_mp(bp);
14321 	if (ump == NULL)
14322 		return (0);
14323 	retval = 0;
14324 	ACQUIRE_LOCK(ump);
14325 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
14326 		switch (wk->wk_type) {
14327 		case D_INODEDEP:
14328 			inodedep = WK_INODEDEP(wk);
14329 			if ((inodedep->id_state & DEPCOMPLETE) == 0) {
14330 				/* bitmap allocation dependency */
14331 				retval += 1;
14332 				if (!wantcount)
14333 					goto out;
14334 			}
14335 			if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
14336 				/* direct block pointer dependency */
14337 				retval += 1;
14338 				if (!wantcount)
14339 					goto out;
14340 			}
14341 			if (TAILQ_FIRST(&inodedep->id_extupdt)) {
14342 				/* direct block pointer dependency */
14343 				retval += 1;
14344 				if (!wantcount)
14345 					goto out;
14346 			}
14347 			if (TAILQ_FIRST(&inodedep->id_inoreflst)) {
14348 				/* Add reference dependency. */
14349 				retval += 1;
14350 				if (!wantcount)
14351 					goto out;
14352 			}
14353 			continue;
14354 
14355 		case D_INDIRDEP:
14356 			indirdep = WK_INDIRDEP(wk);
14357 
14358 			TAILQ_FOREACH(freework, &indirdep->ir_trunc, fw_next) {
14359 				/* indirect truncation dependency */
14360 				retval += 1;
14361 				if (!wantcount)
14362 					goto out;
14363 			}
14364 
14365 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
14366 				/* indirect block pointer dependency */
14367 				retval += 1;
14368 				if (!wantcount)
14369 					goto out;
14370 			}
14371 			continue;
14372 
14373 		case D_PAGEDEP:
14374 			pagedep = WK_PAGEDEP(wk);
14375 			LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
14376 				if (LIST_FIRST(&dirrem->dm_jremrefhd)) {
14377 					/* Journal remove ref dependency. */
14378 					retval += 1;
14379 					if (!wantcount)
14380 						goto out;
14381 				}
14382 			}
14383 			for (i = 0; i < DAHASHSZ; i++) {
14384 				LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
14385 					/* directory entry dependency */
14386 					retval += 1;
14387 					if (!wantcount)
14388 						goto out;
14389 				}
14390 			}
14391 			continue;
14392 
14393 		case D_BMSAFEMAP:
14394 			bmsafemap = WK_BMSAFEMAP(wk);
14395 			if (LIST_FIRST(&bmsafemap->sm_jaddrefhd)) {
14396 				/* Add reference dependency. */
14397 				retval += 1;
14398 				if (!wantcount)
14399 					goto out;
14400 			}
14401 			if (LIST_FIRST(&bmsafemap->sm_jnewblkhd)) {
14402 				/* Allocate block dependency. */
14403 				retval += 1;
14404 				if (!wantcount)
14405 					goto out;
14406 			}
14407 			continue;
14408 
14409 		case D_FREEBLKS:
14410 			freeblks = WK_FREEBLKS(wk);
14411 			if (LIST_FIRST(&freeblks->fb_jblkdephd)) {
14412 				/* Freeblk journal dependency. */
14413 				retval += 1;
14414 				if (!wantcount)
14415 					goto out;
14416 			}
14417 			continue;
14418 
14419 		case D_ALLOCDIRECT:
14420 		case D_ALLOCINDIR:
14421 			newblk = WK_NEWBLK(wk);
14422 			if (newblk->nb_jnewblk) {
14423 				/* Journal allocate dependency. */
14424 				retval += 1;
14425 				if (!wantcount)
14426 					goto out;
14427 			}
14428 			continue;
14429 
14430 		case D_MKDIR:
14431 			mkdir = WK_MKDIR(wk);
14432 			if (mkdir->md_jaddref) {
14433 				/* Journal reference dependency. */
14434 				retval += 1;
14435 				if (!wantcount)
14436 					goto out;
14437 			}
14438 			continue;
14439 
14440 		case D_FREEWORK:
14441 		case D_FREEDEP:
14442 		case D_JSEGDEP:
14443 		case D_JSEG:
14444 		case D_SBDEP:
14445 			/* never a dependency on these blocks */
14446 			continue;
14447 
14448 		default:
14449 			panic("softdep_count_dependencies: Unexpected type %s",
14450 			    TYPENAME(wk->wk_type));
14451 			/* NOTREACHED */
14452 		}
14453 	}
14454 out:
14455 	FREE_LOCK(ump);
14456 	return (retval);
14457 }
14458 
14459 /*
14460  * Acquire exclusive access to a buffer.
14461  * Must be called with a locked mtx parameter.
14462  * Return acquired buffer or NULL on failure.
14463  */
14464 static struct buf *
14465 getdirtybuf(struct buf *bp,
14466 	struct rwlock *lock,
14467 	int waitfor)
14468 {
14469 	int error;
14470 
14471 	if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0) {
14472 		if (waitfor != MNT_WAIT)
14473 			return (NULL);
14474 		error = BUF_LOCK(bp,
14475 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, lock);
14476 		/*
14477 		 * Even if we successfully acquire bp here, we have dropped
14478 		 * lock, which may violates our guarantee.
14479 		 */
14480 		if (error == 0)
14481 			BUF_UNLOCK(bp);
14482 		else if (error != ENOLCK)
14483 			panic("getdirtybuf: inconsistent lock: %d", error);
14484 		rw_wlock(lock);
14485 		return (NULL);
14486 	}
14487 	if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14488 		if (lock != BO_LOCKPTR(bp->b_bufobj) && waitfor == MNT_WAIT) {
14489 			rw_wunlock(lock);
14490 			BO_LOCK(bp->b_bufobj);
14491 			BUF_UNLOCK(bp);
14492 			if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14493 				bp->b_vflags |= BV_BKGRDWAIT;
14494 				msleep(&bp->b_xflags, BO_LOCKPTR(bp->b_bufobj),
14495 				       PRIBIO | PDROP, "getbuf", 0);
14496 			} else
14497 				BO_UNLOCK(bp->b_bufobj);
14498 			rw_wlock(lock);
14499 			return (NULL);
14500 		}
14501 		BUF_UNLOCK(bp);
14502 		if (waitfor != MNT_WAIT)
14503 			return (NULL);
14504 #ifdef DEBUG_VFS_LOCKS
14505 		if (bp->b_vp->v_type != VCHR)
14506 			ASSERT_BO_WLOCKED(bp->b_bufobj);
14507 #endif
14508 		bp->b_vflags |= BV_BKGRDWAIT;
14509 		rw_sleep(&bp->b_xflags, lock, PRIBIO, "getbuf", 0);
14510 		return (NULL);
14511 	}
14512 	if ((bp->b_flags & B_DELWRI) == 0) {
14513 		BUF_UNLOCK(bp);
14514 		return (NULL);
14515 	}
14516 	bremfree(bp);
14517 	return (bp);
14518 }
14519 
14520 /*
14521  * Check if it is safe to suspend the file system now.  On entry,
14522  * the vnode interlock for devvp should be held.  Return 0 with
14523  * the mount interlock held if the file system can be suspended now,
14524  * otherwise return EAGAIN with the mount interlock held.
14525  */
14526 int
14527 softdep_check_suspend(struct mount *mp,
14528 		      struct vnode *devvp,
14529 		      int softdep_depcnt,
14530 		      int softdep_accdepcnt,
14531 		      int secondary_writes,
14532 		      int secondary_accwrites)
14533 {
14534 	struct buf *bp;
14535 	struct bufobj *bo;
14536 	struct ufsmount *ump;
14537 	struct inodedep *inodedep;
14538 	struct indirdep *indirdep;
14539 	struct worklist *wk, *nextwk;
14540 	int error, unlinked;
14541 
14542 	bo = &devvp->v_bufobj;
14543 	ASSERT_BO_WLOCKED(bo);
14544 
14545 	/*
14546 	 * If we are not running with soft updates, then we need only
14547 	 * deal with secondary writes as we try to suspend.
14548 	 */
14549 	if (MOUNTEDSOFTDEP(mp) == 0) {
14550 		MNT_ILOCK(mp);
14551 		while (mp->mnt_secondary_writes != 0) {
14552 			BO_UNLOCK(bo);
14553 			msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
14554 			    (PUSER - 1) | PDROP, "secwr", 0);
14555 			BO_LOCK(bo);
14556 			MNT_ILOCK(mp);
14557 		}
14558 
14559 		/*
14560 		 * Reasons for needing more work before suspend:
14561 		 * - Dirty buffers on devvp.
14562 		 * - Secondary writes occurred after start of vnode sync loop
14563 		 */
14564 		error = 0;
14565 		if (bo->bo_numoutput > 0 ||
14566 		    bo->bo_dirty.bv_cnt > 0 ||
14567 		    secondary_writes != 0 ||
14568 		    mp->mnt_secondary_writes != 0 ||
14569 		    secondary_accwrites != mp->mnt_secondary_accwrites)
14570 			error = EAGAIN;
14571 		BO_UNLOCK(bo);
14572 		return (error);
14573 	}
14574 
14575 	/*
14576 	 * If we are running with soft updates, then we need to coordinate
14577 	 * with them as we try to suspend.
14578 	 */
14579 	ump = VFSTOUFS(mp);
14580 	for (;;) {
14581 		if (!TRY_ACQUIRE_LOCK(ump)) {
14582 			BO_UNLOCK(bo);
14583 			ACQUIRE_LOCK(ump);
14584 			FREE_LOCK(ump);
14585 			BO_LOCK(bo);
14586 			continue;
14587 		}
14588 		MNT_ILOCK(mp);
14589 		if (mp->mnt_secondary_writes != 0) {
14590 			FREE_LOCK(ump);
14591 			BO_UNLOCK(bo);
14592 			msleep(&mp->mnt_secondary_writes,
14593 			       MNT_MTX(mp),
14594 			       (PUSER - 1) | PDROP, "secwr", 0);
14595 			BO_LOCK(bo);
14596 			continue;
14597 		}
14598 		break;
14599 	}
14600 
14601 	unlinked = 0;
14602 	if (MOUNTEDSUJ(mp)) {
14603 		for (inodedep = TAILQ_FIRST(&ump->softdep_unlinked);
14604 		    inodedep != NULL;
14605 		    inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
14606 			if ((inodedep->id_state & (UNLINKED | UNLINKLINKS |
14607 			    UNLINKONLIST)) != (UNLINKED | UNLINKLINKS |
14608 			    UNLINKONLIST) ||
14609 			    !check_inodedep_free(inodedep))
14610 				continue;
14611 			unlinked++;
14612 		}
14613 	}
14614 
14615 	/*
14616 	 * XXX Check for orphaned indirdep dependency structures.
14617 	 *
14618 	 * During forcible unmount after a disk failure there is a
14619 	 * bug that causes one or more indirdep dependency structures
14620 	 * to fail to be deallocated. We check for them here and clean
14621 	 * them up so that the unmount can succeed.
14622 	 */
14623 	if ((ump->um_flags & UM_FSFAIL_CLEANUP) != 0 && ump->softdep_deps > 0 &&
14624 	    ump->softdep_deps == ump->softdep_curdeps[D_INDIRDEP]) {
14625 		LIST_FOREACH_SAFE(wk, &ump->softdep_alldeps[D_INDIRDEP],
14626 		    wk_all, nextwk) {
14627 			indirdep = WK_INDIRDEP(wk);
14628 			if ((indirdep->ir_state & (GOINGAWAY | DEPCOMPLETE)) !=
14629 			    (GOINGAWAY | DEPCOMPLETE) ||
14630 			    !TAILQ_EMPTY(&indirdep->ir_trunc) ||
14631 			    !LIST_EMPTY(&indirdep->ir_completehd) ||
14632 			    !LIST_EMPTY(&indirdep->ir_writehd) ||
14633 			    !LIST_EMPTY(&indirdep->ir_donehd) ||
14634 			    !LIST_EMPTY(&indirdep->ir_deplisthd) ||
14635 			    indirdep->ir_saveddata != NULL ||
14636 			    indirdep->ir_savebp == NULL) {
14637 				printf("%s: skipping orphaned indirdep %p\n",
14638 				    __FUNCTION__, indirdep);
14639 				continue;
14640 			}
14641 			printf("%s: freeing orphaned indirdep %p\n",
14642 			    __FUNCTION__, indirdep);
14643 			bp = indirdep->ir_savebp;
14644 			indirdep->ir_savebp = NULL;
14645 			free_indirdep(indirdep);
14646 			FREE_LOCK(ump);
14647 			brelse(bp);
14648 			while (!TRY_ACQUIRE_LOCK(ump)) {
14649 				BO_UNLOCK(bo);
14650 				ACQUIRE_LOCK(ump);
14651 				FREE_LOCK(ump);
14652 				BO_LOCK(bo);
14653 			}
14654 		}
14655 	}
14656 
14657 	/*
14658 	 * Reasons for needing more work before suspend:
14659 	 * - Dirty buffers on devvp.
14660 	 * - Dependency structures still exist
14661 	 * - Softdep activity occurred after start of vnode sync loop
14662 	 * - Secondary writes occurred after start of vnode sync loop
14663 	 */
14664 	error = 0;
14665 	if (bo->bo_numoutput > 0 ||
14666 	    bo->bo_dirty.bv_cnt > 0 ||
14667 	    softdep_depcnt != unlinked ||
14668 	    ump->softdep_deps != unlinked ||
14669 	    softdep_accdepcnt != ump->softdep_accdeps ||
14670 	    secondary_writes != 0 ||
14671 	    mp->mnt_secondary_writes != 0 ||
14672 	    secondary_accwrites != mp->mnt_secondary_accwrites)
14673 		error = EAGAIN;
14674 	FREE_LOCK(ump);
14675 	BO_UNLOCK(bo);
14676 	return (error);
14677 }
14678 
14679 /*
14680  * Get the number of dependency structures for the file system, both
14681  * the current number and the total number allocated.  These will
14682  * later be used to detect that softdep processing has occurred.
14683  */
14684 void
14685 softdep_get_depcounts(struct mount *mp,
14686 		      int *softdep_depsp,
14687 		      int *softdep_accdepsp)
14688 {
14689 	struct ufsmount *ump;
14690 
14691 	if (MOUNTEDSOFTDEP(mp) == 0) {
14692 		*softdep_depsp = 0;
14693 		*softdep_accdepsp = 0;
14694 		return;
14695 	}
14696 	ump = VFSTOUFS(mp);
14697 	ACQUIRE_LOCK(ump);
14698 	*softdep_depsp = ump->softdep_deps;
14699 	*softdep_accdepsp = ump->softdep_accdeps;
14700 	FREE_LOCK(ump);
14701 }
14702 
14703 /*
14704  * Wait for pending output on a vnode to complete.
14705  */
14706 static void
14707 drain_output(struct vnode *vp)
14708 {
14709 
14710 	ASSERT_VOP_LOCKED(vp, "drain_output");
14711 	(void)bufobj_wwait(&vp->v_bufobj, 0, 0);
14712 }
14713 
14714 /*
14715  * Called whenever a buffer that is being invalidated or reallocated
14716  * contains dependencies. This should only happen if an I/O error has
14717  * occurred. The routine is called with the buffer locked.
14718  */
14719 static void
14720 softdep_deallocate_dependencies(struct buf *bp)
14721 {
14722 
14723 	if ((bp->b_ioflags & BIO_ERROR) == 0)
14724 		panic("softdep_deallocate_dependencies: dangling deps");
14725 	if (bp->b_vp != NULL && bp->b_vp->v_mount != NULL)
14726 		softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntonname, bp->b_error);
14727 	else
14728 		printf("softdep_deallocate_dependencies: "
14729 		    "got error %d while accessing filesystem\n", bp->b_error);
14730 	if (bp->b_error != ENXIO)
14731 		panic("softdep_deallocate_dependencies: unrecovered I/O error");
14732 }
14733 
14734 /*
14735  * Function to handle asynchronous write errors in the filesystem.
14736  */
14737 static void
14738 softdep_error(char *func, int error)
14739 {
14740 
14741 	/* XXX should do something better! */
14742 	printf("%s: got error %d while accessing filesystem\n", func, error);
14743 }
14744 
14745 #ifdef DDB
14746 
14747 /* exported to ffs_vfsops.c */
14748 extern void db_print_ffs(struct ufsmount *ump);
14749 void
14750 db_print_ffs(struct ufsmount *ump)
14751 {
14752 	db_printf("mp %p (%s) devvp %p\n", ump->um_mountp,
14753 	    ump->um_mountp->mnt_stat.f_mntonname, ump->um_devvp);
14754 	db_printf("    fs %p ", ump->um_fs);
14755 
14756 	if (ump->um_softdep != NULL) {
14757 		db_printf("su_wl %d su_deps %d su_req %d\n",
14758 		    ump->softdep_on_worklist, ump->softdep_deps,
14759 		    ump->softdep_req);
14760 	} else {
14761 		db_printf("su disabled\n");
14762 	}
14763 }
14764 
14765 static void
14766 worklist_print(struct worklist *wk, int verbose)
14767 {
14768 
14769 	if (!verbose) {
14770 		db_printf("%s: %p state 0x%b\n", TYPENAME(wk->wk_type), wk,
14771 		    (u_int)wk->wk_state, PRINT_SOFTDEP_FLAGS);
14772 		return;
14773 	}
14774 	db_printf("worklist: %p type %s state 0x%b next %p\n    ", wk,
14775 	    TYPENAME(wk->wk_type), (u_int)wk->wk_state, PRINT_SOFTDEP_FLAGS,
14776 	    LIST_NEXT(wk, wk_list));
14777 	db_print_ffs(VFSTOUFS(wk->wk_mp));
14778 }
14779 
14780 static void
14781 inodedep_print(struct inodedep *inodedep, int verbose)
14782 {
14783 
14784 	worklist_print(&inodedep->id_list, 0);
14785 	db_printf("    fs %p ino %jd inoblk %jd delta %jd nlink %jd\n",
14786 	    inodedep->id_fs,
14787 	    (intmax_t)inodedep->id_ino,
14788 	    (intmax_t)fsbtodb(inodedep->id_fs,
14789 	        ino_to_fsba(inodedep->id_fs, inodedep->id_ino)),
14790 	    (intmax_t)inodedep->id_nlinkdelta,
14791 	    (intmax_t)inodedep->id_savednlink);
14792 
14793 	if (verbose == 0)
14794 		return;
14795 
14796 	db_printf("    bmsafemap %p, mkdiradd %p, inoreflst %p\n",
14797 	    inodedep->id_bmsafemap,
14798 	    inodedep->id_mkdiradd,
14799 	    TAILQ_FIRST(&inodedep->id_inoreflst));
14800 	db_printf("    dirremhd %p, pendinghd %p, bufwait %p\n",
14801 	    LIST_FIRST(&inodedep->id_dirremhd),
14802 	    LIST_FIRST(&inodedep->id_pendinghd),
14803 	    LIST_FIRST(&inodedep->id_bufwait));
14804 	db_printf("    inowait %p, inoupdt %p, newinoupdt %p\n",
14805 	    LIST_FIRST(&inodedep->id_inowait),
14806 	    TAILQ_FIRST(&inodedep->id_inoupdt),
14807 	    TAILQ_FIRST(&inodedep->id_newinoupdt));
14808 	db_printf("    extupdt %p, newextupdt %p, freeblklst %p\n",
14809 	    TAILQ_FIRST(&inodedep->id_extupdt),
14810 	    TAILQ_FIRST(&inodedep->id_newextupdt),
14811 	    TAILQ_FIRST(&inodedep->id_freeblklst));
14812 	db_printf("    saveino %p, savedsize %jd, savedextsize %jd\n",
14813 	    inodedep->id_savedino1,
14814 	    (intmax_t)inodedep->id_savedsize,
14815 	    (intmax_t)inodedep->id_savedextsize);
14816 }
14817 
14818 static void
14819 newblk_print(struct newblk *nbp)
14820 {
14821 
14822 	worklist_print(&nbp->nb_list, 0);
14823 	db_printf("    newblkno %jd\n", (intmax_t)nbp->nb_newblkno);
14824 	db_printf("    jnewblk %p, bmsafemap %p, freefrag %p\n",
14825 	    &nbp->nb_jnewblk,
14826 	    &nbp->nb_bmsafemap,
14827 	    &nbp->nb_freefrag);
14828 	db_printf("    indirdeps %p, newdirblk %p, jwork %p\n",
14829 	    LIST_FIRST(&nbp->nb_indirdeps),
14830 	    LIST_FIRST(&nbp->nb_newdirblk),
14831 	    LIST_FIRST(&nbp->nb_jwork));
14832 }
14833 
14834 static void
14835 allocdirect_print(struct allocdirect *adp)
14836 {
14837 
14838 	newblk_print(&adp->ad_block);
14839 	db_printf("    oldblkno %jd, oldsize %ld, newsize %ld\n",
14840 	    adp->ad_oldblkno, adp->ad_oldsize, adp->ad_newsize);
14841 	db_printf("    offset %d, inodedep %p\n",
14842 	    adp->ad_offset, adp->ad_inodedep);
14843 }
14844 
14845 static void
14846 allocindir_print(struct allocindir *aip)
14847 {
14848 
14849 	newblk_print(&aip->ai_block);
14850 	db_printf("    oldblkno %jd, lbn %jd\n",
14851 	    (intmax_t)aip->ai_oldblkno, (intmax_t)aip->ai_lbn);
14852 	db_printf("    offset %d, indirdep %p\n",
14853 	    aip->ai_offset, aip->ai_indirdep);
14854 }
14855 
14856 static void
14857 mkdir_print(struct mkdir *mkdir)
14858 {
14859 
14860 	worklist_print(&mkdir->md_list, 0);
14861 	db_printf("    diradd %p, jaddref %p, buf %p\n",
14862 		mkdir->md_diradd, mkdir->md_jaddref, mkdir->md_buf);
14863 }
14864 
14865 DB_SHOW_COMMAND(sd_inodedep, db_show_sd_inodedep)
14866 {
14867 
14868 	if (have_addr == 0) {
14869 		db_printf("inodedep address required\n");
14870 		return;
14871 	}
14872 	inodedep_print((struct inodedep*)addr, 1);
14873 }
14874 
14875 DB_SHOW_COMMAND(sd_allinodedeps, db_show_sd_allinodedeps)
14876 {
14877 	struct inodedep_hashhead *inodedephd;
14878 	struct inodedep *inodedep;
14879 	struct ufsmount *ump;
14880 	int cnt;
14881 
14882 	if (have_addr == 0) {
14883 		db_printf("ufsmount address required\n");
14884 		return;
14885 	}
14886 	ump = (struct ufsmount *)addr;
14887 	for (cnt = 0; cnt < ump->inodedep_hash_size; cnt++) {
14888 		inodedephd = &ump->inodedep_hashtbl[cnt];
14889 		LIST_FOREACH(inodedep, inodedephd, id_hash) {
14890 			inodedep_print(inodedep, 0);
14891 		}
14892 	}
14893 }
14894 
14895 DB_SHOW_COMMAND(sd_worklist, db_show_sd_worklist)
14896 {
14897 
14898 	if (have_addr == 0) {
14899 		db_printf("worklist address required\n");
14900 		return;
14901 	}
14902 	worklist_print((struct worklist *)addr, 1);
14903 }
14904 
14905 DB_SHOW_COMMAND(sd_workhead, db_show_sd_workhead)
14906 {
14907 	struct worklist *wk;
14908 	struct workhead *wkhd;
14909 
14910 	if (have_addr == 0) {
14911 		db_printf("worklist address required "
14912 		    "(for example value in bp->b_dep)\n");
14913 		return;
14914 	}
14915 	/*
14916 	 * We often do not have the address of the worklist head but
14917 	 * instead a pointer to its first entry (e.g., we have the
14918 	 * contents of bp->b_dep rather than &bp->b_dep). But the back
14919 	 * pointer of bp->b_dep will point at the head of the list, so
14920 	 * we cheat and use that instead. If we are in the middle of
14921 	 * a list we will still get the same result, so nothing
14922 	 * unexpected will result.
14923 	 */
14924 	wk = (struct worklist *)addr;
14925 	if (wk == NULL)
14926 		return;
14927 	wkhd = (struct workhead *)wk->wk_list.le_prev;
14928 	LIST_FOREACH(wk, wkhd, wk_list) {
14929 		switch(wk->wk_type) {
14930 		case D_INODEDEP:
14931 			inodedep_print(WK_INODEDEP(wk), 0);
14932 			continue;
14933 		case D_ALLOCDIRECT:
14934 			allocdirect_print(WK_ALLOCDIRECT(wk));
14935 			continue;
14936 		case D_ALLOCINDIR:
14937 			allocindir_print(WK_ALLOCINDIR(wk));
14938 			continue;
14939 		case D_MKDIR:
14940 			mkdir_print(WK_MKDIR(wk));
14941 			continue;
14942 		default:
14943 			worklist_print(wk, 0);
14944 			continue;
14945 		}
14946 	}
14947 }
14948 
14949 DB_SHOW_COMMAND(sd_mkdir, db_show_sd_mkdir)
14950 {
14951 	if (have_addr == 0) {
14952 		db_printf("mkdir address required\n");
14953 		return;
14954 	}
14955 	mkdir_print((struct mkdir *)addr);
14956 }
14957 
14958 DB_SHOW_COMMAND(sd_mkdir_list, db_show_sd_mkdir_list)
14959 {
14960 	struct mkdirlist *mkdirlisthd;
14961 	struct mkdir *mkdir;
14962 
14963 	if (have_addr == 0) {
14964 		db_printf("mkdir listhead address required\n");
14965 		return;
14966 	}
14967 	mkdirlisthd = (struct mkdirlist *)addr;
14968 	LIST_FOREACH(mkdir, mkdirlisthd, md_mkdirs) {
14969 		mkdir_print(mkdir);
14970 		if (mkdir->md_diradd != NULL) {
14971 			db_printf("    ");
14972 			worklist_print(&mkdir->md_diradd->da_list, 0);
14973 		}
14974 		if (mkdir->md_jaddref != NULL) {
14975 			db_printf("    ");
14976 			worklist_print(&mkdir->md_jaddref->ja_list, 0);
14977 		}
14978 	}
14979 }
14980 
14981 DB_SHOW_COMMAND(sd_allocdirect, db_show_sd_allocdirect)
14982 {
14983 	if (have_addr == 0) {
14984 		db_printf("allocdirect address required\n");
14985 		return;
14986 	}
14987 	allocdirect_print((struct allocdirect *)addr);
14988 }
14989 
14990 DB_SHOW_COMMAND(sd_allocindir, db_show_sd_allocindir)
14991 {
14992 	if (have_addr == 0) {
14993 		db_printf("allocindir address required\n");
14994 		return;
14995 	}
14996 	allocindir_print((struct allocindir *)addr);
14997 }
14998 
14999 #endif /* DDB */
15000 
15001 #endif /* SOFTUPDATES */
15002