xref: /freebsd/sys/ufs/ffs/ffs_softdep.c (revision 86a2c910c05c65d1318aef81ddbde8ac7eab79b9)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
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 
42 #include <sys/cdefs.h>
43 #include "opt_ffs.h"
44 #include "opt_quota.h"
45 #include "opt_ddb.h"
46 
47 #include <sys/param.h>
48 #include <sys/kernel.h>
49 #include <sys/systm.h>
50 #include <sys/bio.h>
51 #include <sys/buf.h>
52 #include <sys/kdb.h>
53 #include <sys/kthread.h>
54 #include <sys/ktr.h>
55 #include <sys/limits.h>
56 #include <sys/lock.h>
57 #include <sys/malloc.h>
58 #include <sys/mount.h>
59 #include <sys/mutex.h>
60 #include <sys/namei.h>
61 #include <sys/priv.h>
62 #include <sys/proc.h>
63 #include <sys/racct.h>
64 #include <sys/rwlock.h>
65 #include <sys/stat.h>
66 #include <sys/sysctl.h>
67 #include <sys/syslog.h>
68 #include <sys/vnode.h>
69 #include <sys/conf.h>
70 
71 #include <ufs/ufs/dir.h>
72 #include <ufs/ufs/extattr.h>
73 #include <ufs/ufs/quota.h>
74 #include <ufs/ufs/inode.h>
75 #include <ufs/ufs/ufsmount.h>
76 #include <ufs/ffs/fs.h>
77 #include <ufs/ffs/softdep.h>
78 #include <ufs/ffs/ffs_extern.h>
79 #include <ufs/ufs/ufs_extern.h>
80 
81 #include <vm/vm.h>
82 #include <vm/vm_extern.h>
83 #include <vm/vm_object.h>
84 
85 #include <geom/geom.h>
86 #include <geom/geom_vfs.h>
87 
88 #include <ddb/ddb.h>
89 
90 #define	KTR_SUJ	0	/* Define to KTR_SPARE. */
91 
92 #ifndef SOFTUPDATES
93 
94 int
95 softdep_flushfiles(struct mount *oldmnt,
96 	int flags,
97 	struct thread *td)
98 {
99 
100 	panic("softdep_flushfiles called");
101 }
102 
103 int
104 softdep_mount(struct vnode *devvp,
105 	struct mount *mp,
106 	struct fs *fs,
107 	struct ucred *cred)
108 {
109 
110 	return (0);
111 }
112 
113 void
114 softdep_initialize(void)
115 {
116 
117 	return;
118 }
119 
120 void
121 softdep_uninitialize(void)
122 {
123 
124 	return;
125 }
126 
127 void
128 softdep_unmount(struct mount *mp)
129 {
130 
131 	panic("softdep_unmount called");
132 }
133 
134 void
135 softdep_setup_sbupdate(struct ufsmount *ump,
136 	struct fs *fs,
137 	struct buf *bp)
138 {
139 
140 	panic("softdep_setup_sbupdate called");
141 }
142 
143 void
144 softdep_setup_inomapdep(struct buf *bp,
145 	struct inode *ip,
146 	ino_t newinum,
147 	int mode)
148 {
149 
150 	panic("softdep_setup_inomapdep called");
151 }
152 
153 void
154 softdep_setup_blkmapdep(struct buf *bp,
155 	struct mount *mp,
156 	ufs2_daddr_t newblkno,
157 	int frags,
158 	int oldfrags)
159 {
160 
161 	panic("softdep_setup_blkmapdep called");
162 }
163 
164 void
165 softdep_setup_allocdirect(struct inode *ip,
166 	ufs_lbn_t lbn,
167 	ufs2_daddr_t newblkno,
168 	ufs2_daddr_t oldblkno,
169 	long newsize,
170 	long oldsize,
171 	struct buf *bp)
172 {
173 
174 	panic("softdep_setup_allocdirect called");
175 }
176 
177 void
178 softdep_setup_allocext(struct inode *ip,
179 	ufs_lbn_t lbn,
180 	ufs2_daddr_t newblkno,
181 	ufs2_daddr_t oldblkno,
182 	long newsize,
183 	long oldsize,
184 	struct buf *bp)
185 {
186 
187 	panic("softdep_setup_allocext called");
188 }
189 
190 void
191 softdep_setup_allocindir_page(struct inode *ip,
192 	ufs_lbn_t lbn,
193 	struct buf *bp,
194 	int ptrno,
195 	ufs2_daddr_t newblkno,
196 	ufs2_daddr_t oldblkno,
197 	struct buf *nbp)
198 {
199 
200 	panic("softdep_setup_allocindir_page called");
201 }
202 
203 void
204 softdep_setup_allocindir_meta(struct buf *nbp,
205 	struct inode *ip,
206 	struct buf *bp,
207 	int ptrno,
208 	ufs2_daddr_t newblkno)
209 {
210 
211 	panic("softdep_setup_allocindir_meta called");
212 }
213 
214 void
215 softdep_journal_freeblocks(struct inode *ip,
216 	struct ucred *cred,
217 	off_t length,
218 	int flags)
219 {
220 
221 	panic("softdep_journal_freeblocks called");
222 }
223 
224 void
225 softdep_journal_fsync(struct inode *ip)
226 {
227 
228 	panic("softdep_journal_fsync called");
229 }
230 
231 void
232 softdep_setup_freeblocks(struct inode *ip,
233 	off_t length,
234 	int flags)
235 {
236 
237 	panic("softdep_setup_freeblocks called");
238 }
239 
240 void
241 softdep_freefile(struct vnode *pvp,
242 		ino_t ino,
243 		int mode)
244 {
245 
246 	panic("softdep_freefile called");
247 }
248 
249 int
250 softdep_setup_directory_add(struct buf *bp,
251 	struct inode *dp,
252 	off_t diroffset,
253 	ino_t newinum,
254 	struct buf *newdirbp,
255 	int isnewblk)
256 {
257 
258 	panic("softdep_setup_directory_add called");
259 }
260 
261 void
262 softdep_change_directoryentry_offset(struct buf *bp,
263 	struct inode *dp,
264 	caddr_t base,
265 	caddr_t oldloc,
266 	caddr_t newloc,
267 	int entrysize)
268 {
269 
270 	panic("softdep_change_directoryentry_offset called");
271 }
272 
273 void
274 softdep_setup_remove(struct buf *bp,
275 	struct inode *dp,
276 	struct inode *ip,
277 	int isrmdir)
278 {
279 
280 	panic("softdep_setup_remove called");
281 }
282 
283 void
284 softdep_setup_directory_change(struct buf *bp,
285 	struct inode *dp,
286 	struct inode *ip,
287 	ino_t newinum,
288 	int isrmdir)
289 {
290 
291 	panic("softdep_setup_directory_change called");
292 }
293 
294 void
295 softdep_setup_blkfree(struct mount *mp,
296 	struct buf *bp,
297 	ufs2_daddr_t blkno,
298 	int frags,
299 	struct workhead *wkhd,
300 	bool doingrecovery)
301 {
302 
303 	panic("%s called", __FUNCTION__);
304 }
305 
306 void
307 softdep_setup_inofree(struct mount *mp,
308 	struct buf *bp,
309 	ino_t ino,
310 	struct workhead *wkhd,
311 	bool doingrecovery)
312 {
313 
314 	panic("%s called", __FUNCTION__);
315 }
316 
317 void
318 softdep_setup_unlink(struct inode *dp, struct inode *ip)
319 {
320 
321 	panic("%s called", __FUNCTION__);
322 }
323 
324 void
325 softdep_setup_link(struct inode *dp, struct inode *ip)
326 {
327 
328 	panic("%s called", __FUNCTION__);
329 }
330 
331 void
332 softdep_revert_link(struct inode *dp, struct inode *ip)
333 {
334 
335 	panic("%s called", __FUNCTION__);
336 }
337 
338 void
339 softdep_setup_rmdir(struct inode *dp, struct inode *ip)
340 {
341 
342 	panic("%s called", __FUNCTION__);
343 }
344 
345 void
346 softdep_revert_rmdir(struct inode *dp, struct inode *ip)
347 {
348 
349 	panic("%s called", __FUNCTION__);
350 }
351 
352 void
353 softdep_setup_create(struct inode *dp, struct inode *ip)
354 {
355 
356 	panic("%s called", __FUNCTION__);
357 }
358 
359 void
360 softdep_revert_create(struct inode *dp, struct inode *ip)
361 {
362 
363 	panic("%s called", __FUNCTION__);
364 }
365 
366 void
367 softdep_setup_mkdir(struct inode *dp, struct inode *ip)
368 {
369 
370 	panic("%s called", __FUNCTION__);
371 }
372 
373 void
374 softdep_revert_mkdir(struct inode *dp, struct inode *ip)
375 {
376 
377 	panic("%s called", __FUNCTION__);
378 }
379 
380 void
381 softdep_setup_dotdot_link(struct inode *dp, struct inode *ip)
382 {
383 
384 	panic("%s called", __FUNCTION__);
385 }
386 
387 int
388 softdep_prealloc(struct vnode *vp, int waitok)
389 {
390 
391 	panic("%s called", __FUNCTION__);
392 }
393 
394 int
395 softdep_journal_lookup(struct mount *mp, struct vnode **vpp)
396 {
397 
398 	return (ENOENT);
399 }
400 
401 void
402 softdep_change_linkcnt(struct inode *ip)
403 {
404 
405 	panic("softdep_change_linkcnt called");
406 }
407 
408 void
409 softdep_load_inodeblock(struct inode *ip)
410 {
411 
412 	panic("softdep_load_inodeblock called");
413 }
414 
415 void
416 softdep_update_inodeblock(struct inode *ip,
417 	struct buf *bp,
418 	int waitfor)
419 {
420 
421 	panic("softdep_update_inodeblock called");
422 }
423 
424 int
425 softdep_fsync(struct vnode *vp)	/* the "in_core" copy of the inode */
426 {
427 
428 	return (0);
429 }
430 
431 void
432 softdep_fsync_mountdev(struct vnode *vp)
433 {
434 
435 	return;
436 }
437 
438 int
439 softdep_flushworklist(struct mount *oldmnt,
440 	int *countp,
441 	struct thread *td)
442 {
443 
444 	*countp = 0;
445 	return (0);
446 }
447 
448 int
449 softdep_sync_metadata(struct vnode *vp)
450 {
451 
452 	panic("softdep_sync_metadata called");
453 }
454 
455 int
456 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
457 {
458 
459 	panic("softdep_sync_buf called");
460 }
461 
462 int
463 softdep_slowdown(struct vnode *vp)
464 {
465 
466 	panic("softdep_slowdown called");
467 }
468 
469 int
470 softdep_request_cleanup(struct fs *fs,
471 	struct vnode *vp,
472 	struct ucred *cred,
473 	int resource)
474 {
475 
476 	return (0);
477 }
478 
479 int
480 softdep_check_suspend(struct mount *mp,
481 		      struct vnode *devvp,
482 		      int softdep_depcnt,
483 		      int softdep_accdepcnt,
484 		      int secondary_writes,
485 		      int secondary_accwrites)
486 {
487 	struct bufobj *bo;
488 	int error;
489 
490 	(void) softdep_depcnt,
491 	(void) softdep_accdepcnt;
492 
493 	bo = &devvp->v_bufobj;
494 	ASSERT_BO_WLOCKED(bo);
495 
496 	MNT_ILOCK(mp);
497 	while (mp->mnt_secondary_writes != 0) {
498 		BO_UNLOCK(bo);
499 		msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
500 		    (PUSER - 1) | PDROP, "secwr", 0);
501 		BO_LOCK(bo);
502 		MNT_ILOCK(mp);
503 	}
504 
505 	/*
506 	 * Reasons for needing more work before suspend:
507 	 * - Dirty buffers on devvp.
508 	 * - Secondary writes occurred after start of vnode sync loop
509 	 */
510 	error = 0;
511 	if (bo->bo_numoutput > 0 ||
512 	    bo->bo_dirty.bv_cnt > 0 ||
513 	    secondary_writes != 0 ||
514 	    mp->mnt_secondary_writes != 0 ||
515 	    secondary_accwrites != mp->mnt_secondary_accwrites)
516 		error = EAGAIN;
517 	BO_UNLOCK(bo);
518 	return (error);
519 }
520 
521 void
522 softdep_get_depcounts(struct mount *mp,
523 		      int *softdepactivep,
524 		      int *softdepactiveaccp)
525 {
526 	(void) mp;
527 	*softdepactivep = 0;
528 	*softdepactiveaccp = 0;
529 }
530 
531 void
532 softdep_buf_append(struct buf *bp, struct workhead *wkhd)
533 {
534 
535 	panic("softdep_buf_appendwork called");
536 }
537 
538 void
539 softdep_inode_append(struct inode *ip,
540 	struct ucred *cred,
541 	struct workhead *wkhd)
542 {
543 
544 	panic("softdep_inode_appendwork called");
545 }
546 
547 void
548 softdep_freework(struct workhead *wkhd)
549 {
550 
551 	panic("softdep_freework called");
552 }
553 
554 int
555 softdep_prerename(struct vnode *fdvp,
556 	struct vnode *fvp,
557 	struct vnode *tdvp,
558 	struct vnode *tvp)
559 {
560 
561 	panic("softdep_prerename called");
562 }
563 
564 int
565 softdep_prelink(struct vnode *dvp,
566 	struct vnode *vp,
567 	struct componentname *cnp)
568 {
569 
570 	panic("softdep_prelink called");
571 }
572 
573 #else
574 
575 FEATURE(softupdates, "FFS soft-updates support");
576 
577 static SYSCTL_NODE(_debug, OID_AUTO, softdep, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
578     "soft updates stats");
579 static SYSCTL_NODE(_debug_softdep, OID_AUTO, total,
580     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
581     "total dependencies allocated");
582 static SYSCTL_NODE(_debug_softdep, OID_AUTO, highuse,
583     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
584     "high use dependencies allocated");
585 static SYSCTL_NODE(_debug_softdep, OID_AUTO, current,
586     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
587     "current dependencies allocated");
588 static SYSCTL_NODE(_debug_softdep, OID_AUTO, write,
589     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
590     "current dependencies written");
591 
592 unsigned long dep_current[D_LAST + 1];
593 unsigned long dep_highuse[D_LAST + 1];
594 unsigned long dep_total[D_LAST + 1];
595 unsigned long dep_write[D_LAST + 1];
596 
597 #define	SOFTDEP_TYPE(type, str, long)					\
598     static MALLOC_DEFINE(M_ ## type, #str, long);			\
599     SYSCTL_ULONG(_debug_softdep_total, OID_AUTO, str, CTLFLAG_RD,	\
600 	&dep_total[D_ ## type], 0, "");					\
601     SYSCTL_ULONG(_debug_softdep_current, OID_AUTO, str, CTLFLAG_RD, 	\
602 	&dep_current[D_ ## type], 0, "");				\
603     SYSCTL_ULONG(_debug_softdep_highuse, OID_AUTO, str, CTLFLAG_RD, 	\
604 	&dep_highuse[D_ ## type], 0, "");				\
605     SYSCTL_ULONG(_debug_softdep_write, OID_AUTO, str, CTLFLAG_RD, 	\
606 	&dep_write[D_ ## type], 0, "");
607 
608 SOFTDEP_TYPE(PAGEDEP, pagedep, "File page dependencies");
609 SOFTDEP_TYPE(INODEDEP, inodedep, "Inode dependencies");
610 SOFTDEP_TYPE(BMSAFEMAP, bmsafemap,
611     "Block or frag allocated from cyl group map");
612 SOFTDEP_TYPE(NEWBLK, newblk, "New block or frag allocation dependency");
613 SOFTDEP_TYPE(ALLOCDIRECT, allocdirect, "Block or frag dependency for an inode");
614 SOFTDEP_TYPE(INDIRDEP, indirdep, "Indirect block dependencies");
615 SOFTDEP_TYPE(ALLOCINDIR, allocindir, "Block dependency for an indirect block");
616 SOFTDEP_TYPE(FREEFRAG, freefrag, "Previously used frag for an inode");
617 SOFTDEP_TYPE(FREEBLKS, freeblks, "Blocks freed from an inode");
618 SOFTDEP_TYPE(FREEFILE, freefile, "Inode deallocated");
619 SOFTDEP_TYPE(DIRADD, diradd, "New directory entry");
620 SOFTDEP_TYPE(MKDIR, mkdir, "New directory");
621 SOFTDEP_TYPE(DIRREM, dirrem, "Directory entry deleted");
622 SOFTDEP_TYPE(NEWDIRBLK, newdirblk, "Unclaimed new directory block");
623 SOFTDEP_TYPE(FREEWORK, freework, "free an inode block");
624 SOFTDEP_TYPE(FREEDEP, freedep, "track a block free");
625 SOFTDEP_TYPE(JADDREF, jaddref, "Journal inode ref add");
626 SOFTDEP_TYPE(JREMREF, jremref, "Journal inode ref remove");
627 SOFTDEP_TYPE(JMVREF, jmvref, "Journal inode ref move");
628 SOFTDEP_TYPE(JNEWBLK, jnewblk, "Journal new block");
629 SOFTDEP_TYPE(JFREEBLK, jfreeblk, "Journal free block");
630 SOFTDEP_TYPE(JFREEFRAG, jfreefrag, "Journal free frag");
631 SOFTDEP_TYPE(JSEG, jseg, "Journal segment");
632 SOFTDEP_TYPE(JSEGDEP, jsegdep, "Journal segment complete");
633 SOFTDEP_TYPE(SBDEP, sbdep, "Superblock write dependency");
634 SOFTDEP_TYPE(JTRUNC, jtrunc, "Journal inode truncation");
635 SOFTDEP_TYPE(JFSYNC, jfsync, "Journal fsync complete");
636 
637 static MALLOC_DEFINE(M_SENTINEL, "sentinel", "Worklist sentinel");
638 
639 static MALLOC_DEFINE(M_SAVEDINO, "savedino", "Saved inodes");
640 static MALLOC_DEFINE(M_JBLOCKS, "jblocks", "Journal block locations");
641 static MALLOC_DEFINE(M_MOUNTDATA, "softdep", "Softdep per-mount data");
642 
643 #define M_SOFTDEP_FLAGS	(M_WAITOK)
644 
645 /*
646  * translate from workitem type to memory type
647  * MUST match the defines above, such that memtype[D_XXX] == M_XXX
648  */
649 static struct malloc_type *memtype[] = {
650 	NULL,
651 	M_PAGEDEP,
652 	M_INODEDEP,
653 	M_BMSAFEMAP,
654 	M_NEWBLK,
655 	M_ALLOCDIRECT,
656 	M_INDIRDEP,
657 	M_ALLOCINDIR,
658 	M_FREEFRAG,
659 	M_FREEBLKS,
660 	M_FREEFILE,
661 	M_DIRADD,
662 	M_MKDIR,
663 	M_DIRREM,
664 	M_NEWDIRBLK,
665 	M_FREEWORK,
666 	M_FREEDEP,
667 	M_JADDREF,
668 	M_JREMREF,
669 	M_JMVREF,
670 	M_JNEWBLK,
671 	M_JFREEBLK,
672 	M_JFREEFRAG,
673 	M_JSEG,
674 	M_JSEGDEP,
675 	M_SBDEP,
676 	M_JTRUNC,
677 	M_JFSYNC,
678 	M_SENTINEL
679 };
680 
681 #define DtoM(type) (memtype[type])
682 
683 /*
684  * Names of malloc types.
685  */
686 #define TYPENAME(type)  \
687 	((unsigned)(type) <= D_LAST && (unsigned)(type) >= D_FIRST ? \
688 	memtype[type]->ks_shortdesc : "???")
689 /*
690  * End system adaptation definitions.
691  */
692 
693 #define	DOTDOT_OFFSET	offsetof(struct dirtemplate, dotdot_ino)
694 #define	DOT_OFFSET	offsetof(struct dirtemplate, dot_ino)
695 
696 /*
697  * Internal function prototypes.
698  */
699 static	void check_clear_deps(struct mount *);
700 static	void softdep_error(char *, int);
701 static	int softdep_prerename_vnode(struct ufsmount *, struct vnode *);
702 static	int softdep_process_worklist(struct mount *, int);
703 static	int softdep_waitidle(struct mount *, int);
704 static	void drain_output(struct vnode *);
705 static	struct buf *getdirtybuf(struct buf *, struct rwlock *, int);
706 static	int check_inodedep_free(struct inodedep *);
707 static	void clear_remove(struct mount *);
708 static	void clear_inodedeps(struct mount *);
709 static	void unlinked_inodedep(struct mount *, struct inodedep *);
710 static	void clear_unlinked_inodedep(struct inodedep *);
711 static	struct inodedep *first_unlinked_inodedep(struct ufsmount *);
712 static	int flush_pagedep_deps(struct vnode *, struct mount *,
713 	    struct diraddhd *, struct buf *);
714 static	int free_pagedep(struct pagedep *);
715 static	int flush_newblk_dep(struct vnode *, struct mount *, ufs_lbn_t);
716 static	int flush_inodedep_deps(struct vnode *, struct mount *, ino_t);
717 static	int flush_deplist(struct allocdirectlst *, int, int *);
718 static	int sync_cgs(struct mount *, int);
719 static	int handle_written_filepage(struct pagedep *, struct buf *, int);
720 static	int handle_written_sbdep(struct sbdep *, struct buf *);
721 static	void initiate_write_sbdep(struct sbdep *);
722 static	void diradd_inode_written(struct diradd *, struct inodedep *);
723 static	int handle_written_indirdep(struct indirdep *, struct buf *,
724 	    struct buf**, int);
725 static	int handle_written_inodeblock(struct inodedep *, struct buf *, int);
726 static	int jnewblk_rollforward(struct jnewblk *, struct fs *, struct cg *,
727 	    uint8_t *);
728 static	int handle_written_bmsafemap(struct bmsafemap *, struct buf *, int);
729 static	void handle_written_jaddref(struct jaddref *);
730 static	void handle_written_jremref(struct jremref *);
731 static	void handle_written_jseg(struct jseg *, struct buf *);
732 static	void handle_written_jnewblk(struct jnewblk *);
733 static	void handle_written_jblkdep(struct jblkdep *);
734 static	void handle_written_jfreefrag(struct jfreefrag *);
735 static	void complete_jseg(struct jseg *);
736 static	void complete_jsegs(struct jseg *);
737 static	void jseg_write(struct ufsmount *ump, struct jseg *, uint8_t *);
738 static	void jaddref_write(struct jaddref *, struct jseg *, uint8_t *);
739 static	void jremref_write(struct jremref *, struct jseg *, uint8_t *);
740 static	void jmvref_write(struct jmvref *, struct jseg *, uint8_t *);
741 static	void jtrunc_write(struct jtrunc *, struct jseg *, uint8_t *);
742 static	void jfsync_write(struct jfsync *, struct jseg *, uint8_t *data);
743 static	void jnewblk_write(struct jnewblk *, struct jseg *, uint8_t *);
744 static	void jfreeblk_write(struct jfreeblk *, struct jseg *, uint8_t *);
745 static	void jfreefrag_write(struct jfreefrag *, struct jseg *, uint8_t *);
746 static	inline void inoref_write(struct inoref *, struct jseg *,
747 	    struct jrefrec *);
748 static	void handle_allocdirect_partdone(struct allocdirect *,
749 	    struct workhead *);
750 static	struct jnewblk *cancel_newblk(struct newblk *, struct worklist *,
751 	    struct workhead *);
752 static	void indirdep_complete(struct indirdep *);
753 static	int indirblk_lookup(struct mount *, ufs2_daddr_t);
754 static	void indirblk_insert(struct freework *);
755 static	void indirblk_remove(struct freework *);
756 static	void handle_allocindir_partdone(struct allocindir *);
757 static	void initiate_write_filepage(struct pagedep *, struct buf *);
758 static	void initiate_write_indirdep(struct indirdep*, struct buf *);
759 static	void handle_written_mkdir(struct mkdir *, int);
760 static	int jnewblk_rollback(struct jnewblk *, struct fs *, struct cg *,
761 	    uint8_t *);
762 static	void initiate_write_bmsafemap(struct bmsafemap *, struct buf *);
763 static	void initiate_write_inodeblock_ufs1(struct inodedep *, struct buf *);
764 static	void initiate_write_inodeblock_ufs2(struct inodedep *, struct buf *);
765 static	void handle_workitem_freefile(struct freefile *);
766 static	int handle_workitem_remove(struct dirrem *, int);
767 static	struct dirrem *newdirrem(struct buf *, struct inode *,
768 	    struct inode *, int, struct dirrem **);
769 static	struct indirdep *indirdep_lookup(struct mount *, struct inode *,
770 	    struct buf *);
771 static	void cancel_indirdep(struct indirdep *, struct buf *,
772 	    struct freeblks *);
773 static	void free_indirdep(struct indirdep *);
774 static	void free_diradd(struct diradd *, struct workhead *);
775 static	void merge_diradd(struct inodedep *, struct diradd *);
776 static	void complete_diradd(struct diradd *);
777 static	struct diradd *diradd_lookup(struct pagedep *, int);
778 static	struct jremref *cancel_diradd_dotdot(struct inode *, struct dirrem *,
779 	    struct jremref *);
780 static	struct jremref *cancel_mkdir_dotdot(struct inode *, struct dirrem *,
781 	    struct jremref *);
782 static	void cancel_diradd(struct diradd *, struct dirrem *, struct jremref *,
783 	    struct jremref *, struct jremref *);
784 static	void dirrem_journal(struct dirrem *, struct jremref *, struct jremref *,
785 	    struct jremref *);
786 static	void cancel_allocindir(struct allocindir *, struct buf *bp,
787 	    struct freeblks *, int);
788 static	int setup_trunc_indir(struct freeblks *, struct inode *,
789 	    ufs_lbn_t, ufs_lbn_t, ufs2_daddr_t);
790 static	void complete_trunc_indir(struct freework *);
791 static	void trunc_indirdep(struct indirdep *, struct freeblks *, struct buf *,
792 	    int);
793 static	void complete_mkdir(struct mkdir *);
794 static	void free_newdirblk(struct newdirblk *);
795 static	void free_jremref(struct jremref *);
796 static	void free_jaddref(struct jaddref *);
797 static	void free_jsegdep(struct jsegdep *);
798 static	void free_jsegs(struct jblocks *);
799 static	void rele_jseg(struct jseg *);
800 static	void free_jseg(struct jseg *, struct jblocks *);
801 static	void free_jnewblk(struct jnewblk *);
802 static	void free_jblkdep(struct jblkdep *);
803 static	void free_jfreefrag(struct jfreefrag *);
804 static	void free_freedep(struct freedep *);
805 static	void journal_jremref(struct dirrem *, struct jremref *,
806 	    struct inodedep *);
807 static	void cancel_jnewblk(struct jnewblk *, struct workhead *);
808 static	int cancel_jaddref(struct jaddref *, struct inodedep *,
809 	    struct workhead *);
810 static	void cancel_jfreefrag(struct jfreefrag *);
811 static	inline void setup_freedirect(struct freeblks *, struct inode *,
812 	    int, int);
813 static	inline void setup_freeext(struct freeblks *, struct inode *, int, int);
814 static	inline void setup_freeindir(struct freeblks *, struct inode *, int,
815 	    ufs_lbn_t, int);
816 static	inline struct freeblks *newfreeblks(struct mount *, struct inode *);
817 static	void freeblks_free(struct ufsmount *, struct freeblks *, int);
818 static	void indir_trunc(struct freework *, ufs2_daddr_t, ufs_lbn_t);
819 static	ufs2_daddr_t blkcount(struct fs *, ufs2_daddr_t, off_t);
820 static	int trunc_check_buf(struct buf *, int *, ufs_lbn_t, int, int);
821 static	void trunc_dependencies(struct inode *, struct freeblks *, ufs_lbn_t,
822 	    int, int);
823 static	void trunc_pages(struct inode *, off_t, ufs2_daddr_t, int);
824 static 	int cancel_pagedep(struct pagedep *, struct freeblks *, int);
825 static	int deallocate_dependencies(struct buf *, struct freeblks *, int);
826 static	void newblk_freefrag(struct newblk*);
827 static	void free_newblk(struct newblk *);
828 static	void cancel_allocdirect(struct allocdirectlst *,
829 	    struct allocdirect *, struct freeblks *);
830 static	int check_inode_unwritten(struct inodedep *);
831 static	int free_inodedep(struct inodedep *);
832 static	void freework_freeblock(struct freework *, uint64_t);
833 static	void freework_enqueue(struct freework *);
834 static	int handle_workitem_freeblocks(struct freeblks *, int);
835 static	int handle_complete_freeblocks(struct freeblks *, int);
836 static	void handle_workitem_indirblk(struct freework *);
837 static	void handle_written_freework(struct freework *);
838 static	void merge_inode_lists(struct allocdirectlst *,struct allocdirectlst *);
839 static	struct worklist *jnewblk_merge(struct worklist *, struct worklist *,
840 	    struct workhead *);
841 static	struct freefrag *setup_allocindir_phase2(struct buf *, struct inode *,
842 	    struct inodedep *, struct allocindir *, ufs_lbn_t);
843 static	struct allocindir *newallocindir(struct inode *, int, ufs2_daddr_t,
844 	    ufs2_daddr_t, ufs_lbn_t);
845 static	void handle_workitem_freefrag(struct freefrag *);
846 static	struct freefrag *newfreefrag(struct inode *, ufs2_daddr_t, long,
847 	    ufs_lbn_t, uint64_t);
848 static	void allocdirect_merge(struct allocdirectlst *,
849 	    struct allocdirect *, struct allocdirect *);
850 static	struct freefrag *allocindir_merge(struct allocindir *,
851 	    struct allocindir *);
852 static	int bmsafemap_find(struct bmsafemap_hashhead *, int,
853 	    struct bmsafemap **);
854 static	struct bmsafemap *bmsafemap_lookup(struct mount *, struct buf *,
855 	    int cg, struct bmsafemap *);
856 static	int newblk_find(struct newblk_hashhead *, ufs2_daddr_t, int,
857 	    struct newblk **);
858 static	int newblk_lookup(struct mount *, ufs2_daddr_t, int, struct newblk **);
859 static	int inodedep_find(struct inodedep_hashhead *, ino_t,
860 	    struct inodedep **);
861 static	int inodedep_lookup(struct mount *, ino_t, int, struct inodedep **);
862 static	int pagedep_lookup(struct mount *, struct buf *bp, ino_t, ufs_lbn_t,
863 	    int, struct pagedep **);
864 static	int pagedep_find(struct pagedep_hashhead *, ino_t, ufs_lbn_t,
865 	    struct pagedep **);
866 static	void pause_timer(void *);
867 static	int request_cleanup(struct mount *, int);
868 static	int softdep_request_cleanup_flush(struct mount *, struct ufsmount *);
869 static	void schedule_cleanup(struct mount *);
870 static void softdep_ast_cleanup_proc(struct thread *, int);
871 static struct ufsmount *softdep_bp_to_mp(struct buf *bp);
872 static	int process_worklist_item(struct mount *, int, int);
873 static	void process_removes(struct vnode *);
874 static	void process_truncates(struct vnode *);
875 static	void jwork_move(struct workhead *, struct workhead *);
876 static	void jwork_insert(struct workhead *, struct jsegdep *);
877 static	void add_to_worklist(struct worklist *, int);
878 static	void wake_worklist(struct worklist *);
879 static	void wait_worklist(struct worklist *, char *);
880 static	void remove_from_worklist(struct worklist *);
881 static	void softdep_flush(void *);
882 static	void softdep_flushjournal(struct mount *);
883 static	int softdep_speedup(struct ufsmount *);
884 static	void worklist_speedup(struct mount *);
885 static	int journal_mount(struct mount *, struct fs *, struct ucred *);
886 static	void journal_unmount(struct ufsmount *);
887 static	int journal_space(struct ufsmount *, int);
888 static	void journal_suspend(struct ufsmount *);
889 static	int journal_unsuspend(struct ufsmount *ump);
890 static	void add_to_journal(struct worklist *);
891 static	void remove_from_journal(struct worklist *);
892 static	bool softdep_excess_items(struct ufsmount *, int);
893 static	void softdep_process_journal(struct mount *, struct worklist *, int);
894 static	struct jremref *newjremref(struct dirrem *, struct inode *,
895 	    struct inode *ip, off_t, nlink_t);
896 static	struct jaddref *newjaddref(struct inode *, ino_t, off_t, int16_t,
897 	    uint16_t);
898 static	inline void newinoref(struct inoref *, ino_t, ino_t, off_t, nlink_t,
899 	    uint16_t);
900 static	inline struct jsegdep *inoref_jseg(struct inoref *);
901 static	struct jmvref *newjmvref(struct inode *, ino_t, off_t, off_t);
902 static	struct jfreeblk *newjfreeblk(struct freeblks *, ufs_lbn_t,
903 	    ufs2_daddr_t, int);
904 static	void adjust_newfreework(struct freeblks *, int);
905 static	struct jtrunc *newjtrunc(struct freeblks *, off_t, int);
906 static	void move_newblock_dep(struct jaddref *, struct inodedep *);
907 static	void cancel_jfreeblk(struct freeblks *, ufs2_daddr_t);
908 static	struct jfreefrag *newjfreefrag(struct freefrag *, struct inode *,
909 	    ufs2_daddr_t, long, ufs_lbn_t);
910 static	struct freework *newfreework(struct ufsmount *, struct freeblks *,
911 	    struct freework *, ufs_lbn_t, ufs2_daddr_t, int, int, int);
912 static	int jwait(struct worklist *, int);
913 static	struct inodedep *inodedep_lookup_ip(struct inode *);
914 static	int bmsafemap_backgroundwrite(struct bmsafemap *, struct buf *);
915 static	struct freefile *handle_bufwait(struct inodedep *, struct workhead *);
916 static	void handle_jwork(struct workhead *);
917 static	struct mkdir *setup_newdir(struct diradd *, ino_t, ino_t, struct buf *,
918 	    struct mkdir **);
919 static	struct jblocks *jblocks_create(void);
920 static	ufs2_daddr_t jblocks_alloc(struct jblocks *, int, int *);
921 static	void jblocks_free(struct jblocks *, struct mount *, int);
922 static	void jblocks_destroy(struct jblocks *);
923 static	void jblocks_add(struct jblocks *, ufs2_daddr_t, int);
924 
925 /*
926  * Exported softdep operations.
927  */
928 static	void softdep_disk_io_initiation(struct buf *);
929 static	void softdep_disk_write_complete(struct buf *);
930 static	void softdep_deallocate_dependencies(struct buf *);
931 static	int softdep_count_dependencies(struct buf *bp, int);
932 
933 /*
934  * Global lock over all of soft updates.
935  */
936 static struct mtx lk;
937 MTX_SYSINIT(softdep_lock, &lk, "global softdep", MTX_DEF);
938 
939 #define ACQUIRE_GBLLOCK(lk)	mtx_lock(lk)
940 #define FREE_GBLLOCK(lk)	mtx_unlock(lk)
941 #define GBLLOCK_OWNED(lk)	mtx_assert((lk), MA_OWNED)
942 
943 /*
944  * Per-filesystem soft-updates locking.
945  */
946 #define LOCK_PTR(ump)		(&(ump)->um_softdep->sd_fslock)
947 #define TRY_ACQUIRE_LOCK(ump)	rw_try_wlock(&(ump)->um_softdep->sd_fslock)
948 #define ACQUIRE_LOCK(ump)	rw_wlock(&(ump)->um_softdep->sd_fslock)
949 #define FREE_LOCK(ump)		rw_wunlock(&(ump)->um_softdep->sd_fslock)
950 #define LOCK_OWNED(ump)		rw_assert(&(ump)->um_softdep->sd_fslock, \
951 				    RA_WLOCKED)
952 
953 #define	BUF_AREC(bp)		lockallowrecurse(&(bp)->b_lock)
954 #define	BUF_NOREC(bp)		lockdisablerecurse(&(bp)->b_lock)
955 
956 /*
957  * Worklist queue management.
958  * These routines require that the lock be held.
959  */
960 #ifndef /* NOT */ INVARIANTS
961 #define WORKLIST_INSERT(head, item) do {	\
962 	(item)->wk_state |= ONWORKLIST;		\
963 	LIST_INSERT_HEAD(head, item, wk_list);	\
964 } while (0)
965 #define WORKLIST_REMOVE(item) do {		\
966 	(item)->wk_state &= ~ONWORKLIST;	\
967 	LIST_REMOVE(item, wk_list);		\
968 } while (0)
969 #define WORKLIST_INSERT_UNLOCKED	WORKLIST_INSERT
970 #define WORKLIST_REMOVE_UNLOCKED	WORKLIST_REMOVE
971 
972 #else /* INVARIANTS */
973 static	void worklist_insert(struct workhead *, struct worklist *, int,
974 	const char *, int);
975 static	void worklist_remove(struct worklist *, int, const char *, int);
976 
977 #define WORKLIST_INSERT(head, item) \
978 	worklist_insert(head, item, 1, __func__, __LINE__)
979 #define WORKLIST_INSERT_UNLOCKED(head, item)\
980 	worklist_insert(head, item, 0, __func__, __LINE__)
981 #define WORKLIST_REMOVE(item)\
982 	worklist_remove(item, 1, __func__, __LINE__)
983 #define WORKLIST_REMOVE_UNLOCKED(item)\
984 	worklist_remove(item, 0, __func__, __LINE__)
985 
986 static void
987 worklist_insert(struct workhead *head,
988 	struct worklist *item,
989 	int locked,
990 	const char *func,
991 	int line)
992 {
993 
994 	if (locked)
995 		LOCK_OWNED(VFSTOUFS(item->wk_mp));
996 	if (item->wk_state & ONWORKLIST)
997 		panic("worklist_insert: %p %s(0x%X) already on list, "
998 		    "added in function %s at line %d",
999 		    item, TYPENAME(item->wk_type), item->wk_state,
1000 		    item->wk_func, item->wk_line);
1001 	item->wk_state |= ONWORKLIST;
1002 	item->wk_func = func;
1003 	item->wk_line = line;
1004 	LIST_INSERT_HEAD(head, item, wk_list);
1005 }
1006 
1007 static void
1008 worklist_remove(struct worklist *item,
1009 	int locked,
1010 	const char *func,
1011 	int line)
1012 {
1013 
1014 	if (locked)
1015 		LOCK_OWNED(VFSTOUFS(item->wk_mp));
1016 	if ((item->wk_state & ONWORKLIST) == 0)
1017 		panic("worklist_remove: %p %s(0x%X) not on list, "
1018 		    "removed in function %s at line %d",
1019 		    item, TYPENAME(item->wk_type), item->wk_state,
1020 		    item->wk_func, item->wk_line);
1021 	item->wk_state &= ~ONWORKLIST;
1022 	item->wk_func = func;
1023 	item->wk_line = line;
1024 	LIST_REMOVE(item, wk_list);
1025 }
1026 #endif /* INVARIANTS */
1027 
1028 /*
1029  * Merge two jsegdeps keeping only the oldest one as newer references
1030  * can't be discarded until after older references.
1031  */
1032 static inline struct jsegdep *
1033 jsegdep_merge(struct jsegdep *one, struct jsegdep *two)
1034 {
1035 	struct jsegdep *swp;
1036 
1037 	if (two == NULL)
1038 		return (one);
1039 
1040 	if (one->jd_seg->js_seq > two->jd_seg->js_seq) {
1041 		swp = one;
1042 		one = two;
1043 		two = swp;
1044 	}
1045 	WORKLIST_REMOVE(&two->jd_list);
1046 	free_jsegdep(two);
1047 
1048 	return (one);
1049 }
1050 
1051 /*
1052  * If two freedeps are compatible free one to reduce list size.
1053  */
1054 static inline struct freedep *
1055 freedep_merge(struct freedep *one, struct freedep *two)
1056 {
1057 	if (two == NULL)
1058 		return (one);
1059 
1060 	if (one->fd_freework == two->fd_freework) {
1061 		WORKLIST_REMOVE(&two->fd_list);
1062 		free_freedep(two);
1063 	}
1064 	return (one);
1065 }
1066 
1067 /*
1068  * Move journal work from one list to another.  Duplicate freedeps and
1069  * jsegdeps are coalesced to keep the lists as small as possible.
1070  */
1071 static void
1072 jwork_move(struct workhead *dst, struct workhead *src)
1073 {
1074 	struct freedep *freedep;
1075 	struct jsegdep *jsegdep;
1076 	struct worklist *wkn;
1077 	struct worklist *wk;
1078 
1079 	KASSERT(dst != src,
1080 	    ("jwork_move: dst == src"));
1081 	freedep = NULL;
1082 	jsegdep = NULL;
1083 	LIST_FOREACH_SAFE(wk, dst, wk_list, wkn) {
1084 		if (wk->wk_type == D_JSEGDEP)
1085 			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1086 		else if (wk->wk_type == D_FREEDEP)
1087 			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1088 	}
1089 
1090 	while ((wk = LIST_FIRST(src)) != NULL) {
1091 		WORKLIST_REMOVE(wk);
1092 		WORKLIST_INSERT(dst, wk);
1093 		if (wk->wk_type == D_JSEGDEP) {
1094 			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1095 			continue;
1096 		}
1097 		if (wk->wk_type == D_FREEDEP)
1098 			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1099 	}
1100 }
1101 
1102 static void
1103 jwork_insert(struct workhead *dst, struct jsegdep *jsegdep)
1104 {
1105 	struct jsegdep *jsegdepn;
1106 	struct worklist *wk;
1107 
1108 	LIST_FOREACH(wk, dst, wk_list)
1109 		if (wk->wk_type == D_JSEGDEP)
1110 			break;
1111 	if (wk == NULL) {
1112 		WORKLIST_INSERT(dst, &jsegdep->jd_list);
1113 		return;
1114 	}
1115 	jsegdepn = WK_JSEGDEP(wk);
1116 	if (jsegdep->jd_seg->js_seq < jsegdepn->jd_seg->js_seq) {
1117 		WORKLIST_REMOVE(wk);
1118 		free_jsegdep(jsegdepn);
1119 		WORKLIST_INSERT(dst, &jsegdep->jd_list);
1120 	} else
1121 		free_jsegdep(jsegdep);
1122 }
1123 
1124 /*
1125  * Routines for tracking and managing workitems.
1126  */
1127 static	void workitem_free(struct worklist *, int);
1128 static	void workitem_alloc(struct worklist *, int, struct mount *);
1129 static	void workitem_reassign(struct worklist *, int);
1130 
1131 #define	WORKITEM_FREE(item, type) \
1132 	workitem_free((struct worklist *)(item), (type))
1133 #define	WORKITEM_REASSIGN(item, type) \
1134 	workitem_reassign((struct worklist *)(item), (type))
1135 
1136 static void
1137 workitem_free(struct worklist *item, int type)
1138 {
1139 	struct ufsmount *ump;
1140 
1141 #ifdef INVARIANTS
1142 	if (item->wk_state & ONWORKLIST)
1143 		panic("workitem_free: %s(0x%X) still on list, "
1144 		    "added in function %s at line %d",
1145 		    TYPENAME(item->wk_type), item->wk_state,
1146 		    item->wk_func, item->wk_line);
1147 	if (item->wk_type != type && type != D_NEWBLK)
1148 		panic("workitem_free: type mismatch %s != %s",
1149 		    TYPENAME(item->wk_type), TYPENAME(type));
1150 #endif
1151 	if (item->wk_state & IOWAITING)
1152 		wakeup(item);
1153 	ump = VFSTOUFS(item->wk_mp);
1154 	LOCK_OWNED(ump);
1155 	KASSERT(ump->softdep_deps > 0,
1156 	    ("workitem_free: %s: softdep_deps going negative",
1157 	    ump->um_fs->fs_fsmnt));
1158 	if (--ump->softdep_deps == 0 && ump->softdep_req)
1159 		wakeup(&ump->softdep_deps);
1160 	KASSERT(dep_current[item->wk_type] > 0,
1161 	    ("workitem_free: %s: dep_current[%s] going negative",
1162 	    ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1163 	KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1164 	    ("workitem_free: %s: softdep_curdeps[%s] going negative",
1165 	    ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1166 	atomic_subtract_long(&dep_current[item->wk_type], 1);
1167 	ump->softdep_curdeps[item->wk_type] -= 1;
1168 	LIST_REMOVE(item, wk_all);
1169 	free(item, DtoM(type));
1170 }
1171 
1172 static void
1173 workitem_alloc(struct worklist *item,
1174 	int type,
1175 	struct mount *mp)
1176 {
1177 	struct ufsmount *ump;
1178 
1179 	item->wk_type = type;
1180 	item->wk_mp = mp;
1181 	item->wk_state = 0;
1182 
1183 	ump = VFSTOUFS(mp);
1184 	ACQUIRE_GBLLOCK(&lk);
1185 	dep_current[type]++;
1186 	if (dep_current[type] > dep_highuse[type])
1187 		dep_highuse[type] = dep_current[type];
1188 	dep_total[type]++;
1189 	FREE_GBLLOCK(&lk);
1190 	ACQUIRE_LOCK(ump);
1191 	ump->softdep_curdeps[type] += 1;
1192 	ump->softdep_deps++;
1193 	ump->softdep_accdeps++;
1194 	LIST_INSERT_HEAD(&ump->softdep_alldeps[type], item, wk_all);
1195 	FREE_LOCK(ump);
1196 }
1197 
1198 static void
1199 workitem_reassign(struct worklist *item, int newtype)
1200 {
1201 	struct ufsmount *ump;
1202 
1203 	ump = VFSTOUFS(item->wk_mp);
1204 	LOCK_OWNED(ump);
1205 	KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1206 	    ("workitem_reassign: %s: softdep_curdeps[%s] going negative",
1207 	    VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1208 	ump->softdep_curdeps[item->wk_type] -= 1;
1209 	ump->softdep_curdeps[newtype] += 1;
1210 	KASSERT(dep_current[item->wk_type] > 0,
1211 	    ("workitem_reassign: %s: dep_current[%s] going negative",
1212 	    VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1213 	ACQUIRE_GBLLOCK(&lk);
1214 	dep_current[newtype]++;
1215 	dep_current[item->wk_type]--;
1216 	if (dep_current[newtype] > dep_highuse[newtype])
1217 		dep_highuse[newtype] = dep_current[newtype];
1218 	dep_total[newtype]++;
1219 	FREE_GBLLOCK(&lk);
1220 	item->wk_type = newtype;
1221 	LIST_REMOVE(item, wk_all);
1222 	LIST_INSERT_HEAD(&ump->softdep_alldeps[newtype], item, wk_all);
1223 }
1224 
1225 /*
1226  * Workitem queue management
1227  */
1228 static int max_softdeps;	/* maximum number of structs before slowdown */
1229 static int tickdelay = 2;	/* number of ticks to pause during slowdown */
1230 static int proc_waiting;	/* tracks whether we have a timeout posted */
1231 static int *stat_countp;	/* statistic to count in proc_waiting timeout */
1232 static struct callout softdep_callout;
1233 static int req_clear_inodedeps;	/* syncer process flush some inodedeps */
1234 static int req_clear_remove;	/* syncer process flush some freeblks */
1235 static int softdep_flushcache = 0; /* Should we do BIO_FLUSH? */
1236 
1237 /*
1238  * runtime statistics
1239  */
1240 static int stat_flush_threads;	/* number of softdep flushing threads */
1241 static int stat_worklist_push;	/* number of worklist cleanups */
1242 static int stat_delayed_inact;	/* number of delayed inactivation cleanups */
1243 static int stat_blk_limit_push;	/* number of times block limit neared */
1244 static int stat_ino_limit_push;	/* number of times inode limit neared */
1245 static int stat_blk_limit_hit;	/* number of times block slowdown imposed */
1246 static int stat_ino_limit_hit;	/* number of times inode slowdown imposed */
1247 static int stat_sync_limit_hit;	/* number of synchronous slowdowns imposed */
1248 static int stat_indir_blk_ptrs;	/* bufs redirtied as indir ptrs not written */
1249 static int stat_inode_bitmap;	/* bufs redirtied as inode bitmap not written */
1250 static int stat_direct_blk_ptrs;/* bufs redirtied as direct ptrs not written */
1251 static int stat_dir_entry;	/* bufs redirtied as dir entry cannot write */
1252 static int stat_jaddref;	/* bufs redirtied as ino bitmap can not write */
1253 static int stat_jnewblk;	/* bufs redirtied as blk bitmap can not write */
1254 static int stat_journal_min;	/* Times hit journal min threshold */
1255 static int stat_journal_low;	/* Times hit journal low threshold */
1256 static int stat_journal_wait;	/* Times blocked in jwait(). */
1257 static int stat_jwait_filepage;	/* Times blocked in jwait() for filepage. */
1258 static int stat_jwait_freeblks;	/* Times blocked in jwait() for freeblks. */
1259 static int stat_jwait_inode;	/* Times blocked in jwait() for inodes. */
1260 static int stat_jwait_newblk;	/* Times blocked in jwait() for newblks. */
1261 static int stat_cleanup_high_delay; /* Maximum cleanup delay (in ticks) */
1262 static int stat_cleanup_blkrequests; /* Number of block cleanup requests */
1263 static int stat_cleanup_inorequests; /* Number of inode cleanup requests */
1264 static int stat_cleanup_retries; /* Number of cleanups that needed to flush */
1265 static int stat_cleanup_failures; /* Number of cleanup requests that failed */
1266 static int stat_emptyjblocks; /* Number of potentially empty journal blocks */
1267 
1268 SYSCTL_INT(_debug_softdep, OID_AUTO, max_softdeps, CTLFLAG_RW,
1269     &max_softdeps, 0, "");
1270 SYSCTL_INT(_debug_softdep, OID_AUTO, tickdelay, CTLFLAG_RW,
1271     &tickdelay, 0, "");
1272 SYSCTL_INT(_debug_softdep, OID_AUTO, flush_threads, CTLFLAG_RD,
1273     &stat_flush_threads, 0, "");
1274 SYSCTL_INT(_debug_softdep, OID_AUTO, worklist_push,
1275     CTLFLAG_RW | CTLFLAG_STATS, &stat_worklist_push, 0,"");
1276 SYSCTL_INT(_debug_softdep, OID_AUTO, delayed_inactivations, CTLFLAG_RD,
1277     &stat_delayed_inact, 0, "");
1278 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_push,
1279     CTLFLAG_RW | CTLFLAG_STATS, &stat_blk_limit_push, 0,"");
1280 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_push,
1281     CTLFLAG_RW | CTLFLAG_STATS, &stat_ino_limit_push, 0,"");
1282 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_hit,
1283     CTLFLAG_RW | CTLFLAG_STATS, &stat_blk_limit_hit, 0, "");
1284 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_hit,
1285     CTLFLAG_RW | CTLFLAG_STATS, &stat_ino_limit_hit, 0, "");
1286 SYSCTL_INT(_debug_softdep, OID_AUTO, sync_limit_hit,
1287     CTLFLAG_RW | CTLFLAG_STATS, &stat_sync_limit_hit, 0, "");
1288 SYSCTL_INT(_debug_softdep, OID_AUTO, indir_blk_ptrs,
1289     CTLFLAG_RW | CTLFLAG_STATS, &stat_indir_blk_ptrs, 0, "");
1290 SYSCTL_INT(_debug_softdep, OID_AUTO, inode_bitmap,
1291     CTLFLAG_RW | CTLFLAG_STATS, &stat_inode_bitmap, 0, "");
1292 SYSCTL_INT(_debug_softdep, OID_AUTO, direct_blk_ptrs,
1293     CTLFLAG_RW | CTLFLAG_STATS, &stat_direct_blk_ptrs, 0, "");
1294 SYSCTL_INT(_debug_softdep, OID_AUTO, dir_entry,
1295     CTLFLAG_RW | CTLFLAG_STATS, &stat_dir_entry, 0, "");
1296 SYSCTL_INT(_debug_softdep, OID_AUTO, jaddref_rollback,
1297     CTLFLAG_RW | CTLFLAG_STATS, &stat_jaddref, 0, "");
1298 SYSCTL_INT(_debug_softdep, OID_AUTO, jnewblk_rollback,
1299     CTLFLAG_RW | CTLFLAG_STATS, &stat_jnewblk, 0, "");
1300 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_low,
1301     CTLFLAG_RW | CTLFLAG_STATS, &stat_journal_low, 0, "");
1302 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_min,
1303     CTLFLAG_RW | CTLFLAG_STATS, &stat_journal_min, 0, "");
1304 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_wait,
1305     CTLFLAG_RW | CTLFLAG_STATS, &stat_journal_wait, 0, "");
1306 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_filepage,
1307     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_filepage, 0, "");
1308 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_freeblks,
1309     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_freeblks, 0, "");
1310 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_inode,
1311     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_inode, 0, "");
1312 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_newblk,
1313     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_newblk, 0, "");
1314 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_blkrequests,
1315     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_blkrequests, 0, "");
1316 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_inorequests,
1317     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_inorequests, 0, "");
1318 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_high_delay,
1319     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_high_delay, 0, "");
1320 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_retries,
1321     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_retries, 0, "");
1322 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_failures,
1323     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_failures, 0, "");
1324 
1325 SYSCTL_INT(_debug_softdep, OID_AUTO, flushcache, CTLFLAG_RW,
1326     &softdep_flushcache, 0, "");
1327 SYSCTL_INT(_debug_softdep, OID_AUTO, emptyjblocks, CTLFLAG_RD,
1328     &stat_emptyjblocks, 0, "");
1329 
1330 SYSCTL_DECL(_vfs_ffs);
1331 
1332 /* Whether to recompute the summary at mount time */
1333 static int compute_summary_at_mount = 0;
1334 SYSCTL_INT(_vfs_ffs, OID_AUTO, compute_summary_at_mount, CTLFLAG_RW,
1335 	   &compute_summary_at_mount, 0, "Recompute summary at mount");
1336 static int print_threads = 0;
1337 SYSCTL_INT(_debug_softdep, OID_AUTO, print_threads, CTLFLAG_RW,
1338     &print_threads, 0, "Notify flusher thread start/stop");
1339 
1340 /* List of all filesystems mounted with soft updates */
1341 static TAILQ_HEAD(, mount_softdeps) softdepmounts;
1342 
1343 static void
1344 get_parent_vp_unlock_bp(struct mount *mp,
1345 	struct buf *bp,
1346 	struct diraddhd *diraddhdp,
1347 	struct diraddhd *unfinishedp)
1348 {
1349 	struct diradd *dap;
1350 
1351 	/*
1352 	 * Requeue unfinished dependencies before
1353 	 * unlocking buffer, which could make
1354 	 * diraddhdp invalid.
1355 	 */
1356 	ACQUIRE_LOCK(VFSTOUFS(mp));
1357 	while ((dap = LIST_FIRST(unfinishedp)) != NULL) {
1358 		LIST_REMOVE(dap, da_pdlist);
1359 		LIST_INSERT_HEAD(diraddhdp, dap, da_pdlist);
1360 	}
1361 	FREE_LOCK(VFSTOUFS(mp));
1362 
1363 	bp->b_vflags &= ~BV_SCANNED;
1364 	BUF_NOREC(bp);
1365 	BUF_UNLOCK(bp);
1366 }
1367 
1368 /*
1369  * This function fetches inode inum on mount point mp.  We already
1370  * hold a locked vnode vp, and might have a locked buffer bp belonging
1371  * to vp.
1372 
1373  * We must not block on acquiring the new inode lock as we will get
1374  * into a lock-order reversal with the buffer lock and possibly get a
1375  * deadlock.  Thus if we cannot instantiate the requested vnode
1376  * without sleeping on its lock, we must unlock the vnode and the
1377  * buffer before doing a blocking on the vnode lock.  We return
1378  * ERELOOKUP if we have had to unlock either the vnode or the buffer so
1379  * that the caller can reassess its state.
1380  *
1381  * Top-level VFS code (for syscalls and other consumers, e.g. callers
1382  * of VOP_FSYNC() in syncer) check for ERELOOKUP and restart at safe
1383  * point.
1384  *
1385  * Since callers expect to operate on fully constructed vnode, we also
1386  * recheck v_data after relock, and return ENOENT if NULL.
1387  *
1388  * If unlocking bp, we must unroll dequeueing its unfinished
1389  * dependencies, and clear scan flag, before unlocking.  If unlocking
1390  * vp while it is under deactivation, we re-queue deactivation.
1391  */
1392 static int
1393 get_parent_vp(struct vnode *vp,
1394 	struct mount *mp,
1395 	ino_t inum,
1396 	struct buf *bp,
1397 	struct diraddhd *diraddhdp,
1398 	struct diraddhd *unfinishedp,
1399 	struct vnode **rvp)
1400 {
1401 	struct vnode *pvp;
1402 	int error;
1403 	bool bplocked;
1404 
1405 	ASSERT_VOP_ELOCKED(vp, "child vnode must be locked");
1406 	for (bplocked = true, pvp = NULL;;) {
1407 		error = ffs_vgetf(mp, inum, LK_EXCLUSIVE | LK_NOWAIT, &pvp,
1408 		    FFSV_FORCEINSMQ | FFSV_FORCEINODEDEP);
1409 		if (error == 0) {
1410 			/*
1411 			 * Since we could have unlocked vp, the inode
1412 			 * number could no longer indicate a
1413 			 * constructed node.  In this case, we must
1414 			 * restart the syscall.
1415 			 */
1416 			if (VTOI(pvp)->i_mode == 0 || !bplocked) {
1417 				if (bp != NULL && bplocked)
1418 					get_parent_vp_unlock_bp(mp, bp,
1419 					    diraddhdp, unfinishedp);
1420 				if (VTOI(pvp)->i_mode == 0)
1421 					vgone(pvp);
1422 				error = ERELOOKUP;
1423 				goto out2;
1424 			}
1425 			goto out1;
1426 		}
1427 		if (bp != NULL && bplocked) {
1428 			get_parent_vp_unlock_bp(mp, bp, diraddhdp, unfinishedp);
1429 			bplocked = false;
1430 		}
1431 
1432 		/*
1433 		 * Do not drop vnode lock while inactivating during
1434 		 * vunref.  This would result in leaks of the VI flags
1435 		 * and reclaiming of non-truncated vnode.  Instead,
1436 		 * re-schedule inactivation hoping that we would be
1437 		 * able to sync inode later.
1438 		 */
1439 		if ((vp->v_iflag & VI_DOINGINACT) != 0 &&
1440 		    (vp->v_vflag & VV_UNREF) != 0) {
1441 			VI_LOCK(vp);
1442 			vp->v_iflag |= VI_OWEINACT;
1443 			VI_UNLOCK(vp);
1444 			return (ERELOOKUP);
1445 		}
1446 
1447 		VOP_UNLOCK(vp);
1448 		error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &pvp,
1449 		    FFSV_FORCEINSMQ | FFSV_FORCEINODEDEP);
1450 		if (error != 0) {
1451 			MPASS(error != ERELOOKUP);
1452 			vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1453 			break;
1454 		}
1455 		if (VTOI(pvp)->i_mode == 0) {
1456 			vgone(pvp);
1457 			vput(pvp);
1458 			pvp = NULL;
1459 			vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1460 			error = ERELOOKUP;
1461 			break;
1462 		}
1463 		error = vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT);
1464 		if (error == 0)
1465 			break;
1466 		vput(pvp);
1467 		pvp = NULL;
1468 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1469 		if (vp->v_data == NULL) {
1470 			error = ENOENT;
1471 			break;
1472 		}
1473 	}
1474 	if (bp != NULL) {
1475 		MPASS(!bplocked);
1476 		error = ERELOOKUP;
1477 	}
1478 out2:
1479 	if (error != 0 && pvp != NULL) {
1480 		vput(pvp);
1481 		pvp = NULL;
1482 	}
1483 out1:
1484 	*rvp = pvp;
1485 	ASSERT_VOP_ELOCKED(vp, "child vnode must be locked on return");
1486 	return (error);
1487 }
1488 
1489 /*
1490  * This function cleans the worklist for a filesystem.
1491  * Each filesystem running with soft dependencies gets its own
1492  * thread to run in this function. The thread is started up in
1493  * softdep_mount and shutdown in softdep_unmount. They show up
1494  * as part of the kernel "bufdaemon" process whose process
1495  * entry is available in bufdaemonproc.
1496  */
1497 static int searchfailed;
1498 extern struct proc *bufdaemonproc;
1499 static void
1500 softdep_flush(void *addr)
1501 {
1502 	struct mount *mp;
1503 	struct thread *td;
1504 	struct ufsmount *ump;
1505 	int cleanups;
1506 
1507 	td = curthread;
1508 	td->td_pflags |= TDP_NORUNNINGBUF;
1509 	mp = (struct mount *)addr;
1510 	ump = VFSTOUFS(mp);
1511 	atomic_add_int(&stat_flush_threads, 1);
1512 	ACQUIRE_LOCK(ump);
1513 	ump->softdep_flags &= ~FLUSH_STARTING;
1514 	wakeup(&ump->softdep_flushtd);
1515 	FREE_LOCK(ump);
1516 	if (print_threads) {
1517 		if (stat_flush_threads == 1)
1518 			printf("Running %s at pid %d\n", bufdaemonproc->p_comm,
1519 			    bufdaemonproc->p_pid);
1520 		printf("Start thread %s\n", td->td_name);
1521 	}
1522 	for (;;) {
1523 		while (softdep_process_worklist(mp, 0) > 0 ||
1524 		    (MOUNTEDSUJ(mp) &&
1525 		    VFSTOUFS(mp)->softdep_jblocks->jb_suspended))
1526 			kthread_suspend_check();
1527 		ACQUIRE_LOCK(ump);
1528 		if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1529 			msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM,
1530 			    "sdflush", hz / 2);
1531 		ump->softdep_flags &= ~FLUSH_CLEANUP;
1532 		/*
1533 		 * Check to see if we are done and need to exit.
1534 		 */
1535 		if ((ump->softdep_flags & FLUSH_EXIT) == 0) {
1536 			FREE_LOCK(ump);
1537 			continue;
1538 		}
1539 		ump->softdep_flags &= ~FLUSH_EXIT;
1540 		cleanups = ump->um_softdep->sd_cleanups;
1541 		FREE_LOCK(ump);
1542 		wakeup(&ump->softdep_flags);
1543 		if (print_threads) {
1544 			printf("Stop thread %s: searchfailed %d, "
1545 			    "did cleanups %d\n",
1546 			    td->td_name, searchfailed, cleanups);
1547 		}
1548 		atomic_subtract_int(&stat_flush_threads, 1);
1549 		kthread_exit();
1550 		panic("kthread_exit failed\n");
1551 	}
1552 }
1553 
1554 static void
1555 worklist_speedup(struct mount *mp)
1556 {
1557 	struct ufsmount *ump;
1558 
1559 	ump = VFSTOUFS(mp);
1560 	LOCK_OWNED(ump);
1561 	if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1562 		ump->softdep_flags |= FLUSH_CLEANUP;
1563 	wakeup(&ump->softdep_flushtd);
1564 }
1565 
1566 static void
1567 softdep_send_speedup(struct ufsmount *ump,
1568 	off_t shortage,
1569 	uint64_t flags)
1570 {
1571 	struct buf *bp;
1572 
1573 	if ((ump->um_flags & UM_CANSPEEDUP) == 0)
1574 		return;
1575 
1576 	bp = malloc(sizeof(*bp), M_TRIM, M_WAITOK | M_ZERO);
1577 	bp->b_iocmd = BIO_SPEEDUP;
1578 	bp->b_ioflags = flags;
1579 	bp->b_bcount = omin(shortage, LONG_MAX);
1580 	g_vfs_strategy(ump->um_bo, bp);
1581 	bufwait(bp);
1582 	free(bp, M_TRIM);
1583 }
1584 
1585 static int
1586 softdep_speedup(struct ufsmount *ump)
1587 {
1588 	struct ufsmount *altump;
1589 	struct mount_softdeps *sdp;
1590 
1591 	LOCK_OWNED(ump);
1592 	worklist_speedup(ump->um_mountp);
1593 	bd_speedup();
1594 	/*
1595 	 * If we have global shortages, then we need other
1596 	 * filesystems to help with the cleanup. Here we wakeup a
1597 	 * flusher thread for a filesystem that is over its fair
1598 	 * share of resources.
1599 	 */
1600 	if (req_clear_inodedeps || req_clear_remove) {
1601 		ACQUIRE_GBLLOCK(&lk);
1602 		TAILQ_FOREACH(sdp, &softdepmounts, sd_next) {
1603 			if ((altump = sdp->sd_ump) == ump)
1604 				continue;
1605 			if (((req_clear_inodedeps &&
1606 			    altump->softdep_curdeps[D_INODEDEP] >
1607 			    max_softdeps / stat_flush_threads) ||
1608 			    (req_clear_remove &&
1609 			    altump->softdep_curdeps[D_DIRREM] >
1610 			    (max_softdeps / 2) / stat_flush_threads)) &&
1611 			    TRY_ACQUIRE_LOCK(altump))
1612 				break;
1613 		}
1614 		if (sdp == NULL) {
1615 			searchfailed++;
1616 			FREE_GBLLOCK(&lk);
1617 		} else {
1618 			/*
1619 			 * Move to the end of the list so we pick a
1620 			 * different one on out next try.
1621 			 */
1622 			TAILQ_REMOVE(&softdepmounts, sdp, sd_next);
1623 			TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
1624 			FREE_GBLLOCK(&lk);
1625 			if ((altump->softdep_flags &
1626 			    (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1627 				altump->softdep_flags |= FLUSH_CLEANUP;
1628 			altump->um_softdep->sd_cleanups++;
1629 			wakeup(&altump->softdep_flushtd);
1630 			FREE_LOCK(altump);
1631 		}
1632 	}
1633 	return (speedup_syncer());
1634 }
1635 
1636 /*
1637  * Add an item to the end of the work queue.
1638  * This routine requires that the lock be held.
1639  * This is the only routine that adds items to the list.
1640  * The following routine is the only one that removes items
1641  * and does so in order from first to last.
1642  */
1643 
1644 #define	WK_HEAD		0x0001	/* Add to HEAD. */
1645 #define	WK_NODELAY	0x0002	/* Process immediately. */
1646 
1647 static void
1648 add_to_worklist(struct worklist *wk, int flags)
1649 {
1650 	struct ufsmount *ump;
1651 
1652 	ump = VFSTOUFS(wk->wk_mp);
1653 	LOCK_OWNED(ump);
1654 	if (wk->wk_state & ONWORKLIST)
1655 		panic("add_to_worklist: %s(0x%X) already on list",
1656 		    TYPENAME(wk->wk_type), wk->wk_state);
1657 	wk->wk_state |= ONWORKLIST;
1658 	if (ump->softdep_on_worklist == 0) {
1659 		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1660 		ump->softdep_worklist_tail = wk;
1661 	} else if (flags & WK_HEAD) {
1662 		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1663 	} else {
1664 		LIST_INSERT_AFTER(ump->softdep_worklist_tail, wk, wk_list);
1665 		ump->softdep_worklist_tail = wk;
1666 	}
1667 	ump->softdep_on_worklist += 1;
1668 	if (flags & WK_NODELAY)
1669 		worklist_speedup(wk->wk_mp);
1670 }
1671 
1672 /*
1673  * Remove the item to be processed. If we are removing the last
1674  * item on the list, we need to recalculate the tail pointer.
1675  */
1676 static void
1677 remove_from_worklist(struct worklist *wk)
1678 {
1679 	struct ufsmount *ump;
1680 
1681 	ump = VFSTOUFS(wk->wk_mp);
1682 	if (ump->softdep_worklist_tail == wk)
1683 		ump->softdep_worklist_tail =
1684 		    (struct worklist *)wk->wk_list.le_prev;
1685 	WORKLIST_REMOVE(wk);
1686 	ump->softdep_on_worklist -= 1;
1687 }
1688 
1689 static void
1690 wake_worklist(struct worklist *wk)
1691 {
1692 	if (wk->wk_state & IOWAITING) {
1693 		wk->wk_state &= ~IOWAITING;
1694 		wakeup(wk);
1695 	}
1696 }
1697 
1698 static void
1699 wait_worklist(struct worklist *wk, char *wmesg)
1700 {
1701 	struct ufsmount *ump;
1702 
1703 	ump = VFSTOUFS(wk->wk_mp);
1704 	wk->wk_state |= IOWAITING;
1705 	msleep(wk, LOCK_PTR(ump), PVM, wmesg, 0);
1706 }
1707 
1708 /*
1709  * Process that runs once per second to handle items in the background queue.
1710  *
1711  * Note that we ensure that everything is done in the order in which they
1712  * appear in the queue. The code below depends on this property to ensure
1713  * that blocks of a file are freed before the inode itself is freed. This
1714  * ordering ensures that no new <vfsid, inum, lbn> triples will be generated
1715  * until all the old ones have been purged from the dependency lists.
1716  */
1717 static int
1718 softdep_process_worklist(struct mount *mp, int full)
1719 {
1720 	int cnt, matchcnt;
1721 	struct ufsmount *ump;
1722 	long starttime;
1723 
1724 	KASSERT(mp != NULL, ("softdep_process_worklist: NULL mp"));
1725 	ump = VFSTOUFS(mp);
1726 	if (ump->um_softdep == NULL)
1727 		return (0);
1728 	matchcnt = 0;
1729 	ACQUIRE_LOCK(ump);
1730 	starttime = time_second;
1731 	softdep_process_journal(mp, NULL, full ? MNT_WAIT : 0);
1732 	check_clear_deps(mp);
1733 	while (ump->softdep_on_worklist > 0) {
1734 		if ((cnt = process_worklist_item(mp, 10, LK_NOWAIT)) == 0)
1735 			break;
1736 		else
1737 			matchcnt += cnt;
1738 		check_clear_deps(mp);
1739 		/*
1740 		 * We do not generally want to stop for buffer space, but if
1741 		 * we are really being a buffer hog, we will stop and wait.
1742 		 */
1743 		if (should_yield()) {
1744 			FREE_LOCK(ump);
1745 			kern_yield(PRI_USER);
1746 			bwillwrite();
1747 			ACQUIRE_LOCK(ump);
1748 		}
1749 		/*
1750 		 * Never allow processing to run for more than one
1751 		 * second. This gives the syncer thread the opportunity
1752 		 * to pause if appropriate.
1753 		 */
1754 		if (!full && starttime != time_second)
1755 			break;
1756 	}
1757 	if (full == 0)
1758 		journal_unsuspend(ump);
1759 	FREE_LOCK(ump);
1760 	return (matchcnt);
1761 }
1762 
1763 /*
1764  * Process all removes associated with a vnode if we are running out of
1765  * journal space.  Any other process which attempts to flush these will
1766  * be unable as we have the vnodes locked.
1767  */
1768 static void
1769 process_removes(struct vnode *vp)
1770 {
1771 	struct inodedep *inodedep;
1772 	struct dirrem *dirrem;
1773 	struct ufsmount *ump;
1774 	struct mount *mp;
1775 	ino_t inum;
1776 
1777 	mp = vp->v_mount;
1778 	ump = VFSTOUFS(mp);
1779 	LOCK_OWNED(ump);
1780 	inum = VTOI(vp)->i_number;
1781 	for (;;) {
1782 top:
1783 		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1784 			return;
1785 		LIST_FOREACH(dirrem, &inodedep->id_dirremhd, dm_inonext) {
1786 			/*
1787 			 * If another thread is trying to lock this vnode
1788 			 * it will fail but we must wait for it to do so
1789 			 * before we can proceed.
1790 			 */
1791 			if (dirrem->dm_state & INPROGRESS) {
1792 				wait_worklist(&dirrem->dm_list, "pwrwait");
1793 				goto top;
1794 			}
1795 			if ((dirrem->dm_state & (COMPLETE | ONWORKLIST)) ==
1796 			    (COMPLETE | ONWORKLIST))
1797 				break;
1798 		}
1799 		if (dirrem == NULL)
1800 			return;
1801 		remove_from_worklist(&dirrem->dm_list);
1802 		FREE_LOCK(ump);
1803 		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1804 			panic("process_removes: suspended filesystem");
1805 		handle_workitem_remove(dirrem, 0);
1806 		vn_finished_secondary_write(mp);
1807 		ACQUIRE_LOCK(ump);
1808 	}
1809 }
1810 
1811 /*
1812  * Process all truncations associated with a vnode if we are running out
1813  * of journal space.  This is called when the vnode lock is already held
1814  * and no other process can clear the truncation.  This function returns
1815  * a value greater than zero if it did any work.
1816  */
1817 static void
1818 process_truncates(struct vnode *vp)
1819 {
1820 	struct inodedep *inodedep;
1821 	struct freeblks *freeblks;
1822 	struct ufsmount *ump;
1823 	struct mount *mp;
1824 	ino_t inum;
1825 	int cgwait;
1826 
1827 	mp = vp->v_mount;
1828 	ump = VFSTOUFS(mp);
1829 	LOCK_OWNED(ump);
1830 	inum = VTOI(vp)->i_number;
1831 	for (;;) {
1832 		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1833 			return;
1834 		cgwait = 0;
1835 		TAILQ_FOREACH(freeblks, &inodedep->id_freeblklst, fb_next) {
1836 			/* Journal entries not yet written.  */
1837 			if (!LIST_EMPTY(&freeblks->fb_jblkdephd)) {
1838 				jwait(&LIST_FIRST(
1839 				    &freeblks->fb_jblkdephd)->jb_list,
1840 				    MNT_WAIT);
1841 				break;
1842 			}
1843 			/* Another thread is executing this item. */
1844 			if (freeblks->fb_state & INPROGRESS) {
1845 				wait_worklist(&freeblks->fb_list, "ptrwait");
1846 				break;
1847 			}
1848 			/* Freeblks is waiting on a inode write. */
1849 			if ((freeblks->fb_state & COMPLETE) == 0) {
1850 				FREE_LOCK(ump);
1851 				ffs_update(vp, 1);
1852 				ACQUIRE_LOCK(ump);
1853 				break;
1854 			}
1855 			if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST)) ==
1856 			    (ALLCOMPLETE | ONWORKLIST)) {
1857 				remove_from_worklist(&freeblks->fb_list);
1858 				freeblks->fb_state |= INPROGRESS;
1859 				FREE_LOCK(ump);
1860 				if (vn_start_secondary_write(NULL, &mp,
1861 				    V_NOWAIT))
1862 					panic("process_truncates: "
1863 					    "suspended filesystem");
1864 				handle_workitem_freeblocks(freeblks, 0);
1865 				vn_finished_secondary_write(mp);
1866 				ACQUIRE_LOCK(ump);
1867 				break;
1868 			}
1869 			if (freeblks->fb_cgwait)
1870 				cgwait++;
1871 		}
1872 		if (cgwait) {
1873 			FREE_LOCK(ump);
1874 			sync_cgs(mp, MNT_WAIT);
1875 			ffs_sync_snap(mp, MNT_WAIT);
1876 			ACQUIRE_LOCK(ump);
1877 			continue;
1878 		}
1879 		if (freeblks == NULL)
1880 			break;
1881 	}
1882 	return;
1883 }
1884 
1885 /*
1886  * Process one item on the worklist.
1887  */
1888 static int
1889 process_worklist_item(struct mount *mp,
1890 	int target,
1891 	int flags)
1892 {
1893 	struct worklist sentinel;
1894 	struct worklist *wk;
1895 	struct ufsmount *ump;
1896 	int matchcnt;
1897 	int error;
1898 
1899 	KASSERT(mp != NULL, ("process_worklist_item: NULL mp"));
1900 	/*
1901 	 * If we are being called because of a process doing a
1902 	 * copy-on-write, then it is not safe to write as we may
1903 	 * recurse into the copy-on-write routine.
1904 	 */
1905 	if (curthread->td_pflags & TDP_COWINPROGRESS)
1906 		return (-1);
1907 	ump = VFSTOUFS(mp);
1908 	LOCK_OWNED(ump);
1909 	matchcnt = 0;
1910 	sentinel.wk_mp = NULL;
1911 	sentinel.wk_type = D_SENTINEL;
1912 	LIST_INSERT_HEAD(&ump->softdep_workitem_pending, &sentinel, wk_list);
1913 	for (wk = LIST_NEXT(&sentinel, wk_list); wk != NULL;
1914 	    wk = LIST_NEXT(&sentinel, wk_list)) {
1915 		if (wk->wk_type == D_SENTINEL) {
1916 			LIST_REMOVE(&sentinel, wk_list);
1917 			LIST_INSERT_AFTER(wk, &sentinel, wk_list);
1918 			continue;
1919 		}
1920 		if (wk->wk_state & INPROGRESS)
1921 			panic("process_worklist_item: %p already in progress.",
1922 			    wk);
1923 		wk->wk_state |= INPROGRESS;
1924 		remove_from_worklist(wk);
1925 		FREE_LOCK(ump);
1926 		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1927 			panic("process_worklist_item: suspended filesystem");
1928 		switch (wk->wk_type) {
1929 		case D_DIRREM:
1930 			/* removal of a directory entry */
1931 			error = handle_workitem_remove(WK_DIRREM(wk), flags);
1932 			break;
1933 
1934 		case D_FREEBLKS:
1935 			/* releasing blocks and/or fragments from a file */
1936 			error = handle_workitem_freeblocks(WK_FREEBLKS(wk),
1937 			    flags);
1938 			break;
1939 
1940 		case D_FREEFRAG:
1941 			/* releasing a fragment when replaced as a file grows */
1942 			handle_workitem_freefrag(WK_FREEFRAG(wk));
1943 			error = 0;
1944 			break;
1945 
1946 		case D_FREEFILE:
1947 			/* releasing an inode when its link count drops to 0 */
1948 			handle_workitem_freefile(WK_FREEFILE(wk));
1949 			error = 0;
1950 			break;
1951 
1952 		default:
1953 			panic("%s_process_worklist: Unknown type %s",
1954 			    "softdep", TYPENAME(wk->wk_type));
1955 			/* NOTREACHED */
1956 		}
1957 		vn_finished_secondary_write(mp);
1958 		ACQUIRE_LOCK(ump);
1959 		if (error == 0) {
1960 			if (++matchcnt == target)
1961 				break;
1962 			continue;
1963 		}
1964 		/*
1965 		 * We have to retry the worklist item later.  Wake up any
1966 		 * waiters who may be able to complete it immediately and
1967 		 * add the item back to the head so we don't try to execute
1968 		 * it again.
1969 		 */
1970 		wk->wk_state &= ~INPROGRESS;
1971 		wake_worklist(wk);
1972 		add_to_worklist(wk, WK_HEAD);
1973 	}
1974 	/* Sentinal could've become the tail from remove_from_worklist. */
1975 	if (ump->softdep_worklist_tail == &sentinel)
1976 		ump->softdep_worklist_tail =
1977 		    (struct worklist *)sentinel.wk_list.le_prev;
1978 	LIST_REMOVE(&sentinel, wk_list);
1979 	return (matchcnt);
1980 }
1981 
1982 /*
1983  * Move dependencies from one buffer to another.
1984  */
1985 int
1986 softdep_move_dependencies(struct buf *oldbp, struct buf *newbp)
1987 {
1988 	struct worklist *wk, *wktail;
1989 	struct ufsmount *ump;
1990 	int dirty;
1991 
1992 	if ((wk = LIST_FIRST(&oldbp->b_dep)) == NULL)
1993 		return (0);
1994 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
1995 	    ("softdep_move_dependencies called on non-softdep filesystem"));
1996 	dirty = 0;
1997 	wktail = NULL;
1998 	ump = VFSTOUFS(wk->wk_mp);
1999 	ACQUIRE_LOCK(ump);
2000 	while ((wk = LIST_FIRST(&oldbp->b_dep)) != NULL) {
2001 		LIST_REMOVE(wk, wk_list);
2002 		if (wk->wk_type == D_BMSAFEMAP &&
2003 		    bmsafemap_backgroundwrite(WK_BMSAFEMAP(wk), newbp))
2004 			dirty = 1;
2005 		if (wktail == NULL)
2006 			LIST_INSERT_HEAD(&newbp->b_dep, wk, wk_list);
2007 		else
2008 			LIST_INSERT_AFTER(wktail, wk, wk_list);
2009 		wktail = wk;
2010 	}
2011 	FREE_LOCK(ump);
2012 
2013 	return (dirty);
2014 }
2015 
2016 /*
2017  * Purge the work list of all items associated with a particular mount point.
2018  */
2019 int
2020 softdep_flushworklist(struct mount *oldmnt,
2021 	int *countp,
2022 	struct thread *td)
2023 {
2024 	struct vnode *devvp;
2025 	struct ufsmount *ump;
2026 	int count, error;
2027 
2028 	/*
2029 	 * Alternately flush the block device associated with the mount
2030 	 * point and process any dependencies that the flushing
2031 	 * creates. We continue until no more worklist dependencies
2032 	 * are found.
2033 	 */
2034 	*countp = 0;
2035 	error = 0;
2036 	ump = VFSTOUFS(oldmnt);
2037 	devvp = ump->um_devvp;
2038 	while ((count = softdep_process_worklist(oldmnt, 1)) > 0) {
2039 		*countp += count;
2040 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
2041 		error = VOP_FSYNC(devvp, MNT_WAIT, td);
2042 		VOP_UNLOCK(devvp);
2043 		if (error != 0)
2044 			break;
2045 	}
2046 	return (error);
2047 }
2048 
2049 #define	SU_WAITIDLE_RETRIES	20
2050 static int
2051 softdep_waitidle(struct mount *mp, int flags __unused)
2052 {
2053 	struct ufsmount *ump;
2054 	struct vnode *devvp;
2055 	struct thread *td;
2056 	int error, i;
2057 
2058 	ump = VFSTOUFS(mp);
2059 	KASSERT(ump->um_softdep != NULL,
2060 	    ("softdep_waitidle called on non-softdep filesystem"));
2061 	devvp = ump->um_devvp;
2062 	td = curthread;
2063 	error = 0;
2064 	ACQUIRE_LOCK(ump);
2065 	for (i = 0; i < SU_WAITIDLE_RETRIES && ump->softdep_deps != 0; i++) {
2066 		ump->softdep_req = 1;
2067 		KASSERT((flags & FORCECLOSE) == 0 ||
2068 		    ump->softdep_on_worklist == 0,
2069 		    ("softdep_waitidle: work added after flush"));
2070 		msleep(&ump->softdep_deps, LOCK_PTR(ump), PVM | PDROP,
2071 		    "softdeps", 10 * hz);
2072 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
2073 		error = VOP_FSYNC(devvp, MNT_WAIT, td);
2074 		VOP_UNLOCK(devvp);
2075 		ACQUIRE_LOCK(ump);
2076 		if (error != 0)
2077 			break;
2078 	}
2079 	ump->softdep_req = 0;
2080 	if (i == SU_WAITIDLE_RETRIES && error == 0 && ump->softdep_deps != 0) {
2081 		error = EBUSY;
2082 		printf("softdep_waitidle: Failed to flush worklist for %p\n",
2083 		    mp);
2084 	}
2085 	FREE_LOCK(ump);
2086 	return (error);
2087 }
2088 
2089 /*
2090  * Flush all vnodes and worklist items associated with a specified mount point.
2091  */
2092 int
2093 softdep_flushfiles(struct mount *oldmnt,
2094 	int flags,
2095 	struct thread *td)
2096 {
2097 	struct ufsmount *ump __unused;
2098 #ifdef QUOTA
2099 	int i;
2100 #endif
2101 	int error, early, depcount, loopcnt, retry_flush_count, retry;
2102 	int morework;
2103 
2104 	ump = VFSTOUFS(oldmnt);
2105 	KASSERT(ump->um_softdep != NULL,
2106 	    ("softdep_flushfiles called on non-softdep filesystem"));
2107 	loopcnt = 10;
2108 	retry_flush_count = 3;
2109 retry_flush:
2110 	error = 0;
2111 
2112 	/*
2113 	 * Alternately flush the vnodes associated with the mount
2114 	 * point and process any dependencies that the flushing
2115 	 * creates. In theory, this loop can happen at most twice,
2116 	 * but we give it a few extra just to be sure.
2117 	 */
2118 	for (; loopcnt > 0; loopcnt--) {
2119 		/*
2120 		 * Do another flush in case any vnodes were brought in
2121 		 * as part of the cleanup operations.
2122 		 */
2123 		early = retry_flush_count == 1 || (oldmnt->mnt_kern_flag &
2124 		    MNTK_UNMOUNT) == 0 ? 0 : EARLYFLUSH;
2125 		if ((error = ffs_flushfiles(oldmnt, flags | early, td)) != 0)
2126 			break;
2127 		if ((error = softdep_flushworklist(oldmnt, &depcount, td)) != 0 ||
2128 		    depcount == 0)
2129 			break;
2130 	}
2131 	/*
2132 	 * If we are unmounting then it is an error to fail. If we
2133 	 * are simply trying to downgrade to read-only, then filesystem
2134 	 * activity can keep us busy forever, so we just fail with EBUSY.
2135 	 */
2136 	if (loopcnt == 0) {
2137 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT)
2138 			panic("softdep_flushfiles: looping");
2139 		error = EBUSY;
2140 	}
2141 	if (!error)
2142 		error = softdep_waitidle(oldmnt, flags);
2143 	if (!error) {
2144 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT) {
2145 			retry = 0;
2146 			MNT_ILOCK(oldmnt);
2147 			morework = oldmnt->mnt_nvnodelistsize > 0;
2148 #ifdef QUOTA
2149 			UFS_LOCK(ump);
2150 			for (i = 0; i < MAXQUOTAS; i++) {
2151 				if (ump->um_quotas[i] != NULLVP)
2152 					morework = 1;
2153 			}
2154 			UFS_UNLOCK(ump);
2155 #endif
2156 			if (morework) {
2157 				if (--retry_flush_count > 0) {
2158 					retry = 1;
2159 					loopcnt = 3;
2160 				} else
2161 					error = EBUSY;
2162 			}
2163 			MNT_IUNLOCK(oldmnt);
2164 			if (retry)
2165 				goto retry_flush;
2166 		}
2167 	}
2168 	return (error);
2169 }
2170 
2171 /*
2172  * Structure hashing.
2173  *
2174  * There are four types of structures that can be looked up:
2175  *	1) pagedep structures identified by mount point, inode number,
2176  *	   and logical block.
2177  *	2) inodedep structures identified by mount point and inode number.
2178  *	3) newblk structures identified by mount point and
2179  *	   physical block number.
2180  *	4) bmsafemap structures identified by mount point and
2181  *	   cylinder group number.
2182  *
2183  * The "pagedep" and "inodedep" dependency structures are hashed
2184  * separately from the file blocks and inodes to which they correspond.
2185  * This separation helps when the in-memory copy of an inode or
2186  * file block must be replaced. It also obviates the need to access
2187  * an inode or file page when simply updating (or de-allocating)
2188  * dependency structures. Lookup of newblk structures is needed to
2189  * find newly allocated blocks when trying to associate them with
2190  * their allocdirect or allocindir structure.
2191  *
2192  * The lookup routines optionally create and hash a new instance when
2193  * an existing entry is not found. The bmsafemap lookup routine always
2194  * allocates a new structure if an existing one is not found.
2195  */
2196 #define DEPALLOC	0x0001	/* allocate structure if lookup fails */
2197 
2198 /*
2199  * Structures and routines associated with pagedep caching.
2200  */
2201 #define	PAGEDEP_HASH(ump, inum, lbn) \
2202 	(&(ump)->pagedep_hashtbl[((inum) + (lbn)) & (ump)->pagedep_hash_size])
2203 
2204 static int
2205 pagedep_find(struct pagedep_hashhead *pagedephd,
2206 	ino_t ino,
2207 	ufs_lbn_t lbn,
2208 	struct pagedep **pagedeppp)
2209 {
2210 	struct pagedep *pagedep;
2211 
2212 	LIST_FOREACH(pagedep, pagedephd, pd_hash) {
2213 		if (ino == pagedep->pd_ino && lbn == pagedep->pd_lbn) {
2214 			*pagedeppp = pagedep;
2215 			return (1);
2216 		}
2217 	}
2218 	*pagedeppp = NULL;
2219 	return (0);
2220 }
2221 /*
2222  * Look up a pagedep. Return 1 if found, 0 otherwise.
2223  * If not found, allocate if DEPALLOC flag is passed.
2224  * Found or allocated entry is returned in pagedeppp.
2225  */
2226 static int
2227 pagedep_lookup(struct mount *mp,
2228 	struct buf *bp,
2229 	ino_t ino,
2230 	ufs_lbn_t lbn,
2231 	int flags,
2232 	struct pagedep **pagedeppp)
2233 {
2234 	struct pagedep *pagedep;
2235 	struct pagedep_hashhead *pagedephd;
2236 	struct worklist *wk;
2237 	struct ufsmount *ump;
2238 	int ret;
2239 	int i;
2240 
2241 	ump = VFSTOUFS(mp);
2242 	LOCK_OWNED(ump);
2243 	if (bp) {
2244 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
2245 			if (wk->wk_type == D_PAGEDEP) {
2246 				*pagedeppp = WK_PAGEDEP(wk);
2247 				return (1);
2248 			}
2249 		}
2250 	}
2251 	pagedephd = PAGEDEP_HASH(ump, ino, lbn);
2252 	ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2253 	if (ret) {
2254 		if (((*pagedeppp)->pd_state & ONWORKLIST) == 0 && bp)
2255 			WORKLIST_INSERT(&bp->b_dep, &(*pagedeppp)->pd_list);
2256 		return (1);
2257 	}
2258 	if ((flags & DEPALLOC) == 0)
2259 		return (0);
2260 	FREE_LOCK(ump);
2261 	pagedep = malloc(sizeof(struct pagedep),
2262 	    M_PAGEDEP, M_SOFTDEP_FLAGS|M_ZERO);
2263 	workitem_alloc(&pagedep->pd_list, D_PAGEDEP, mp);
2264 	ACQUIRE_LOCK(ump);
2265 	ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2266 	if (*pagedeppp) {
2267 		/*
2268 		 * This should never happen since we only create pagedeps
2269 		 * with the vnode lock held.  Could be an assert.
2270 		 */
2271 		WORKITEM_FREE(pagedep, D_PAGEDEP);
2272 		return (ret);
2273 	}
2274 	pagedep->pd_ino = ino;
2275 	pagedep->pd_lbn = lbn;
2276 	LIST_INIT(&pagedep->pd_dirremhd);
2277 	LIST_INIT(&pagedep->pd_pendinghd);
2278 	for (i = 0; i < DAHASHSZ; i++)
2279 		LIST_INIT(&pagedep->pd_diraddhd[i]);
2280 	LIST_INSERT_HEAD(pagedephd, pagedep, pd_hash);
2281 	WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
2282 	*pagedeppp = pagedep;
2283 	return (0);
2284 }
2285 
2286 /*
2287  * Structures and routines associated with inodedep caching.
2288  */
2289 #define	INODEDEP_HASH(ump, inum) \
2290       (&(ump)->inodedep_hashtbl[(inum) & (ump)->inodedep_hash_size])
2291 
2292 static int
2293 inodedep_find(struct inodedep_hashhead *inodedephd,
2294 	ino_t inum,
2295 	struct inodedep **inodedeppp)
2296 {
2297 	struct inodedep *inodedep;
2298 
2299 	LIST_FOREACH(inodedep, inodedephd, id_hash)
2300 		if (inum == inodedep->id_ino)
2301 			break;
2302 	if (inodedep) {
2303 		*inodedeppp = inodedep;
2304 		return (1);
2305 	}
2306 	*inodedeppp = NULL;
2307 
2308 	return (0);
2309 }
2310 /*
2311  * Look up an inodedep. Return 1 if found, 0 if not found.
2312  * If not found, allocate if DEPALLOC flag is passed.
2313  * Found or allocated entry is returned in inodedeppp.
2314  */
2315 static int
2316 inodedep_lookup(struct mount *mp,
2317 	ino_t inum,
2318 	int flags,
2319 	struct inodedep **inodedeppp)
2320 {
2321 	struct inodedep *inodedep;
2322 	struct inodedep_hashhead *inodedephd;
2323 	struct ufsmount *ump;
2324 	struct fs *fs;
2325 
2326 	ump = VFSTOUFS(mp);
2327 	LOCK_OWNED(ump);
2328 	fs = ump->um_fs;
2329 	inodedephd = INODEDEP_HASH(ump, inum);
2330 
2331 	if (inodedep_find(inodedephd, inum, inodedeppp))
2332 		return (1);
2333 	if ((flags & DEPALLOC) == 0)
2334 		return (0);
2335 	/*
2336 	 * If the system is over its limit and our filesystem is
2337 	 * responsible for more than our share of that usage and
2338 	 * we are not in a rush, request some inodedep cleanup.
2339 	 */
2340 	if (softdep_excess_items(ump, D_INODEDEP))
2341 		schedule_cleanup(mp);
2342 	else
2343 		FREE_LOCK(ump);
2344 	inodedep = malloc(sizeof(struct inodedep),
2345 		M_INODEDEP, M_SOFTDEP_FLAGS);
2346 	workitem_alloc(&inodedep->id_list, D_INODEDEP, mp);
2347 	ACQUIRE_LOCK(ump);
2348 	if (inodedep_find(inodedephd, inum, inodedeppp)) {
2349 		WORKITEM_FREE(inodedep, D_INODEDEP);
2350 		return (1);
2351 	}
2352 	inodedep->id_fs = fs;
2353 	inodedep->id_ino = inum;
2354 	inodedep->id_state = ALLCOMPLETE;
2355 	inodedep->id_nlinkdelta = 0;
2356 	inodedep->id_nlinkwrote = -1;
2357 	inodedep->id_savedino1 = NULL;
2358 	inodedep->id_savedsize = -1;
2359 	inodedep->id_savedextsize = -1;
2360 	inodedep->id_savednlink = -1;
2361 	inodedep->id_bmsafemap = NULL;
2362 	inodedep->id_mkdiradd = NULL;
2363 	LIST_INIT(&inodedep->id_dirremhd);
2364 	LIST_INIT(&inodedep->id_pendinghd);
2365 	LIST_INIT(&inodedep->id_inowait);
2366 	LIST_INIT(&inodedep->id_bufwait);
2367 	TAILQ_INIT(&inodedep->id_inoreflst);
2368 	TAILQ_INIT(&inodedep->id_inoupdt);
2369 	TAILQ_INIT(&inodedep->id_newinoupdt);
2370 	TAILQ_INIT(&inodedep->id_extupdt);
2371 	TAILQ_INIT(&inodedep->id_newextupdt);
2372 	TAILQ_INIT(&inodedep->id_freeblklst);
2373 	LIST_INSERT_HEAD(inodedephd, inodedep, id_hash);
2374 	*inodedeppp = inodedep;
2375 	return (0);
2376 }
2377 
2378 /*
2379  * Structures and routines associated with newblk caching.
2380  */
2381 #define	NEWBLK_HASH(ump, inum) \
2382 	(&(ump)->newblk_hashtbl[(inum) & (ump)->newblk_hash_size])
2383 
2384 static int
2385 newblk_find(struct newblk_hashhead *newblkhd,
2386 	ufs2_daddr_t newblkno,
2387 	int flags,
2388 	struct newblk **newblkpp)
2389 {
2390 	struct newblk *newblk;
2391 
2392 	LIST_FOREACH(newblk, newblkhd, nb_hash) {
2393 		if (newblkno != newblk->nb_newblkno)
2394 			continue;
2395 		/*
2396 		 * If we're creating a new dependency don't match those that
2397 		 * have already been converted to allocdirects.  This is for
2398 		 * a frag extend.
2399 		 */
2400 		if ((flags & DEPALLOC) && newblk->nb_list.wk_type != D_NEWBLK)
2401 			continue;
2402 		break;
2403 	}
2404 	if (newblk) {
2405 		*newblkpp = newblk;
2406 		return (1);
2407 	}
2408 	*newblkpp = NULL;
2409 	return (0);
2410 }
2411 
2412 /*
2413  * Look up a newblk. Return 1 if found, 0 if not found.
2414  * If not found, allocate if DEPALLOC flag is passed.
2415  * Found or allocated entry is returned in newblkpp.
2416  */
2417 static int
2418 newblk_lookup(struct mount *mp,
2419 	ufs2_daddr_t newblkno,
2420 	int flags,
2421 	struct newblk **newblkpp)
2422 {
2423 	struct newblk *newblk;
2424 	struct newblk_hashhead *newblkhd;
2425 	struct ufsmount *ump;
2426 
2427 	ump = VFSTOUFS(mp);
2428 	LOCK_OWNED(ump);
2429 	newblkhd = NEWBLK_HASH(ump, newblkno);
2430 	if (newblk_find(newblkhd, newblkno, flags, newblkpp))
2431 		return (1);
2432 	if ((flags & DEPALLOC) == 0)
2433 		return (0);
2434 	if (softdep_excess_items(ump, D_NEWBLK) ||
2435 	    softdep_excess_items(ump, D_ALLOCDIRECT) ||
2436 	    softdep_excess_items(ump, D_ALLOCINDIR))
2437 		schedule_cleanup(mp);
2438 	else
2439 		FREE_LOCK(ump);
2440 	newblk = malloc(sizeof(union allblk), M_NEWBLK,
2441 	    M_SOFTDEP_FLAGS | M_ZERO);
2442 	workitem_alloc(&newblk->nb_list, D_NEWBLK, mp);
2443 	ACQUIRE_LOCK(ump);
2444 	if (newblk_find(newblkhd, newblkno, flags, newblkpp)) {
2445 		WORKITEM_FREE(newblk, D_NEWBLK);
2446 		return (1);
2447 	}
2448 	newblk->nb_freefrag = NULL;
2449 	LIST_INIT(&newblk->nb_indirdeps);
2450 	LIST_INIT(&newblk->nb_newdirblk);
2451 	LIST_INIT(&newblk->nb_jwork);
2452 	newblk->nb_state = ATTACHED;
2453 	newblk->nb_newblkno = newblkno;
2454 	LIST_INSERT_HEAD(newblkhd, newblk, nb_hash);
2455 	*newblkpp = newblk;
2456 	return (0);
2457 }
2458 
2459 /*
2460  * Structures and routines associated with freed indirect block caching.
2461  */
2462 #define	INDIR_HASH(ump, blkno) \
2463 	(&(ump)->indir_hashtbl[(blkno) & (ump)->indir_hash_size])
2464 
2465 /*
2466  * Lookup an indirect block in the indir hash table.  The freework is
2467  * removed and potentially freed.  The caller must do a blocking journal
2468  * write before writing to the blkno.
2469  */
2470 static int
2471 indirblk_lookup(struct mount *mp, ufs2_daddr_t blkno)
2472 {
2473 	struct freework *freework;
2474 	struct indir_hashhead *wkhd;
2475 	struct ufsmount *ump;
2476 
2477 	ump = VFSTOUFS(mp);
2478 	wkhd = INDIR_HASH(ump, blkno);
2479 	TAILQ_FOREACH(freework, wkhd, fw_next) {
2480 		if (freework->fw_blkno != blkno)
2481 			continue;
2482 		indirblk_remove(freework);
2483 		return (1);
2484 	}
2485 	return (0);
2486 }
2487 
2488 /*
2489  * Insert an indirect block represented by freework into the indirblk
2490  * hash table so that it may prevent the block from being re-used prior
2491  * to the journal being written.
2492  */
2493 static void
2494 indirblk_insert(struct freework *freework)
2495 {
2496 	struct jblocks *jblocks;
2497 	struct jseg *jseg;
2498 	struct ufsmount *ump;
2499 
2500 	ump = VFSTOUFS(freework->fw_list.wk_mp);
2501 	jblocks = ump->softdep_jblocks;
2502 	jseg = TAILQ_LAST(&jblocks->jb_segs, jseglst);
2503 	if (jseg == NULL)
2504 		return;
2505 
2506 	LIST_INSERT_HEAD(&jseg->js_indirs, freework, fw_segs);
2507 	TAILQ_INSERT_HEAD(INDIR_HASH(ump, freework->fw_blkno), freework,
2508 	    fw_next);
2509 	freework->fw_state &= ~DEPCOMPLETE;
2510 }
2511 
2512 static void
2513 indirblk_remove(struct freework *freework)
2514 {
2515 	struct ufsmount *ump;
2516 
2517 	ump = VFSTOUFS(freework->fw_list.wk_mp);
2518 	LIST_REMOVE(freework, fw_segs);
2519 	TAILQ_REMOVE(INDIR_HASH(ump, freework->fw_blkno), freework, fw_next);
2520 	freework->fw_state |= DEPCOMPLETE;
2521 	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
2522 		WORKITEM_FREE(freework, D_FREEWORK);
2523 }
2524 
2525 /*
2526  * Executed during filesystem system initialization before
2527  * mounting any filesystems.
2528  */
2529 void
2530 softdep_initialize(void)
2531 {
2532 
2533 	TAILQ_INIT(&softdepmounts);
2534 #ifdef __LP64__
2535 	max_softdeps = desiredvnodes * 4;
2536 #else
2537 	max_softdeps = desiredvnodes * 2;
2538 #endif
2539 
2540 	/* initialise bioops hack */
2541 	bioops.io_start = softdep_disk_io_initiation;
2542 	bioops.io_complete = softdep_disk_write_complete;
2543 	bioops.io_deallocate = softdep_deallocate_dependencies;
2544 	bioops.io_countdeps = softdep_count_dependencies;
2545 	ast_register(TDA_UFS, ASTR_KCLEAR | ASTR_ASTF_REQUIRED, 0,
2546 	    softdep_ast_cleanup_proc);
2547 
2548 	/* Initialize the callout with an mtx. */
2549 	callout_init_mtx(&softdep_callout, &lk, 0);
2550 }
2551 
2552 /*
2553  * Executed after all filesystems have been unmounted during
2554  * filesystem module unload.
2555  */
2556 void
2557 softdep_uninitialize(void)
2558 {
2559 
2560 	/* clear bioops hack */
2561 	bioops.io_start = NULL;
2562 	bioops.io_complete = NULL;
2563 	bioops.io_deallocate = NULL;
2564 	bioops.io_countdeps = NULL;
2565 	ast_deregister(TDA_UFS);
2566 
2567 	callout_drain(&softdep_callout);
2568 }
2569 
2570 /*
2571  * Called at mount time to notify the dependency code that a
2572  * filesystem wishes to use it.
2573  */
2574 int
2575 softdep_mount(struct vnode *devvp,
2576 	struct mount *mp,
2577 	struct fs *fs,
2578 	struct ucred *cred)
2579 {
2580 	struct csum_total cstotal;
2581 	struct mount_softdeps *sdp;
2582 	struct ufsmount *ump;
2583 	struct cg *cgp;
2584 	struct buf *bp;
2585 	uint64_t cyl, i;
2586 	int error;
2587 
2588 	ump = VFSTOUFS(mp);
2589 
2590 	sdp = malloc(sizeof(struct mount_softdeps), M_MOUNTDATA,
2591 	    M_WAITOK | M_ZERO);
2592 	rw_init(&sdp->sd_fslock, "SUrw");
2593 	sdp->sd_ump = ump;
2594 	LIST_INIT(&sdp->sd_workitem_pending);
2595 	LIST_INIT(&sdp->sd_journal_pending);
2596 	TAILQ_INIT(&sdp->sd_unlinked);
2597 	LIST_INIT(&sdp->sd_dirtycg);
2598 	sdp->sd_worklist_tail = NULL;
2599 	sdp->sd_on_worklist = 0;
2600 	sdp->sd_deps = 0;
2601 	LIST_INIT(&sdp->sd_mkdirlisthd);
2602 	sdp->sd_pdhash = hashinit(desiredvnodes / 5, M_PAGEDEP,
2603 	    &sdp->sd_pdhashsize);
2604 	sdp->sd_pdnextclean = 0;
2605 	sdp->sd_idhash = hashinit(desiredvnodes, M_INODEDEP,
2606 	    &sdp->sd_idhashsize);
2607 	sdp->sd_idnextclean = 0;
2608 	sdp->sd_newblkhash = hashinit(max_softdeps / 2,  M_NEWBLK,
2609 	    &sdp->sd_newblkhashsize);
2610 	sdp->sd_bmhash = hashinit(1024, M_BMSAFEMAP, &sdp->sd_bmhashsize);
2611 	i = 1 << (ffs(desiredvnodes / 10) - 1);
2612 	sdp->sd_indirhash = malloc(i * sizeof(struct indir_hashhead),
2613 	    M_FREEWORK, M_WAITOK);
2614 	sdp->sd_indirhashsize = i - 1;
2615 	for (i = 0; i <= sdp->sd_indirhashsize; i++)
2616 		TAILQ_INIT(&sdp->sd_indirhash[i]);
2617 	for (i = 0; i <= D_LAST; i++)
2618 		LIST_INIT(&sdp->sd_alldeps[i]);
2619 	ACQUIRE_GBLLOCK(&lk);
2620 	TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
2621 	FREE_GBLLOCK(&lk);
2622 
2623 	ump->um_softdep = sdp;
2624 	MNT_ILOCK(mp);
2625 	mp->mnt_flag = (mp->mnt_flag & ~MNT_ASYNC) | MNT_SOFTDEP;
2626 	if ((mp->mnt_kern_flag & MNTK_SOFTDEP) == 0) {
2627 		mp->mnt_kern_flag = (mp->mnt_kern_flag & ~MNTK_ASYNC) |
2628 		    MNTK_SOFTDEP | MNTK_NOASYNC;
2629 	}
2630 	MNT_IUNLOCK(mp);
2631 
2632 	if ((fs->fs_flags & FS_SUJ) &&
2633 	    (error = journal_mount(mp, fs, cred)) != 0) {
2634 		printf("%s: failed to start journal: %d\n",
2635 		    mp->mnt_stat.f_mntonname, error);
2636 		softdep_unmount(mp);
2637 		return (error);
2638 	}
2639 	/*
2640 	 * Start our flushing thread in the bufdaemon process.
2641 	 */
2642 	ACQUIRE_LOCK(ump);
2643 	ump->softdep_flags |= FLUSH_STARTING;
2644 	FREE_LOCK(ump);
2645 	error = kproc_kthread_add(&softdep_flush, mp, &bufdaemonproc,
2646 	    &ump->softdep_flushtd, 0, 0, "softdepflush", "%s worker",
2647 	    mp->mnt_stat.f_mntonname);
2648 	ACQUIRE_LOCK(ump);
2649 	if (error != 0) {
2650 		printf("%s: failed to start softdepflush thread: %d\n",
2651 		    mp->mnt_stat.f_mntonname, error);
2652 		ump->softdep_flags &= ~FLUSH_STARTING;
2653 		FREE_LOCK(ump);
2654 		softdep_unmount(mp);
2655 		return (error);
2656 	}
2657 	while ((ump->softdep_flags & FLUSH_STARTING) != 0) {
2658 		msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM, "sdstart",
2659 		    hz / 2);
2660 	}
2661 	FREE_LOCK(ump);
2662 	/*
2663 	 * When doing soft updates, the counters in the
2664 	 * superblock may have gotten out of sync. Recomputation
2665 	 * can take a long time and can be deferred for background
2666 	 * fsck.  However, the old behavior of scanning the cylinder
2667 	 * groups and recalculating them at mount time is available
2668 	 * by setting vfs.ffs.compute_summary_at_mount to one.
2669 	 */
2670 	if (compute_summary_at_mount == 0 || fs->fs_clean != 0)
2671 		return (0);
2672 	bzero(&cstotal, sizeof cstotal);
2673 	for (cyl = 0; cyl < fs->fs_ncg; cyl++) {
2674 		if ((error = bread(devvp, fsbtodb(fs, cgtod(fs, cyl)),
2675 		    fs->fs_cgsize, cred, &bp)) != 0) {
2676 			brelse(bp);
2677 			softdep_unmount(mp);
2678 			return (error);
2679 		}
2680 		cgp = (struct cg *)bp->b_data;
2681 		cstotal.cs_nffree += cgp->cg_cs.cs_nffree;
2682 		cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree;
2683 		cstotal.cs_nifree += cgp->cg_cs.cs_nifree;
2684 		cstotal.cs_ndir += cgp->cg_cs.cs_ndir;
2685 		fs->fs_cs(fs, cyl) = cgp->cg_cs;
2686 		brelse(bp);
2687 	}
2688 #ifdef INVARIANTS
2689 	if (bcmp(&cstotal, &fs->fs_cstotal, sizeof cstotal))
2690 		printf("%s: superblock summary recomputed\n", fs->fs_fsmnt);
2691 #endif
2692 	bcopy(&cstotal, &fs->fs_cstotal, sizeof cstotal);
2693 	return (0);
2694 }
2695 
2696 void
2697 softdep_unmount(struct mount *mp)
2698 {
2699 	struct ufsmount *ump;
2700 	struct mount_softdeps *ums;
2701 
2702 	ump = VFSTOUFS(mp);
2703 	KASSERT(ump->um_softdep != NULL,
2704 	    ("softdep_unmount called on non-softdep filesystem"));
2705 	MNT_ILOCK(mp);
2706 	mp->mnt_flag &= ~MNT_SOFTDEP;
2707 	if ((mp->mnt_flag & MNT_SUJ) == 0) {
2708 		MNT_IUNLOCK(mp);
2709 	} else {
2710 		mp->mnt_flag &= ~MNT_SUJ;
2711 		MNT_IUNLOCK(mp);
2712 		journal_unmount(ump);
2713 	}
2714 	/*
2715 	 * Shut down our flushing thread. Check for NULL is if
2716 	 * softdep_mount errors out before the thread has been created.
2717 	 */
2718 	if (ump->softdep_flushtd != NULL) {
2719 		ACQUIRE_LOCK(ump);
2720 		ump->softdep_flags |= FLUSH_EXIT;
2721 		wakeup(&ump->softdep_flushtd);
2722 		while ((ump->softdep_flags & FLUSH_EXIT) != 0) {
2723 			msleep(&ump->softdep_flags, LOCK_PTR(ump), PVM,
2724 			    "sdwait", 0);
2725 		}
2726 		KASSERT((ump->softdep_flags & FLUSH_EXIT) == 0,
2727 		    ("Thread shutdown failed"));
2728 		FREE_LOCK(ump);
2729 	}
2730 
2731 	/*
2732 	 * We are no longer have softdep structure attached to ump.
2733 	 */
2734 	ums = ump->um_softdep;
2735 	ACQUIRE_GBLLOCK(&lk);
2736 	TAILQ_REMOVE(&softdepmounts, ums, sd_next);
2737 	FREE_GBLLOCK(&lk);
2738 	ump->um_softdep = NULL;
2739 
2740 	KASSERT(ums->sd_on_journal == 0,
2741 	    ("ump %p ums %p on_journal %d", ump, ums, ums->sd_on_journal));
2742 	KASSERT(ums->sd_on_worklist == 0,
2743 	    ("ump %p ums %p on_worklist %d", ump, ums, ums->sd_on_worklist));
2744 	KASSERT(ums->sd_deps == 0,
2745 	    ("ump %p ums %p deps %d", ump, ums, ums->sd_deps));
2746 
2747 	/*
2748 	 * Free up our resources.
2749 	 */
2750 	rw_destroy(&ums->sd_fslock);
2751 	hashdestroy(ums->sd_pdhash, M_PAGEDEP, ums->sd_pdhashsize);
2752 	hashdestroy(ums->sd_idhash, M_INODEDEP, ums->sd_idhashsize);
2753 	hashdestroy(ums->sd_newblkhash, M_NEWBLK, ums->sd_newblkhashsize);
2754 	hashdestroy(ums->sd_bmhash, M_BMSAFEMAP, ums->sd_bmhashsize);
2755 	free(ums->sd_indirhash, M_FREEWORK);
2756 #ifdef INVARIANTS
2757 	for (int i = 0; i <= D_LAST; i++) {
2758 		KASSERT(ums->sd_curdeps[i] == 0,
2759 		    ("Unmount %s: Dep type %s != 0 (%jd)", ump->um_fs->fs_fsmnt,
2760 		    TYPENAME(i), (intmax_t)ums->sd_curdeps[i]));
2761 		KASSERT(LIST_EMPTY(&ums->sd_alldeps[i]),
2762 		    ("Unmount %s: Dep type %s not empty (%p)",
2763 		    ump->um_fs->fs_fsmnt,
2764 		    TYPENAME(i), LIST_FIRST(&ums->sd_alldeps[i])));
2765 	}
2766 #endif
2767 	free(ums, M_MOUNTDATA);
2768 }
2769 
2770 static struct jblocks *
2771 jblocks_create(void)
2772 {
2773 	struct jblocks *jblocks;
2774 
2775 	jblocks = malloc(sizeof(*jblocks), M_JBLOCKS, M_WAITOK | M_ZERO);
2776 	TAILQ_INIT(&jblocks->jb_segs);
2777 	jblocks->jb_avail = 10;
2778 	jblocks->jb_extent = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2779 	    M_JBLOCKS, M_WAITOK | M_ZERO);
2780 
2781 	return (jblocks);
2782 }
2783 
2784 static ufs2_daddr_t
2785 jblocks_alloc(struct jblocks *jblocks,
2786 	int bytes,
2787 	int *actual)
2788 {
2789 	ufs2_daddr_t daddr;
2790 	struct jextent *jext;
2791 	int freecnt;
2792 	int blocks;
2793 
2794 	blocks = bytes / DEV_BSIZE;
2795 	jext = &jblocks->jb_extent[jblocks->jb_head];
2796 	freecnt = jext->je_blocks - jblocks->jb_off;
2797 	if (freecnt == 0) {
2798 		jblocks->jb_off = 0;
2799 		if (++jblocks->jb_head > jblocks->jb_used)
2800 			jblocks->jb_head = 0;
2801 		jext = &jblocks->jb_extent[jblocks->jb_head];
2802 		freecnt = jext->je_blocks;
2803 	}
2804 	if (freecnt > blocks)
2805 		freecnt = blocks;
2806 	*actual = freecnt * DEV_BSIZE;
2807 	daddr = jext->je_daddr + jblocks->jb_off;
2808 	jblocks->jb_off += freecnt;
2809 	jblocks->jb_free -= freecnt;
2810 
2811 	return (daddr);
2812 }
2813 
2814 static void
2815 jblocks_free(struct jblocks *jblocks,
2816 	struct mount *mp,
2817 	int bytes)
2818 {
2819 
2820 	LOCK_OWNED(VFSTOUFS(mp));
2821 	jblocks->jb_free += bytes / DEV_BSIZE;
2822 	if (jblocks->jb_suspended)
2823 		worklist_speedup(mp);
2824 	wakeup(jblocks);
2825 }
2826 
2827 static void
2828 jblocks_destroy(struct jblocks *jblocks)
2829 {
2830 
2831 	if (jblocks->jb_extent)
2832 		free(jblocks->jb_extent, M_JBLOCKS);
2833 	free(jblocks, M_JBLOCKS);
2834 }
2835 
2836 static void
2837 jblocks_add(struct jblocks *jblocks,
2838 	ufs2_daddr_t daddr,
2839 	int blocks)
2840 {
2841 	struct jextent *jext;
2842 
2843 	jblocks->jb_blocks += blocks;
2844 	jblocks->jb_free += blocks;
2845 	jext = &jblocks->jb_extent[jblocks->jb_used];
2846 	/* Adding the first block. */
2847 	if (jext->je_daddr == 0) {
2848 		jext->je_daddr = daddr;
2849 		jext->je_blocks = blocks;
2850 		return;
2851 	}
2852 	/* Extending the last extent. */
2853 	if (jext->je_daddr + jext->je_blocks == daddr) {
2854 		jext->je_blocks += blocks;
2855 		return;
2856 	}
2857 	/* Adding a new extent. */
2858 	if (++jblocks->jb_used == jblocks->jb_avail) {
2859 		jblocks->jb_avail *= 2;
2860 		jext = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2861 		    M_JBLOCKS, M_WAITOK | M_ZERO);
2862 		memcpy(jext, jblocks->jb_extent,
2863 		    sizeof(struct jextent) * jblocks->jb_used);
2864 		free(jblocks->jb_extent, M_JBLOCKS);
2865 		jblocks->jb_extent = jext;
2866 	}
2867 	jext = &jblocks->jb_extent[jblocks->jb_used];
2868 	jext->je_daddr = daddr;
2869 	jext->je_blocks = blocks;
2870 	return;
2871 }
2872 
2873 int
2874 softdep_journal_lookup(struct mount *mp, struct vnode **vpp)
2875 {
2876 	struct componentname cnp;
2877 	struct vnode *dvp;
2878 	ino_t sujournal;
2879 	int error;
2880 
2881 	error = VFS_VGET(mp, UFS_ROOTINO, LK_EXCLUSIVE, &dvp);
2882 	if (error)
2883 		return (error);
2884 	bzero(&cnp, sizeof(cnp));
2885 	cnp.cn_nameiop = LOOKUP;
2886 	cnp.cn_flags = ISLASTCN;
2887 	cnp.cn_cred = curthread->td_ucred;
2888 	cnp.cn_pnbuf = SUJ_FILE;
2889 	cnp.cn_nameptr = SUJ_FILE;
2890 	cnp.cn_namelen = strlen(SUJ_FILE);
2891 	error = ufs_lookup_ino(dvp, NULL, &cnp, &sujournal);
2892 	vput(dvp);
2893 	if (error != 0)
2894 		return (error);
2895 	error = VFS_VGET(mp, sujournal, LK_EXCLUSIVE, vpp);
2896 	return (error);
2897 }
2898 
2899 /*
2900  * Open and verify the journal file.
2901  */
2902 static int
2903 journal_mount(struct mount *mp,
2904 	struct fs *fs,
2905 	struct ucred *cred)
2906 {
2907 	struct jblocks *jblocks;
2908 	struct ufsmount *ump;
2909 	struct vnode *vp;
2910 	struct inode *ip;
2911 	ufs2_daddr_t blkno;
2912 	int bcount;
2913 	int error;
2914 	int i;
2915 
2916 	ump = VFSTOUFS(mp);
2917 	ump->softdep_journal_tail = NULL;
2918 	ump->softdep_on_journal = 0;
2919 	ump->softdep_accdeps = 0;
2920 	ump->softdep_req = 0;
2921 	ump->softdep_jblocks = NULL;
2922 	error = softdep_journal_lookup(mp, &vp);
2923 	if (error != 0) {
2924 		printf("Failed to find journal.  Use tunefs to create one\n");
2925 		return (error);
2926 	}
2927 	ip = VTOI(vp);
2928 	if (ip->i_size < SUJ_MIN) {
2929 		error = ENOSPC;
2930 		goto out;
2931 	}
2932 	bcount = lblkno(fs, ip->i_size);	/* Only use whole blocks. */
2933 	jblocks = jblocks_create();
2934 	for (i = 0; i < bcount; i++) {
2935 		error = ufs_bmaparray(vp, i, &blkno, NULL, NULL, NULL);
2936 		if (error)
2937 			break;
2938 		jblocks_add(jblocks, blkno, fsbtodb(fs, fs->fs_frag));
2939 	}
2940 	if (error) {
2941 		jblocks_destroy(jblocks);
2942 		goto out;
2943 	}
2944 	jblocks->jb_low = jblocks->jb_free / 3;	/* Reserve 33%. */
2945 	jblocks->jb_min = jblocks->jb_free / 10; /* Suspend at 10%. */
2946 	ump->softdep_jblocks = jblocks;
2947 
2948 	MNT_ILOCK(mp);
2949 	mp->mnt_flag |= MNT_SUJ;
2950 	MNT_IUNLOCK(mp);
2951 
2952 	/*
2953 	 * Only validate the journal contents if the
2954 	 * filesystem is clean, otherwise we write the logs
2955 	 * but they'll never be used.  If the filesystem was
2956 	 * still dirty when we mounted it the journal is
2957 	 * invalid and a new journal can only be valid if it
2958 	 * starts from a clean mount.
2959 	 */
2960 	if (fs->fs_clean) {
2961 		DIP_SET(ip, i_modrev, fs->fs_mtime);
2962 		ip->i_flags |= IN_MODIFIED;
2963 		ffs_update(vp, 1);
2964 	}
2965 out:
2966 	vput(vp);
2967 	return (error);
2968 }
2969 
2970 static void
2971 journal_unmount(struct ufsmount *ump)
2972 {
2973 
2974 	if (ump->softdep_jblocks)
2975 		jblocks_destroy(ump->softdep_jblocks);
2976 	ump->softdep_jblocks = NULL;
2977 }
2978 
2979 /*
2980  * Called when a journal record is ready to be written.  Space is allocated
2981  * and the journal entry is created when the journal is flushed to stable
2982  * store.
2983  */
2984 static void
2985 add_to_journal(struct worklist *wk)
2986 {
2987 	struct ufsmount *ump;
2988 
2989 	ump = VFSTOUFS(wk->wk_mp);
2990 	LOCK_OWNED(ump);
2991 	if (wk->wk_state & ONWORKLIST)
2992 		panic("add_to_journal: %s(0x%X) already on list",
2993 		    TYPENAME(wk->wk_type), wk->wk_state);
2994 	wk->wk_state |= ONWORKLIST | DEPCOMPLETE;
2995 	if (LIST_EMPTY(&ump->softdep_journal_pending)) {
2996 		ump->softdep_jblocks->jb_age = ticks;
2997 		LIST_INSERT_HEAD(&ump->softdep_journal_pending, wk, wk_list);
2998 	} else
2999 		LIST_INSERT_AFTER(ump->softdep_journal_tail, wk, wk_list);
3000 	ump->softdep_journal_tail = wk;
3001 	ump->softdep_on_journal += 1;
3002 }
3003 
3004 /*
3005  * Remove an arbitrary item for the journal worklist maintain the tail
3006  * pointer.  This happens when a new operation obviates the need to
3007  * journal an old operation.
3008  */
3009 static void
3010 remove_from_journal(struct worklist *wk)
3011 {
3012 	struct ufsmount *ump;
3013 
3014 	ump = VFSTOUFS(wk->wk_mp);
3015 	LOCK_OWNED(ump);
3016 #ifdef INVARIANTS
3017 	{
3018 		struct worklist *wkn;
3019 
3020 		LIST_FOREACH(wkn, &ump->softdep_journal_pending, wk_list)
3021 			if (wkn == wk)
3022 				break;
3023 		if (wkn == NULL)
3024 			panic("remove_from_journal: %p is not in journal", wk);
3025 	}
3026 #endif
3027 	/*
3028 	 * We emulate a TAILQ to save space in most structures which do not
3029 	 * require TAILQ semantics.  Here we must update the tail position
3030 	 * when removing the tail which is not the final entry. This works
3031 	 * only if the worklist linkage are at the beginning of the structure.
3032 	 */
3033 	if (ump->softdep_journal_tail == wk)
3034 		ump->softdep_journal_tail =
3035 		    (struct worklist *)wk->wk_list.le_prev;
3036 	WORKLIST_REMOVE(wk);
3037 	ump->softdep_on_journal -= 1;
3038 }
3039 
3040 /*
3041  * Check for journal space as well as dependency limits so the prelink
3042  * code can throttle both journaled and non-journaled filesystems.
3043  * Threshold is 0 for low and 1 for min.
3044  */
3045 static int
3046 journal_space(struct ufsmount *ump, int thresh)
3047 {
3048 	struct jblocks *jblocks;
3049 	int limit, avail;
3050 
3051 	jblocks = ump->softdep_jblocks;
3052 	if (jblocks == NULL)
3053 		return (1);
3054 	/*
3055 	 * We use a tighter restriction here to prevent request_cleanup()
3056 	 * running in threads from running into locks we currently hold.
3057 	 * We have to be over the limit and our filesystem has to be
3058 	 * responsible for more than our share of that usage.
3059 	 */
3060 	limit = (max_softdeps / 10) * 9;
3061 	if (dep_current[D_INODEDEP] > limit &&
3062 	    ump->softdep_curdeps[D_INODEDEP] > limit / stat_flush_threads)
3063 		return (0);
3064 	if (thresh)
3065 		thresh = jblocks->jb_min;
3066 	else
3067 		thresh = jblocks->jb_low;
3068 	avail = (ump->softdep_on_journal * JREC_SIZE) / DEV_BSIZE;
3069 	avail = jblocks->jb_free - avail;
3070 
3071 	return (avail > thresh);
3072 }
3073 
3074 static void
3075 journal_suspend(struct ufsmount *ump)
3076 {
3077 	struct jblocks *jblocks;
3078 	struct mount *mp;
3079 	bool set;
3080 
3081 	mp = UFSTOVFS(ump);
3082 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0)
3083 		return;
3084 
3085 	jblocks = ump->softdep_jblocks;
3086 	vfs_op_enter(mp);
3087 	set = false;
3088 	MNT_ILOCK(mp);
3089 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
3090 		stat_journal_min++;
3091 		mp->mnt_kern_flag |= MNTK_SUSPEND;
3092 		mp->mnt_susp_owner = ump->softdep_flushtd;
3093 		set = true;
3094 	}
3095 	jblocks->jb_suspended = 1;
3096 	MNT_IUNLOCK(mp);
3097 	if (!set)
3098 		vfs_op_exit(mp);
3099 }
3100 
3101 static int
3102 journal_unsuspend(struct ufsmount *ump)
3103 {
3104 	struct jblocks *jblocks;
3105 	struct mount *mp;
3106 
3107 	mp = UFSTOVFS(ump);
3108 	jblocks = ump->softdep_jblocks;
3109 
3110 	if (jblocks != NULL && jblocks->jb_suspended &&
3111 	    journal_space(ump, jblocks->jb_min)) {
3112 		jblocks->jb_suspended = 0;
3113 		FREE_LOCK(ump);
3114 		mp->mnt_susp_owner = curthread;
3115 		vfs_write_resume(mp, 0);
3116 		ACQUIRE_LOCK(ump);
3117 		return (1);
3118 	}
3119 	return (0);
3120 }
3121 
3122 static void
3123 journal_check_space(struct ufsmount *ump)
3124 {
3125 	struct mount *mp;
3126 
3127 	LOCK_OWNED(ump);
3128 
3129 	if (journal_space(ump, 0) == 0) {
3130 		softdep_speedup(ump);
3131 		mp = UFSTOVFS(ump);
3132 		FREE_LOCK(ump);
3133 		VFS_SYNC(mp, MNT_NOWAIT);
3134 		ffs_sbupdate(ump, MNT_WAIT, 0);
3135 		ACQUIRE_LOCK(ump);
3136 		if (journal_space(ump, 1) == 0)
3137 			journal_suspend(ump);
3138 	}
3139 }
3140 
3141 /*
3142  * Called before any allocation function to be certain that there is
3143  * sufficient space in the journal prior to creating any new records.
3144  * Since in the case of block allocation we may have multiple locked
3145  * buffers at the time of the actual allocation we can not block
3146  * when the journal records are created.  Doing so would create a deadlock
3147  * if any of these buffers needed to be flushed to reclaim space.  Instead
3148  * we require a sufficiently large amount of available space such that
3149  * each thread in the system could have passed this allocation check and
3150  * still have sufficient free space.  With 20% of a minimum journal size
3151  * of 1MB we have 6553 records available.
3152  */
3153 int
3154 softdep_prealloc(struct vnode *vp, int waitok)
3155 {
3156 	struct ufsmount *ump;
3157 
3158 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
3159 	    ("softdep_prealloc called on non-softdep filesystem"));
3160 	/*
3161 	 * Nothing to do if we are not running journaled soft updates.
3162 	 * If we currently hold the snapshot lock, we must avoid
3163 	 * handling other resources that could cause deadlock.  Do not
3164 	 * touch quotas vnode since it is typically recursed with
3165 	 * other vnode locks held.
3166 	 */
3167 	if (DOINGSUJ(vp) == 0 || IS_SNAPSHOT(VTOI(vp)) ||
3168 	    (vp->v_vflag & VV_SYSTEM) != 0)
3169 		return (0);
3170 	ump = VFSTOUFS(vp->v_mount);
3171 	ACQUIRE_LOCK(ump);
3172 	if (journal_space(ump, 0)) {
3173 		FREE_LOCK(ump);
3174 		return (0);
3175 	}
3176 	stat_journal_low++;
3177 	FREE_LOCK(ump);
3178 	if (waitok == MNT_NOWAIT)
3179 		return (ENOSPC);
3180 	/*
3181 	 * Attempt to sync this vnode once to flush any journal
3182 	 * work attached to it.
3183 	 */
3184 	if ((curthread->td_pflags & TDP_COWINPROGRESS) == 0)
3185 		ffs_syncvnode(vp, waitok, 0);
3186 	ACQUIRE_LOCK(ump);
3187 	process_removes(vp);
3188 	process_truncates(vp);
3189 	journal_check_space(ump);
3190 	FREE_LOCK(ump);
3191 
3192 	return (0);
3193 }
3194 
3195 /*
3196  * Try hard to sync all data and metadata for the vnode, and workitems
3197  * flushing which might conflict with the vnode lock.  This is a
3198  * helper for softdep_prerename().
3199  */
3200 static int
3201 softdep_prerename_vnode(struct ufsmount *ump, struct vnode *vp)
3202 {
3203 	int error;
3204 
3205 	ASSERT_VOP_ELOCKED(vp, "prehandle");
3206 	if (vp->v_data == NULL)
3207 		return (0);
3208 	error = VOP_FSYNC(vp, MNT_WAIT, curthread);
3209 	if (error != 0)
3210 		return (error);
3211 	ACQUIRE_LOCK(ump);
3212 	process_removes(vp);
3213 	process_truncates(vp);
3214 	FREE_LOCK(ump);
3215 	return (0);
3216 }
3217 
3218 /*
3219  * Must be called from VOP_RENAME() after all vnodes are locked.
3220  * Ensures that there is enough journal space for rename.  It is
3221  * sufficiently different from softdep_prelink() by having to handle
3222  * four vnodes.
3223  */
3224 int
3225 softdep_prerename(struct vnode *fdvp,
3226 	struct vnode *fvp,
3227 	struct vnode *tdvp,
3228 	struct vnode *tvp)
3229 {
3230 	struct ufsmount *ump;
3231 	int error;
3232 
3233 	ump = VFSTOUFS(fdvp->v_mount);
3234 
3235 	if (journal_space(ump, 0))
3236 		return (0);
3237 
3238 	VOP_UNLOCK(tdvp);
3239 	VOP_UNLOCK(fvp);
3240 	if (tvp != NULL && tvp != tdvp)
3241 		VOP_UNLOCK(tvp);
3242 
3243 	error = softdep_prerename_vnode(ump, fdvp);
3244 	VOP_UNLOCK(fdvp);
3245 	if (error != 0)
3246 		return (error);
3247 
3248 	VOP_LOCK(fvp, LK_EXCLUSIVE | LK_RETRY);
3249 	error = softdep_prerename_vnode(ump, fvp);
3250 	VOP_UNLOCK(fvp);
3251 	if (error != 0)
3252 		return (error);
3253 
3254 	if (tdvp != fdvp) {
3255 		VOP_LOCK(tdvp, LK_EXCLUSIVE | LK_RETRY);
3256 		error = softdep_prerename_vnode(ump, tdvp);
3257 		VOP_UNLOCK(tdvp);
3258 		if (error != 0)
3259 			return (error);
3260 	}
3261 
3262 	if (tvp != fvp && tvp != NULL) {
3263 		VOP_LOCK(tvp, LK_EXCLUSIVE | LK_RETRY);
3264 		error = softdep_prerename_vnode(ump, tvp);
3265 		VOP_UNLOCK(tvp);
3266 		if (error != 0)
3267 			return (error);
3268 	}
3269 
3270 	ACQUIRE_LOCK(ump);
3271 	softdep_speedup(ump);
3272 	process_worklist_item(UFSTOVFS(ump), 2, LK_NOWAIT);
3273 	journal_check_space(ump);
3274 	FREE_LOCK(ump);
3275 	return (ERELOOKUP);
3276 }
3277 
3278 /*
3279  * Before adjusting a link count on a vnode verify that we have sufficient
3280  * journal space.  If not, process operations that depend on the currently
3281  * locked pair of vnodes to try to flush space as the syncer, buf daemon,
3282  * and softdep flush threads can not acquire these locks to reclaim space.
3283  *
3284  * Returns 0 if all owned locks are still valid and were not dropped
3285  * in the process, in other case it returns either an error from sync,
3286  * or ERELOOKUP if any of the locks were re-acquired.  In the later
3287  * case, the state of the vnodes cannot be relied upon and our VFS
3288  * syscall must be restarted at top level from the lookup.
3289  */
3290 int
3291 softdep_prelink(struct vnode *dvp,
3292 	struct vnode *vp,
3293 	struct componentname *cnp)
3294 {
3295 	struct ufsmount *ump;
3296 	struct nameidata *ndp;
3297 
3298 	ASSERT_VOP_ELOCKED(dvp, "prelink dvp");
3299 	if (vp != NULL)
3300 		ASSERT_VOP_ELOCKED(vp, "prelink vp");
3301 	ump = VFSTOUFS(dvp->v_mount);
3302 
3303 	/*
3304 	 * Nothing to do if we have sufficient journal space.  We skip
3305 	 * flushing when vp is a snapshot to avoid deadlock where
3306 	 * another thread is trying to update the inodeblock for dvp
3307 	 * and is waiting on snaplk that vp holds.
3308 	 */
3309 	if (journal_space(ump, 0) || (vp != NULL && IS_SNAPSHOT(VTOI(vp))))
3310 		return (0);
3311 
3312 	/*
3313 	 * Check if the journal space consumption can in theory be
3314 	 * accounted on dvp and vp.  If the vnodes metadata was not
3315 	 * changed comparing with the previous round-trip into
3316 	 * softdep_prelink(), as indicated by the seqc generation
3317 	 * recorded in the nameidata, then there is no point in
3318 	 * starting the sync.
3319 	 */
3320 	ndp = __containerof(cnp, struct nameidata, ni_cnd);
3321 	if (!seqc_in_modify(ndp->ni_dvp_seqc) &&
3322 	    vn_seqc_consistent(dvp, ndp->ni_dvp_seqc) &&
3323 	    (vp == NULL || (!seqc_in_modify(ndp->ni_vp_seqc) &&
3324 	    vn_seqc_consistent(vp, ndp->ni_vp_seqc))))
3325 		return (0);
3326 
3327 	stat_journal_low++;
3328 	if (vp != NULL) {
3329 		VOP_UNLOCK(dvp);
3330 		ffs_syncvnode(vp, MNT_NOWAIT, 0);
3331 		vn_lock_pair(dvp, false, LK_EXCLUSIVE, vp, true, LK_EXCLUSIVE);
3332 		if (dvp->v_data == NULL)
3333 			goto out;
3334 	}
3335 	if (vp != NULL)
3336 		VOP_UNLOCK(vp);
3337 	ffs_syncvnode(dvp, MNT_WAIT, 0);
3338 	/* Process vp before dvp as it may create .. removes. */
3339 	if (vp != NULL) {
3340 		VOP_UNLOCK(dvp);
3341 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3342 		if (vp->v_data == NULL) {
3343 			vn_lock_pair(dvp, false, LK_EXCLUSIVE, vp, true,
3344 			    LK_EXCLUSIVE);
3345 			goto out;
3346 		}
3347 		ACQUIRE_LOCK(ump);
3348 		process_removes(vp);
3349 		process_truncates(vp);
3350 		FREE_LOCK(ump);
3351 		VOP_UNLOCK(vp);
3352 		vn_lock(dvp, LK_EXCLUSIVE | LK_RETRY);
3353 		if (dvp->v_data == NULL) {
3354 			vn_lock_pair(dvp, true, LK_EXCLUSIVE, vp, false,
3355 			    LK_EXCLUSIVE);
3356 			goto out;
3357 		}
3358 	}
3359 
3360 	ACQUIRE_LOCK(ump);
3361 	process_removes(dvp);
3362 	process_truncates(dvp);
3363 	VOP_UNLOCK(dvp);
3364 	softdep_speedup(ump);
3365 
3366 	process_worklist_item(UFSTOVFS(ump), 2, LK_NOWAIT);
3367 	journal_check_space(ump);
3368 	FREE_LOCK(ump);
3369 
3370 	vn_lock_pair(dvp, false, LK_EXCLUSIVE, vp, false, LK_EXCLUSIVE);
3371 out:
3372 	ndp->ni_dvp_seqc = vn_seqc_read_any(dvp);
3373 	if (vp != NULL)
3374 		ndp->ni_vp_seqc = vn_seqc_read_any(vp);
3375 	return (ERELOOKUP);
3376 }
3377 
3378 static void
3379 jseg_write(struct ufsmount *ump,
3380 	struct jseg *jseg,
3381 	uint8_t *data)
3382 {
3383 	struct jsegrec *rec;
3384 
3385 	rec = (struct jsegrec *)data;
3386 	rec->jsr_seq = jseg->js_seq;
3387 	rec->jsr_oldest = jseg->js_oldseq;
3388 	rec->jsr_cnt = jseg->js_cnt;
3389 	rec->jsr_blocks = jseg->js_size / ump->um_devvp->v_bufobj.bo_bsize;
3390 	rec->jsr_crc = 0;
3391 	rec->jsr_time = ump->um_fs->fs_mtime;
3392 }
3393 
3394 static inline void
3395 inoref_write(struct inoref *inoref,
3396 	struct jseg *jseg,
3397 	struct jrefrec *rec)
3398 {
3399 
3400 	inoref->if_jsegdep->jd_seg = jseg;
3401 	rec->jr_ino = inoref->if_ino;
3402 	rec->jr_parent = inoref->if_parent;
3403 	rec->jr_nlink = inoref->if_nlink;
3404 	rec->jr_mode = inoref->if_mode;
3405 	rec->jr_diroff = inoref->if_diroff;
3406 }
3407 
3408 static void
3409 jaddref_write(struct jaddref *jaddref,
3410 	struct jseg *jseg,
3411 	uint8_t *data)
3412 {
3413 	struct jrefrec *rec;
3414 
3415 	rec = (struct jrefrec *)data;
3416 	rec->jr_op = JOP_ADDREF;
3417 	inoref_write(&jaddref->ja_ref, jseg, rec);
3418 }
3419 
3420 static void
3421 jremref_write(struct jremref *jremref,
3422 	struct jseg *jseg,
3423 	uint8_t *data)
3424 {
3425 	struct jrefrec *rec;
3426 
3427 	rec = (struct jrefrec *)data;
3428 	rec->jr_op = JOP_REMREF;
3429 	inoref_write(&jremref->jr_ref, jseg, rec);
3430 }
3431 
3432 static void
3433 jmvref_write(struct jmvref *jmvref,
3434 	struct jseg *jseg,
3435 	uint8_t *data)
3436 {
3437 	struct jmvrec *rec;
3438 
3439 	rec = (struct jmvrec *)data;
3440 	rec->jm_op = JOP_MVREF;
3441 	rec->jm_ino = jmvref->jm_ino;
3442 	rec->jm_parent = jmvref->jm_parent;
3443 	rec->jm_oldoff = jmvref->jm_oldoff;
3444 	rec->jm_newoff = jmvref->jm_newoff;
3445 }
3446 
3447 static void
3448 jnewblk_write(struct jnewblk *jnewblk,
3449 	struct jseg *jseg,
3450 	uint8_t *data)
3451 {
3452 	struct jblkrec *rec;
3453 
3454 	jnewblk->jn_jsegdep->jd_seg = jseg;
3455 	rec = (struct jblkrec *)data;
3456 	rec->jb_op = JOP_NEWBLK;
3457 	rec->jb_ino = jnewblk->jn_ino;
3458 	rec->jb_blkno = jnewblk->jn_blkno;
3459 	rec->jb_lbn = jnewblk->jn_lbn;
3460 	rec->jb_frags = jnewblk->jn_frags;
3461 	rec->jb_oldfrags = jnewblk->jn_oldfrags;
3462 }
3463 
3464 static void
3465 jfreeblk_write(struct jfreeblk *jfreeblk,
3466 	struct jseg *jseg,
3467 	uint8_t *data)
3468 {
3469 	struct jblkrec *rec;
3470 
3471 	jfreeblk->jf_dep.jb_jsegdep->jd_seg = jseg;
3472 	rec = (struct jblkrec *)data;
3473 	rec->jb_op = JOP_FREEBLK;
3474 	rec->jb_ino = jfreeblk->jf_ino;
3475 	rec->jb_blkno = jfreeblk->jf_blkno;
3476 	rec->jb_lbn = jfreeblk->jf_lbn;
3477 	rec->jb_frags = jfreeblk->jf_frags;
3478 	rec->jb_oldfrags = 0;
3479 }
3480 
3481 static void
3482 jfreefrag_write(struct jfreefrag *jfreefrag,
3483 	struct jseg *jseg,
3484 	uint8_t *data)
3485 {
3486 	struct jblkrec *rec;
3487 
3488 	jfreefrag->fr_jsegdep->jd_seg = jseg;
3489 	rec = (struct jblkrec *)data;
3490 	rec->jb_op = JOP_FREEBLK;
3491 	rec->jb_ino = jfreefrag->fr_ino;
3492 	rec->jb_blkno = jfreefrag->fr_blkno;
3493 	rec->jb_lbn = jfreefrag->fr_lbn;
3494 	rec->jb_frags = jfreefrag->fr_frags;
3495 	rec->jb_oldfrags = 0;
3496 }
3497 
3498 static void
3499 jtrunc_write(struct jtrunc *jtrunc,
3500 	struct jseg *jseg,
3501 	uint8_t *data)
3502 {
3503 	struct jtrncrec *rec;
3504 
3505 	jtrunc->jt_dep.jb_jsegdep->jd_seg = jseg;
3506 	rec = (struct jtrncrec *)data;
3507 	rec->jt_op = JOP_TRUNC;
3508 	rec->jt_ino = jtrunc->jt_ino;
3509 	rec->jt_size = jtrunc->jt_size;
3510 	rec->jt_extsize = jtrunc->jt_extsize;
3511 }
3512 
3513 static void
3514 jfsync_write(struct jfsync *jfsync,
3515 	struct jseg *jseg,
3516 	uint8_t *data)
3517 {
3518 	struct jtrncrec *rec;
3519 
3520 	rec = (struct jtrncrec *)data;
3521 	rec->jt_op = JOP_SYNC;
3522 	rec->jt_ino = jfsync->jfs_ino;
3523 	rec->jt_size = jfsync->jfs_size;
3524 	rec->jt_extsize = jfsync->jfs_extsize;
3525 }
3526 
3527 static void
3528 softdep_flushjournal(struct mount *mp)
3529 {
3530 	struct jblocks *jblocks;
3531 	struct ufsmount *ump;
3532 
3533 	if (MOUNTEDSUJ(mp) == 0)
3534 		return;
3535 	ump = VFSTOUFS(mp);
3536 	jblocks = ump->softdep_jblocks;
3537 	ACQUIRE_LOCK(ump);
3538 	while (ump->softdep_on_journal) {
3539 		jblocks->jb_needseg = 1;
3540 		softdep_process_journal(mp, NULL, MNT_WAIT);
3541 	}
3542 	FREE_LOCK(ump);
3543 }
3544 
3545 static void softdep_synchronize_completed(struct bio *);
3546 static void softdep_synchronize(struct bio *, struct ufsmount *, void *);
3547 
3548 static void
3549 softdep_synchronize_completed(struct bio *bp)
3550 {
3551 	struct jseg *oldest;
3552 	struct jseg *jseg;
3553 	struct ufsmount *ump;
3554 
3555 	/*
3556 	 * caller1 marks the last segment written before we issued the
3557 	 * synchronize cache.
3558 	 */
3559 	jseg = bp->bio_caller1;
3560 	if (jseg == NULL) {
3561 		g_destroy_bio(bp);
3562 		return;
3563 	}
3564 	ump = VFSTOUFS(jseg->js_list.wk_mp);
3565 	ACQUIRE_LOCK(ump);
3566 	oldest = NULL;
3567 	/*
3568 	 * Mark all the journal entries waiting on the synchronize cache
3569 	 * as completed so they may continue on.
3570 	 */
3571 	while (jseg != NULL && (jseg->js_state & COMPLETE) == 0) {
3572 		jseg->js_state |= COMPLETE;
3573 		oldest = jseg;
3574 		jseg = TAILQ_PREV(jseg, jseglst, js_next);
3575 	}
3576 	/*
3577 	 * Restart deferred journal entry processing from the oldest
3578 	 * completed jseg.
3579 	 */
3580 	if (oldest)
3581 		complete_jsegs(oldest);
3582 
3583 	FREE_LOCK(ump);
3584 	g_destroy_bio(bp);
3585 }
3586 
3587 /*
3588  * Send BIO_FLUSH/SYNCHRONIZE CACHE to the device to enforce write ordering
3589  * barriers.  The journal must be written prior to any blocks that depend
3590  * on it and the journal can not be released until the blocks have be
3591  * written.  This code handles both barriers simultaneously.
3592  */
3593 static void
3594 softdep_synchronize(struct bio *bp,
3595 	struct ufsmount *ump,
3596 	void *caller1)
3597 {
3598 
3599 	bp->bio_cmd = BIO_FLUSH;
3600 	bp->bio_flags |= BIO_ORDERED;
3601 	bp->bio_data = NULL;
3602 	bp->bio_offset = ump->um_cp->provider->mediasize;
3603 	bp->bio_length = 0;
3604 	bp->bio_done = softdep_synchronize_completed;
3605 	bp->bio_caller1 = caller1;
3606 	g_io_request(bp, ump->um_cp);
3607 }
3608 
3609 /*
3610  * Flush some journal records to disk.
3611  */
3612 static void
3613 softdep_process_journal(struct mount *mp,
3614 	struct worklist *needwk,
3615 	int flags)
3616 {
3617 	struct jblocks *jblocks;
3618 	struct ufsmount *ump;
3619 	struct worklist *wk;
3620 	struct jseg *jseg;
3621 	struct buf *bp;
3622 	struct bio *bio;
3623 	uint8_t *data;
3624 	struct fs *fs;
3625 	int shouldflush;
3626 	int segwritten;
3627 	int jrecmin;	/* Minimum records per block. */
3628 	int jrecmax;	/* Maximum records per block. */
3629 	int size;
3630 	int cnt;
3631 	int off;
3632 	int devbsize;
3633 
3634 	ump = VFSTOUFS(mp);
3635 	if (ump->um_softdep == NULL || ump->um_softdep->sd_jblocks == NULL)
3636 		return;
3637 	shouldflush = softdep_flushcache;
3638 	bio = NULL;
3639 	jseg = NULL;
3640 	LOCK_OWNED(ump);
3641 	fs = ump->um_fs;
3642 	jblocks = ump->softdep_jblocks;
3643 	devbsize = ump->um_devvp->v_bufobj.bo_bsize;
3644 	/*
3645 	 * We write anywhere between a disk block and fs block.  The upper
3646 	 * bound is picked to prevent buffer cache fragmentation and limit
3647 	 * processing time per I/O.
3648 	 */
3649 	jrecmin = (devbsize / JREC_SIZE) - 1; /* -1 for seg header */
3650 	jrecmax = (fs->fs_bsize / devbsize) * jrecmin;
3651 	segwritten = 0;
3652 	for (;;) {
3653 		cnt = ump->softdep_on_journal;
3654 		/*
3655 		 * Criteria for writing a segment:
3656 		 * 1) We have a full block.
3657 		 * 2) We're called from jwait() and haven't found the
3658 		 *    journal item yet.
3659 		 * 3) Always write if needseg is set.
3660 		 * 4) If we are called from process_worklist and have
3661 		 *    not yet written anything we write a partial block
3662 		 *    to enforce a 1 second maximum latency on journal
3663 		 *    entries.
3664 		 */
3665 		if (cnt < (jrecmax - 1) && needwk == NULL &&
3666 		    jblocks->jb_needseg == 0 && (segwritten || cnt == 0))
3667 			break;
3668 		cnt++;
3669 		/*
3670 		 * Verify some free journal space.  softdep_prealloc() should
3671 		 * guarantee that we don't run out so this is indicative of
3672 		 * a problem with the flow control.  Try to recover
3673 		 * gracefully in any event.
3674 		 */
3675 		while (jblocks->jb_free == 0) {
3676 			if (flags != MNT_WAIT)
3677 				break;
3678 			printf("softdep: Out of journal space!\n");
3679 			softdep_speedup(ump);
3680 			msleep(jblocks, LOCK_PTR(ump), PRIBIO, "jblocks", hz);
3681 		}
3682 		FREE_LOCK(ump);
3683 		jseg = malloc(sizeof(*jseg), M_JSEG, M_SOFTDEP_FLAGS);
3684 		workitem_alloc(&jseg->js_list, D_JSEG, mp);
3685 		LIST_INIT(&jseg->js_entries);
3686 		LIST_INIT(&jseg->js_indirs);
3687 		jseg->js_state = ATTACHED;
3688 		if (shouldflush == 0)
3689 			jseg->js_state |= COMPLETE;
3690 		else if (bio == NULL)
3691 			bio = g_alloc_bio();
3692 		jseg->js_jblocks = jblocks;
3693 		bp = geteblk(fs->fs_bsize, 0);
3694 		ACQUIRE_LOCK(ump);
3695 		/*
3696 		 * If there was a race while we were allocating the block
3697 		 * and jseg the entry we care about was likely written.
3698 		 * We bail out in both the WAIT and NOWAIT case and assume
3699 		 * the caller will loop if the entry it cares about is
3700 		 * not written.
3701 		 */
3702 		cnt = ump->softdep_on_journal;
3703 		if (cnt + jblocks->jb_needseg == 0 || jblocks->jb_free == 0) {
3704 			bp->b_flags |= B_INVAL | B_NOCACHE;
3705 			WORKITEM_FREE(jseg, D_JSEG);
3706 			FREE_LOCK(ump);
3707 			brelse(bp);
3708 			ACQUIRE_LOCK(ump);
3709 			break;
3710 		}
3711 		/*
3712 		 * Calculate the disk block size required for the available
3713 		 * records rounded to the min size.
3714 		 */
3715 		if (cnt == 0)
3716 			size = devbsize;
3717 		else if (cnt < jrecmax)
3718 			size = howmany(cnt, jrecmin) * devbsize;
3719 		else
3720 			size = fs->fs_bsize;
3721 		/*
3722 		 * Allocate a disk block for this journal data and account
3723 		 * for truncation of the requested size if enough contiguous
3724 		 * space was not available.
3725 		 */
3726 		bp->b_blkno = jblocks_alloc(jblocks, size, &size);
3727 		bp->b_lblkno = bp->b_blkno;
3728 		bp->b_offset = bp->b_blkno * DEV_BSIZE;
3729 		bp->b_bcount = size;
3730 		bp->b_flags &= ~B_INVAL;
3731 		bp->b_flags |= B_VALIDSUSPWRT | B_NOCOPY;
3732 		/*
3733 		 * Initialize our jseg with cnt records.  Assign the next
3734 		 * sequence number to it and link it in-order.
3735 		 */
3736 		cnt = MIN(cnt, (size / devbsize) * jrecmin);
3737 		jseg->js_buf = bp;
3738 		jseg->js_cnt = cnt;
3739 		jseg->js_refs = cnt + 1;	/* Self ref. */
3740 		jseg->js_size = size;
3741 		jseg->js_seq = jblocks->jb_nextseq++;
3742 		if (jblocks->jb_oldestseg == NULL)
3743 			jblocks->jb_oldestseg = jseg;
3744 		jseg->js_oldseq = jblocks->jb_oldestseg->js_seq;
3745 		TAILQ_INSERT_TAIL(&jblocks->jb_segs, jseg, js_next);
3746 		if (jblocks->jb_writeseg == NULL)
3747 			jblocks->jb_writeseg = jseg;
3748 		/*
3749 		 * Start filling in records from the pending list.
3750 		 */
3751 		data = bp->b_data;
3752 		off = 0;
3753 
3754 		/*
3755 		 * Always put a header on the first block.
3756 		 * XXX As with below, there might not be a chance to get
3757 		 * into the loop.  Ensure that something valid is written.
3758 		 */
3759 		jseg_write(ump, jseg, data);
3760 		off += JREC_SIZE;
3761 		data = bp->b_data + off;
3762 
3763 		/*
3764 		 * XXX Something is wrong here.  There's no work to do,
3765 		 * but we need to perform and I/O and allow it to complete
3766 		 * anyways.
3767 		 */
3768 		if (LIST_EMPTY(&ump->softdep_journal_pending))
3769 			stat_emptyjblocks++;
3770 
3771 		while ((wk = LIST_FIRST(&ump->softdep_journal_pending))
3772 		    != NULL) {
3773 			if (cnt == 0)
3774 				break;
3775 			/* Place a segment header on every device block. */
3776 			if ((off % devbsize) == 0) {
3777 				jseg_write(ump, jseg, data);
3778 				off += JREC_SIZE;
3779 				data = bp->b_data + off;
3780 			}
3781 			if (wk == needwk)
3782 				needwk = NULL;
3783 			remove_from_journal(wk);
3784 			wk->wk_state |= INPROGRESS;
3785 			WORKLIST_INSERT(&jseg->js_entries, wk);
3786 			switch (wk->wk_type) {
3787 			case D_JADDREF:
3788 				jaddref_write(WK_JADDREF(wk), jseg, data);
3789 				break;
3790 			case D_JREMREF:
3791 				jremref_write(WK_JREMREF(wk), jseg, data);
3792 				break;
3793 			case D_JMVREF:
3794 				jmvref_write(WK_JMVREF(wk), jseg, data);
3795 				break;
3796 			case D_JNEWBLK:
3797 				jnewblk_write(WK_JNEWBLK(wk), jseg, data);
3798 				break;
3799 			case D_JFREEBLK:
3800 				jfreeblk_write(WK_JFREEBLK(wk), jseg, data);
3801 				break;
3802 			case D_JFREEFRAG:
3803 				jfreefrag_write(WK_JFREEFRAG(wk), jseg, data);
3804 				break;
3805 			case D_JTRUNC:
3806 				jtrunc_write(WK_JTRUNC(wk), jseg, data);
3807 				break;
3808 			case D_JFSYNC:
3809 				jfsync_write(WK_JFSYNC(wk), jseg, data);
3810 				break;
3811 			default:
3812 				panic("process_journal: Unknown type %s",
3813 				    TYPENAME(wk->wk_type));
3814 				/* NOTREACHED */
3815 			}
3816 			off += JREC_SIZE;
3817 			data = bp->b_data + off;
3818 			cnt--;
3819 		}
3820 
3821 		/* Clear any remaining space so we don't leak kernel data */
3822 		if (size > off)
3823 			bzero(data, size - off);
3824 
3825 		/*
3826 		 * Write this one buffer and continue.
3827 		 */
3828 		segwritten = 1;
3829 		jblocks->jb_needseg = 0;
3830 		WORKLIST_INSERT(&bp->b_dep, &jseg->js_list);
3831 		FREE_LOCK(ump);
3832 		bp->b_xflags |= BX_CVTENXIO;
3833 		pbgetvp(ump->um_devvp, bp);
3834 		/*
3835 		 * We only do the blocking wait once we find the journal
3836 		 * entry we're looking for.
3837 		 */
3838 		if (needwk == NULL && flags == MNT_WAIT)
3839 			bwrite(bp);
3840 		else
3841 			bawrite(bp);
3842 		ACQUIRE_LOCK(ump);
3843 	}
3844 	/*
3845 	 * If we wrote a segment issue a synchronize cache so the journal
3846 	 * is reflected on disk before the data is written.  Since reclaiming
3847 	 * journal space also requires writing a journal record this
3848 	 * process also enforces a barrier before reclamation.
3849 	 */
3850 	if (segwritten && shouldflush) {
3851 		softdep_synchronize(bio, ump,
3852 		    TAILQ_LAST(&jblocks->jb_segs, jseglst));
3853 	} else if (bio)
3854 		g_destroy_bio(bio);
3855 	/*
3856 	 * If we've suspended the filesystem because we ran out of journal
3857 	 * space either try to sync it here to make some progress or
3858 	 * unsuspend it if we already have.
3859 	 */
3860 	if (flags == 0 && jblocks->jb_suspended) {
3861 		if (journal_unsuspend(ump))
3862 			return;
3863 		FREE_LOCK(ump);
3864 		VFS_SYNC(mp, MNT_NOWAIT);
3865 		ffs_sbupdate(ump, MNT_WAIT, 0);
3866 		ACQUIRE_LOCK(ump);
3867 	}
3868 }
3869 
3870 /*
3871  * Complete a jseg, allowing all dependencies awaiting journal writes
3872  * to proceed.  Each journal dependency also attaches a jsegdep to dependent
3873  * structures so that the journal segment can be freed to reclaim space.
3874  */
3875 static void
3876 complete_jseg(struct jseg *jseg)
3877 {
3878 	struct worklist *wk;
3879 	struct jmvref *jmvref;
3880 #ifdef INVARIANTS
3881 	int i = 0;
3882 #endif
3883 
3884 	while ((wk = LIST_FIRST(&jseg->js_entries)) != NULL) {
3885 		WORKLIST_REMOVE(wk);
3886 		wk->wk_state &= ~INPROGRESS;
3887 		wk->wk_state |= COMPLETE;
3888 		KASSERT(i++ < jseg->js_cnt,
3889 		    ("handle_written_jseg: overflow %d >= %d",
3890 		    i - 1, jseg->js_cnt));
3891 		switch (wk->wk_type) {
3892 		case D_JADDREF:
3893 			handle_written_jaddref(WK_JADDREF(wk));
3894 			break;
3895 		case D_JREMREF:
3896 			handle_written_jremref(WK_JREMREF(wk));
3897 			break;
3898 		case D_JMVREF:
3899 			rele_jseg(jseg);	/* No jsegdep. */
3900 			jmvref = WK_JMVREF(wk);
3901 			LIST_REMOVE(jmvref, jm_deps);
3902 			if ((jmvref->jm_pagedep->pd_state & ONWORKLIST) == 0)
3903 				free_pagedep(jmvref->jm_pagedep);
3904 			WORKITEM_FREE(jmvref, D_JMVREF);
3905 			break;
3906 		case D_JNEWBLK:
3907 			handle_written_jnewblk(WK_JNEWBLK(wk));
3908 			break;
3909 		case D_JFREEBLK:
3910 			handle_written_jblkdep(&WK_JFREEBLK(wk)->jf_dep);
3911 			break;
3912 		case D_JTRUNC:
3913 			handle_written_jblkdep(&WK_JTRUNC(wk)->jt_dep);
3914 			break;
3915 		case D_JFSYNC:
3916 			rele_jseg(jseg);	/* No jsegdep. */
3917 			WORKITEM_FREE(wk, D_JFSYNC);
3918 			break;
3919 		case D_JFREEFRAG:
3920 			handle_written_jfreefrag(WK_JFREEFRAG(wk));
3921 			break;
3922 		default:
3923 			panic("handle_written_jseg: Unknown type %s",
3924 			    TYPENAME(wk->wk_type));
3925 			/* NOTREACHED */
3926 		}
3927 	}
3928 	/* Release the self reference so the structure may be freed. */
3929 	rele_jseg(jseg);
3930 }
3931 
3932 /*
3933  * Determine which jsegs are ready for completion processing.  Waits for
3934  * synchronize cache to complete as well as forcing in-order completion
3935  * of journal entries.
3936  */
3937 static void
3938 complete_jsegs(struct jseg *jseg)
3939 {
3940 	struct jblocks *jblocks;
3941 	struct jseg *jsegn;
3942 
3943 	jblocks = jseg->js_jblocks;
3944 	/*
3945 	 * Don't allow out of order completions.  If this isn't the first
3946 	 * block wait for it to write before we're done.
3947 	 */
3948 	if (jseg != jblocks->jb_writeseg)
3949 		return;
3950 	/* Iterate through available jsegs processing their entries. */
3951 	while (jseg && (jseg->js_state & ALLCOMPLETE) == ALLCOMPLETE) {
3952 		jblocks->jb_oldestwrseq = jseg->js_oldseq;
3953 		jsegn = TAILQ_NEXT(jseg, js_next);
3954 		complete_jseg(jseg);
3955 		jseg = jsegn;
3956 	}
3957 	jblocks->jb_writeseg = jseg;
3958 	/*
3959 	 * Attempt to free jsegs now that oldestwrseq may have advanced.
3960 	 */
3961 	free_jsegs(jblocks);
3962 }
3963 
3964 /*
3965  * Mark a jseg as DEPCOMPLETE and throw away the buffer.  Attempt to handle
3966  * the final completions.
3967  */
3968 static void
3969 handle_written_jseg(struct jseg *jseg, struct buf *bp)
3970 {
3971 
3972 	if (jseg->js_refs == 0)
3973 		panic("handle_written_jseg: No self-reference on %p", jseg);
3974 	jseg->js_state |= DEPCOMPLETE;
3975 	/*
3976 	 * We'll never need this buffer again, set flags so it will be
3977 	 * discarded.
3978 	 */
3979 	bp->b_flags |= B_INVAL | B_NOCACHE;
3980 	pbrelvp(bp);
3981 	complete_jsegs(jseg);
3982 }
3983 
3984 static inline struct jsegdep *
3985 inoref_jseg(struct inoref *inoref)
3986 {
3987 	struct jsegdep *jsegdep;
3988 
3989 	jsegdep = inoref->if_jsegdep;
3990 	inoref->if_jsegdep = NULL;
3991 
3992 	return (jsegdep);
3993 }
3994 
3995 /*
3996  * Called once a jremref has made it to stable store.  The jremref is marked
3997  * complete and we attempt to free it.  Any pagedeps writes sleeping waiting
3998  * for the jremref to complete will be awoken by free_jremref.
3999  */
4000 static void
4001 handle_written_jremref(struct jremref *jremref)
4002 {
4003 	struct inodedep *inodedep;
4004 	struct jsegdep *jsegdep;
4005 	struct dirrem *dirrem;
4006 
4007 	/* Grab the jsegdep. */
4008 	jsegdep = inoref_jseg(&jremref->jr_ref);
4009 	/*
4010 	 * Remove us from the inoref list.
4011 	 */
4012 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino,
4013 	    0, &inodedep) == 0)
4014 		panic("handle_written_jremref: Lost inodedep");
4015 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
4016 	/*
4017 	 * Complete the dirrem.
4018 	 */
4019 	dirrem = jremref->jr_dirrem;
4020 	jremref->jr_dirrem = NULL;
4021 	LIST_REMOVE(jremref, jr_deps);
4022 	jsegdep->jd_state |= jremref->jr_state & MKDIR_PARENT;
4023 	jwork_insert(&dirrem->dm_jwork, jsegdep);
4024 	if (LIST_EMPTY(&dirrem->dm_jremrefhd) &&
4025 	    (dirrem->dm_state & COMPLETE) != 0)
4026 		add_to_worklist(&dirrem->dm_list, 0);
4027 	free_jremref(jremref);
4028 }
4029 
4030 /*
4031  * Called once a jaddref has made it to stable store.  The dependency is
4032  * marked complete and any dependent structures are added to the inode
4033  * bufwait list to be completed as soon as it is written.  If a bitmap write
4034  * depends on this entry we move the inode into the inodedephd of the
4035  * bmsafemap dependency and attempt to remove the jaddref from the bmsafemap.
4036  */
4037 static void
4038 handle_written_jaddref(struct jaddref *jaddref)
4039 {
4040 	struct jsegdep *jsegdep;
4041 	struct inodedep *inodedep;
4042 	struct diradd *diradd;
4043 	struct mkdir *mkdir;
4044 
4045 	/* Grab the jsegdep. */
4046 	jsegdep = inoref_jseg(&jaddref->ja_ref);
4047 	mkdir = NULL;
4048 	diradd = NULL;
4049 	if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
4050 	    0, &inodedep) == 0)
4051 		panic("handle_written_jaddref: Lost inodedep.");
4052 	if (jaddref->ja_diradd == NULL)
4053 		panic("handle_written_jaddref: No dependency");
4054 	if (jaddref->ja_diradd->da_list.wk_type == D_DIRADD) {
4055 		diradd = jaddref->ja_diradd;
4056 		WORKLIST_INSERT(&inodedep->id_bufwait, &diradd->da_list);
4057 	} else if (jaddref->ja_state & MKDIR_PARENT) {
4058 		mkdir = jaddref->ja_mkdir;
4059 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir->md_list);
4060 	} else if (jaddref->ja_state & MKDIR_BODY)
4061 		mkdir = jaddref->ja_mkdir;
4062 	else
4063 		panic("handle_written_jaddref: Unknown dependency %p",
4064 		    jaddref->ja_diradd);
4065 	jaddref->ja_diradd = NULL;	/* also clears ja_mkdir */
4066 	/*
4067 	 * Remove us from the inode list.
4068 	 */
4069 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref, if_deps);
4070 	/*
4071 	 * The mkdir may be waiting on the jaddref to clear before freeing.
4072 	 */
4073 	if (mkdir) {
4074 		KASSERT(mkdir->md_list.wk_type == D_MKDIR,
4075 		    ("handle_written_jaddref: Incorrect type for mkdir %s",
4076 		    TYPENAME(mkdir->md_list.wk_type)));
4077 		mkdir->md_jaddref = NULL;
4078 		diradd = mkdir->md_diradd;
4079 		mkdir->md_state |= DEPCOMPLETE;
4080 		complete_mkdir(mkdir);
4081 	}
4082 	jwork_insert(&diradd->da_jwork, jsegdep);
4083 	if (jaddref->ja_state & NEWBLOCK) {
4084 		inodedep->id_state |= ONDEPLIST;
4085 		LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_inodedephd,
4086 		    inodedep, id_deps);
4087 	}
4088 	free_jaddref(jaddref);
4089 }
4090 
4091 /*
4092  * Called once a jnewblk journal is written.  The allocdirect or allocindir
4093  * is placed in the bmsafemap to await notification of a written bitmap.  If
4094  * the operation was canceled we add the segdep to the appropriate
4095  * dependency to free the journal space once the canceling operation
4096  * completes.
4097  */
4098 static void
4099 handle_written_jnewblk(struct jnewblk *jnewblk)
4100 {
4101 	struct bmsafemap *bmsafemap;
4102 	struct freefrag *freefrag;
4103 	struct freework *freework;
4104 	struct jsegdep *jsegdep;
4105 	struct newblk *newblk;
4106 
4107 	/* Grab the jsegdep. */
4108 	jsegdep = jnewblk->jn_jsegdep;
4109 	jnewblk->jn_jsegdep = NULL;
4110 	if (jnewblk->jn_dep == NULL)
4111 		panic("handle_written_jnewblk: No dependency for the segdep.");
4112 	switch (jnewblk->jn_dep->wk_type) {
4113 	case D_NEWBLK:
4114 	case D_ALLOCDIRECT:
4115 	case D_ALLOCINDIR:
4116 		/*
4117 		 * Add the written block to the bmsafemap so it can
4118 		 * be notified when the bitmap is on disk.
4119 		 */
4120 		newblk = WK_NEWBLK(jnewblk->jn_dep);
4121 		newblk->nb_jnewblk = NULL;
4122 		if ((newblk->nb_state & GOINGAWAY) == 0) {
4123 			bmsafemap = newblk->nb_bmsafemap;
4124 			newblk->nb_state |= ONDEPLIST;
4125 			LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk,
4126 			    nb_deps);
4127 		}
4128 		jwork_insert(&newblk->nb_jwork, jsegdep);
4129 		break;
4130 	case D_FREEFRAG:
4131 		/*
4132 		 * A newblock being removed by a freefrag when replaced by
4133 		 * frag extension.
4134 		 */
4135 		freefrag = WK_FREEFRAG(jnewblk->jn_dep);
4136 		freefrag->ff_jdep = NULL;
4137 		jwork_insert(&freefrag->ff_jwork, jsegdep);
4138 		break;
4139 	case D_FREEWORK:
4140 		/*
4141 		 * A direct block was removed by truncate.
4142 		 */
4143 		freework = WK_FREEWORK(jnewblk->jn_dep);
4144 		freework->fw_jnewblk = NULL;
4145 		jwork_insert(&freework->fw_freeblks->fb_jwork, jsegdep);
4146 		break;
4147 	default:
4148 		panic("handle_written_jnewblk: Unknown type %d.",
4149 		    jnewblk->jn_dep->wk_type);
4150 	}
4151 	jnewblk->jn_dep = NULL;
4152 	free_jnewblk(jnewblk);
4153 }
4154 
4155 /*
4156  * Cancel a jfreefrag that won't be needed, probably due to colliding with
4157  * an in-flight allocation that has not yet been committed.  Divorce us
4158  * from the freefrag and mark it DEPCOMPLETE so that it may be added
4159  * to the worklist.
4160  */
4161 static void
4162 cancel_jfreefrag(struct jfreefrag *jfreefrag)
4163 {
4164 	struct freefrag *freefrag;
4165 
4166 	if (jfreefrag->fr_jsegdep) {
4167 		free_jsegdep(jfreefrag->fr_jsegdep);
4168 		jfreefrag->fr_jsegdep = NULL;
4169 	}
4170 	freefrag = jfreefrag->fr_freefrag;
4171 	jfreefrag->fr_freefrag = NULL;
4172 	free_jfreefrag(jfreefrag);
4173 	freefrag->ff_state |= DEPCOMPLETE;
4174 	CTR1(KTR_SUJ, "cancel_jfreefrag: blkno %jd", freefrag->ff_blkno);
4175 }
4176 
4177 /*
4178  * Free a jfreefrag when the parent freefrag is rendered obsolete.
4179  */
4180 static void
4181 free_jfreefrag(struct jfreefrag *jfreefrag)
4182 {
4183 
4184 	if (jfreefrag->fr_state & INPROGRESS)
4185 		WORKLIST_REMOVE(&jfreefrag->fr_list);
4186 	else if (jfreefrag->fr_state & ONWORKLIST)
4187 		remove_from_journal(&jfreefrag->fr_list);
4188 	if (jfreefrag->fr_freefrag != NULL)
4189 		panic("free_jfreefrag:  Still attached to a freefrag.");
4190 	WORKITEM_FREE(jfreefrag, D_JFREEFRAG);
4191 }
4192 
4193 /*
4194  * Called when the journal write for a jfreefrag completes.  The parent
4195  * freefrag is added to the worklist if this completes its dependencies.
4196  */
4197 static void
4198 handle_written_jfreefrag(struct jfreefrag *jfreefrag)
4199 {
4200 	struct jsegdep *jsegdep;
4201 	struct freefrag *freefrag;
4202 
4203 	/* Grab the jsegdep. */
4204 	jsegdep = jfreefrag->fr_jsegdep;
4205 	jfreefrag->fr_jsegdep = NULL;
4206 	freefrag = jfreefrag->fr_freefrag;
4207 	if (freefrag == NULL)
4208 		panic("handle_written_jfreefrag: No freefrag.");
4209 	freefrag->ff_state |= DEPCOMPLETE;
4210 	freefrag->ff_jdep = NULL;
4211 	jwork_insert(&freefrag->ff_jwork, jsegdep);
4212 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
4213 		add_to_worklist(&freefrag->ff_list, 0);
4214 	jfreefrag->fr_freefrag = NULL;
4215 	free_jfreefrag(jfreefrag);
4216 }
4217 
4218 /*
4219  * Called when the journal write for a jfreeblk completes.  The jfreeblk
4220  * is removed from the freeblks list of pending journal writes and the
4221  * jsegdep is moved to the freeblks jwork to be completed when all blocks
4222  * have been reclaimed.
4223  */
4224 static void
4225 handle_written_jblkdep(struct jblkdep *jblkdep)
4226 {
4227 	struct freeblks *freeblks;
4228 	struct jsegdep *jsegdep;
4229 
4230 	/* Grab the jsegdep. */
4231 	jsegdep = jblkdep->jb_jsegdep;
4232 	jblkdep->jb_jsegdep = NULL;
4233 	freeblks = jblkdep->jb_freeblks;
4234 	LIST_REMOVE(jblkdep, jb_deps);
4235 	jwork_insert(&freeblks->fb_jwork, jsegdep);
4236 	/*
4237 	 * If the freeblks is all journaled, we can add it to the worklist.
4238 	 */
4239 	if (LIST_EMPTY(&freeblks->fb_jblkdephd) &&
4240 	    (freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
4241 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
4242 
4243 	free_jblkdep(jblkdep);
4244 }
4245 
4246 static struct jsegdep *
4247 newjsegdep(struct worklist *wk)
4248 {
4249 	struct jsegdep *jsegdep;
4250 
4251 	jsegdep = malloc(sizeof(*jsegdep), M_JSEGDEP, M_SOFTDEP_FLAGS);
4252 	workitem_alloc(&jsegdep->jd_list, D_JSEGDEP, wk->wk_mp);
4253 	jsegdep->jd_seg = NULL;
4254 
4255 	return (jsegdep);
4256 }
4257 
4258 static struct jmvref *
4259 newjmvref(struct inode *dp,
4260 	ino_t ino,
4261 	off_t oldoff,
4262 	off_t newoff)
4263 {
4264 	struct jmvref *jmvref;
4265 
4266 	jmvref = malloc(sizeof(*jmvref), M_JMVREF, M_SOFTDEP_FLAGS);
4267 	workitem_alloc(&jmvref->jm_list, D_JMVREF, ITOVFS(dp));
4268 	jmvref->jm_list.wk_state = ATTACHED | DEPCOMPLETE;
4269 	jmvref->jm_parent = dp->i_number;
4270 	jmvref->jm_ino = ino;
4271 	jmvref->jm_oldoff = oldoff;
4272 	jmvref->jm_newoff = newoff;
4273 
4274 	return (jmvref);
4275 }
4276 
4277 /*
4278  * Allocate a new jremref that tracks the removal of ip from dp with the
4279  * directory entry offset of diroff.  Mark the entry as ATTACHED and
4280  * DEPCOMPLETE as we have all the information required for the journal write
4281  * and the directory has already been removed from the buffer.  The caller
4282  * is responsible for linking the jremref into the pagedep and adding it
4283  * to the journal to write.  The MKDIR_PARENT flag is set if we're doing
4284  * a DOTDOT addition so handle_workitem_remove() can properly assign
4285  * the jsegdep when we're done.
4286  */
4287 static struct jremref *
4288 newjremref(struct dirrem *dirrem,
4289 	struct inode *dp,
4290 	struct inode *ip,
4291 	off_t diroff,
4292 	nlink_t nlink)
4293 {
4294 	struct jremref *jremref;
4295 
4296 	jremref = malloc(sizeof(*jremref), M_JREMREF, M_SOFTDEP_FLAGS);
4297 	workitem_alloc(&jremref->jr_list, D_JREMREF, ITOVFS(dp));
4298 	jremref->jr_state = ATTACHED;
4299 	newinoref(&jremref->jr_ref, ip->i_number, dp->i_number, diroff,
4300 	   nlink, ip->i_mode);
4301 	jremref->jr_dirrem = dirrem;
4302 
4303 	return (jremref);
4304 }
4305 
4306 static inline void
4307 newinoref(struct inoref *inoref,
4308 	ino_t ino,
4309 	ino_t parent,
4310 	off_t diroff,
4311 	nlink_t nlink,
4312 	uint16_t mode)
4313 {
4314 
4315 	inoref->if_jsegdep = newjsegdep(&inoref->if_list);
4316 	inoref->if_diroff = diroff;
4317 	inoref->if_ino = ino;
4318 	inoref->if_parent = parent;
4319 	inoref->if_nlink = nlink;
4320 	inoref->if_mode = mode;
4321 }
4322 
4323 /*
4324  * Allocate a new jaddref to track the addition of ino to dp at diroff.  The
4325  * directory offset may not be known until later.  The caller is responsible
4326  * adding the entry to the journal when this information is available.  nlink
4327  * should be the link count prior to the addition and mode is only required
4328  * to have the correct FMT.
4329  */
4330 static struct jaddref *
4331 newjaddref(struct inode *dp,
4332 	ino_t ino,
4333 	off_t diroff,
4334 	int16_t nlink,
4335 	uint16_t mode)
4336 {
4337 	struct jaddref *jaddref;
4338 
4339 	jaddref = malloc(sizeof(*jaddref), M_JADDREF, M_SOFTDEP_FLAGS);
4340 	workitem_alloc(&jaddref->ja_list, D_JADDREF, ITOVFS(dp));
4341 	jaddref->ja_state = ATTACHED;
4342 	jaddref->ja_mkdir = NULL;
4343 	newinoref(&jaddref->ja_ref, ino, dp->i_number, diroff, nlink, mode);
4344 
4345 	return (jaddref);
4346 }
4347 
4348 /*
4349  * Create a new free dependency for a freework.  The caller is responsible
4350  * for adjusting the reference count when it has the lock held.  The freedep
4351  * will track an outstanding bitmap write that will ultimately clear the
4352  * freework to continue.
4353  */
4354 static struct freedep *
4355 newfreedep(struct freework *freework)
4356 {
4357 	struct freedep *freedep;
4358 
4359 	freedep = malloc(sizeof(*freedep), M_FREEDEP, M_SOFTDEP_FLAGS);
4360 	workitem_alloc(&freedep->fd_list, D_FREEDEP, freework->fw_list.wk_mp);
4361 	freedep->fd_freework = freework;
4362 
4363 	return (freedep);
4364 }
4365 
4366 /*
4367  * Free a freedep structure once the buffer it is linked to is written.  If
4368  * this is the last reference to the freework schedule it for completion.
4369  */
4370 static void
4371 free_freedep(struct freedep *freedep)
4372 {
4373 	struct freework *freework;
4374 
4375 	freework = freedep->fd_freework;
4376 	freework->fw_freeblks->fb_cgwait--;
4377 	if (--freework->fw_ref == 0)
4378 		freework_enqueue(freework);
4379 	WORKITEM_FREE(freedep, D_FREEDEP);
4380 }
4381 
4382 /*
4383  * Allocate a new freework structure that may be a level in an indirect
4384  * when parent is not NULL or a top level block when it is.  The top level
4385  * freework structures are allocated without the per-filesystem lock held
4386  * and before the freeblks is visible outside of softdep_setup_freeblocks().
4387  */
4388 static struct freework *
4389 newfreework(struct ufsmount *ump,
4390 	struct freeblks *freeblks,
4391 	struct freework *parent,
4392 	ufs_lbn_t lbn,
4393 	ufs2_daddr_t nb,
4394 	int frags,
4395 	int off,
4396 	int journal)
4397 {
4398 	struct freework *freework;
4399 
4400 	freework = malloc(sizeof(*freework), M_FREEWORK, M_SOFTDEP_FLAGS);
4401 	workitem_alloc(&freework->fw_list, D_FREEWORK, freeblks->fb_list.wk_mp);
4402 	freework->fw_state = ATTACHED;
4403 	freework->fw_jnewblk = NULL;
4404 	freework->fw_freeblks = freeblks;
4405 	freework->fw_parent = parent;
4406 	freework->fw_lbn = lbn;
4407 	freework->fw_blkno = nb;
4408 	freework->fw_frags = frags;
4409 	freework->fw_indir = NULL;
4410 	freework->fw_ref = (MOUNTEDSUJ(UFSTOVFS(ump)) == 0 ||
4411 	    lbn >= -UFS_NXADDR) ? 0 : NINDIR(ump->um_fs) + 1;
4412 	freework->fw_start = freework->fw_off = off;
4413 	if (journal)
4414 		newjfreeblk(freeblks, lbn, nb, frags);
4415 	if (parent == NULL) {
4416 		ACQUIRE_LOCK(ump);
4417 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
4418 		freeblks->fb_ref++;
4419 		FREE_LOCK(ump);
4420 	}
4421 
4422 	return (freework);
4423 }
4424 
4425 /*
4426  * Eliminate a jfreeblk for a block that does not need journaling.
4427  */
4428 static void
4429 cancel_jfreeblk(struct freeblks *freeblks, ufs2_daddr_t blkno)
4430 {
4431 	struct jfreeblk *jfreeblk;
4432 	struct jblkdep *jblkdep;
4433 
4434 	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps) {
4435 		if (jblkdep->jb_list.wk_type != D_JFREEBLK)
4436 			continue;
4437 		jfreeblk = WK_JFREEBLK(&jblkdep->jb_list);
4438 		if (jfreeblk->jf_blkno == blkno)
4439 			break;
4440 	}
4441 	if (jblkdep == NULL)
4442 		return;
4443 	CTR1(KTR_SUJ, "cancel_jfreeblk: blkno %jd", blkno);
4444 	free_jsegdep(jblkdep->jb_jsegdep);
4445 	LIST_REMOVE(jblkdep, jb_deps);
4446 	WORKITEM_FREE(jfreeblk, D_JFREEBLK);
4447 }
4448 
4449 /*
4450  * Allocate a new jfreeblk to journal top level block pointer when truncating
4451  * a file.  The caller must add this to the worklist when the per-filesystem
4452  * lock is held.
4453  */
4454 static struct jfreeblk *
4455 newjfreeblk(struct freeblks *freeblks,
4456 	ufs_lbn_t lbn,
4457 	ufs2_daddr_t blkno,
4458 	int frags)
4459 {
4460 	struct jfreeblk *jfreeblk;
4461 
4462 	jfreeblk = malloc(sizeof(*jfreeblk), M_JFREEBLK, M_SOFTDEP_FLAGS);
4463 	workitem_alloc(&jfreeblk->jf_dep.jb_list, D_JFREEBLK,
4464 	    freeblks->fb_list.wk_mp);
4465 	jfreeblk->jf_dep.jb_jsegdep = newjsegdep(&jfreeblk->jf_dep.jb_list);
4466 	jfreeblk->jf_dep.jb_freeblks = freeblks;
4467 	jfreeblk->jf_ino = freeblks->fb_inum;
4468 	jfreeblk->jf_lbn = lbn;
4469 	jfreeblk->jf_blkno = blkno;
4470 	jfreeblk->jf_frags = frags;
4471 	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jfreeblk->jf_dep, jb_deps);
4472 
4473 	return (jfreeblk);
4474 }
4475 
4476 /*
4477  * The journal is only prepared to handle full-size block numbers, so we
4478  * have to adjust the record to reflect the change to a full-size block.
4479  * For example, suppose we have a block made up of fragments 8-15 and
4480  * want to free its last two fragments. We are given a request that says:
4481  *     FREEBLK ino=5, blkno=14, lbn=0, frags=2, oldfrags=0
4482  * where frags are the number of fragments to free and oldfrags are the
4483  * number of fragments to keep. To block align it, we have to change it to
4484  * have a valid full-size blkno, so it becomes:
4485  *     FREEBLK ino=5, blkno=8, lbn=0, frags=2, oldfrags=6
4486  */
4487 static void
4488 adjust_newfreework(struct freeblks *freeblks, int frag_offset)
4489 {
4490 	struct jfreeblk *jfreeblk;
4491 
4492 	KASSERT((LIST_FIRST(&freeblks->fb_jblkdephd) != NULL &&
4493 	    LIST_FIRST(&freeblks->fb_jblkdephd)->jb_list.wk_type == D_JFREEBLK),
4494 	    ("adjust_newfreework: Missing freeblks dependency"));
4495 
4496 	jfreeblk = WK_JFREEBLK(LIST_FIRST(&freeblks->fb_jblkdephd));
4497 	jfreeblk->jf_blkno -= frag_offset;
4498 	jfreeblk->jf_frags += frag_offset;
4499 }
4500 
4501 /*
4502  * Allocate a new jtrunc to track a partial truncation.
4503  */
4504 static struct jtrunc *
4505 newjtrunc(struct freeblks *freeblks,
4506 	off_t size,
4507 	int extsize)
4508 {
4509 	struct jtrunc *jtrunc;
4510 
4511 	jtrunc = malloc(sizeof(*jtrunc), M_JTRUNC, M_SOFTDEP_FLAGS);
4512 	workitem_alloc(&jtrunc->jt_dep.jb_list, D_JTRUNC,
4513 	    freeblks->fb_list.wk_mp);
4514 	jtrunc->jt_dep.jb_jsegdep = newjsegdep(&jtrunc->jt_dep.jb_list);
4515 	jtrunc->jt_dep.jb_freeblks = freeblks;
4516 	jtrunc->jt_ino = freeblks->fb_inum;
4517 	jtrunc->jt_size = size;
4518 	jtrunc->jt_extsize = extsize;
4519 	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jtrunc->jt_dep, jb_deps);
4520 
4521 	return (jtrunc);
4522 }
4523 
4524 /*
4525  * If we're canceling a new bitmap we have to search for another ref
4526  * to move into the bmsafemap dep.  This might be better expressed
4527  * with another structure.
4528  */
4529 static void
4530 move_newblock_dep(struct jaddref *jaddref, struct inodedep *inodedep)
4531 {
4532 	struct inoref *inoref;
4533 	struct jaddref *jaddrefn;
4534 
4535 	jaddrefn = NULL;
4536 	for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4537 	    inoref = TAILQ_NEXT(inoref, if_deps)) {
4538 		if ((jaddref->ja_state & NEWBLOCK) &&
4539 		    inoref->if_list.wk_type == D_JADDREF) {
4540 			jaddrefn = (struct jaddref *)inoref;
4541 			break;
4542 		}
4543 	}
4544 	if (jaddrefn == NULL)
4545 		return;
4546 	jaddrefn->ja_state &= ~(ATTACHED | UNDONE);
4547 	jaddrefn->ja_state |= jaddref->ja_state &
4548 	    (ATTACHED | UNDONE | NEWBLOCK);
4549 	jaddref->ja_state &= ~(ATTACHED | UNDONE | NEWBLOCK);
4550 	jaddref->ja_state |= ATTACHED;
4551 	LIST_REMOVE(jaddref, ja_bmdeps);
4552 	LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_jaddrefhd, jaddrefn,
4553 	    ja_bmdeps);
4554 }
4555 
4556 /*
4557  * Cancel a jaddref either before it has been written or while it is being
4558  * written.  This happens when a link is removed before the add reaches
4559  * the disk.  The jaddref dependency is kept linked into the bmsafemap
4560  * and inode to prevent the link count or bitmap from reaching the disk
4561  * until handle_workitem_remove() re-adjusts the counts and bitmaps as
4562  * required.
4563  *
4564  * Returns 1 if the canceled addref requires journaling of the remove and
4565  * 0 otherwise.
4566  */
4567 static int
4568 cancel_jaddref(struct jaddref *jaddref,
4569 	struct inodedep *inodedep,
4570 	struct workhead *wkhd)
4571 {
4572 	struct inoref *inoref;
4573 	struct jsegdep *jsegdep;
4574 	int needsj;
4575 
4576 	KASSERT((jaddref->ja_state & COMPLETE) == 0,
4577 	    ("cancel_jaddref: Canceling complete jaddref"));
4578 	if (jaddref->ja_state & (INPROGRESS | COMPLETE))
4579 		needsj = 1;
4580 	else
4581 		needsj = 0;
4582 	if (inodedep == NULL)
4583 		if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
4584 		    0, &inodedep) == 0)
4585 			panic("cancel_jaddref: Lost inodedep");
4586 	/*
4587 	 * We must adjust the nlink of any reference operation that follows
4588 	 * us so that it is consistent with the in-memory reference.  This
4589 	 * ensures that inode nlink rollbacks always have the correct link.
4590 	 */
4591 	if (needsj == 0) {
4592 		for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4593 		    inoref = TAILQ_NEXT(inoref, if_deps)) {
4594 			if (inoref->if_state & GOINGAWAY)
4595 				break;
4596 			inoref->if_nlink--;
4597 		}
4598 	}
4599 	jsegdep = inoref_jseg(&jaddref->ja_ref);
4600 	if (jaddref->ja_state & NEWBLOCK)
4601 		move_newblock_dep(jaddref, inodedep);
4602 	wake_worklist(&jaddref->ja_list);
4603 	jaddref->ja_mkdir = NULL;
4604 	if (jaddref->ja_state & INPROGRESS) {
4605 		jaddref->ja_state &= ~INPROGRESS;
4606 		WORKLIST_REMOVE(&jaddref->ja_list);
4607 		jwork_insert(wkhd, jsegdep);
4608 	} else {
4609 		free_jsegdep(jsegdep);
4610 		if (jaddref->ja_state & DEPCOMPLETE)
4611 			remove_from_journal(&jaddref->ja_list);
4612 	}
4613 	jaddref->ja_state |= (GOINGAWAY | DEPCOMPLETE);
4614 	/*
4615 	 * Leave NEWBLOCK jaddrefs on the inodedep so handle_workitem_remove
4616 	 * can arrange for them to be freed with the bitmap.  Otherwise we
4617 	 * no longer need this addref attached to the inoreflst and it
4618 	 * will incorrectly adjust nlink if we leave it.
4619 	 */
4620 	if ((jaddref->ja_state & NEWBLOCK) == 0) {
4621 		TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
4622 		    if_deps);
4623 		jaddref->ja_state |= COMPLETE;
4624 		free_jaddref(jaddref);
4625 		return (needsj);
4626 	}
4627 	/*
4628 	 * Leave the head of the list for jsegdeps for fast merging.
4629 	 */
4630 	if (LIST_FIRST(wkhd) != NULL) {
4631 		jaddref->ja_state |= ONWORKLIST;
4632 		LIST_INSERT_AFTER(LIST_FIRST(wkhd), &jaddref->ja_list, wk_list);
4633 	} else
4634 		WORKLIST_INSERT(wkhd, &jaddref->ja_list);
4635 
4636 	return (needsj);
4637 }
4638 
4639 /*
4640  * Attempt to free a jaddref structure when some work completes.  This
4641  * should only succeed once the entry is written and all dependencies have
4642  * been notified.
4643  */
4644 static void
4645 free_jaddref(struct jaddref *jaddref)
4646 {
4647 
4648 	if ((jaddref->ja_state & ALLCOMPLETE) != ALLCOMPLETE)
4649 		return;
4650 	if (jaddref->ja_ref.if_jsegdep)
4651 		panic("free_jaddref: segdep attached to jaddref %p(0x%X)\n",
4652 		    jaddref, jaddref->ja_state);
4653 	if (jaddref->ja_state & NEWBLOCK)
4654 		LIST_REMOVE(jaddref, ja_bmdeps);
4655 	if (jaddref->ja_state & (INPROGRESS | ONWORKLIST))
4656 		panic("free_jaddref: Bad state %p(0x%X)",
4657 		    jaddref, jaddref->ja_state);
4658 	if (jaddref->ja_mkdir != NULL)
4659 		panic("free_jaddref: Work pending, 0x%X\n", jaddref->ja_state);
4660 	WORKITEM_FREE(jaddref, D_JADDREF);
4661 }
4662 
4663 /*
4664  * Free a jremref structure once it has been written or discarded.
4665  */
4666 static void
4667 free_jremref(struct jremref *jremref)
4668 {
4669 
4670 	if (jremref->jr_ref.if_jsegdep)
4671 		free_jsegdep(jremref->jr_ref.if_jsegdep);
4672 	if (jremref->jr_state & INPROGRESS)
4673 		panic("free_jremref: IO still pending");
4674 	WORKITEM_FREE(jremref, D_JREMREF);
4675 }
4676 
4677 /*
4678  * Free a jnewblk structure.
4679  */
4680 static void
4681 free_jnewblk(struct jnewblk *jnewblk)
4682 {
4683 
4684 	if ((jnewblk->jn_state & ALLCOMPLETE) != ALLCOMPLETE)
4685 		return;
4686 	LIST_REMOVE(jnewblk, jn_deps);
4687 	if (jnewblk->jn_dep != NULL)
4688 		panic("free_jnewblk: Dependency still attached.");
4689 	WORKITEM_FREE(jnewblk, D_JNEWBLK);
4690 }
4691 
4692 /*
4693  * Cancel a jnewblk which has been been made redundant by frag extension.
4694  */
4695 static void
4696 cancel_jnewblk(struct jnewblk *jnewblk, struct workhead *wkhd)
4697 {
4698 	struct jsegdep *jsegdep;
4699 
4700 	CTR1(KTR_SUJ, "cancel_jnewblk: blkno %jd", jnewblk->jn_blkno);
4701 	jsegdep = jnewblk->jn_jsegdep;
4702 	if (jnewblk->jn_jsegdep == NULL || jnewblk->jn_dep == NULL)
4703 		panic("cancel_jnewblk: Invalid state");
4704 	jnewblk->jn_jsegdep  = NULL;
4705 	jnewblk->jn_dep = NULL;
4706 	jnewblk->jn_state |= GOINGAWAY;
4707 	if (jnewblk->jn_state & INPROGRESS) {
4708 		jnewblk->jn_state &= ~INPROGRESS;
4709 		WORKLIST_REMOVE(&jnewblk->jn_list);
4710 		jwork_insert(wkhd, jsegdep);
4711 	} else {
4712 		free_jsegdep(jsegdep);
4713 		remove_from_journal(&jnewblk->jn_list);
4714 	}
4715 	wake_worklist(&jnewblk->jn_list);
4716 	WORKLIST_INSERT(wkhd, &jnewblk->jn_list);
4717 }
4718 
4719 static void
4720 free_jblkdep(struct jblkdep *jblkdep)
4721 {
4722 
4723 	if (jblkdep->jb_list.wk_type == D_JFREEBLK)
4724 		WORKITEM_FREE(jblkdep, D_JFREEBLK);
4725 	else if (jblkdep->jb_list.wk_type == D_JTRUNC)
4726 		WORKITEM_FREE(jblkdep, D_JTRUNC);
4727 	else
4728 		panic("free_jblkdep: Unexpected type %s",
4729 		    TYPENAME(jblkdep->jb_list.wk_type));
4730 }
4731 
4732 /*
4733  * Free a single jseg once it is no longer referenced in memory or on
4734  * disk.  Reclaim journal blocks and dependencies waiting for the segment
4735  * to disappear.
4736  */
4737 static void
4738 free_jseg(struct jseg *jseg, struct jblocks *jblocks)
4739 {
4740 	struct freework *freework;
4741 
4742 	/*
4743 	 * Free freework structures that were lingering to indicate freed
4744 	 * indirect blocks that forced journal write ordering on reallocate.
4745 	 */
4746 	while ((freework = LIST_FIRST(&jseg->js_indirs)) != NULL)
4747 		indirblk_remove(freework);
4748 	if (jblocks->jb_oldestseg == jseg)
4749 		jblocks->jb_oldestseg = TAILQ_NEXT(jseg, js_next);
4750 	TAILQ_REMOVE(&jblocks->jb_segs, jseg, js_next);
4751 	jblocks_free(jblocks, jseg->js_list.wk_mp, jseg->js_size);
4752 	KASSERT(LIST_EMPTY(&jseg->js_entries),
4753 	    ("free_jseg: Freed jseg has valid entries."));
4754 	WORKITEM_FREE(jseg, D_JSEG);
4755 }
4756 
4757 /*
4758  * Free all jsegs that meet the criteria for being reclaimed and update
4759  * oldestseg.
4760  */
4761 static void
4762 free_jsegs(struct jblocks *jblocks)
4763 {
4764 	struct jseg *jseg;
4765 
4766 	/*
4767 	 * Free only those jsegs which have none allocated before them to
4768 	 * preserve the journal space ordering.
4769 	 */
4770 	while ((jseg = TAILQ_FIRST(&jblocks->jb_segs)) != NULL) {
4771 		/*
4772 		 * Only reclaim space when nothing depends on this journal
4773 		 * set and another set has written that it is no longer
4774 		 * valid.
4775 		 */
4776 		if (jseg->js_refs != 0) {
4777 			jblocks->jb_oldestseg = jseg;
4778 			return;
4779 		}
4780 		if ((jseg->js_state & ALLCOMPLETE) != ALLCOMPLETE)
4781 			break;
4782 		if (jseg->js_seq > jblocks->jb_oldestwrseq)
4783 			break;
4784 		/*
4785 		 * We can free jsegs that didn't write entries when
4786 		 * oldestwrseq == js_seq.
4787 		 */
4788 		if (jseg->js_seq == jblocks->jb_oldestwrseq &&
4789 		    jseg->js_cnt != 0)
4790 			break;
4791 		free_jseg(jseg, jblocks);
4792 	}
4793 	/*
4794 	 * If we exited the loop above we still must discover the
4795 	 * oldest valid segment.
4796 	 */
4797 	if (jseg)
4798 		for (jseg = jblocks->jb_oldestseg; jseg != NULL;
4799 		     jseg = TAILQ_NEXT(jseg, js_next))
4800 			if (jseg->js_refs != 0)
4801 				break;
4802 	jblocks->jb_oldestseg = jseg;
4803 	/*
4804 	 * The journal has no valid records but some jsegs may still be
4805 	 * waiting on oldestwrseq to advance.  We force a small record
4806 	 * out to permit these lingering records to be reclaimed.
4807 	 */
4808 	if (jblocks->jb_oldestseg == NULL && !TAILQ_EMPTY(&jblocks->jb_segs))
4809 		jblocks->jb_needseg = 1;
4810 }
4811 
4812 /*
4813  * Release one reference to a jseg and free it if the count reaches 0.  This
4814  * should eventually reclaim journal space as well.
4815  */
4816 static void
4817 rele_jseg(struct jseg *jseg)
4818 {
4819 
4820 	KASSERT(jseg->js_refs > 0,
4821 	    ("free_jseg: Invalid refcnt %d", jseg->js_refs));
4822 	if (--jseg->js_refs != 0)
4823 		return;
4824 	free_jsegs(jseg->js_jblocks);
4825 }
4826 
4827 /*
4828  * Release a jsegdep and decrement the jseg count.
4829  */
4830 static void
4831 free_jsegdep(struct jsegdep *jsegdep)
4832 {
4833 
4834 	if (jsegdep->jd_seg)
4835 		rele_jseg(jsegdep->jd_seg);
4836 	WORKITEM_FREE(jsegdep, D_JSEGDEP);
4837 }
4838 
4839 /*
4840  * Wait for a journal item to make it to disk.  Initiate journal processing
4841  * if required.
4842  */
4843 static int
4844 jwait(struct worklist *wk, int waitfor)
4845 {
4846 
4847 	LOCK_OWNED(VFSTOUFS(wk->wk_mp));
4848 	/*
4849 	 * Blocking journal waits cause slow synchronous behavior.  Record
4850 	 * stats on the frequency of these blocking operations.
4851 	 */
4852 	if (waitfor == MNT_WAIT) {
4853 		stat_journal_wait++;
4854 		switch (wk->wk_type) {
4855 		case D_JREMREF:
4856 		case D_JMVREF:
4857 			stat_jwait_filepage++;
4858 			break;
4859 		case D_JTRUNC:
4860 		case D_JFREEBLK:
4861 			stat_jwait_freeblks++;
4862 			break;
4863 		case D_JNEWBLK:
4864 			stat_jwait_newblk++;
4865 			break;
4866 		case D_JADDREF:
4867 			stat_jwait_inode++;
4868 			break;
4869 		default:
4870 			break;
4871 		}
4872 	}
4873 	/*
4874 	 * If IO has not started we process the journal.  We can't mark the
4875 	 * worklist item as IOWAITING because we drop the lock while
4876 	 * processing the journal and the worklist entry may be freed after
4877 	 * this point.  The caller may call back in and re-issue the request.
4878 	 */
4879 	if ((wk->wk_state & INPROGRESS) == 0) {
4880 		softdep_process_journal(wk->wk_mp, wk, waitfor);
4881 		if (waitfor != MNT_WAIT)
4882 			return (EBUSY);
4883 		return (0);
4884 	}
4885 	if (waitfor != MNT_WAIT)
4886 		return (EBUSY);
4887 	wait_worklist(wk, "jwait");
4888 	return (0);
4889 }
4890 
4891 /*
4892  * Lookup an inodedep based on an inode pointer and set the nlinkdelta as
4893  * appropriate.  This is a convenience function to reduce duplicate code
4894  * for the setup and revert functions below.
4895  */
4896 static struct inodedep *
4897 inodedep_lookup_ip(struct inode *ip)
4898 {
4899 	struct inodedep *inodedep;
4900 
4901 	KASSERT(ip->i_nlink >= ip->i_effnlink,
4902 	    ("inodedep_lookup_ip: bad delta"));
4903 	(void) inodedep_lookup(ITOVFS(ip), ip->i_number, DEPALLOC,
4904 	    &inodedep);
4905 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
4906 	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
4907 
4908 	return (inodedep);
4909 }
4910 
4911 /*
4912  * Called prior to creating a new inode and linking it to a directory.  The
4913  * jaddref structure must already be allocated by softdep_setup_inomapdep
4914  * and it is discovered here so we can initialize the mode and update
4915  * nlinkdelta.
4916  */
4917 void
4918 softdep_setup_create(struct inode *dp, struct inode *ip)
4919 {
4920 	struct inodedep *inodedep;
4921 	struct jaddref *jaddref __diagused;
4922 	struct vnode *dvp;
4923 
4924 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4925 	    ("softdep_setup_create called on non-softdep filesystem"));
4926 	KASSERT(ip->i_nlink == 1,
4927 	    ("softdep_setup_create: Invalid link count."));
4928 	dvp = ITOV(dp);
4929 	ACQUIRE_LOCK(ITOUMP(dp));
4930 	inodedep = inodedep_lookup_ip(ip);
4931 	if (DOINGSUJ(dvp)) {
4932 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4933 		    inoreflst);
4934 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
4935 		    ("softdep_setup_create: No addref structure present."));
4936 	}
4937 	FREE_LOCK(ITOUMP(dp));
4938 }
4939 
4940 /*
4941  * Create a jaddref structure to track the addition of a DOTDOT link when
4942  * we are reparenting an inode as part of a rename.  This jaddref will be
4943  * found by softdep_setup_directory_change.  Adjusts nlinkdelta for
4944  * non-journaling softdep.
4945  */
4946 void
4947 softdep_setup_dotdot_link(struct inode *dp, struct inode *ip)
4948 {
4949 	struct inodedep *inodedep;
4950 	struct jaddref *jaddref;
4951 	struct vnode *dvp;
4952 
4953 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4954 	    ("softdep_setup_dotdot_link called on non-softdep filesystem"));
4955 	dvp = ITOV(dp);
4956 	jaddref = NULL;
4957 	/*
4958 	 * We don't set MKDIR_PARENT as this is not tied to a mkdir and
4959 	 * is used as a normal link would be.
4960 	 */
4961 	if (DOINGSUJ(dvp))
4962 		jaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4963 		    dp->i_effnlink - 1, dp->i_mode);
4964 	ACQUIRE_LOCK(ITOUMP(dp));
4965 	inodedep = inodedep_lookup_ip(dp);
4966 	if (jaddref)
4967 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4968 		    if_deps);
4969 	FREE_LOCK(ITOUMP(dp));
4970 }
4971 
4972 /*
4973  * Create a jaddref structure to track a new link to an inode.  The directory
4974  * offset is not known until softdep_setup_directory_add or
4975  * softdep_setup_directory_change.  Adjusts nlinkdelta for non-journaling
4976  * softdep.
4977  */
4978 void
4979 softdep_setup_link(struct inode *dp, struct inode *ip)
4980 {
4981 	struct inodedep *inodedep;
4982 	struct jaddref *jaddref;
4983 	struct vnode *dvp;
4984 
4985 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4986 	    ("softdep_setup_link called on non-softdep filesystem"));
4987 	dvp = ITOV(dp);
4988 	jaddref = NULL;
4989 	if (DOINGSUJ(dvp))
4990 		jaddref = newjaddref(dp, ip->i_number, 0, ip->i_effnlink - 1,
4991 		    ip->i_mode);
4992 	ACQUIRE_LOCK(ITOUMP(dp));
4993 	inodedep = inodedep_lookup_ip(ip);
4994 	if (jaddref)
4995 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4996 		    if_deps);
4997 	FREE_LOCK(ITOUMP(dp));
4998 }
4999 
5000 /*
5001  * Called to create the jaddref structures to track . and .. references as
5002  * well as lookup and further initialize the incomplete jaddref created
5003  * by softdep_setup_inomapdep when the inode was allocated.  Adjusts
5004  * nlinkdelta for non-journaling softdep.
5005  */
5006 void
5007 softdep_setup_mkdir(struct inode *dp, struct inode *ip)
5008 {
5009 	struct inodedep *inodedep;
5010 	struct jaddref *dotdotaddref;
5011 	struct jaddref *dotaddref;
5012 	struct jaddref *jaddref;
5013 	struct vnode *dvp;
5014 
5015 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5016 	    ("softdep_setup_mkdir called on non-softdep filesystem"));
5017 	dvp = ITOV(dp);
5018 	dotaddref = dotdotaddref = NULL;
5019 	if (DOINGSUJ(dvp)) {
5020 		dotaddref = newjaddref(ip, ip->i_number, DOT_OFFSET, 1,
5021 		    ip->i_mode);
5022 		dotaddref->ja_state |= MKDIR_BODY;
5023 		dotdotaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
5024 		    dp->i_effnlink - 1, dp->i_mode);
5025 		dotdotaddref->ja_state |= MKDIR_PARENT;
5026 	}
5027 	ACQUIRE_LOCK(ITOUMP(dp));
5028 	inodedep = inodedep_lookup_ip(ip);
5029 	if (DOINGSUJ(dvp)) {
5030 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5031 		    inoreflst);
5032 		KASSERT(jaddref != NULL,
5033 		    ("softdep_setup_mkdir: No addref structure present."));
5034 		KASSERT(jaddref->ja_parent == dp->i_number,
5035 		    ("softdep_setup_mkdir: bad parent %ju",
5036 		    (uintmax_t)jaddref->ja_parent));
5037 		TAILQ_INSERT_BEFORE(&jaddref->ja_ref, &dotaddref->ja_ref,
5038 		    if_deps);
5039 	}
5040 	inodedep = inodedep_lookup_ip(dp);
5041 	if (DOINGSUJ(dvp))
5042 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst,
5043 		    &dotdotaddref->ja_ref, if_deps);
5044 	FREE_LOCK(ITOUMP(dp));
5045 }
5046 
5047 /*
5048  * Called to track nlinkdelta of the inode and parent directories prior to
5049  * unlinking a directory.
5050  */
5051 void
5052 softdep_setup_rmdir(struct inode *dp, struct inode *ip)
5053 {
5054 
5055 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5056 	    ("softdep_setup_rmdir called on non-softdep filesystem"));
5057 	ACQUIRE_LOCK(ITOUMP(dp));
5058 	(void) inodedep_lookup_ip(ip);
5059 	(void) inodedep_lookup_ip(dp);
5060 	FREE_LOCK(ITOUMP(dp));
5061 }
5062 
5063 /*
5064  * Called to track nlinkdelta of the inode and parent directories prior to
5065  * unlink.
5066  */
5067 void
5068 softdep_setup_unlink(struct inode *dp, struct inode *ip)
5069 {
5070 
5071 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5072 	    ("softdep_setup_unlink called on non-softdep filesystem"));
5073 	ACQUIRE_LOCK(ITOUMP(dp));
5074 	(void) inodedep_lookup_ip(ip);
5075 	(void) inodedep_lookup_ip(dp);
5076 	FREE_LOCK(ITOUMP(dp));
5077 }
5078 
5079 /*
5080  * Called to release the journal structures created by a failed non-directory
5081  * creation.  Adjusts nlinkdelta for non-journaling softdep.
5082  */
5083 void
5084 softdep_revert_create(struct inode *dp, struct inode *ip)
5085 {
5086 	struct inodedep *inodedep;
5087 	struct jaddref *jaddref;
5088 	struct vnode *dvp;
5089 
5090 	KASSERT(MOUNTEDSOFTDEP(ITOVFS((dp))) != 0,
5091 	    ("softdep_revert_create called on non-softdep filesystem"));
5092 	dvp = ITOV(dp);
5093 	ACQUIRE_LOCK(ITOUMP(dp));
5094 	inodedep = inodedep_lookup_ip(ip);
5095 	if (DOINGSUJ(dvp)) {
5096 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5097 		    inoreflst);
5098 		KASSERT(jaddref->ja_parent == dp->i_number,
5099 		    ("softdep_revert_create: addref parent mismatch"));
5100 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
5101 	}
5102 	FREE_LOCK(ITOUMP(dp));
5103 }
5104 
5105 /*
5106  * Called to release the journal structures created by a failed link
5107  * addition.  Adjusts nlinkdelta for non-journaling softdep.
5108  */
5109 void
5110 softdep_revert_link(struct inode *dp, struct inode *ip)
5111 {
5112 	struct inodedep *inodedep;
5113 	struct jaddref *jaddref;
5114 	struct vnode *dvp;
5115 
5116 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5117 	    ("softdep_revert_link called on non-softdep filesystem"));
5118 	dvp = ITOV(dp);
5119 	ACQUIRE_LOCK(ITOUMP(dp));
5120 	inodedep = inodedep_lookup_ip(ip);
5121 	if (DOINGSUJ(dvp)) {
5122 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5123 		    inoreflst);
5124 		KASSERT(jaddref->ja_parent == dp->i_number,
5125 		    ("softdep_revert_link: addref parent mismatch"));
5126 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
5127 	}
5128 	FREE_LOCK(ITOUMP(dp));
5129 }
5130 
5131 /*
5132  * Called to release the journal structures created by a failed mkdir
5133  * attempt.  Adjusts nlinkdelta for non-journaling softdep.
5134  */
5135 void
5136 softdep_revert_mkdir(struct inode *dp, struct inode *ip)
5137 {
5138 	struct inodedep *inodedep;
5139 	struct jaddref *jaddref;
5140 	struct jaddref *dotaddref;
5141 	struct vnode *dvp;
5142 
5143 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5144 	    ("softdep_revert_mkdir called on non-softdep filesystem"));
5145 	dvp = ITOV(dp);
5146 
5147 	ACQUIRE_LOCK(ITOUMP(dp));
5148 	inodedep = inodedep_lookup_ip(dp);
5149 	if (DOINGSUJ(dvp)) {
5150 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5151 		    inoreflst);
5152 		KASSERT(jaddref->ja_parent == ip->i_number,
5153 		    ("softdep_revert_mkdir: dotdot addref parent mismatch"));
5154 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
5155 	}
5156 	inodedep = inodedep_lookup_ip(ip);
5157 	if (DOINGSUJ(dvp)) {
5158 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5159 		    inoreflst);
5160 		KASSERT(jaddref->ja_parent == dp->i_number,
5161 		    ("softdep_revert_mkdir: addref parent mismatch"));
5162 		dotaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
5163 		    inoreflst, if_deps);
5164 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
5165 		KASSERT(dotaddref->ja_parent == ip->i_number,
5166 		    ("softdep_revert_mkdir: dot addref parent mismatch"));
5167 		cancel_jaddref(dotaddref, inodedep, &inodedep->id_inowait);
5168 	}
5169 	FREE_LOCK(ITOUMP(dp));
5170 }
5171 
5172 /*
5173  * Called to correct nlinkdelta after a failed rmdir.
5174  */
5175 void
5176 softdep_revert_rmdir(struct inode *dp, struct inode *ip)
5177 {
5178 
5179 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5180 	    ("softdep_revert_rmdir called on non-softdep filesystem"));
5181 	ACQUIRE_LOCK(ITOUMP(dp));
5182 	(void) inodedep_lookup_ip(ip);
5183 	(void) inodedep_lookup_ip(dp);
5184 	FREE_LOCK(ITOUMP(dp));
5185 }
5186 
5187 /*
5188  * Protecting the freemaps (or bitmaps).
5189  *
5190  * To eliminate the need to execute fsck before mounting a filesystem
5191  * after a power failure, one must (conservatively) guarantee that the
5192  * on-disk copy of the bitmaps never indicate that a live inode or block is
5193  * free.  So, when a block or inode is allocated, the bitmap should be
5194  * updated (on disk) before any new pointers.  When a block or inode is
5195  * freed, the bitmap should not be updated until all pointers have been
5196  * reset.  The latter dependency is handled by the delayed de-allocation
5197  * approach described below for block and inode de-allocation.  The former
5198  * dependency is handled by calling the following procedure when a block or
5199  * inode is allocated. When an inode is allocated an "inodedep" is created
5200  * with its DEPCOMPLETE flag cleared until its bitmap is written to disk.
5201  * Each "inodedep" is also inserted into the hash indexing structure so
5202  * that any additional link additions can be made dependent on the inode
5203  * allocation.
5204  *
5205  * The ufs filesystem maintains a number of free block counts (e.g., per
5206  * cylinder group, per cylinder and per <cylinder, rotational position> pair)
5207  * in addition to the bitmaps.  These counts are used to improve efficiency
5208  * during allocation and therefore must be consistent with the bitmaps.
5209  * There is no convenient way to guarantee post-crash consistency of these
5210  * counts with simple update ordering, for two main reasons: (1) The counts
5211  * and bitmaps for a single cylinder group block are not in the same disk
5212  * sector.  If a disk write is interrupted (e.g., by power failure), one may
5213  * be written and the other not.  (2) Some of the counts are located in the
5214  * superblock rather than the cylinder group block. So, we focus our soft
5215  * updates implementation on protecting the bitmaps. When mounting a
5216  * filesystem, we recompute the auxiliary counts from the bitmaps.
5217  */
5218 
5219 /*
5220  * Called just after updating the cylinder group block to allocate an inode.
5221  */
5222 void
5223 softdep_setup_inomapdep(
5224 	struct buf *bp,		/* buffer for cylgroup block with inode map */
5225 	struct inode *ip,	/* inode related to allocation */
5226 	ino_t newinum,		/* new inode number being allocated */
5227 	int mode)
5228 {
5229 	struct inodedep *inodedep;
5230 	struct bmsafemap *bmsafemap;
5231 	struct jaddref *jaddref;
5232 	struct mount *mp;
5233 	struct fs *fs;
5234 
5235 	mp = ITOVFS(ip);
5236 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5237 	    ("softdep_setup_inomapdep called on non-softdep filesystem"));
5238 	fs = VFSTOUFS(mp)->um_fs;
5239 	jaddref = NULL;
5240 
5241 	/*
5242 	 * Allocate the journal reference add structure so that the bitmap
5243 	 * can be dependent on it.
5244 	 */
5245 	if (MOUNTEDSUJ(mp)) {
5246 		jaddref = newjaddref(ip, newinum, 0, 0, mode);
5247 		jaddref->ja_state |= NEWBLOCK;
5248 	}
5249 
5250 	/*
5251 	 * Create a dependency for the newly allocated inode.
5252 	 * Panic if it already exists as something is seriously wrong.
5253 	 * Otherwise add it to the dependency list for the buffer holding
5254 	 * the cylinder group map from which it was allocated.
5255 	 *
5256 	 * We have to preallocate a bmsafemap entry in case it is needed
5257 	 * in bmsafemap_lookup since once we allocate the inodedep, we
5258 	 * have to finish initializing it before we can FREE_LOCK().
5259 	 * By preallocating, we avoid FREE_LOCK() while doing a malloc
5260 	 * in bmsafemap_lookup. We cannot call bmsafemap_lookup before
5261 	 * creating the inodedep as it can be freed during the time
5262 	 * that we FREE_LOCK() while allocating the inodedep. We must
5263 	 * call workitem_alloc() before entering the locked section as
5264 	 * it also acquires the lock and we must avoid trying doing so
5265 	 * recursively.
5266 	 */
5267 	bmsafemap = malloc(sizeof(struct bmsafemap),
5268 	    M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5269 	workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5270 	ACQUIRE_LOCK(ITOUMP(ip));
5271 	if ((inodedep_lookup(mp, newinum, DEPALLOC, &inodedep)))
5272 		panic("softdep_setup_inomapdep: dependency %p for new"
5273 		    "inode already exists", inodedep);
5274 	bmsafemap = bmsafemap_lookup(mp, bp, ino_to_cg(fs, newinum), bmsafemap);
5275 	if (jaddref) {
5276 		LIST_INSERT_HEAD(&bmsafemap->sm_jaddrefhd, jaddref, ja_bmdeps);
5277 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
5278 		    if_deps);
5279 	} else {
5280 		inodedep->id_state |= ONDEPLIST;
5281 		LIST_INSERT_HEAD(&bmsafemap->sm_inodedephd, inodedep, id_deps);
5282 	}
5283 	inodedep->id_bmsafemap = bmsafemap;
5284 	inodedep->id_state &= ~DEPCOMPLETE;
5285 	FREE_LOCK(ITOUMP(ip));
5286 }
5287 
5288 /*
5289  * Called just after updating the cylinder group block to
5290  * allocate block or fragment.
5291  */
5292 void
5293 softdep_setup_blkmapdep(
5294 	struct buf *bp,		/* buffer for cylgroup block with block map */
5295 	struct mount *mp,	/* filesystem doing allocation */
5296 	ufs2_daddr_t newblkno,	/* number of newly allocated block */
5297 	int frags,		/* Number of fragments. */
5298 	int oldfrags)		/* Previous number of fragments for extend. */
5299 {
5300 	struct newblk *newblk;
5301 	struct bmsafemap *bmsafemap;
5302 	struct jnewblk *jnewblk;
5303 	struct ufsmount *ump;
5304 	struct fs *fs;
5305 
5306 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5307 	    ("softdep_setup_blkmapdep called on non-softdep filesystem"));
5308 	ump = VFSTOUFS(mp);
5309 	fs = ump->um_fs;
5310 	jnewblk = NULL;
5311 	/*
5312 	 * Create a dependency for the newly allocated block.
5313 	 * Add it to the dependency list for the buffer holding
5314 	 * the cylinder group map from which it was allocated.
5315 	 */
5316 	if (MOUNTEDSUJ(mp)) {
5317 		jnewblk = malloc(sizeof(*jnewblk), M_JNEWBLK, M_SOFTDEP_FLAGS);
5318 		workitem_alloc(&jnewblk->jn_list, D_JNEWBLK, mp);
5319 		jnewblk->jn_jsegdep = newjsegdep(&jnewblk->jn_list);
5320 		jnewblk->jn_state = ATTACHED;
5321 		jnewblk->jn_blkno = newblkno;
5322 		jnewblk->jn_frags = frags;
5323 		jnewblk->jn_oldfrags = oldfrags;
5324 #ifdef INVARIANTS
5325 		{
5326 			struct cg *cgp;
5327 			uint8_t *blksfree;
5328 			long bno;
5329 			int i;
5330 
5331 			cgp = (struct cg *)bp->b_data;
5332 			blksfree = cg_blksfree(cgp);
5333 			bno = dtogd(fs, jnewblk->jn_blkno);
5334 			for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags;
5335 			    i++) {
5336 				if (isset(blksfree, bno + i))
5337 					panic("softdep_setup_blkmapdep: "
5338 					    "free fragment %d from %d-%d "
5339 					    "state 0x%X dep %p", i,
5340 					    jnewblk->jn_oldfrags,
5341 					    jnewblk->jn_frags,
5342 					    jnewblk->jn_state,
5343 					    jnewblk->jn_dep);
5344 			}
5345 		}
5346 #endif
5347 	}
5348 
5349 	CTR3(KTR_SUJ,
5350 	    "softdep_setup_blkmapdep: blkno %jd frags %d oldfrags %d",
5351 	    newblkno, frags, oldfrags);
5352 	ACQUIRE_LOCK(ump);
5353 	if (newblk_lookup(mp, newblkno, DEPALLOC, &newblk) != 0)
5354 		panic("softdep_setup_blkmapdep: found block");
5355 	newblk->nb_bmsafemap = bmsafemap = bmsafemap_lookup(mp, bp,
5356 	    dtog(fs, newblkno), NULL);
5357 	if (jnewblk) {
5358 		jnewblk->jn_dep = (struct worklist *)newblk;
5359 		LIST_INSERT_HEAD(&bmsafemap->sm_jnewblkhd, jnewblk, jn_deps);
5360 	} else {
5361 		newblk->nb_state |= ONDEPLIST;
5362 		LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
5363 	}
5364 	newblk->nb_bmsafemap = bmsafemap;
5365 	newblk->nb_jnewblk = jnewblk;
5366 	FREE_LOCK(ump);
5367 }
5368 
5369 #define	BMSAFEMAP_HASH(ump, cg) \
5370       (&(ump)->bmsafemap_hashtbl[(cg) & (ump)->bmsafemap_hash_size])
5371 
5372 static int
5373 bmsafemap_find(
5374 	struct bmsafemap_hashhead *bmsafemaphd,
5375 	int cg,
5376 	struct bmsafemap **bmsafemapp)
5377 {
5378 	struct bmsafemap *bmsafemap;
5379 
5380 	LIST_FOREACH(bmsafemap, bmsafemaphd, sm_hash)
5381 		if (bmsafemap->sm_cg == cg)
5382 			break;
5383 	if (bmsafemap) {
5384 		*bmsafemapp = bmsafemap;
5385 		return (1);
5386 	}
5387 	*bmsafemapp = NULL;
5388 
5389 	return (0);
5390 }
5391 
5392 /*
5393  * Find the bmsafemap associated with a cylinder group buffer.
5394  * If none exists, create one. The buffer must be locked when
5395  * this routine is called and this routine must be called with
5396  * the softdep lock held. To avoid giving up the lock while
5397  * allocating a new bmsafemap, a preallocated bmsafemap may be
5398  * provided. If it is provided but not needed, it is freed.
5399  */
5400 static struct bmsafemap *
5401 bmsafemap_lookup(struct mount *mp,
5402 	struct buf *bp,
5403 	int cg,
5404 	struct bmsafemap *newbmsafemap)
5405 {
5406 	struct bmsafemap_hashhead *bmsafemaphd;
5407 	struct bmsafemap *bmsafemap, *collision;
5408 	struct worklist *wk;
5409 	struct ufsmount *ump;
5410 
5411 	ump = VFSTOUFS(mp);
5412 	LOCK_OWNED(ump);
5413 	KASSERT(bp != NULL, ("bmsafemap_lookup: missing buffer"));
5414 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5415 		if (wk->wk_type == D_BMSAFEMAP) {
5416 			if (newbmsafemap)
5417 				WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5418 			return (WK_BMSAFEMAP(wk));
5419 		}
5420 	}
5421 	bmsafemaphd = BMSAFEMAP_HASH(ump, cg);
5422 	if (bmsafemap_find(bmsafemaphd, cg, &bmsafemap) == 1) {
5423 		if (newbmsafemap)
5424 			WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5425 		return (bmsafemap);
5426 	}
5427 	if (newbmsafemap) {
5428 		bmsafemap = newbmsafemap;
5429 	} else {
5430 		FREE_LOCK(ump);
5431 		bmsafemap = malloc(sizeof(struct bmsafemap),
5432 			M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5433 		workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5434 		ACQUIRE_LOCK(ump);
5435 	}
5436 	bmsafemap->sm_buf = bp;
5437 	LIST_INIT(&bmsafemap->sm_inodedephd);
5438 	LIST_INIT(&bmsafemap->sm_inodedepwr);
5439 	LIST_INIT(&bmsafemap->sm_newblkhd);
5440 	LIST_INIT(&bmsafemap->sm_newblkwr);
5441 	LIST_INIT(&bmsafemap->sm_jaddrefhd);
5442 	LIST_INIT(&bmsafemap->sm_jnewblkhd);
5443 	LIST_INIT(&bmsafemap->sm_freehd);
5444 	LIST_INIT(&bmsafemap->sm_freewr);
5445 	if (bmsafemap_find(bmsafemaphd, cg, &collision) == 1) {
5446 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
5447 		return (collision);
5448 	}
5449 	bmsafemap->sm_cg = cg;
5450 	LIST_INSERT_HEAD(bmsafemaphd, bmsafemap, sm_hash);
5451 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
5452 	WORKLIST_INSERT(&bp->b_dep, &bmsafemap->sm_list);
5453 	return (bmsafemap);
5454 }
5455 
5456 /*
5457  * Direct block allocation dependencies.
5458  *
5459  * When a new block is allocated, the corresponding disk locations must be
5460  * initialized (with zeros or new data) before the on-disk inode points to
5461  * them.  Also, the freemap from which the block was allocated must be
5462  * updated (on disk) before the inode's pointer. These two dependencies are
5463  * independent of each other and are needed for all file blocks and indirect
5464  * blocks that are pointed to directly by the inode.  Just before the
5465  * "in-core" version of the inode is updated with a newly allocated block
5466  * number, a procedure (below) is called to setup allocation dependency
5467  * structures.  These structures are removed when the corresponding
5468  * dependencies are satisfied or when the block allocation becomes obsolete
5469  * (i.e., the file is deleted, the block is de-allocated, or the block is a
5470  * fragment that gets upgraded).  All of these cases are handled in
5471  * procedures described later.
5472  *
5473  * When a file extension causes a fragment to be upgraded, either to a larger
5474  * fragment or to a full block, the on-disk location may change (if the
5475  * previous fragment could not simply be extended). In this case, the old
5476  * fragment must be de-allocated, but not until after the inode's pointer has
5477  * been updated. In most cases, this is handled by later procedures, which
5478  * will construct a "freefrag" structure to be added to the workitem queue
5479  * when the inode update is complete (or obsolete).  The main exception to
5480  * this is when an allocation occurs while a pending allocation dependency
5481  * (for the same block pointer) remains.  This case is handled in the main
5482  * allocation dependency setup procedure by immediately freeing the
5483  * unreferenced fragments.
5484  */
5485 void
5486 softdep_setup_allocdirect(
5487 	struct inode *ip,	/* inode to which block is being added */
5488 	ufs_lbn_t off,		/* block pointer within inode */
5489 	ufs2_daddr_t newblkno,	/* disk block number being added */
5490 	ufs2_daddr_t oldblkno,	/* previous block number, 0 unless frag */
5491 	long newsize,		/* size of new block */
5492 	long oldsize,		/* size of new block */
5493 	struct buf *bp)		/* bp for allocated block */
5494 {
5495 	struct allocdirect *adp, *oldadp;
5496 	struct allocdirectlst *adphead;
5497 	struct freefrag *freefrag;
5498 	struct inodedep *inodedep;
5499 	struct pagedep *pagedep;
5500 	struct jnewblk *jnewblk;
5501 	struct newblk *newblk;
5502 	struct mount *mp;
5503 	ufs_lbn_t lbn;
5504 
5505 	lbn = bp->b_lblkno;
5506 	mp = ITOVFS(ip);
5507 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5508 	    ("softdep_setup_allocdirect called on non-softdep filesystem"));
5509 	if (oldblkno && oldblkno != newblkno)
5510 		/*
5511 		 * The usual case is that a smaller fragment that
5512 		 * was just allocated has been replaced with a bigger
5513 		 * fragment or a full-size block. If it is marked as
5514 		 * B_DELWRI, the current contents have not been written
5515 		 * to disk. It is possible that the block was written
5516 		 * earlier, but very uncommon. If the block has never
5517 		 * been written, there is no need to send a BIO_DELETE
5518 		 * for it when it is freed. The gain from avoiding the
5519 		 * TRIMs for the common case of unwritten blocks far
5520 		 * exceeds the cost of the write amplification for the
5521 		 * uncommon case of failing to send a TRIM for a block
5522 		 * that had been written.
5523 		 */
5524 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn,
5525 		    (bp->b_flags & B_DELWRI) != 0 ? NOTRIM_KEY : SINGLETON_KEY);
5526 	else
5527 		freefrag = NULL;
5528 
5529 	CTR6(KTR_SUJ,
5530 	    "softdep_setup_allocdirect: ino %d blkno %jd oldblkno %jd "
5531 	    "off %jd newsize %ld oldsize %d",
5532 	    ip->i_number, newblkno, oldblkno, off, newsize, oldsize);
5533 	ACQUIRE_LOCK(ITOUMP(ip));
5534 	if (off >= UFS_NDADDR) {
5535 		if (lbn > 0)
5536 			panic("softdep_setup_allocdirect: bad lbn %jd, off %jd",
5537 			    lbn, off);
5538 		/* allocating an indirect block */
5539 		if (oldblkno != 0)
5540 			panic("softdep_setup_allocdirect: non-zero indir");
5541 	} else {
5542 		if (off != lbn)
5543 			panic("softdep_setup_allocdirect: lbn %jd != off %jd",
5544 			    lbn, off);
5545 		/*
5546 		 * Allocating a direct block.
5547 		 *
5548 		 * If we are allocating a directory block, then we must
5549 		 * allocate an associated pagedep to track additions and
5550 		 * deletions.
5551 		 */
5552 		if ((ip->i_mode & IFMT) == IFDIR)
5553 			pagedep_lookup(mp, bp, ip->i_number, off, DEPALLOC,
5554 			    &pagedep);
5555 	}
5556 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5557 		panic("softdep_setup_allocdirect: lost block");
5558 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5559 	    ("softdep_setup_allocdirect: newblk already initialized"));
5560 	/*
5561 	 * Convert the newblk to an allocdirect.
5562 	 */
5563 	WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5564 	adp = (struct allocdirect *)newblk;
5565 	newblk->nb_freefrag = freefrag;
5566 	adp->ad_offset = off;
5567 	adp->ad_oldblkno = oldblkno;
5568 	adp->ad_newsize = newsize;
5569 	adp->ad_oldsize = oldsize;
5570 
5571 	/*
5572 	 * Finish initializing the journal.
5573 	 */
5574 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5575 		jnewblk->jn_ino = ip->i_number;
5576 		jnewblk->jn_lbn = lbn;
5577 		add_to_journal(&jnewblk->jn_list);
5578 	}
5579 	if (freefrag && freefrag->ff_jdep != NULL &&
5580 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5581 		add_to_journal(freefrag->ff_jdep);
5582 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5583 	adp->ad_inodedep = inodedep;
5584 
5585 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5586 	/*
5587 	 * The list of allocdirects must be kept in sorted and ascending
5588 	 * order so that the rollback routines can quickly determine the
5589 	 * first uncommitted block (the size of the file stored on disk
5590 	 * ends at the end of the lowest committed fragment, or if there
5591 	 * are no fragments, at the end of the highest committed block).
5592 	 * Since files generally grow, the typical case is that the new
5593 	 * block is to be added at the end of the list. We speed this
5594 	 * special case by checking against the last allocdirect in the
5595 	 * list before laboriously traversing the list looking for the
5596 	 * insertion point.
5597 	 */
5598 	adphead = &inodedep->id_newinoupdt;
5599 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
5600 	if (oldadp == NULL || oldadp->ad_offset <= off) {
5601 		/* insert at end of list */
5602 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5603 		if (oldadp != NULL && oldadp->ad_offset == off)
5604 			allocdirect_merge(adphead, adp, oldadp);
5605 		FREE_LOCK(ITOUMP(ip));
5606 		return;
5607 	}
5608 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
5609 		if (oldadp->ad_offset >= off)
5610 			break;
5611 	}
5612 	if (oldadp == NULL)
5613 		panic("softdep_setup_allocdirect: lost entry");
5614 	/* insert in middle of list */
5615 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5616 	if (oldadp->ad_offset == off)
5617 		allocdirect_merge(adphead, adp, oldadp);
5618 
5619 	FREE_LOCK(ITOUMP(ip));
5620 }
5621 
5622 /*
5623  * Merge a newer and older journal record to be stored either in a
5624  * newblock or freefrag.  This handles aggregating journal records for
5625  * fragment allocation into a second record as well as replacing a
5626  * journal free with an aborted journal allocation.  A segment for the
5627  * oldest record will be placed on wkhd if it has been written.  If not
5628  * the segment for the newer record will suffice.
5629  */
5630 static struct worklist *
5631 jnewblk_merge(struct worklist *new,
5632 	struct worklist *old,
5633 	struct workhead *wkhd)
5634 {
5635 	struct jnewblk *njnewblk;
5636 	struct jnewblk *jnewblk;
5637 
5638 	/* Handle NULLs to simplify callers. */
5639 	if (new == NULL)
5640 		return (old);
5641 	if (old == NULL)
5642 		return (new);
5643 	/* Replace a jfreefrag with a jnewblk. */
5644 	if (new->wk_type == D_JFREEFRAG) {
5645 		if (WK_JNEWBLK(old)->jn_blkno != WK_JFREEFRAG(new)->fr_blkno)
5646 			panic("jnewblk_merge: blkno mismatch: %p, %p",
5647 			    old, new);
5648 		cancel_jfreefrag(WK_JFREEFRAG(new));
5649 		return (old);
5650 	}
5651 	if (old->wk_type != D_JNEWBLK || new->wk_type != D_JNEWBLK)
5652 		panic("jnewblk_merge: Bad type: old %d new %d\n",
5653 		    old->wk_type, new->wk_type);
5654 	/*
5655 	 * Handle merging of two jnewblk records that describe
5656 	 * different sets of fragments in the same block.
5657 	 */
5658 	jnewblk = WK_JNEWBLK(old);
5659 	njnewblk = WK_JNEWBLK(new);
5660 	if (jnewblk->jn_blkno != njnewblk->jn_blkno)
5661 		panic("jnewblk_merge: Merging disparate blocks.");
5662 	/*
5663 	 * The record may be rolled back in the cg.
5664 	 */
5665 	if (jnewblk->jn_state & UNDONE) {
5666 		jnewblk->jn_state &= ~UNDONE;
5667 		njnewblk->jn_state |= UNDONE;
5668 		njnewblk->jn_state &= ~ATTACHED;
5669 	}
5670 	/*
5671 	 * We modify the newer addref and free the older so that if neither
5672 	 * has been written the most up-to-date copy will be on disk.  If
5673 	 * both have been written but rolled back we only temporarily need
5674 	 * one of them to fix the bits when the cg write completes.
5675 	 */
5676 	jnewblk->jn_state |= ATTACHED | COMPLETE;
5677 	njnewblk->jn_oldfrags = jnewblk->jn_oldfrags;
5678 	cancel_jnewblk(jnewblk, wkhd);
5679 	WORKLIST_REMOVE(&jnewblk->jn_list);
5680 	free_jnewblk(jnewblk);
5681 	return (new);
5682 }
5683 
5684 /*
5685  * Replace an old allocdirect dependency with a newer one.
5686  */
5687 static void
5688 allocdirect_merge(
5689 	struct allocdirectlst *adphead,	/* head of list holding allocdirects */
5690 	struct allocdirect *newadp,	/* allocdirect being added */
5691 	struct allocdirect *oldadp)	/* existing allocdirect being checked */
5692 {
5693 	struct worklist *wk;
5694 	struct freefrag *freefrag;
5695 
5696 	freefrag = NULL;
5697 	LOCK_OWNED(VFSTOUFS(newadp->ad_list.wk_mp));
5698 	if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
5699 	    newadp->ad_oldsize != oldadp->ad_newsize ||
5700 	    newadp->ad_offset >= UFS_NDADDR)
5701 		panic("%s %jd != new %jd || old size %ld != new %ld",
5702 		    "allocdirect_merge: old blkno",
5703 		    (intmax_t)newadp->ad_oldblkno,
5704 		    (intmax_t)oldadp->ad_newblkno,
5705 		    newadp->ad_oldsize, oldadp->ad_newsize);
5706 	newadp->ad_oldblkno = oldadp->ad_oldblkno;
5707 	newadp->ad_oldsize = oldadp->ad_oldsize;
5708 	/*
5709 	 * If the old dependency had a fragment to free or had never
5710 	 * previously had a block allocated, then the new dependency
5711 	 * can immediately post its freefrag and adopt the old freefrag.
5712 	 * This action is done by swapping the freefrag dependencies.
5713 	 * The new dependency gains the old one's freefrag, and the
5714 	 * old one gets the new one and then immediately puts it on
5715 	 * the worklist when it is freed by free_newblk. It is
5716 	 * not possible to do this swap when the old dependency had a
5717 	 * non-zero size but no previous fragment to free. This condition
5718 	 * arises when the new block is an extension of the old block.
5719 	 * Here, the first part of the fragment allocated to the new
5720 	 * dependency is part of the block currently claimed on disk by
5721 	 * the old dependency, so cannot legitimately be freed until the
5722 	 * conditions for the new dependency are fulfilled.
5723 	 */
5724 	freefrag = newadp->ad_freefrag;
5725 	if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
5726 		newadp->ad_freefrag = oldadp->ad_freefrag;
5727 		oldadp->ad_freefrag = freefrag;
5728 	}
5729 	/*
5730 	 * If we are tracking a new directory-block allocation,
5731 	 * move it from the old allocdirect to the new allocdirect.
5732 	 */
5733 	if ((wk = LIST_FIRST(&oldadp->ad_newdirblk)) != NULL) {
5734 		WORKLIST_REMOVE(wk);
5735 		if (!LIST_EMPTY(&oldadp->ad_newdirblk))
5736 			panic("allocdirect_merge: extra newdirblk");
5737 		WORKLIST_INSERT(&newadp->ad_newdirblk, wk);
5738 	}
5739 	TAILQ_REMOVE(adphead, oldadp, ad_next);
5740 	/*
5741 	 * We need to move any journal dependencies over to the freefrag
5742 	 * that releases this block if it exists.  Otherwise we are
5743 	 * extending an existing block and we'll wait until that is
5744 	 * complete to release the journal space and extend the
5745 	 * new journal to cover this old space as well.
5746 	 */
5747 	if (freefrag == NULL) {
5748 		if (oldadp->ad_newblkno != newadp->ad_newblkno)
5749 			panic("allocdirect_merge: %jd != %jd",
5750 			    oldadp->ad_newblkno, newadp->ad_newblkno);
5751 		newadp->ad_block.nb_jnewblk = (struct jnewblk *)
5752 		    jnewblk_merge(&newadp->ad_block.nb_jnewblk->jn_list,
5753 		    &oldadp->ad_block.nb_jnewblk->jn_list,
5754 		    &newadp->ad_block.nb_jwork);
5755 		oldadp->ad_block.nb_jnewblk = NULL;
5756 		cancel_newblk(&oldadp->ad_block, NULL,
5757 		    &newadp->ad_block.nb_jwork);
5758 	} else {
5759 		wk = (struct worklist *) cancel_newblk(&oldadp->ad_block,
5760 		    &freefrag->ff_list, &freefrag->ff_jwork);
5761 		freefrag->ff_jdep = jnewblk_merge(freefrag->ff_jdep, wk,
5762 		    &freefrag->ff_jwork);
5763 	}
5764 	free_newblk(&oldadp->ad_block);
5765 }
5766 
5767 /*
5768  * Allocate a jfreefrag structure to journal a single block free.
5769  */
5770 static struct jfreefrag *
5771 newjfreefrag(struct freefrag *freefrag,
5772 	struct inode *ip,
5773 	ufs2_daddr_t blkno,
5774 	long size,
5775 	ufs_lbn_t lbn)
5776 {
5777 	struct jfreefrag *jfreefrag;
5778 	struct fs *fs;
5779 
5780 	fs = ITOFS(ip);
5781 	jfreefrag = malloc(sizeof(struct jfreefrag), M_JFREEFRAG,
5782 	    M_SOFTDEP_FLAGS);
5783 	workitem_alloc(&jfreefrag->fr_list, D_JFREEFRAG, ITOVFS(ip));
5784 	jfreefrag->fr_jsegdep = newjsegdep(&jfreefrag->fr_list);
5785 	jfreefrag->fr_state = ATTACHED | DEPCOMPLETE;
5786 	jfreefrag->fr_ino = ip->i_number;
5787 	jfreefrag->fr_lbn = lbn;
5788 	jfreefrag->fr_blkno = blkno;
5789 	jfreefrag->fr_frags = numfrags(fs, size);
5790 	jfreefrag->fr_freefrag = freefrag;
5791 
5792 	return (jfreefrag);
5793 }
5794 
5795 /*
5796  * Allocate a new freefrag structure.
5797  */
5798 static struct freefrag *
5799 newfreefrag(struct inode *ip,
5800 	ufs2_daddr_t blkno,
5801 	long size,
5802 	ufs_lbn_t lbn,
5803 	uint64_t key)
5804 {
5805 	struct freefrag *freefrag;
5806 	struct ufsmount *ump;
5807 	struct fs *fs;
5808 
5809 	CTR4(KTR_SUJ, "newfreefrag: ino %d blkno %jd size %ld lbn %jd",
5810 	    ip->i_number, blkno, size, lbn);
5811 	ump = ITOUMP(ip);
5812 	fs = ump->um_fs;
5813 	if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
5814 		panic("newfreefrag: frag size");
5815 	freefrag = malloc(sizeof(struct freefrag),
5816 	    M_FREEFRAG, M_SOFTDEP_FLAGS);
5817 	workitem_alloc(&freefrag->ff_list, D_FREEFRAG, UFSTOVFS(ump));
5818 	freefrag->ff_state = ATTACHED;
5819 	LIST_INIT(&freefrag->ff_jwork);
5820 	freefrag->ff_inum = ip->i_number;
5821 	freefrag->ff_vtype = ITOV(ip)->v_type;
5822 	freefrag->ff_blkno = blkno;
5823 	freefrag->ff_fragsize = size;
5824 	freefrag->ff_key = key;
5825 
5826 	if (MOUNTEDSUJ(UFSTOVFS(ump))) {
5827 		freefrag->ff_jdep = (struct worklist *)
5828 		    newjfreefrag(freefrag, ip, blkno, size, lbn);
5829 	} else {
5830 		freefrag->ff_state |= DEPCOMPLETE;
5831 		freefrag->ff_jdep = NULL;
5832 	}
5833 
5834 	return (freefrag);
5835 }
5836 
5837 /*
5838  * This workitem de-allocates fragments that were replaced during
5839  * file block allocation.
5840  */
5841 static void
5842 handle_workitem_freefrag(struct freefrag *freefrag)
5843 {
5844 	struct ufsmount *ump = VFSTOUFS(freefrag->ff_list.wk_mp);
5845 	struct workhead wkhd;
5846 
5847 	CTR3(KTR_SUJ,
5848 	    "handle_workitem_freefrag: ino %d blkno %jd size %ld",
5849 	    freefrag->ff_inum, freefrag->ff_blkno, freefrag->ff_fragsize);
5850 	/*
5851 	 * It would be illegal to add new completion items to the
5852 	 * freefrag after it was schedule to be done so it must be
5853 	 * safe to modify the list head here.
5854 	 */
5855 	LIST_INIT(&wkhd);
5856 	ACQUIRE_LOCK(ump);
5857 	LIST_SWAP(&freefrag->ff_jwork, &wkhd, worklist, wk_list);
5858 	/*
5859 	 * If the journal has not been written we must cancel it here.
5860 	 */
5861 	if (freefrag->ff_jdep) {
5862 		if (freefrag->ff_jdep->wk_type != D_JNEWBLK)
5863 			panic("handle_workitem_freefrag: Unexpected type %d\n",
5864 			    freefrag->ff_jdep->wk_type);
5865 		cancel_jnewblk(WK_JNEWBLK(freefrag->ff_jdep), &wkhd);
5866 	}
5867 	FREE_LOCK(ump);
5868 	ffs_blkfree(ump, ump->um_fs, ump->um_devvp, freefrag->ff_blkno,
5869 	   freefrag->ff_fragsize, freefrag->ff_inum, freefrag->ff_vtype,
5870 	   &wkhd, freefrag->ff_key);
5871 	ACQUIRE_LOCK(ump);
5872 	WORKITEM_FREE(freefrag, D_FREEFRAG);
5873 	FREE_LOCK(ump);
5874 }
5875 
5876 /*
5877  * Set up a dependency structure for an external attributes data block.
5878  * This routine follows much of the structure of softdep_setup_allocdirect.
5879  * See the description of softdep_setup_allocdirect above for details.
5880  */
5881 void
5882 softdep_setup_allocext(
5883 	struct inode *ip,
5884 	ufs_lbn_t off,
5885 	ufs2_daddr_t newblkno,
5886 	ufs2_daddr_t oldblkno,
5887 	long newsize,
5888 	long oldsize,
5889 	struct buf *bp)
5890 {
5891 	struct allocdirect *adp, *oldadp;
5892 	struct allocdirectlst *adphead;
5893 	struct freefrag *freefrag;
5894 	struct inodedep *inodedep;
5895 	struct jnewblk *jnewblk;
5896 	struct newblk *newblk;
5897 	struct mount *mp;
5898 	struct ufsmount *ump;
5899 	ufs_lbn_t lbn;
5900 
5901 	mp = ITOVFS(ip);
5902 	ump = VFSTOUFS(mp);
5903 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5904 	    ("softdep_setup_allocext called on non-softdep filesystem"));
5905 	KASSERT(off < UFS_NXADDR,
5906 	    ("softdep_setup_allocext: lbn %lld > UFS_NXADDR", (long long)off));
5907 
5908 	lbn = bp->b_lblkno;
5909 	if (oldblkno && oldblkno != newblkno)
5910 		/*
5911 		 * The usual case is that a smaller fragment that
5912 		 * was just allocated has been replaced with a bigger
5913 		 * fragment or a full-size block. If it is marked as
5914 		 * B_DELWRI, the current contents have not been written
5915 		 * to disk. It is possible that the block was written
5916 		 * earlier, but very uncommon. If the block has never
5917 		 * been written, there is no need to send a BIO_DELETE
5918 		 * for it when it is freed. The gain from avoiding the
5919 		 * TRIMs for the common case of unwritten blocks far
5920 		 * exceeds the cost of the write amplification for the
5921 		 * uncommon case of failing to send a TRIM for a block
5922 		 * that had been written.
5923 		 */
5924 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn,
5925 		    (bp->b_flags & B_DELWRI) != 0 ? NOTRIM_KEY : SINGLETON_KEY);
5926 	else
5927 		freefrag = NULL;
5928 
5929 	ACQUIRE_LOCK(ump);
5930 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5931 		panic("softdep_setup_allocext: lost block");
5932 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5933 	    ("softdep_setup_allocext: newblk already initialized"));
5934 	/*
5935 	 * Convert the newblk to an allocdirect.
5936 	 */
5937 	WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5938 	adp = (struct allocdirect *)newblk;
5939 	newblk->nb_freefrag = freefrag;
5940 	adp->ad_offset = off;
5941 	adp->ad_oldblkno = oldblkno;
5942 	adp->ad_newsize = newsize;
5943 	adp->ad_oldsize = oldsize;
5944 	adp->ad_state |=  EXTDATA;
5945 
5946 	/*
5947 	 * Finish initializing the journal.
5948 	 */
5949 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5950 		jnewblk->jn_ino = ip->i_number;
5951 		jnewblk->jn_lbn = lbn;
5952 		add_to_journal(&jnewblk->jn_list);
5953 	}
5954 	if (freefrag && freefrag->ff_jdep != NULL &&
5955 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5956 		add_to_journal(freefrag->ff_jdep);
5957 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5958 	adp->ad_inodedep = inodedep;
5959 
5960 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5961 	/*
5962 	 * The list of allocdirects must be kept in sorted and ascending
5963 	 * order so that the rollback routines can quickly determine the
5964 	 * first uncommitted block (the size of the file stored on disk
5965 	 * ends at the end of the lowest committed fragment, or if there
5966 	 * are no fragments, at the end of the highest committed block).
5967 	 * Since files generally grow, the typical case is that the new
5968 	 * block is to be added at the end of the list. We speed this
5969 	 * special case by checking against the last allocdirect in the
5970 	 * list before laboriously traversing the list looking for the
5971 	 * insertion point.
5972 	 */
5973 	adphead = &inodedep->id_newextupdt;
5974 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
5975 	if (oldadp == NULL || oldadp->ad_offset <= off) {
5976 		/* insert at end of list */
5977 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5978 		if (oldadp != NULL && oldadp->ad_offset == off)
5979 			allocdirect_merge(adphead, adp, oldadp);
5980 		FREE_LOCK(ump);
5981 		return;
5982 	}
5983 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
5984 		if (oldadp->ad_offset >= off)
5985 			break;
5986 	}
5987 	if (oldadp == NULL)
5988 		panic("softdep_setup_allocext: lost entry");
5989 	/* insert in middle of list */
5990 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5991 	if (oldadp->ad_offset == off)
5992 		allocdirect_merge(adphead, adp, oldadp);
5993 	FREE_LOCK(ump);
5994 }
5995 
5996 /*
5997  * Indirect block allocation dependencies.
5998  *
5999  * The same dependencies that exist for a direct block also exist when
6000  * a new block is allocated and pointed to by an entry in a block of
6001  * indirect pointers. The undo/redo states described above are also
6002  * used here. Because an indirect block contains many pointers that
6003  * may have dependencies, a second copy of the entire in-memory indirect
6004  * block is kept. The buffer cache copy is always completely up-to-date.
6005  * The second copy, which is used only as a source for disk writes,
6006  * contains only the safe pointers (i.e., those that have no remaining
6007  * update dependencies). The second copy is freed when all pointers
6008  * are safe. The cache is not allowed to replace indirect blocks with
6009  * pending update dependencies. If a buffer containing an indirect
6010  * block with dependencies is written, these routines will mark it
6011  * dirty again. It can only be successfully written once all the
6012  * dependencies are removed. The ffs_fsync routine in conjunction with
6013  * softdep_sync_metadata work together to get all the dependencies
6014  * removed so that a file can be successfully written to disk. Three
6015  * procedures are used when setting up indirect block pointer
6016  * dependencies. The division is necessary because of the organization
6017  * of the "balloc" routine and because of the distinction between file
6018  * pages and file metadata blocks.
6019  */
6020 
6021 /*
6022  * Allocate a new allocindir structure.
6023  */
6024 static struct allocindir *
6025 newallocindir(
6026 	struct inode *ip,	/* inode for file being extended */
6027 	int ptrno,		/* offset of pointer in indirect block */
6028 	ufs2_daddr_t newblkno,	/* disk block number being added */
6029 	ufs2_daddr_t oldblkno,	/* previous block number, 0 if none */
6030 	ufs_lbn_t lbn)
6031 {
6032 	struct newblk *newblk;
6033 	struct allocindir *aip;
6034 	struct freefrag *freefrag;
6035 	struct jnewblk *jnewblk;
6036 
6037 	if (oldblkno)
6038 		freefrag = newfreefrag(ip, oldblkno, ITOFS(ip)->fs_bsize, lbn,
6039 		    SINGLETON_KEY);
6040 	else
6041 		freefrag = NULL;
6042 	ACQUIRE_LOCK(ITOUMP(ip));
6043 	if (newblk_lookup(ITOVFS(ip), newblkno, 0, &newblk) == 0)
6044 		panic("new_allocindir: lost block");
6045 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
6046 	    ("newallocindir: newblk already initialized"));
6047 	WORKITEM_REASSIGN(newblk, D_ALLOCINDIR);
6048 	newblk->nb_freefrag = freefrag;
6049 	aip = (struct allocindir *)newblk;
6050 	aip->ai_offset = ptrno;
6051 	aip->ai_oldblkno = oldblkno;
6052 	aip->ai_lbn = lbn;
6053 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
6054 		jnewblk->jn_ino = ip->i_number;
6055 		jnewblk->jn_lbn = lbn;
6056 		add_to_journal(&jnewblk->jn_list);
6057 	}
6058 	if (freefrag && freefrag->ff_jdep != NULL &&
6059 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
6060 		add_to_journal(freefrag->ff_jdep);
6061 	return (aip);
6062 }
6063 
6064 /*
6065  * Called just before setting an indirect block pointer
6066  * to a newly allocated file page.
6067  */
6068 void
6069 softdep_setup_allocindir_page(
6070 	struct inode *ip,	/* inode for file being extended */
6071 	ufs_lbn_t lbn,		/* allocated block number within file */
6072 	struct buf *bp,		/* buffer with indirect blk referencing page */
6073 	int ptrno,		/* offset of pointer in indirect block */
6074 	ufs2_daddr_t newblkno,	/* disk block number being added */
6075 	ufs2_daddr_t oldblkno,	/* previous block number, 0 if none */
6076 	struct buf *nbp)	/* buffer holding allocated page */
6077 {
6078 	struct inodedep *inodedep;
6079 	struct freefrag *freefrag;
6080 	struct allocindir *aip;
6081 	struct pagedep *pagedep;
6082 	struct mount *mp;
6083 	struct ufsmount *ump;
6084 
6085 	mp = ITOVFS(ip);
6086 	ump = VFSTOUFS(mp);
6087 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6088 	    ("softdep_setup_allocindir_page called on non-softdep filesystem"));
6089 	KASSERT(lbn == nbp->b_lblkno,
6090 	    ("softdep_setup_allocindir_page: lbn %jd != lblkno %jd",
6091 	    lbn, bp->b_lblkno));
6092 	CTR4(KTR_SUJ,
6093 	    "softdep_setup_allocindir_page: ino %d blkno %jd oldblkno %jd "
6094 	    "lbn %jd", ip->i_number, newblkno, oldblkno, lbn);
6095 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_page");
6096 	aip = newallocindir(ip, ptrno, newblkno, oldblkno, lbn);
6097 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6098 	/*
6099 	 * If we are allocating a directory page, then we must
6100 	 * allocate an associated pagedep to track additions and
6101 	 * deletions.
6102 	 */
6103 	if ((ip->i_mode & IFMT) == IFDIR)
6104 		pagedep_lookup(mp, nbp, ip->i_number, lbn, DEPALLOC, &pagedep);
6105 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
6106 	freefrag = setup_allocindir_phase2(bp, ip, inodedep, aip, lbn);
6107 	FREE_LOCK(ump);
6108 	if (freefrag)
6109 		handle_workitem_freefrag(freefrag);
6110 }
6111 
6112 /*
6113  * Called just before setting an indirect block pointer to a
6114  * newly allocated indirect block.
6115  */
6116 void
6117 softdep_setup_allocindir_meta(
6118 	struct buf *nbp,	/* newly allocated indirect block */
6119 	struct inode *ip,	/* inode for file being extended */
6120 	struct buf *bp,		/* indirect block referencing allocated block */
6121 	int ptrno,		/* offset of pointer in indirect block */
6122 	ufs2_daddr_t newblkno)	/* disk block number being added */
6123 {
6124 	struct inodedep *inodedep;
6125 	struct allocindir *aip;
6126 	struct ufsmount *ump;
6127 	ufs_lbn_t lbn;
6128 
6129 	ump = ITOUMP(ip);
6130 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
6131 	    ("softdep_setup_allocindir_meta called on non-softdep filesystem"));
6132 	CTR3(KTR_SUJ,
6133 	    "softdep_setup_allocindir_meta: ino %d blkno %jd ptrno %d",
6134 	    ip->i_number, newblkno, ptrno);
6135 	lbn = nbp->b_lblkno;
6136 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_meta");
6137 	aip = newallocindir(ip, ptrno, newblkno, 0, lbn);
6138 	inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
6139 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
6140 	if (setup_allocindir_phase2(bp, ip, inodedep, aip, lbn))
6141 		panic("softdep_setup_allocindir_meta: Block already existed");
6142 	FREE_LOCK(ump);
6143 }
6144 
6145 static void
6146 indirdep_complete(struct indirdep *indirdep)
6147 {
6148 	struct allocindir *aip;
6149 
6150 	LIST_REMOVE(indirdep, ir_next);
6151 	indirdep->ir_state |= DEPCOMPLETE;
6152 
6153 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL) {
6154 		LIST_REMOVE(aip, ai_next);
6155 		free_newblk(&aip->ai_block);
6156 	}
6157 	/*
6158 	 * If this indirdep is not attached to a buf it was simply waiting
6159 	 * on completion to clear completehd.  free_indirdep() asserts
6160 	 * that nothing is dangling.
6161 	 */
6162 	if ((indirdep->ir_state & ONWORKLIST) == 0)
6163 		free_indirdep(indirdep);
6164 }
6165 
6166 static struct indirdep *
6167 indirdep_lookup(struct mount *mp,
6168 	struct inode *ip,
6169 	struct buf *bp)
6170 {
6171 	struct indirdep *indirdep, *newindirdep;
6172 	struct newblk *newblk;
6173 	struct ufsmount *ump;
6174 	struct worklist *wk;
6175 	struct fs *fs;
6176 	ufs2_daddr_t blkno;
6177 
6178 	ump = VFSTOUFS(mp);
6179 	LOCK_OWNED(ump);
6180 	indirdep = NULL;
6181 	newindirdep = NULL;
6182 	fs = ump->um_fs;
6183 	for (;;) {
6184 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
6185 			if (wk->wk_type != D_INDIRDEP)
6186 				continue;
6187 			indirdep = WK_INDIRDEP(wk);
6188 			break;
6189 		}
6190 		/* Found on the buffer worklist, no new structure to free. */
6191 		if (indirdep != NULL && newindirdep == NULL)
6192 			return (indirdep);
6193 		if (indirdep != NULL && newindirdep != NULL)
6194 			panic("indirdep_lookup: simultaneous create");
6195 		/* None found on the buffer and a new structure is ready. */
6196 		if (indirdep == NULL && newindirdep != NULL)
6197 			break;
6198 		/* None found and no new structure available. */
6199 		FREE_LOCK(ump);
6200 		newindirdep = malloc(sizeof(struct indirdep),
6201 		    M_INDIRDEP, M_SOFTDEP_FLAGS);
6202 		workitem_alloc(&newindirdep->ir_list, D_INDIRDEP, mp);
6203 		newindirdep->ir_state = ATTACHED;
6204 		if (I_IS_UFS1(ip))
6205 			newindirdep->ir_state |= UFS1FMT;
6206 		TAILQ_INIT(&newindirdep->ir_trunc);
6207 		newindirdep->ir_saveddata = NULL;
6208 		LIST_INIT(&newindirdep->ir_deplisthd);
6209 		LIST_INIT(&newindirdep->ir_donehd);
6210 		LIST_INIT(&newindirdep->ir_writehd);
6211 		LIST_INIT(&newindirdep->ir_completehd);
6212 		if (bp->b_blkno == bp->b_lblkno) {
6213 			ufs_bmaparray(bp->b_vp, bp->b_lblkno, &blkno, bp,
6214 			    NULL, NULL);
6215 			bp->b_blkno = blkno;
6216 		}
6217 		newindirdep->ir_freeblks = NULL;
6218 		newindirdep->ir_savebp =
6219 		    getblk(ump->um_devvp, bp->b_blkno, bp->b_bcount, 0, 0, 0);
6220 		newindirdep->ir_bp = bp;
6221 		BUF_KERNPROC(newindirdep->ir_savebp);
6222 		bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
6223 		ACQUIRE_LOCK(ump);
6224 	}
6225 	indirdep = newindirdep;
6226 	WORKLIST_INSERT(&bp->b_dep, &indirdep->ir_list);
6227 	/*
6228 	 * If the block is not yet allocated we don't set DEPCOMPLETE so
6229 	 * that we don't free dependencies until the pointers are valid.
6230 	 * This could search b_dep for D_ALLOCDIRECT/D_ALLOCINDIR rather
6231 	 * than using the hash.
6232 	 */
6233 	if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk))
6234 		LIST_INSERT_HEAD(&newblk->nb_indirdeps, indirdep, ir_next);
6235 	else
6236 		indirdep->ir_state |= DEPCOMPLETE;
6237 	return (indirdep);
6238 }
6239 
6240 /*
6241  * Called to finish the allocation of the "aip" allocated
6242  * by one of the two routines above.
6243  */
6244 static struct freefrag *
6245 setup_allocindir_phase2(
6246 	struct buf *bp,		/* in-memory copy of the indirect block */
6247 	struct inode *ip,	/* inode for file being extended */
6248 	struct inodedep *inodedep, /* Inodedep for ip */
6249 	struct allocindir *aip,	/* allocindir allocated by the above routines */
6250 	ufs_lbn_t lbn)		/* Logical block number for this block. */
6251 {
6252 	struct fs *fs __diagused;
6253 	struct indirdep *indirdep;
6254 	struct allocindir *oldaip;
6255 	struct freefrag *freefrag;
6256 	struct mount *mp;
6257 	struct ufsmount *ump;
6258 
6259 	mp = ITOVFS(ip);
6260 	ump = VFSTOUFS(mp);
6261 	LOCK_OWNED(ump);
6262 	fs = ump->um_fs;
6263 	if (bp->b_lblkno >= 0)
6264 		panic("setup_allocindir_phase2: not indir blk");
6265 	KASSERT(aip->ai_offset >= 0 && aip->ai_offset < NINDIR(fs),
6266 	    ("setup_allocindir_phase2: Bad offset %d", aip->ai_offset));
6267 	indirdep = indirdep_lookup(mp, ip, bp);
6268 	KASSERT(indirdep->ir_savebp != NULL,
6269 	    ("setup_allocindir_phase2 NULL ir_savebp"));
6270 	aip->ai_indirdep = indirdep;
6271 	/*
6272 	 * Check for an unwritten dependency for this indirect offset.  If
6273 	 * there is, merge the old dependency into the new one.  This happens
6274 	 * as a result of reallocblk only.
6275 	 */
6276 	freefrag = NULL;
6277 	if (aip->ai_oldblkno != 0) {
6278 		LIST_FOREACH(oldaip, &indirdep->ir_deplisthd, ai_next) {
6279 			if (oldaip->ai_offset == aip->ai_offset) {
6280 				freefrag = allocindir_merge(aip, oldaip);
6281 				goto done;
6282 			}
6283 		}
6284 		LIST_FOREACH(oldaip, &indirdep->ir_donehd, ai_next) {
6285 			if (oldaip->ai_offset == aip->ai_offset) {
6286 				freefrag = allocindir_merge(aip, oldaip);
6287 				goto done;
6288 			}
6289 		}
6290 	}
6291 done:
6292 	LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
6293 	return (freefrag);
6294 }
6295 
6296 /*
6297  * Merge two allocindirs which refer to the same block.  Move newblock
6298  * dependencies and setup the freefrags appropriately.
6299  */
6300 static struct freefrag *
6301 allocindir_merge(
6302 	struct allocindir *aip,
6303 	struct allocindir *oldaip)
6304 {
6305 	struct freefrag *freefrag;
6306 	struct worklist *wk;
6307 
6308 	if (oldaip->ai_newblkno != aip->ai_oldblkno)
6309 		panic("allocindir_merge: blkno");
6310 	aip->ai_oldblkno = oldaip->ai_oldblkno;
6311 	freefrag = aip->ai_freefrag;
6312 	aip->ai_freefrag = oldaip->ai_freefrag;
6313 	oldaip->ai_freefrag = NULL;
6314 	KASSERT(freefrag != NULL, ("setup_allocindir_phase2: No freefrag"));
6315 	/*
6316 	 * If we are tracking a new directory-block allocation,
6317 	 * move it from the old allocindir to the new allocindir.
6318 	 */
6319 	if ((wk = LIST_FIRST(&oldaip->ai_newdirblk)) != NULL) {
6320 		WORKLIST_REMOVE(wk);
6321 		if (!LIST_EMPTY(&oldaip->ai_newdirblk))
6322 			panic("allocindir_merge: extra newdirblk");
6323 		WORKLIST_INSERT(&aip->ai_newdirblk, wk);
6324 	}
6325 	/*
6326 	 * We can skip journaling for this freefrag and just complete
6327 	 * any pending journal work for the allocindir that is being
6328 	 * removed after the freefrag completes.
6329 	 */
6330 	if (freefrag->ff_jdep)
6331 		cancel_jfreefrag(WK_JFREEFRAG(freefrag->ff_jdep));
6332 	LIST_REMOVE(oldaip, ai_next);
6333 	freefrag->ff_jdep = (struct worklist *)cancel_newblk(&oldaip->ai_block,
6334 	    &freefrag->ff_list, &freefrag->ff_jwork);
6335 	free_newblk(&oldaip->ai_block);
6336 
6337 	return (freefrag);
6338 }
6339 
6340 static inline void
6341 setup_freedirect(
6342 	struct freeblks *freeblks,
6343 	struct inode *ip,
6344 	int i,
6345 	int needj)
6346 {
6347 	struct ufsmount *ump;
6348 	ufs2_daddr_t blkno;
6349 	int frags;
6350 
6351 	blkno = DIP(ip, i_db[i]);
6352 	if (blkno == 0)
6353 		return;
6354 	DIP_SET(ip, i_db[i], 0);
6355 	ump = ITOUMP(ip);
6356 	frags = sblksize(ump->um_fs, ip->i_size, i);
6357 	frags = numfrags(ump->um_fs, frags);
6358 	newfreework(ump, freeblks, NULL, i, blkno, frags, 0, needj);
6359 }
6360 
6361 static inline void
6362 setup_freeext(
6363 	struct freeblks *freeblks,
6364 	struct inode *ip,
6365 	int i,
6366 	int needj)
6367 {
6368 	struct ufsmount *ump;
6369 	ufs2_daddr_t blkno;
6370 	int frags;
6371 
6372 	blkno = ip->i_din2->di_extb[i];
6373 	if (blkno == 0)
6374 		return;
6375 	ip->i_din2->di_extb[i] = 0;
6376 	ump = ITOUMP(ip);
6377 	frags = sblksize(ump->um_fs, ip->i_din2->di_extsize, i);
6378 	frags = numfrags(ump->um_fs, frags);
6379 	newfreework(ump, freeblks, NULL, -1 - i, blkno, frags, 0, needj);
6380 }
6381 
6382 static inline void
6383 setup_freeindir(
6384 	struct freeblks *freeblks,
6385 	struct inode *ip,
6386 	int i,
6387 	ufs_lbn_t lbn,
6388 	int needj)
6389 {
6390 	struct ufsmount *ump;
6391 	ufs2_daddr_t blkno;
6392 
6393 	blkno = DIP(ip, i_ib[i]);
6394 	if (blkno == 0)
6395 		return;
6396 	DIP_SET(ip, i_ib[i], 0);
6397 	ump = ITOUMP(ip);
6398 	newfreework(ump, freeblks, NULL, lbn, blkno, ump->um_fs->fs_frag,
6399 	    0, needj);
6400 }
6401 
6402 static inline struct freeblks *
6403 newfreeblks(struct mount *mp, struct inode *ip)
6404 {
6405 	struct freeblks *freeblks;
6406 
6407 	freeblks = malloc(sizeof(struct freeblks),
6408 		M_FREEBLKS, M_SOFTDEP_FLAGS|M_ZERO);
6409 	workitem_alloc(&freeblks->fb_list, D_FREEBLKS, mp);
6410 	LIST_INIT(&freeblks->fb_jblkdephd);
6411 	LIST_INIT(&freeblks->fb_jwork);
6412 	freeblks->fb_ref = 0;
6413 	freeblks->fb_cgwait = 0;
6414 	freeblks->fb_state = ATTACHED;
6415 	freeblks->fb_uid = ip->i_uid;
6416 	freeblks->fb_inum = ip->i_number;
6417 	freeblks->fb_vtype = ITOV(ip)->v_type;
6418 	freeblks->fb_modrev = DIP(ip, i_modrev);
6419 	freeblks->fb_devvp = ITODEVVP(ip);
6420 	freeblks->fb_chkcnt = 0;
6421 	freeblks->fb_len = 0;
6422 
6423 	return (freeblks);
6424 }
6425 
6426 static void
6427 trunc_indirdep(
6428 	struct indirdep *indirdep,
6429 	struct freeblks *freeblks,
6430 	struct buf *bp,
6431 	int off)
6432 {
6433 	struct allocindir *aip, *aipn;
6434 
6435 	/*
6436 	 * The first set of allocindirs won't be in savedbp.
6437 	 */
6438 	LIST_FOREACH_SAFE(aip, &indirdep->ir_deplisthd, ai_next, aipn)
6439 		if (aip->ai_offset > off)
6440 			cancel_allocindir(aip, bp, freeblks, 1);
6441 	LIST_FOREACH_SAFE(aip, &indirdep->ir_donehd, ai_next, aipn)
6442 		if (aip->ai_offset > off)
6443 			cancel_allocindir(aip, bp, freeblks, 1);
6444 	/*
6445 	 * These will exist in savedbp.
6446 	 */
6447 	LIST_FOREACH_SAFE(aip, &indirdep->ir_writehd, ai_next, aipn)
6448 		if (aip->ai_offset > off)
6449 			cancel_allocindir(aip, NULL, freeblks, 0);
6450 	LIST_FOREACH_SAFE(aip, &indirdep->ir_completehd, ai_next, aipn)
6451 		if (aip->ai_offset > off)
6452 			cancel_allocindir(aip, NULL, freeblks, 0);
6453 }
6454 
6455 /*
6456  * Follow the chain of indirects down to lastlbn creating a freework
6457  * structure for each.  This will be used to start indir_trunc() at
6458  * the right offset and create the journal records for the parrtial
6459  * truncation.  A second step will handle the truncated dependencies.
6460  */
6461 static int
6462 setup_trunc_indir(
6463 	struct freeblks *freeblks,
6464 	struct inode *ip,
6465 	ufs_lbn_t lbn,
6466 	ufs_lbn_t lastlbn,
6467 	ufs2_daddr_t blkno)
6468 {
6469 	struct indirdep *indirdep;
6470 	struct indirdep *indirn;
6471 	struct freework *freework;
6472 	struct newblk *newblk;
6473 	struct mount *mp;
6474 	struct ufsmount *ump;
6475 	struct buf *bp;
6476 	uint8_t *start;
6477 	uint8_t *end;
6478 	ufs_lbn_t lbnadd;
6479 	int level;
6480 	int error;
6481 	int off;
6482 
6483 	freework = NULL;
6484 	if (blkno == 0)
6485 		return (0);
6486 	mp = freeblks->fb_list.wk_mp;
6487 	ump = VFSTOUFS(mp);
6488 	/*
6489 	 * Here, calls to VOP_BMAP() will fail.  However, we already have
6490 	 * the on-disk address, so we just pass it to bread() instead of
6491 	 * having bread() attempt to calculate it using VOP_BMAP().
6492 	 */
6493 	error = ffs_breadz(ump, ITOV(ip), lbn, blkptrtodb(ump, blkno),
6494 	    (int)mp->mnt_stat.f_iosize, NULL, NULL, 0, NOCRED, 0, NULL, &bp);
6495 	if (error)
6496 		return (error);
6497 	level = lbn_level(lbn);
6498 	lbnadd = lbn_offset(ump->um_fs, level);
6499 	/*
6500 	 * Compute the offset of the last block we want to keep.  Store
6501 	 * in the freework the first block we want to completely free.
6502 	 */
6503 	off = (lastlbn - -(lbn + level)) / lbnadd;
6504 	if (off + 1 == NINDIR(ump->um_fs))
6505 		goto nowork;
6506 	freework = newfreework(ump, freeblks, NULL, lbn, blkno, 0, off + 1, 0);
6507 	/*
6508 	 * Link the freework into the indirdep.  This will prevent any new
6509 	 * allocations from proceeding until we are finished with the
6510 	 * truncate and the block is written.
6511 	 */
6512 	ACQUIRE_LOCK(ump);
6513 	indirdep = indirdep_lookup(mp, ip, bp);
6514 	if (indirdep->ir_freeblks)
6515 		panic("setup_trunc_indir: indirdep already truncated.");
6516 	TAILQ_INSERT_TAIL(&indirdep->ir_trunc, freework, fw_next);
6517 	freework->fw_indir = indirdep;
6518 	/*
6519 	 * Cancel any allocindirs that will not make it to disk.
6520 	 * We have to do this for all copies of the indirdep that
6521 	 * live on this newblk.
6522 	 */
6523 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
6524 		if (newblk_lookup(mp, dbtofsb(ump->um_fs, bp->b_blkno), 0,
6525 		    &newblk) == 0)
6526 			panic("setup_trunc_indir: lost block");
6527 		LIST_FOREACH(indirn, &newblk->nb_indirdeps, ir_next)
6528 			trunc_indirdep(indirn, freeblks, bp, off);
6529 	} else
6530 		trunc_indirdep(indirdep, freeblks, bp, off);
6531 	FREE_LOCK(ump);
6532 	/*
6533 	 * Creation is protected by the buf lock. The saveddata is only
6534 	 * needed if a full truncation follows a partial truncation but it
6535 	 * is difficult to allocate in that case so we fetch it anyway.
6536 	 */
6537 	if (indirdep->ir_saveddata == NULL)
6538 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
6539 		    M_SOFTDEP_FLAGS);
6540 nowork:
6541 	/* Fetch the blkno of the child and the zero start offset. */
6542 	if (I_IS_UFS1(ip)) {
6543 		blkno = ((ufs1_daddr_t *)bp->b_data)[off];
6544 		start = (uint8_t *)&((ufs1_daddr_t *)bp->b_data)[off+1];
6545 	} else {
6546 		blkno = ((ufs2_daddr_t *)bp->b_data)[off];
6547 		start = (uint8_t *)&((ufs2_daddr_t *)bp->b_data)[off+1];
6548 	}
6549 	if (freework) {
6550 		/* Zero the truncated pointers. */
6551 		end = bp->b_data + bp->b_bcount;
6552 		bzero(start, end - start);
6553 		bdwrite(bp);
6554 	} else
6555 		bqrelse(bp);
6556 	if (level == 0)
6557 		return (0);
6558 	lbn++; /* adjust level */
6559 	lbn -= (off * lbnadd);
6560 	return setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno);
6561 }
6562 
6563 /*
6564  * Complete the partial truncation of an indirect block setup by
6565  * setup_trunc_indir().  This zeros the truncated pointers in the saved
6566  * copy and writes them to disk before the freeblks is allowed to complete.
6567  */
6568 static void
6569 complete_trunc_indir(struct freework *freework)
6570 {
6571 	struct freework *fwn;
6572 	struct indirdep *indirdep;
6573 	struct ufsmount *ump;
6574 	struct buf *bp;
6575 	uintptr_t start;
6576 	int count;
6577 
6578 	ump = VFSTOUFS(freework->fw_list.wk_mp);
6579 	LOCK_OWNED(ump);
6580 	indirdep = freework->fw_indir;
6581 	for (;;) {
6582 		bp = indirdep->ir_bp;
6583 		/* See if the block was discarded. */
6584 		if (bp == NULL)
6585 			break;
6586 		/* Inline part of getdirtybuf().  We dont want bremfree. */
6587 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) == 0)
6588 			break;
6589 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
6590 		    LOCK_PTR(ump)) == 0)
6591 			BUF_UNLOCK(bp);
6592 		ACQUIRE_LOCK(ump);
6593 	}
6594 	freework->fw_state |= DEPCOMPLETE;
6595 	TAILQ_REMOVE(&indirdep->ir_trunc, freework, fw_next);
6596 	/*
6597 	 * Zero the pointers in the saved copy.
6598 	 */
6599 	if (indirdep->ir_state & UFS1FMT)
6600 		start = sizeof(ufs1_daddr_t);
6601 	else
6602 		start = sizeof(ufs2_daddr_t);
6603 	start *= freework->fw_start;
6604 	count = indirdep->ir_savebp->b_bcount - start;
6605 	start += (uintptr_t)indirdep->ir_savebp->b_data;
6606 	bzero((char *)start, count);
6607 	/*
6608 	 * We need to start the next truncation in the list if it has not
6609 	 * been started yet.
6610 	 */
6611 	fwn = TAILQ_FIRST(&indirdep->ir_trunc);
6612 	if (fwn != NULL) {
6613 		if (fwn->fw_freeblks == indirdep->ir_freeblks)
6614 			TAILQ_REMOVE(&indirdep->ir_trunc, fwn, fw_next);
6615 		if ((fwn->fw_state & ONWORKLIST) == 0)
6616 			freework_enqueue(fwn);
6617 	}
6618 	/*
6619 	 * If bp is NULL the block was fully truncated, restore
6620 	 * the saved block list otherwise free it if it is no
6621 	 * longer needed.
6622 	 */
6623 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
6624 		if (bp == NULL)
6625 			bcopy(indirdep->ir_saveddata,
6626 			    indirdep->ir_savebp->b_data,
6627 			    indirdep->ir_savebp->b_bcount);
6628 		free(indirdep->ir_saveddata, M_INDIRDEP);
6629 		indirdep->ir_saveddata = NULL;
6630 	}
6631 	/*
6632 	 * When bp is NULL there is a full truncation pending.  We
6633 	 * must wait for this full truncation to be journaled before
6634 	 * we can release this freework because the disk pointers will
6635 	 * never be written as zero.
6636 	 */
6637 	if (bp == NULL)  {
6638 		if (LIST_EMPTY(&indirdep->ir_freeblks->fb_jblkdephd))
6639 			handle_written_freework(freework);
6640 		else
6641 			WORKLIST_INSERT(&indirdep->ir_freeblks->fb_freeworkhd,
6642 			   &freework->fw_list);
6643 		if (fwn == NULL) {
6644 			freework->fw_indir = (void *)0x0000deadbeef0000;
6645 			bp = indirdep->ir_savebp;
6646 			indirdep->ir_savebp = NULL;
6647 			free_indirdep(indirdep);
6648 			FREE_LOCK(ump);
6649 			brelse(bp);
6650 			ACQUIRE_LOCK(ump);
6651 		}
6652 	} else {
6653 		/* Complete when the real copy is written. */
6654 		WORKLIST_INSERT(&bp->b_dep, &freework->fw_list);
6655 		BUF_UNLOCK(bp);
6656 	}
6657 }
6658 
6659 /*
6660  * Calculate the number of blocks we are going to release where datablocks
6661  * is the current total and length is the new file size.
6662  */
6663 static ufs2_daddr_t
6664 blkcount(struct fs *fs,
6665 	ufs2_daddr_t datablocks,
6666 	off_t length)
6667 {
6668 	off_t totblks, numblks;
6669 
6670 	totblks = 0;
6671 	numblks = howmany(length, fs->fs_bsize);
6672 	if (numblks <= UFS_NDADDR) {
6673 		totblks = howmany(length, fs->fs_fsize);
6674 		goto out;
6675 	}
6676         totblks = blkstofrags(fs, numblks);
6677 	numblks -= UFS_NDADDR;
6678 	/*
6679 	 * Count all single, then double, then triple indirects required.
6680 	 * Subtracting one indirects worth of blocks for each pass
6681 	 * acknowledges one of each pointed to by the inode.
6682 	 */
6683 	for (;;) {
6684 		totblks += blkstofrags(fs, howmany(numblks, NINDIR(fs)));
6685 		numblks -= NINDIR(fs);
6686 		if (numblks <= 0)
6687 			break;
6688 		numblks = howmany(numblks, NINDIR(fs));
6689 	}
6690 out:
6691 	totblks = fsbtodb(fs, totblks);
6692 	/*
6693 	 * Handle sparse files.  We can't reclaim more blocks than the inode
6694 	 * references.  We will correct it later in handle_complete_freeblks()
6695 	 * when we know the real count.
6696 	 */
6697 	if (totblks > datablocks)
6698 		return (0);
6699 	return (datablocks - totblks);
6700 }
6701 
6702 /*
6703  * Handle freeblocks for journaled softupdate filesystems.
6704  *
6705  * Contrary to normal softupdates, we must preserve the block pointers in
6706  * indirects until their subordinates are free.  This is to avoid journaling
6707  * every block that is freed which may consume more space than the journal
6708  * itself.  The recovery program will see the free block journals at the
6709  * base of the truncated area and traverse them to reclaim space.  The
6710  * pointers in the inode may be cleared immediately after the journal
6711  * records are written because each direct and indirect pointer in the
6712  * inode is recorded in a journal.  This permits full truncation to proceed
6713  * asynchronously.  The write order is journal -> inode -> cgs -> indirects.
6714  *
6715  * The algorithm is as follows:
6716  * 1) Traverse the in-memory state and create journal entries to release
6717  *    the relevant blocks and full indirect trees.
6718  * 2) Traverse the indirect block chain adding partial truncation freework
6719  *    records to indirects in the path to lastlbn.  The freework will
6720  *    prevent new allocation dependencies from being satisfied in this
6721  *    indirect until the truncation completes.
6722  * 3) Read and lock the inode block, performing an update with the new size
6723  *    and pointers.  This prevents truncated data from becoming valid on
6724  *    disk through step 4.
6725  * 4) Reap unsatisfied dependencies that are beyond the truncated area,
6726  *    eliminate journal work for those records that do not require it.
6727  * 5) Schedule the journal records to be written followed by the inode block.
6728  * 6) Allocate any necessary frags for the end of file.
6729  * 7) Zero any partially truncated blocks.
6730  *
6731  * From this truncation proceeds asynchronously using the freework and
6732  * indir_trunc machinery.  The file will not be extended again into a
6733  * partially truncated indirect block until all work is completed but
6734  * the normal dependency mechanism ensures that it is rolled back/forward
6735  * as appropriate.  Further truncation may occur without delay and is
6736  * serialized in indir_trunc().
6737  */
6738 void
6739 softdep_journal_freeblocks(
6740 	struct inode *ip,	/* The inode whose length is to be reduced */
6741 	struct ucred *cred,
6742 	off_t length,		/* The new length for the file */
6743 	int flags)		/* IO_EXT and/or IO_NORMAL */
6744 {
6745 	struct freeblks *freeblks, *fbn;
6746 	struct worklist *wk, *wkn;
6747 	struct inodedep *inodedep;
6748 	struct jblkdep *jblkdep;
6749 	struct allocdirect *adp, *adpn;
6750 	struct ufsmount *ump;
6751 	struct fs *fs;
6752 	struct buf *bp;
6753 	struct vnode *vp;
6754 	struct mount *mp;
6755 	daddr_t dbn;
6756 	ufs2_daddr_t extblocks, datablocks;
6757 	ufs_lbn_t tmpval, lbn, lastlbn;
6758 	int frags, lastoff, iboff, allocblock, needj, error, i;
6759 
6760 	ump = ITOUMP(ip);
6761 	mp = UFSTOVFS(ump);
6762 	fs = ump->um_fs;
6763 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6764 	    ("softdep_journal_freeblocks called on non-softdep filesystem"));
6765 	vp = ITOV(ip);
6766 	needj = 1;
6767 	iboff = -1;
6768 	allocblock = 0;
6769 	extblocks = 0;
6770 	datablocks = 0;
6771 	frags = 0;
6772 	freeblks = newfreeblks(mp, ip);
6773 	ACQUIRE_LOCK(ump);
6774 	/*
6775 	 * If we're truncating a removed file that will never be written
6776 	 * we don't need to journal the block frees.  The canceled journals
6777 	 * for the allocations will suffice.
6778 	 */
6779 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6780 	if ((inodedep->id_state & (UNLINKED | DEPCOMPLETE)) == UNLINKED &&
6781 	    length == 0)
6782 		needj = 0;
6783 	CTR3(KTR_SUJ, "softdep_journal_freeblks: ip %d length %ld needj %d",
6784 	    ip->i_number, length, needj);
6785 	FREE_LOCK(ump);
6786 	/*
6787 	 * Calculate the lbn that we are truncating to.  This results in -1
6788 	 * if we're truncating the 0 bytes.  So it is the last lbn we want
6789 	 * to keep, not the first lbn we want to truncate.
6790 	 */
6791 	lastlbn = lblkno(fs, length + fs->fs_bsize - 1) - 1;
6792 	lastoff = blkoff(fs, length);
6793 	/*
6794 	 * Compute frags we are keeping in lastlbn.  0 means all.
6795 	 */
6796 	if (lastlbn >= 0 && lastlbn < UFS_NDADDR) {
6797 		frags = fragroundup(fs, lastoff);
6798 		/* adp offset of last valid allocdirect. */
6799 		iboff = lastlbn;
6800 	} else if (lastlbn > 0)
6801 		iboff = UFS_NDADDR;
6802 	if (fs->fs_magic == FS_UFS2_MAGIC)
6803 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6804 	/*
6805 	 * Handle normal data blocks and indirects.  This section saves
6806 	 * values used after the inode update to complete frag and indirect
6807 	 * truncation.
6808 	 */
6809 	if ((flags & IO_NORMAL) != 0) {
6810 		/*
6811 		 * Handle truncation of whole direct and indirect blocks.
6812 		 */
6813 		for (i = iboff + 1; i < UFS_NDADDR; i++)
6814 			setup_freedirect(freeblks, ip, i, needj);
6815 		for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
6816 		    i < UFS_NIADDR;
6817 		    i++, lbn += tmpval, tmpval *= NINDIR(fs)) {
6818 			/* Release a whole indirect tree. */
6819 			if (lbn > lastlbn) {
6820 				setup_freeindir(freeblks, ip, i, -lbn -i,
6821 				    needj);
6822 				continue;
6823 			}
6824 			iboff = i + UFS_NDADDR;
6825 			/*
6826 			 * Traverse partially truncated indirect tree.
6827 			 */
6828 			if (lbn <= lastlbn && lbn + tmpval - 1 > lastlbn)
6829 				setup_trunc_indir(freeblks, ip, -lbn - i,
6830 				    lastlbn, DIP(ip, i_ib[i]));
6831 		}
6832 		/*
6833 		 * Handle partial truncation to a frag boundary.
6834 		 */
6835 		if (frags) {
6836 			ufs2_daddr_t blkno;
6837 			long oldfrags;
6838 
6839 			oldfrags = blksize(fs, ip, lastlbn);
6840 			blkno = DIP(ip, i_db[lastlbn]);
6841 			if (blkno && oldfrags != frags) {
6842 				oldfrags -= frags;
6843 				oldfrags = numfrags(fs, oldfrags);
6844 				blkno += numfrags(fs, frags);
6845 				newfreework(ump, freeblks, NULL, lastlbn,
6846 				    blkno, oldfrags, 0, needj);
6847 				if (needj)
6848 					adjust_newfreework(freeblks,
6849 					    numfrags(fs, frags));
6850 			} else if (blkno == 0)
6851 				allocblock = 1;
6852 		}
6853 		/*
6854 		 * Add a journal record for partial truncate if we are
6855 		 * handling indirect blocks.  Non-indirects need no extra
6856 		 * journaling.
6857 		 */
6858 		if (length != 0 && lastlbn >= UFS_NDADDR) {
6859 			UFS_INODE_SET_FLAG(ip, IN_TRUNCATED);
6860 			newjtrunc(freeblks, length, 0);
6861 		}
6862 		ip->i_size = length;
6863 		DIP_SET(ip, i_size, ip->i_size);
6864 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE);
6865 		datablocks = DIP(ip, i_blocks) - extblocks;
6866 		if (length != 0)
6867 			datablocks = blkcount(fs, datablocks, length);
6868 		freeblks->fb_len = length;
6869 	}
6870 	if ((flags & IO_EXT) != 0) {
6871 		for (i = 0; i < UFS_NXADDR; i++)
6872 			setup_freeext(freeblks, ip, i, needj);
6873 		ip->i_din2->di_extsize = 0;
6874 		datablocks += extblocks;
6875 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE);
6876 	}
6877 #ifdef QUOTA
6878 	/* Reference the quotas in case the block count is wrong in the end. */
6879 	quotaref(vp, freeblks->fb_quota);
6880 	(void) chkdq(ip, -datablocks, NOCRED, FORCE);
6881 #endif
6882 	freeblks->fb_chkcnt = -datablocks;
6883 	UFS_LOCK(ump);
6884 	fs->fs_pendingblocks += datablocks;
6885 	UFS_UNLOCK(ump);
6886 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6887 	/*
6888 	 * Handle truncation of incomplete alloc direct dependencies.  We
6889 	 * hold the inode block locked to prevent incomplete dependencies
6890 	 * from reaching the disk while we are eliminating those that
6891 	 * have been truncated.  This is a partially inlined ffs_update().
6892 	 */
6893 	ufs_itimes(vp);
6894 	ip->i_flag &= ~(IN_LAZYACCESS | IN_LAZYMOD | IN_MODIFIED);
6895 	dbn = fsbtodb(fs, ino_to_fsba(fs, ip->i_number));
6896 	error = ffs_breadz(ump, ump->um_devvp, dbn, dbn, (int)fs->fs_bsize,
6897 	    NULL, NULL, 0, cred, 0, NULL, &bp);
6898 	if (error) {
6899 		softdep_error("softdep_journal_freeblocks", error);
6900 		return;
6901 	}
6902 	if (bp->b_bufsize == fs->fs_bsize)
6903 		bp->b_flags |= B_CLUSTEROK;
6904 	softdep_update_inodeblock(ip, bp, 0);
6905 	if (ump->um_fstype == UFS1) {
6906 		*((struct ufs1_dinode *)bp->b_data +
6907 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din1;
6908 	} else {
6909 		ffs_update_dinode_ckhash(fs, ip->i_din2);
6910 		*((struct ufs2_dinode *)bp->b_data +
6911 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din2;
6912 	}
6913 	ACQUIRE_LOCK(ump);
6914 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6915 	if ((inodedep->id_state & IOSTARTED) != 0)
6916 		panic("softdep_setup_freeblocks: inode busy");
6917 	/*
6918 	 * Add the freeblks structure to the list of operations that
6919 	 * must await the zero'ed inode being written to disk. If we
6920 	 * still have a bitmap dependency (needj), then the inode
6921 	 * has never been written to disk, so we can process the
6922 	 * freeblks below once we have deleted the dependencies.
6923 	 */
6924 	if (needj)
6925 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6926 	else
6927 		freeblks->fb_state |= COMPLETE;
6928 	if ((flags & IO_NORMAL) != 0) {
6929 		TAILQ_FOREACH_SAFE(adp, &inodedep->id_inoupdt, ad_next, adpn) {
6930 			if (adp->ad_offset > iboff)
6931 				cancel_allocdirect(&inodedep->id_inoupdt, adp,
6932 				    freeblks);
6933 			/*
6934 			 * Truncate the allocdirect.  We could eliminate
6935 			 * or modify journal records as well.
6936 			 */
6937 			else if (adp->ad_offset == iboff && frags)
6938 				adp->ad_newsize = frags;
6939 		}
6940 	}
6941 	if ((flags & IO_EXT) != 0)
6942 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
6943 			cancel_allocdirect(&inodedep->id_extupdt, adp,
6944 			    freeblks);
6945 	/*
6946 	 * Scan the bufwait list for newblock dependencies that will never
6947 	 * make it to disk.
6948 	 */
6949 	LIST_FOREACH_SAFE(wk, &inodedep->id_bufwait, wk_list, wkn) {
6950 		if (wk->wk_type != D_ALLOCDIRECT)
6951 			continue;
6952 		adp = WK_ALLOCDIRECT(wk);
6953 		if (((flags & IO_NORMAL) != 0 && (adp->ad_offset > iboff)) ||
6954 		    ((flags & IO_EXT) != 0 && (adp->ad_state & EXTDATA))) {
6955 			cancel_jfreeblk(freeblks, adp->ad_newblkno);
6956 			cancel_newblk(WK_NEWBLK(wk), NULL, &freeblks->fb_jwork);
6957 			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
6958 		}
6959 	}
6960 	/*
6961 	 * Add journal work.
6962 	 */
6963 	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps)
6964 		add_to_journal(&jblkdep->jb_list);
6965 	FREE_LOCK(ump);
6966 	bdwrite(bp);
6967 	/*
6968 	 * Truncate dependency structures beyond length.
6969 	 */
6970 	trunc_dependencies(ip, freeblks, lastlbn, frags, flags);
6971 	/*
6972 	 * This is only set when we need to allocate a fragment because
6973 	 * none existed at the end of a frag-sized file.  It handles only
6974 	 * allocating a new, zero filled block.
6975 	 */
6976 	if (allocblock) {
6977 		ip->i_size = length - lastoff;
6978 		DIP_SET(ip, i_size, ip->i_size);
6979 		error = UFS_BALLOC(vp, length - 1, 1, cred, BA_CLRBUF, &bp);
6980 		if (error != 0) {
6981 			softdep_error("softdep_journal_freeblks", error);
6982 			return;
6983 		}
6984 		ip->i_size = length;
6985 		DIP_SET(ip, i_size, length);
6986 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE | IN_UPDATE);
6987 		allocbuf(bp, frags);
6988 		ffs_update(vp, 0);
6989 		bawrite(bp);
6990 	} else if (lastoff != 0 && vp->v_type != VDIR) {
6991 		int size;
6992 
6993 		/*
6994 		 * Zero the end of a truncated frag or block.
6995 		 */
6996 		size = sblksize(fs, length, lastlbn);
6997 		error = bread(vp, lastlbn, size, cred, &bp);
6998 		if (error == 0) {
6999 			bzero((char *)bp->b_data + lastoff, size - lastoff);
7000 			bawrite(bp);
7001 		} else if (!ffs_fsfail_cleanup(ump, error)) {
7002 			softdep_error("softdep_journal_freeblks", error);
7003 			return;
7004 		}
7005 	}
7006 	ACQUIRE_LOCK(ump);
7007 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
7008 	TAILQ_INSERT_TAIL(&inodedep->id_freeblklst, freeblks, fb_next);
7009 	freeblks->fb_state |= DEPCOMPLETE | ONDEPLIST;
7010 	/*
7011 	 * We zero earlier truncations so they don't erroneously
7012 	 * update i_blocks.
7013 	 */
7014 	if (freeblks->fb_len == 0 && (flags & IO_NORMAL) != 0)
7015 		TAILQ_FOREACH(fbn, &inodedep->id_freeblklst, fb_next)
7016 			fbn->fb_len = 0;
7017 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE &&
7018 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
7019 		freeblks->fb_state |= INPROGRESS;
7020 	else
7021 		freeblks = NULL;
7022 	FREE_LOCK(ump);
7023 	if (freeblks)
7024 		handle_workitem_freeblocks(freeblks, 0);
7025 	trunc_pages(ip, length, extblocks, flags);
7026 
7027 }
7028 
7029 /*
7030  * Flush a JOP_SYNC to the journal.
7031  */
7032 void
7033 softdep_journal_fsync(struct inode *ip)
7034 {
7035 	struct jfsync *jfsync;
7036 	struct ufsmount *ump;
7037 
7038 	ump = ITOUMP(ip);
7039 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
7040 	    ("softdep_journal_fsync called on non-softdep filesystem"));
7041 	if ((ip->i_flag & IN_TRUNCATED) == 0)
7042 		return;
7043 	ip->i_flag &= ~IN_TRUNCATED;
7044 	jfsync = malloc(sizeof(*jfsync), M_JFSYNC, M_SOFTDEP_FLAGS | M_ZERO);
7045 	workitem_alloc(&jfsync->jfs_list, D_JFSYNC, UFSTOVFS(ump));
7046 	jfsync->jfs_size = ip->i_size;
7047 	jfsync->jfs_ino = ip->i_number;
7048 	ACQUIRE_LOCK(ump);
7049 	add_to_journal(&jfsync->jfs_list);
7050 	jwait(&jfsync->jfs_list, MNT_WAIT);
7051 	FREE_LOCK(ump);
7052 }
7053 
7054 /*
7055  * Block de-allocation dependencies.
7056  *
7057  * When blocks are de-allocated, the on-disk pointers must be nullified before
7058  * the blocks are made available for use by other files.  (The true
7059  * requirement is that old pointers must be nullified before new on-disk
7060  * pointers are set.  We chose this slightly more stringent requirement to
7061  * reduce complexity.) Our implementation handles this dependency by updating
7062  * the inode (or indirect block) appropriately but delaying the actual block
7063  * de-allocation (i.e., freemap and free space count manipulation) until
7064  * after the updated versions reach stable storage.  After the disk is
7065  * updated, the blocks can be safely de-allocated whenever it is convenient.
7066  * This implementation handles only the common case of reducing a file's
7067  * length to zero. Other cases are handled by the conventional synchronous
7068  * write approach.
7069  *
7070  * The ffs implementation with which we worked double-checks
7071  * the state of the block pointers and file size as it reduces
7072  * a file's length.  Some of this code is replicated here in our
7073  * soft updates implementation.  The freeblks->fb_chkcnt field is
7074  * used to transfer a part of this information to the procedure
7075  * that eventually de-allocates the blocks.
7076  *
7077  * This routine should be called from the routine that shortens
7078  * a file's length, before the inode's size or block pointers
7079  * are modified. It will save the block pointer information for
7080  * later release and zero the inode so that the calling routine
7081  * can release it.
7082  */
7083 void
7084 softdep_setup_freeblocks(
7085 	struct inode *ip,	/* The inode whose length is to be reduced */
7086 	off_t length,		/* The new length for the file */
7087 	int flags)		/* IO_EXT and/or IO_NORMAL */
7088 {
7089 	struct ufs1_dinode *dp1;
7090 	struct ufs2_dinode *dp2;
7091 	struct freeblks *freeblks;
7092 	struct inodedep *inodedep;
7093 	struct allocdirect *adp;
7094 	struct ufsmount *ump;
7095 	struct buf *bp;
7096 	struct fs *fs;
7097 	ufs2_daddr_t extblocks, datablocks;
7098 	struct mount *mp;
7099 	int i, delay, error;
7100 	ufs_lbn_t tmpval;
7101 	ufs_lbn_t lbn;
7102 
7103 	ump = ITOUMP(ip);
7104 	mp = UFSTOVFS(ump);
7105 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
7106 	    ("softdep_setup_freeblocks called on non-softdep filesystem"));
7107 	CTR2(KTR_SUJ, "softdep_setup_freeblks: ip %d length %ld",
7108 	    ip->i_number, length);
7109 	KASSERT(length == 0, ("softdep_setup_freeblocks: non-zero length"));
7110 	fs = ump->um_fs;
7111 	if ((error = bread(ump->um_devvp,
7112 	    fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
7113 	    (int)fs->fs_bsize, NOCRED, &bp)) != 0) {
7114 		if (!ffs_fsfail_cleanup(ump, error))
7115 			softdep_error("softdep_setup_freeblocks", error);
7116 		return;
7117 	}
7118 	freeblks = newfreeblks(mp, ip);
7119 	extblocks = 0;
7120 	datablocks = 0;
7121 	if (fs->fs_magic == FS_UFS2_MAGIC)
7122 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
7123 	if ((flags & IO_NORMAL) != 0) {
7124 		for (i = 0; i < UFS_NDADDR; i++)
7125 			setup_freedirect(freeblks, ip, i, 0);
7126 		for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
7127 		    i < UFS_NIADDR;
7128 		    i++, lbn += tmpval, tmpval *= NINDIR(fs))
7129 			setup_freeindir(freeblks, ip, i, -lbn -i, 0);
7130 		ip->i_size = 0;
7131 		DIP_SET(ip, i_size, 0);
7132 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE);
7133 		datablocks = DIP(ip, i_blocks) - extblocks;
7134 	}
7135 	if ((flags & IO_EXT) != 0) {
7136 		for (i = 0; i < UFS_NXADDR; i++)
7137 			setup_freeext(freeblks, ip, i, 0);
7138 		ip->i_din2->di_extsize = 0;
7139 		datablocks += extblocks;
7140 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE);
7141 	}
7142 #ifdef QUOTA
7143 	/* Reference the quotas in case the block count is wrong in the end. */
7144 	quotaref(ITOV(ip), freeblks->fb_quota);
7145 	(void) chkdq(ip, -datablocks, NOCRED, FORCE);
7146 #endif
7147 	freeblks->fb_chkcnt = -datablocks;
7148 	UFS_LOCK(ump);
7149 	fs->fs_pendingblocks += datablocks;
7150 	UFS_UNLOCK(ump);
7151 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
7152 	/*
7153 	 * Push the zero'ed inode to its disk buffer so that we are free
7154 	 * to delete its dependencies below. Once the dependencies are gone
7155 	 * the buffer can be safely released.
7156 	 */
7157 	if (ump->um_fstype == UFS1) {
7158 		dp1 = ((struct ufs1_dinode *)bp->b_data +
7159 		    ino_to_fsbo(fs, ip->i_number));
7160 		ip->i_din1->di_freelink = dp1->di_freelink;
7161 		*dp1 = *ip->i_din1;
7162 	} else {
7163 		dp2 = ((struct ufs2_dinode *)bp->b_data +
7164 		    ino_to_fsbo(fs, ip->i_number));
7165 		ip->i_din2->di_freelink = dp2->di_freelink;
7166 		ffs_update_dinode_ckhash(fs, ip->i_din2);
7167 		*dp2 = *ip->i_din2;
7168 	}
7169 	/*
7170 	 * Find and eliminate any inode dependencies.
7171 	 */
7172 	ACQUIRE_LOCK(ump);
7173 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
7174 	if ((inodedep->id_state & IOSTARTED) != 0)
7175 		panic("softdep_setup_freeblocks: inode busy");
7176 	/*
7177 	 * Add the freeblks structure to the list of operations that
7178 	 * must await the zero'ed inode being written to disk. If we
7179 	 * still have a bitmap dependency (delay == 0), then the inode
7180 	 * has never been written to disk, so we can process the
7181 	 * freeblks below once we have deleted the dependencies.
7182 	 */
7183 	delay = (inodedep->id_state & DEPCOMPLETE);
7184 	if (delay)
7185 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
7186 	else
7187 		freeblks->fb_state |= COMPLETE;
7188 	/*
7189 	 * Because the file length has been truncated to zero, any
7190 	 * pending block allocation dependency structures associated
7191 	 * with this inode are obsolete and can simply be de-allocated.
7192 	 * We must first merge the two dependency lists to get rid of
7193 	 * any duplicate freefrag structures, then purge the merged list.
7194 	 * If we still have a bitmap dependency, then the inode has never
7195 	 * been written to disk, so we can free any fragments without delay.
7196 	 */
7197 	if (flags & IO_NORMAL) {
7198 		merge_inode_lists(&inodedep->id_newinoupdt,
7199 		    &inodedep->id_inoupdt);
7200 		while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
7201 			cancel_allocdirect(&inodedep->id_inoupdt, adp,
7202 			    freeblks);
7203 	}
7204 	if (flags & IO_EXT) {
7205 		merge_inode_lists(&inodedep->id_newextupdt,
7206 		    &inodedep->id_extupdt);
7207 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
7208 			cancel_allocdirect(&inodedep->id_extupdt, adp,
7209 			    freeblks);
7210 	}
7211 	FREE_LOCK(ump);
7212 	bdwrite(bp);
7213 	trunc_dependencies(ip, freeblks, -1, 0, flags);
7214 	ACQUIRE_LOCK(ump);
7215 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
7216 		(void) free_inodedep(inodedep);
7217 	freeblks->fb_state |= DEPCOMPLETE;
7218 	/*
7219 	 * If the inode with zeroed block pointers is now on disk
7220 	 * we can start freeing blocks.
7221 	 */
7222 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
7223 		freeblks->fb_state |= INPROGRESS;
7224 	else
7225 		freeblks = NULL;
7226 	FREE_LOCK(ump);
7227 	if (freeblks)
7228 		handle_workitem_freeblocks(freeblks, 0);
7229 	trunc_pages(ip, length, extblocks, flags);
7230 }
7231 
7232 /*
7233  * Eliminate pages from the page cache that back parts of this inode and
7234  * adjust the vnode pager's idea of our size.  This prevents stale data
7235  * from hanging around in the page cache.
7236  */
7237 static void
7238 trunc_pages(
7239 	struct inode *ip,
7240 	off_t length,
7241 	ufs2_daddr_t extblocks,
7242 	int flags)
7243 {
7244 	struct vnode *vp;
7245 	struct fs *fs;
7246 	ufs_lbn_t lbn;
7247 	off_t end, extend;
7248 
7249 	vp = ITOV(ip);
7250 	fs = ITOFS(ip);
7251 	extend = OFF_TO_IDX(lblktosize(fs, -extblocks));
7252 	if ((flags & IO_EXT) != 0)
7253 		vn_pages_remove(vp, extend, 0);
7254 	if ((flags & IO_NORMAL) == 0)
7255 		return;
7256 	BO_LOCK(&vp->v_bufobj);
7257 	drain_output(vp);
7258 	BO_UNLOCK(&vp->v_bufobj);
7259 	/*
7260 	 * The vnode pager eliminates file pages we eliminate indirects
7261 	 * below.
7262 	 */
7263 	vnode_pager_setsize(vp, length);
7264 	/*
7265 	 * Calculate the end based on the last indirect we want to keep.  If
7266 	 * the block extends into indirects we can just use the negative of
7267 	 * its lbn.  Doubles and triples exist at lower numbers so we must
7268 	 * be careful not to remove those, if they exist.  double and triple
7269 	 * indirect lbns do not overlap with others so it is not important
7270 	 * to verify how many levels are required.
7271 	 */
7272 	lbn = lblkno(fs, length);
7273 	if (lbn >= UFS_NDADDR) {
7274 		/* Calculate the virtual lbn of the triple indirect. */
7275 		lbn = -lbn - (UFS_NIADDR - 1);
7276 		end = OFF_TO_IDX(lblktosize(fs, lbn));
7277 	} else
7278 		end = extend;
7279 	vn_pages_remove(vp, OFF_TO_IDX(OFF_MAX), end);
7280 }
7281 
7282 /*
7283  * See if the buf bp is in the range eliminated by truncation.
7284  */
7285 static int
7286 trunc_check_buf(
7287 	struct buf *bp,
7288 	int *blkoffp,
7289 	ufs_lbn_t lastlbn,
7290 	int lastoff,
7291 	int flags)
7292 {
7293 	ufs_lbn_t lbn;
7294 
7295 	*blkoffp = 0;
7296 	/* Only match ext/normal blocks as appropriate. */
7297 	if (((flags & IO_EXT) == 0 && (bp->b_xflags & BX_ALTDATA)) ||
7298 	    ((flags & IO_NORMAL) == 0 && (bp->b_xflags & BX_ALTDATA) == 0))
7299 		return (0);
7300 	/* ALTDATA is always a full truncation. */
7301 	if ((bp->b_xflags & BX_ALTDATA) != 0)
7302 		return (1);
7303 	/* -1 is full truncation. */
7304 	if (lastlbn == -1)
7305 		return (1);
7306 	/*
7307 	 * If this is a partial truncate we only want those
7308 	 * blocks and indirect blocks that cover the range
7309 	 * we're after.
7310 	 */
7311 	lbn = bp->b_lblkno;
7312 	if (lbn < 0)
7313 		lbn = -(lbn + lbn_level(lbn));
7314 	if (lbn < lastlbn)
7315 		return (0);
7316 	/* Here we only truncate lblkno if it's partial. */
7317 	if (lbn == lastlbn) {
7318 		if (lastoff == 0)
7319 			return (0);
7320 		*blkoffp = lastoff;
7321 	}
7322 	return (1);
7323 }
7324 
7325 /*
7326  * Eliminate any dependencies that exist in memory beyond lblkno:off
7327  */
7328 static void
7329 trunc_dependencies(
7330 	struct inode *ip,
7331 	struct freeblks *freeblks,
7332 	ufs_lbn_t lastlbn,
7333 	int lastoff,
7334 	int flags)
7335 {
7336 	struct bufobj *bo;
7337 	struct vnode *vp;
7338 	struct buf *bp;
7339 	int blkoff;
7340 
7341 	/*
7342 	 * We must wait for any I/O in progress to finish so that
7343 	 * all potential buffers on the dirty list will be visible.
7344 	 * Once they are all there, walk the list and get rid of
7345 	 * any dependencies.
7346 	 */
7347 	vp = ITOV(ip);
7348 	bo = &vp->v_bufobj;
7349 	BO_LOCK(bo);
7350 	drain_output(vp);
7351 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs)
7352 		bp->b_vflags &= ~BV_SCANNED;
7353 restart:
7354 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) {
7355 		if (bp->b_vflags & BV_SCANNED)
7356 			continue;
7357 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7358 			bp->b_vflags |= BV_SCANNED;
7359 			continue;
7360 		}
7361 		KASSERT(bp->b_bufobj == bo, ("Wrong object in buffer"));
7362 		if ((bp = getdirtybuf(bp, BO_LOCKPTR(bo), MNT_WAIT)) == NULL)
7363 			goto restart;
7364 		BO_UNLOCK(bo);
7365 		if (deallocate_dependencies(bp, freeblks, blkoff))
7366 			bqrelse(bp);
7367 		else
7368 			brelse(bp);
7369 		BO_LOCK(bo);
7370 		goto restart;
7371 	}
7372 	/*
7373 	 * Now do the work of vtruncbuf while also matching indirect blocks.
7374 	 */
7375 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs)
7376 		bp->b_vflags &= ~BV_SCANNED;
7377 cleanrestart:
7378 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs) {
7379 		if (bp->b_vflags & BV_SCANNED)
7380 			continue;
7381 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7382 			bp->b_vflags |= BV_SCANNED;
7383 			continue;
7384 		}
7385 		if (BUF_LOCK(bp,
7386 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
7387 		    BO_LOCKPTR(bo)) == ENOLCK) {
7388 			BO_LOCK(bo);
7389 			goto cleanrestart;
7390 		}
7391 		BO_LOCK(bo);
7392 		bp->b_vflags |= BV_SCANNED;
7393 		BO_UNLOCK(bo);
7394 		bremfree(bp);
7395 		if (blkoff != 0) {
7396 			allocbuf(bp, blkoff);
7397 			bqrelse(bp);
7398 		} else {
7399 			bp->b_flags |= B_INVAL | B_NOCACHE | B_RELBUF;
7400 			brelse(bp);
7401 		}
7402 		BO_LOCK(bo);
7403 		goto cleanrestart;
7404 	}
7405 	drain_output(vp);
7406 	BO_UNLOCK(bo);
7407 }
7408 
7409 static int
7410 cancel_pagedep(
7411 	struct pagedep *pagedep,
7412 	struct freeblks *freeblks,
7413 	int blkoff)
7414 {
7415 	struct jremref *jremref;
7416 	struct jmvref *jmvref;
7417 	struct dirrem *dirrem, *tmp;
7418 	int i;
7419 
7420 	/*
7421 	 * Copy any directory remove dependencies to the list
7422 	 * to be processed after the freeblks proceeds.  If
7423 	 * directory entry never made it to disk they
7424 	 * can be dumped directly onto the work list.
7425 	 */
7426 	LIST_FOREACH_SAFE(dirrem, &pagedep->pd_dirremhd, dm_next, tmp) {
7427 		/* Skip this directory removal if it is intended to remain. */
7428 		if (dirrem->dm_offset < blkoff)
7429 			continue;
7430 		/*
7431 		 * If there are any dirrems we wait for the journal write
7432 		 * to complete and then restart the buf scan as the lock
7433 		 * has been dropped.
7434 		 */
7435 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL) {
7436 			jwait(&jremref->jr_list, MNT_WAIT);
7437 			return (ERESTART);
7438 		}
7439 		LIST_REMOVE(dirrem, dm_next);
7440 		dirrem->dm_dirinum = pagedep->pd_ino;
7441 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &dirrem->dm_list);
7442 	}
7443 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL) {
7444 		jwait(&jmvref->jm_list, MNT_WAIT);
7445 		return (ERESTART);
7446 	}
7447 	/*
7448 	 * When we're partially truncating a pagedep we just want to flush
7449 	 * journal entries and return.  There can not be any adds in the
7450 	 * truncated portion of the directory and newblk must remain if
7451 	 * part of the block remains.
7452 	 */
7453 	if (blkoff != 0) {
7454 		struct diradd *dap;
7455 
7456 		LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
7457 			if (dap->da_offset > blkoff)
7458 				panic("cancel_pagedep: diradd %p off %d > %d",
7459 				    dap, dap->da_offset, blkoff);
7460 		for (i = 0; i < DAHASHSZ; i++)
7461 			LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist)
7462 				if (dap->da_offset > blkoff)
7463 					panic("cancel_pagedep: diradd %p off %d > %d",
7464 					    dap, dap->da_offset, blkoff);
7465 		return (0);
7466 	}
7467 	/*
7468 	 * There should be no directory add dependencies present
7469 	 * as the directory could not be truncated until all
7470 	 * children were removed.
7471 	 */
7472 	KASSERT(LIST_FIRST(&pagedep->pd_pendinghd) == NULL,
7473 	    ("deallocate_dependencies: pendinghd != NULL"));
7474 	for (i = 0; i < DAHASHSZ; i++)
7475 		KASSERT(LIST_FIRST(&pagedep->pd_diraddhd[i]) == NULL,
7476 		    ("deallocate_dependencies: diraddhd != NULL"));
7477 	if ((pagedep->pd_state & NEWBLOCK) != 0)
7478 		free_newdirblk(pagedep->pd_newdirblk);
7479 	if (free_pagedep(pagedep) == 0)
7480 		panic("Failed to free pagedep %p", pagedep);
7481 	return (0);
7482 }
7483 
7484 /*
7485  * Reclaim any dependency structures from a buffer that is about to
7486  * be reallocated to a new vnode. The buffer must be locked, thus,
7487  * no I/O completion operations can occur while we are manipulating
7488  * its associated dependencies. The mutex is held so that other I/O's
7489  * associated with related dependencies do not occur.
7490  */
7491 static int
7492 deallocate_dependencies(
7493 	struct buf *bp,
7494 	struct freeblks *freeblks,
7495 	int off)
7496 {
7497 	struct indirdep *indirdep;
7498 	struct pagedep *pagedep;
7499 	struct worklist *wk, *wkn;
7500 	struct ufsmount *ump;
7501 
7502 	ump = softdep_bp_to_mp(bp);
7503 	if (ump == NULL)
7504 		goto done;
7505 	ACQUIRE_LOCK(ump);
7506 	LIST_FOREACH_SAFE(wk, &bp->b_dep, wk_list, wkn) {
7507 		switch (wk->wk_type) {
7508 		case D_INDIRDEP:
7509 			indirdep = WK_INDIRDEP(wk);
7510 			if (bp->b_lblkno >= 0 ||
7511 			    bp->b_blkno != indirdep->ir_savebp->b_lblkno)
7512 				panic("deallocate_dependencies: not indir");
7513 			cancel_indirdep(indirdep, bp, freeblks);
7514 			continue;
7515 
7516 		case D_PAGEDEP:
7517 			pagedep = WK_PAGEDEP(wk);
7518 			if (cancel_pagedep(pagedep, freeblks, off)) {
7519 				FREE_LOCK(ump);
7520 				return (ERESTART);
7521 			}
7522 			continue;
7523 
7524 		case D_ALLOCINDIR:
7525 			/*
7526 			 * Simply remove the allocindir, we'll find it via
7527 			 * the indirdep where we can clear pointers if
7528 			 * needed.
7529 			 */
7530 			WORKLIST_REMOVE(wk);
7531 			continue;
7532 
7533 		case D_FREEWORK:
7534 			/*
7535 			 * A truncation is waiting for the zero'd pointers
7536 			 * to be written.  It can be freed when the freeblks
7537 			 * is journaled.
7538 			 */
7539 			WORKLIST_REMOVE(wk);
7540 			wk->wk_state |= ONDEPLIST;
7541 			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
7542 			break;
7543 
7544 		case D_ALLOCDIRECT:
7545 			if (off != 0)
7546 				continue;
7547 			/* FALLTHROUGH */
7548 		default:
7549 			panic("deallocate_dependencies: Unexpected type %s",
7550 			    TYPENAME(wk->wk_type));
7551 			/* NOTREACHED */
7552 		}
7553 	}
7554 	FREE_LOCK(ump);
7555 done:
7556 	/*
7557 	 * Don't throw away this buf, we were partially truncating and
7558 	 * some deps may always remain.
7559 	 */
7560 	if (off) {
7561 		allocbuf(bp, off);
7562 		bp->b_vflags |= BV_SCANNED;
7563 		return (EBUSY);
7564 	}
7565 	bp->b_flags |= B_INVAL | B_NOCACHE;
7566 
7567 	return (0);
7568 }
7569 
7570 /*
7571  * An allocdirect is being canceled due to a truncate.  We must make sure
7572  * the journal entry is released in concert with the blkfree that releases
7573  * the storage.  Completed journal entries must not be released until the
7574  * space is no longer pointed to by the inode or in the bitmap.
7575  */
7576 static void
7577 cancel_allocdirect(
7578 	struct allocdirectlst *adphead,
7579 	struct allocdirect *adp,
7580 	struct freeblks *freeblks)
7581 {
7582 	struct freework *freework;
7583 	struct newblk *newblk;
7584 	struct worklist *wk;
7585 
7586 	TAILQ_REMOVE(adphead, adp, ad_next);
7587 	newblk = (struct newblk *)adp;
7588 	freework = NULL;
7589 	/*
7590 	 * Find the correct freework structure.
7591 	 */
7592 	LIST_FOREACH(wk, &freeblks->fb_freeworkhd, wk_list) {
7593 		if (wk->wk_type != D_FREEWORK)
7594 			continue;
7595 		freework = WK_FREEWORK(wk);
7596 		if (freework->fw_blkno == newblk->nb_newblkno)
7597 			break;
7598 	}
7599 	if (freework == NULL)
7600 		panic("cancel_allocdirect: Freework not found");
7601 	/*
7602 	 * If a newblk exists at all we still have the journal entry that
7603 	 * initiated the allocation so we do not need to journal the free.
7604 	 */
7605 	cancel_jfreeblk(freeblks, freework->fw_blkno);
7606 	/*
7607 	 * If the journal hasn't been written the jnewblk must be passed
7608 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
7609 	 * this by linking the journal dependency into the freework to be
7610 	 * freed when freework_freeblock() is called.  If the journal has
7611 	 * been written we can simply reclaim the journal space when the
7612 	 * freeblks work is complete.
7613 	 */
7614 	freework->fw_jnewblk = cancel_newblk(newblk, &freework->fw_list,
7615 	    &freeblks->fb_jwork);
7616 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
7617 }
7618 
7619 /*
7620  * Cancel a new block allocation.  May be an indirect or direct block.  We
7621  * remove it from various lists and return any journal record that needs to
7622  * be resolved by the caller.
7623  *
7624  * A special consideration is made for indirects which were never pointed
7625  * at on disk and will never be found once this block is released.
7626  */
7627 static struct jnewblk *
7628 cancel_newblk(
7629 	struct newblk *newblk,
7630 	struct worklist *wk,
7631 	struct workhead *wkhd)
7632 {
7633 	struct jnewblk *jnewblk;
7634 
7635 	CTR1(KTR_SUJ, "cancel_newblk: blkno %jd", newblk->nb_newblkno);
7636 
7637 	newblk->nb_state |= GOINGAWAY;
7638 	/*
7639 	 * Previously we traversed the completedhd on each indirdep
7640 	 * attached to this newblk to cancel them and gather journal
7641 	 * work.  Since we need only the oldest journal segment and
7642 	 * the lowest point on the tree will always have the oldest
7643 	 * journal segment we are free to release the segments
7644 	 * of any subordinates and may leave the indirdep list to
7645 	 * indirdep_complete() when this newblk is freed.
7646 	 */
7647 	if (newblk->nb_state & ONDEPLIST) {
7648 		newblk->nb_state &= ~ONDEPLIST;
7649 		LIST_REMOVE(newblk, nb_deps);
7650 	}
7651 	if (newblk->nb_state & ONWORKLIST)
7652 		WORKLIST_REMOVE(&newblk->nb_list);
7653 	/*
7654 	 * If the journal entry hasn't been written we save a pointer to
7655 	 * the dependency that frees it until it is written or the
7656 	 * superseding operation completes.
7657 	 */
7658 	jnewblk = newblk->nb_jnewblk;
7659 	if (jnewblk != NULL && wk != NULL) {
7660 		newblk->nb_jnewblk = NULL;
7661 		jnewblk->jn_dep = wk;
7662 	}
7663 	if (!LIST_EMPTY(&newblk->nb_jwork))
7664 		jwork_move(wkhd, &newblk->nb_jwork);
7665 	/*
7666 	 * When truncating we must free the newdirblk early to remove
7667 	 * the pagedep from the hash before returning.
7668 	 */
7669 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7670 		free_newdirblk(WK_NEWDIRBLK(wk));
7671 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7672 		panic("cancel_newblk: extra newdirblk");
7673 
7674 	return (jnewblk);
7675 }
7676 
7677 /*
7678  * Schedule the freefrag associated with a newblk to be released once
7679  * the pointers are written and the previous block is no longer needed.
7680  */
7681 static void
7682 newblk_freefrag(struct newblk *newblk)
7683 {
7684 	struct freefrag *freefrag;
7685 
7686 	if (newblk->nb_freefrag == NULL)
7687 		return;
7688 	freefrag = newblk->nb_freefrag;
7689 	newblk->nb_freefrag = NULL;
7690 	freefrag->ff_state |= COMPLETE;
7691 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
7692 		add_to_worklist(&freefrag->ff_list, 0);
7693 }
7694 
7695 /*
7696  * Free a newblk. Generate a new freefrag work request if appropriate.
7697  * This must be called after the inode pointer and any direct block pointers
7698  * are valid or fully removed via truncate or frag extension.
7699  */
7700 static void
7701 free_newblk(struct newblk *newblk)
7702 {
7703 	struct indirdep *indirdep;
7704 	struct worklist *wk;
7705 
7706 	KASSERT(newblk->nb_jnewblk == NULL,
7707 	    ("free_newblk: jnewblk %p still attached", newblk->nb_jnewblk));
7708 	KASSERT(newblk->nb_list.wk_type != D_NEWBLK,
7709 	    ("free_newblk: unclaimed newblk"));
7710 	LOCK_OWNED(VFSTOUFS(newblk->nb_list.wk_mp));
7711 	newblk_freefrag(newblk);
7712 	if (newblk->nb_state & ONDEPLIST)
7713 		LIST_REMOVE(newblk, nb_deps);
7714 	if (newblk->nb_state & ONWORKLIST)
7715 		WORKLIST_REMOVE(&newblk->nb_list);
7716 	LIST_REMOVE(newblk, nb_hash);
7717 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7718 		free_newdirblk(WK_NEWDIRBLK(wk));
7719 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7720 		panic("free_newblk: extra newdirblk");
7721 	while ((indirdep = LIST_FIRST(&newblk->nb_indirdeps)) != NULL)
7722 		indirdep_complete(indirdep);
7723 	handle_jwork(&newblk->nb_jwork);
7724 	WORKITEM_FREE(newblk, D_NEWBLK);
7725 }
7726 
7727 /*
7728  * Free a newdirblk. Clear the NEWBLOCK flag on its associated pagedep.
7729  */
7730 static void
7731 free_newdirblk(struct newdirblk *newdirblk)
7732 {
7733 	struct pagedep *pagedep;
7734 	struct diradd *dap;
7735 	struct worklist *wk;
7736 
7737 	LOCK_OWNED(VFSTOUFS(newdirblk->db_list.wk_mp));
7738 	WORKLIST_REMOVE(&newdirblk->db_list);
7739 	/*
7740 	 * If the pagedep is still linked onto the directory buffer
7741 	 * dependency chain, then some of the entries on the
7742 	 * pd_pendinghd list may not be committed to disk yet. In
7743 	 * this case, we will simply clear the NEWBLOCK flag and
7744 	 * let the pd_pendinghd list be processed when the pagedep
7745 	 * is next written. If the pagedep is no longer on the buffer
7746 	 * dependency chain, then all the entries on the pd_pending
7747 	 * list are committed to disk and we can free them here.
7748 	 */
7749 	pagedep = newdirblk->db_pagedep;
7750 	pagedep->pd_state &= ~NEWBLOCK;
7751 	if ((pagedep->pd_state & ONWORKLIST) == 0) {
7752 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
7753 			free_diradd(dap, NULL);
7754 		/*
7755 		 * If no dependencies remain, the pagedep will be freed.
7756 		 */
7757 		free_pagedep(pagedep);
7758 	}
7759 	/* Should only ever be one item in the list. */
7760 	while ((wk = LIST_FIRST(&newdirblk->db_mkdir)) != NULL) {
7761 		WORKLIST_REMOVE(wk);
7762 		handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
7763 	}
7764 	WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
7765 }
7766 
7767 /*
7768  * Prepare an inode to be freed. The actual free operation is not
7769  * done until the zero'ed inode has been written to disk.
7770  */
7771 void
7772 softdep_freefile(
7773 	struct vnode *pvp,
7774 	ino_t ino,
7775 	int mode)
7776 {
7777 	struct inode *ip = VTOI(pvp);
7778 	struct inodedep *inodedep;
7779 	struct freefile *freefile;
7780 	struct freeblks *freeblks;
7781 	struct ufsmount *ump;
7782 
7783 	ump = ITOUMP(ip);
7784 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
7785 	    ("softdep_freefile called on non-softdep filesystem"));
7786 	/*
7787 	 * This sets up the inode de-allocation dependency.
7788 	 */
7789 	freefile = malloc(sizeof(struct freefile),
7790 		M_FREEFILE, M_SOFTDEP_FLAGS);
7791 	workitem_alloc(&freefile->fx_list, D_FREEFILE, pvp->v_mount);
7792 	freefile->fx_mode = mode;
7793 	freefile->fx_oldinum = ino;
7794 	freefile->fx_devvp = ump->um_devvp;
7795 	LIST_INIT(&freefile->fx_jwork);
7796 	UFS_LOCK(ump);
7797 	ump->um_fs->fs_pendinginodes += 1;
7798 	UFS_UNLOCK(ump);
7799 
7800 	/*
7801 	 * If the inodedep does not exist, then the zero'ed inode has
7802 	 * been written to disk. If the allocated inode has never been
7803 	 * written to disk, then the on-disk inode is zero'ed. In either
7804 	 * case we can free the file immediately.  If the journal was
7805 	 * canceled before being written the inode will never make it to
7806 	 * disk and we must send the canceled journal entrys to
7807 	 * ffs_freefile() to be cleared in conjunction with the bitmap.
7808 	 * Any blocks waiting on the inode to write can be safely freed
7809 	 * here as it will never been written.
7810 	 */
7811 	ACQUIRE_LOCK(ump);
7812 	inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7813 	if (inodedep) {
7814 		/*
7815 		 * Clear out freeblks that no longer need to reference
7816 		 * this inode.
7817 		 */
7818 		while ((freeblks =
7819 		    TAILQ_FIRST(&inodedep->id_freeblklst)) != NULL) {
7820 			TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks,
7821 			    fb_next);
7822 			freeblks->fb_state &= ~ONDEPLIST;
7823 		}
7824 		/*
7825 		 * Remove this inode from the unlinked list.
7826 		 */
7827 		if (inodedep->id_state & UNLINKED) {
7828 			/*
7829 			 * Save the journal work to be freed with the bitmap
7830 			 * before we clear UNLINKED.  Otherwise it can be lost
7831 			 * if the inode block is written.
7832 			 */
7833 			handle_bufwait(inodedep, &freefile->fx_jwork);
7834 			clear_unlinked_inodedep(inodedep);
7835 			/*
7836 			 * Re-acquire inodedep as we've dropped the
7837 			 * per-filesystem lock in clear_unlinked_inodedep().
7838 			 */
7839 			inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7840 		}
7841 	}
7842 	if (inodedep == NULL || check_inode_unwritten(inodedep)) {
7843 		FREE_LOCK(ump);
7844 		handle_workitem_freefile(freefile);
7845 		return;
7846 	}
7847 	if ((inodedep->id_state & DEPCOMPLETE) == 0)
7848 		inodedep->id_state |= GOINGAWAY;
7849 	WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
7850 	FREE_LOCK(ump);
7851 	if (ip->i_number == ino)
7852 		UFS_INODE_SET_FLAG(ip, IN_MODIFIED);
7853 }
7854 
7855 /*
7856  * Check to see if an inode has never been written to disk. If
7857  * so free the inodedep and return success, otherwise return failure.
7858  *
7859  * If we still have a bitmap dependency, then the inode has never
7860  * been written to disk. Drop the dependency as it is no longer
7861  * necessary since the inode is being deallocated. We set the
7862  * ALLCOMPLETE flags since the bitmap now properly shows that the
7863  * inode is not allocated. Even if the inode is actively being
7864  * written, it has been rolled back to its zero'ed state, so we
7865  * are ensured that a zero inode is what is on the disk. For short
7866  * lived files, this change will usually result in removing all the
7867  * dependencies from the inode so that it can be freed immediately.
7868  */
7869 static int
7870 check_inode_unwritten(struct inodedep *inodedep)
7871 {
7872 
7873 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7874 
7875 	if ((inodedep->id_state & (DEPCOMPLETE | UNLINKED)) != 0 ||
7876 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
7877 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
7878 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
7879 	    !LIST_EMPTY(&inodedep->id_inowait) ||
7880 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7881 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7882 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7883 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7884 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7885 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7886 	    inodedep->id_mkdiradd != NULL ||
7887 	    inodedep->id_nlinkdelta != 0)
7888 		return (0);
7889 	/*
7890 	 * Another process might be in initiate_write_inodeblock_ufs[12]
7891 	 * trying to allocate memory without holding "Softdep Lock".
7892 	 */
7893 	if ((inodedep->id_state & IOSTARTED) != 0 &&
7894 	    inodedep->id_savedino1 == NULL)
7895 		return (0);
7896 
7897 	if (inodedep->id_state & ONDEPLIST)
7898 		LIST_REMOVE(inodedep, id_deps);
7899 	inodedep->id_state &= ~ONDEPLIST;
7900 	inodedep->id_state |= ALLCOMPLETE;
7901 	inodedep->id_bmsafemap = NULL;
7902 	if (inodedep->id_state & ONWORKLIST)
7903 		WORKLIST_REMOVE(&inodedep->id_list);
7904 	if (inodedep->id_savedino1 != NULL) {
7905 		free(inodedep->id_savedino1, M_SAVEDINO);
7906 		inodedep->id_savedino1 = NULL;
7907 	}
7908 	if (free_inodedep(inodedep) == 0)
7909 		panic("check_inode_unwritten: busy inode");
7910 	return (1);
7911 }
7912 
7913 static int
7914 check_inodedep_free(struct inodedep *inodedep)
7915 {
7916 
7917 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7918 	if ((inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
7919 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
7920 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
7921 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
7922 	    !LIST_EMPTY(&inodedep->id_inowait) ||
7923 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7924 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7925 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7926 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7927 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7928 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7929 	    inodedep->id_mkdiradd != NULL ||
7930 	    inodedep->id_nlinkdelta != 0 ||
7931 	    inodedep->id_savedino1 != NULL)
7932 		return (0);
7933 	return (1);
7934 }
7935 
7936 /*
7937  * Try to free an inodedep structure. Return 1 if it could be freed.
7938  */
7939 static int
7940 free_inodedep(struct inodedep *inodedep)
7941 {
7942 
7943 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7944 	if ((inodedep->id_state & (ONWORKLIST | UNLINKED)) != 0 ||
7945 	    !check_inodedep_free(inodedep))
7946 		return (0);
7947 	if (inodedep->id_state & ONDEPLIST)
7948 		LIST_REMOVE(inodedep, id_deps);
7949 	LIST_REMOVE(inodedep, id_hash);
7950 	WORKITEM_FREE(inodedep, D_INODEDEP);
7951 	return (1);
7952 }
7953 
7954 /*
7955  * Free the block referenced by a freework structure.  The parent freeblks
7956  * structure is released and completed when the final cg bitmap reaches
7957  * the disk.  This routine may be freeing a jnewblk which never made it to
7958  * disk in which case we do not have to wait as the operation is undone
7959  * in memory immediately.
7960  */
7961 static void
7962 freework_freeblock(struct freework *freework, uint64_t key)
7963 {
7964 	struct freeblks *freeblks;
7965 	struct jnewblk *jnewblk;
7966 	struct ufsmount *ump;
7967 	struct workhead wkhd;
7968 	struct fs *fs;
7969 	int bsize;
7970 	int needj;
7971 
7972 	ump = VFSTOUFS(freework->fw_list.wk_mp);
7973 	LOCK_OWNED(ump);
7974 	/*
7975 	 * Handle partial truncate separately.
7976 	 */
7977 	if (freework->fw_indir) {
7978 		complete_trunc_indir(freework);
7979 		return;
7980 	}
7981 	freeblks = freework->fw_freeblks;
7982 	fs = ump->um_fs;
7983 	needj = MOUNTEDSUJ(freeblks->fb_list.wk_mp) != 0;
7984 	bsize = lfragtosize(fs, freework->fw_frags);
7985 	LIST_INIT(&wkhd);
7986 	/*
7987 	 * DEPCOMPLETE is cleared in indirblk_insert() if the block lives
7988 	 * on the indirblk hashtable and prevents premature freeing.
7989 	 */
7990 	freework->fw_state |= DEPCOMPLETE;
7991 	/*
7992 	 * SUJ needs to wait for the segment referencing freed indirect
7993 	 * blocks to expire so that we know the checker will not confuse
7994 	 * a re-allocated indirect block with its old contents.
7995 	 */
7996 	if (needj && freework->fw_lbn <= -UFS_NDADDR)
7997 		indirblk_insert(freework);
7998 	/*
7999 	 * If we are canceling an existing jnewblk pass it to the free
8000 	 * routine, otherwise pass the freeblk which will ultimately
8001 	 * release the freeblks.  If we're not journaling, we can just
8002 	 * free the freeblks immediately.
8003 	 */
8004 	jnewblk = freework->fw_jnewblk;
8005 	if (jnewblk != NULL) {
8006 		cancel_jnewblk(jnewblk, &wkhd);
8007 		needj = 0;
8008 	} else if (needj) {
8009 		freework->fw_state |= DELAYEDFREE;
8010 		freeblks->fb_cgwait++;
8011 		WORKLIST_INSERT(&wkhd, &freework->fw_list);
8012 	}
8013 	FREE_LOCK(ump);
8014 	freeblks_free(ump, freeblks, btodb(bsize));
8015 	CTR4(KTR_SUJ,
8016 	    "freework_freeblock: ino %jd blkno %jd lbn %jd size %d",
8017 	    freeblks->fb_inum, freework->fw_blkno, freework->fw_lbn, bsize);
8018 	ffs_blkfree(ump, fs, freeblks->fb_devvp, freework->fw_blkno, bsize,
8019 	    freeblks->fb_inum, freeblks->fb_vtype, &wkhd, key);
8020 	ACQUIRE_LOCK(ump);
8021 	/*
8022 	 * The jnewblk will be discarded and the bits in the map never
8023 	 * made it to disk.  We can immediately free the freeblk.
8024 	 */
8025 	if (needj == 0)
8026 		handle_written_freework(freework);
8027 }
8028 
8029 /*
8030  * We enqueue freework items that need processing back on the freeblks and
8031  * add the freeblks to the worklist.  This makes it easier to find all work
8032  * required to flush a truncation in process_truncates().
8033  */
8034 static void
8035 freework_enqueue(struct freework *freework)
8036 {
8037 	struct freeblks *freeblks;
8038 
8039 	freeblks = freework->fw_freeblks;
8040 	if ((freework->fw_state & INPROGRESS) == 0)
8041 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
8042 	if ((freeblks->fb_state &
8043 	    (ONWORKLIST | INPROGRESS | ALLCOMPLETE)) == ALLCOMPLETE &&
8044 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
8045 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
8046 }
8047 
8048 /*
8049  * Start, continue, or finish the process of freeing an indirect block tree.
8050  * The free operation may be paused at any point with fw_off containing the
8051  * offset to restart from.  This enables us to implement some flow control
8052  * for large truncates which may fan out and generate a huge number of
8053  * dependencies.
8054  */
8055 static void
8056 handle_workitem_indirblk(struct freework *freework)
8057 {
8058 	struct freeblks *freeblks;
8059 	struct ufsmount *ump;
8060 	struct fs *fs;
8061 
8062 	freeblks = freework->fw_freeblks;
8063 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8064 	fs = ump->um_fs;
8065 	if (freework->fw_state & DEPCOMPLETE) {
8066 		handle_written_freework(freework);
8067 		return;
8068 	}
8069 	if (freework->fw_off == NINDIR(fs)) {
8070 		freework_freeblock(freework, SINGLETON_KEY);
8071 		return;
8072 	}
8073 	freework->fw_state |= INPROGRESS;
8074 	FREE_LOCK(ump);
8075 	indir_trunc(freework, fsbtodb(fs, freework->fw_blkno),
8076 	    freework->fw_lbn);
8077 	ACQUIRE_LOCK(ump);
8078 }
8079 
8080 /*
8081  * Called when a freework structure attached to a cg buf is written.  The
8082  * ref on either the parent or the freeblks structure is released and
8083  * the freeblks is added back to the worklist if there is more work to do.
8084  */
8085 static void
8086 handle_written_freework(struct freework *freework)
8087 {
8088 	struct freeblks *freeblks;
8089 	struct freework *parent;
8090 
8091 	freeblks = freework->fw_freeblks;
8092 	parent = freework->fw_parent;
8093 	if (freework->fw_state & DELAYEDFREE)
8094 		freeblks->fb_cgwait--;
8095 	freework->fw_state |= COMPLETE;
8096 	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
8097 		WORKITEM_FREE(freework, D_FREEWORK);
8098 	if (parent) {
8099 		if (--parent->fw_ref == 0)
8100 			freework_enqueue(parent);
8101 		return;
8102 	}
8103 	if (--freeblks->fb_ref != 0)
8104 		return;
8105 	if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST | INPROGRESS)) ==
8106 	    ALLCOMPLETE && LIST_EMPTY(&freeblks->fb_jblkdephd))
8107 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
8108 }
8109 
8110 /*
8111  * This workitem routine performs the block de-allocation.
8112  * The workitem is added to the pending list after the updated
8113  * inode block has been written to disk.  As mentioned above,
8114  * checks regarding the number of blocks de-allocated (compared
8115  * to the number of blocks allocated for the file) are also
8116  * performed in this function.
8117  */
8118 static int
8119 handle_workitem_freeblocks(struct freeblks *freeblks, int flags)
8120 {
8121 	struct freework *freework;
8122 	struct newblk *newblk;
8123 	struct allocindir *aip;
8124 	struct ufsmount *ump;
8125 	struct worklist *wk;
8126 	uint64_t key;
8127 
8128 	KASSERT(LIST_EMPTY(&freeblks->fb_jblkdephd),
8129 	    ("handle_workitem_freeblocks: Journal entries not written."));
8130 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8131 	key = ffs_blkrelease_start(ump, freeblks->fb_devvp, freeblks->fb_inum);
8132 	ACQUIRE_LOCK(ump);
8133 	while ((wk = LIST_FIRST(&freeblks->fb_freeworkhd)) != NULL) {
8134 		WORKLIST_REMOVE(wk);
8135 		switch (wk->wk_type) {
8136 		case D_DIRREM:
8137 			wk->wk_state |= COMPLETE;
8138 			add_to_worklist(wk, 0);
8139 			continue;
8140 
8141 		case D_ALLOCDIRECT:
8142 			free_newblk(WK_NEWBLK(wk));
8143 			continue;
8144 
8145 		case D_ALLOCINDIR:
8146 			aip = WK_ALLOCINDIR(wk);
8147 			freework = NULL;
8148 			if (aip->ai_state & DELAYEDFREE) {
8149 				FREE_LOCK(ump);
8150 				freework = newfreework(ump, freeblks, NULL,
8151 				    aip->ai_lbn, aip->ai_newblkno,
8152 				    ump->um_fs->fs_frag, 0, 0);
8153 				ACQUIRE_LOCK(ump);
8154 			}
8155 			newblk = WK_NEWBLK(wk);
8156 			if (newblk->nb_jnewblk) {
8157 				freework->fw_jnewblk = newblk->nb_jnewblk;
8158 				newblk->nb_jnewblk->jn_dep = &freework->fw_list;
8159 				newblk->nb_jnewblk = NULL;
8160 			}
8161 			free_newblk(newblk);
8162 			continue;
8163 
8164 		case D_FREEWORK:
8165 			freework = WK_FREEWORK(wk);
8166 			if (freework->fw_lbn <= -UFS_NDADDR)
8167 				handle_workitem_indirblk(freework);
8168 			else
8169 				freework_freeblock(freework, key);
8170 			continue;
8171 		default:
8172 			panic("handle_workitem_freeblocks: Unknown type %s",
8173 			    TYPENAME(wk->wk_type));
8174 		}
8175 	}
8176 	if (freeblks->fb_ref != 0) {
8177 		freeblks->fb_state &= ~INPROGRESS;
8178 		wake_worklist(&freeblks->fb_list);
8179 		freeblks = NULL;
8180 	}
8181 	FREE_LOCK(ump);
8182 	ffs_blkrelease_finish(ump, key);
8183 	if (freeblks)
8184 		return handle_complete_freeblocks(freeblks, flags);
8185 	return (0);
8186 }
8187 
8188 /*
8189  * Handle completion of block free via truncate.  This allows fs_pending
8190  * to track the actual free block count more closely than if we only updated
8191  * it at the end.  We must be careful to handle cases where the block count
8192  * on free was incorrect.
8193  */
8194 static void
8195 freeblks_free(struct ufsmount *ump,
8196 	struct freeblks *freeblks,
8197 	int blocks)
8198 {
8199 	struct fs *fs;
8200 	ufs2_daddr_t remain;
8201 
8202 	UFS_LOCK(ump);
8203 	remain = -freeblks->fb_chkcnt;
8204 	freeblks->fb_chkcnt += blocks;
8205 	if (remain > 0) {
8206 		if (remain < blocks)
8207 			blocks = remain;
8208 		fs = ump->um_fs;
8209 		fs->fs_pendingblocks -= blocks;
8210 	}
8211 	UFS_UNLOCK(ump);
8212 }
8213 
8214 /*
8215  * Once all of the freework workitems are complete we can retire the
8216  * freeblocks dependency and any journal work awaiting completion.  This
8217  * can not be called until all other dependencies are stable on disk.
8218  */
8219 static int
8220 handle_complete_freeblocks(struct freeblks *freeblks, int flags)
8221 {
8222 	struct inodedep *inodedep;
8223 	struct inode *ip;
8224 	struct vnode *vp;
8225 	struct fs *fs;
8226 	struct ufsmount *ump;
8227 	ufs2_daddr_t spare;
8228 
8229 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8230 	fs = ump->um_fs;
8231 	flags = LK_EXCLUSIVE | flags;
8232 	spare = freeblks->fb_chkcnt;
8233 
8234 	/*
8235 	 * If we did not release the expected number of blocks we may have
8236 	 * to adjust the inode block count here.  Only do so if it wasn't
8237 	 * a truncation to zero and the modrev still matches.
8238 	 */
8239 	if (spare && freeblks->fb_len != 0) {
8240 		if (ffs_vgetf(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8241 		    flags, &vp, FFSV_FORCEINSMQ | FFSV_FORCEINODEDEP) != 0)
8242 			return (EBUSY);
8243 		ip = VTOI(vp);
8244 		if (ip->i_mode == 0) {
8245 			vgone(vp);
8246 		} else if (DIP(ip, i_modrev) == freeblks->fb_modrev) {
8247 			DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - spare);
8248 			UFS_INODE_SET_FLAG(ip, IN_CHANGE);
8249 			/*
8250 			 * We must wait so this happens before the
8251 			 * journal is reclaimed.
8252 			 */
8253 			ffs_update(vp, 1);
8254 		}
8255 		vput(vp);
8256 	}
8257 	if (spare < 0) {
8258 		UFS_LOCK(ump);
8259 		fs->fs_pendingblocks += spare;
8260 		UFS_UNLOCK(ump);
8261 	}
8262 #ifdef QUOTA
8263 	/* Handle spare. */
8264 	if (spare)
8265 		quotaadj(freeblks->fb_quota, ump, -spare);
8266 	quotarele(freeblks->fb_quota);
8267 #endif
8268 	ACQUIRE_LOCK(ump);
8269 	if (freeblks->fb_state & ONDEPLIST) {
8270 		inodedep_lookup(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8271 		    0, &inodedep);
8272 		TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks, fb_next);
8273 		freeblks->fb_state &= ~ONDEPLIST;
8274 		if (TAILQ_EMPTY(&inodedep->id_freeblklst))
8275 			free_inodedep(inodedep);
8276 	}
8277 	/*
8278 	 * All of the freeblock deps must be complete prior to this call
8279 	 * so it's now safe to complete earlier outstanding journal entries.
8280 	 */
8281 	handle_jwork(&freeblks->fb_jwork);
8282 	WORKITEM_FREE(freeblks, D_FREEBLKS);
8283 	FREE_LOCK(ump);
8284 	return (0);
8285 }
8286 
8287 /*
8288  * Release blocks associated with the freeblks and stored in the indirect
8289  * block dbn. If level is greater than SINGLE, the block is an indirect block
8290  * and recursive calls to indirtrunc must be used to cleanse other indirect
8291  * blocks.
8292  *
8293  * This handles partial and complete truncation of blocks.  Partial is noted
8294  * with goingaway == 0.  In this case the freework is completed after the
8295  * zero'd indirects are written to disk.  For full truncation the freework
8296  * is completed after the block is freed.
8297  */
8298 static void
8299 indir_trunc(struct freework *freework,
8300 	ufs2_daddr_t dbn,
8301 	ufs_lbn_t lbn)
8302 {
8303 	struct freework *nfreework;
8304 	struct workhead wkhd;
8305 	struct freeblks *freeblks;
8306 	struct buf *bp;
8307 	struct fs *fs;
8308 	struct indirdep *indirdep;
8309 	struct mount *mp;
8310 	struct ufsmount *ump;
8311 	ufs1_daddr_t *bap1;
8312 	ufs2_daddr_t nb, nnb, *bap2;
8313 	ufs_lbn_t lbnadd, nlbn;
8314 	uint64_t key;
8315 	int nblocks, ufs1fmt, freedblocks;
8316 	int goingaway, freedeps, needj, level, cnt, i, error;
8317 
8318 	freeblks = freework->fw_freeblks;
8319 	mp = freeblks->fb_list.wk_mp;
8320 	ump = VFSTOUFS(mp);
8321 	fs = ump->um_fs;
8322 	/*
8323 	 * Get buffer of block pointers to be freed.  There are three cases:
8324 	 *
8325 	 * 1) Partial truncate caches the indirdep pointer in the freework
8326 	 *    which provides us a back copy to the save bp which holds the
8327 	 *    pointers we want to clear.  When this completes the zero
8328 	 *    pointers are written to the real copy.
8329 	 * 2) The indirect is being completely truncated, cancel_indirdep()
8330 	 *    eliminated the real copy and placed the indirdep on the saved
8331 	 *    copy.  The indirdep and buf are discarded when this completes.
8332 	 * 3) The indirect was not in memory, we read a copy off of the disk
8333 	 *    using the devvp and drop and invalidate the buffer when we're
8334 	 *    done.
8335 	 */
8336 	goingaway = 1;
8337 	indirdep = NULL;
8338 	if (freework->fw_indir != NULL) {
8339 		goingaway = 0;
8340 		indirdep = freework->fw_indir;
8341 		bp = indirdep->ir_savebp;
8342 		if (bp == NULL || bp->b_blkno != dbn)
8343 			panic("indir_trunc: Bad saved buf %p blkno %jd",
8344 			    bp, (intmax_t)dbn);
8345 	} else if ((bp = incore(&freeblks->fb_devvp->v_bufobj, dbn)) != NULL) {
8346 		/*
8347 		 * The lock prevents the buf dep list from changing and
8348 	 	 * indirects on devvp should only ever have one dependency.
8349 		 */
8350 		indirdep = WK_INDIRDEP(LIST_FIRST(&bp->b_dep));
8351 		if (indirdep == NULL || (indirdep->ir_state & GOINGAWAY) == 0)
8352 			panic("indir_trunc: Bad indirdep %p from buf %p",
8353 			    indirdep, bp);
8354 	} else {
8355 		error = ffs_breadz(ump, freeblks->fb_devvp, dbn, dbn,
8356 		    (int)fs->fs_bsize, NULL, NULL, 0, NOCRED, 0, NULL, &bp);
8357 		if (error)
8358 			return;
8359 	}
8360 	ACQUIRE_LOCK(ump);
8361 	/* Protects against a race with complete_trunc_indir(). */
8362 	freework->fw_state &= ~INPROGRESS;
8363 	/*
8364 	 * If we have an indirdep we need to enforce the truncation order
8365 	 * and discard it when it is complete.
8366 	 */
8367 	if (indirdep) {
8368 		if (freework != TAILQ_FIRST(&indirdep->ir_trunc) &&
8369 		    !TAILQ_EMPTY(&indirdep->ir_trunc)) {
8370 			/*
8371 			 * Add the complete truncate to the list on the
8372 			 * indirdep to enforce in-order processing.
8373 			 */
8374 			if (freework->fw_indir == NULL)
8375 				TAILQ_INSERT_TAIL(&indirdep->ir_trunc,
8376 				    freework, fw_next);
8377 			FREE_LOCK(ump);
8378 			return;
8379 		}
8380 		/*
8381 		 * If we're goingaway, free the indirdep.  Otherwise it will
8382 		 * linger until the write completes.
8383 		 */
8384 		if (goingaway) {
8385 			KASSERT(indirdep->ir_savebp == bp,
8386 			    ("indir_trunc: losing ir_savebp %p",
8387 			    indirdep->ir_savebp));
8388 			indirdep->ir_savebp = NULL;
8389 			free_indirdep(indirdep);
8390 		}
8391 	}
8392 	FREE_LOCK(ump);
8393 	/* Initialize pointers depending on block size. */
8394 	if (ump->um_fstype == UFS1) {
8395 		bap1 = (ufs1_daddr_t *)bp->b_data;
8396 		nb = bap1[freework->fw_off];
8397 		ufs1fmt = 1;
8398 		bap2 = NULL;
8399 	} else {
8400 		bap2 = (ufs2_daddr_t *)bp->b_data;
8401 		nb = bap2[freework->fw_off];
8402 		ufs1fmt = 0;
8403 		bap1 = NULL;
8404 	}
8405 	level = lbn_level(lbn);
8406 	needj = MOUNTEDSUJ(UFSTOVFS(ump)) != 0;
8407 	lbnadd = lbn_offset(fs, level);
8408 	nblocks = btodb(fs->fs_bsize);
8409 	nfreework = freework;
8410 	freedeps = 0;
8411 	cnt = 0;
8412 	/*
8413 	 * Reclaim blocks.  Traverses into nested indirect levels and
8414 	 * arranges for the current level to be freed when subordinates
8415 	 * are free when journaling.
8416 	 */
8417 	key = ffs_blkrelease_start(ump, freeblks->fb_devvp, freeblks->fb_inum);
8418 	for (i = freework->fw_off; i < NINDIR(fs); i++, nb = nnb) {
8419 		if (UFS_CHECK_BLKNO(mp, freeblks->fb_inum, nb,
8420 		    fs->fs_bsize) != 0)
8421 			nb = 0;
8422 		if (i != NINDIR(fs) - 1) {
8423 			if (ufs1fmt)
8424 				nnb = bap1[i+1];
8425 			else
8426 				nnb = bap2[i+1];
8427 		} else
8428 			nnb = 0;
8429 		if (nb == 0)
8430 			continue;
8431 		cnt++;
8432 		if (level != 0) {
8433 			nlbn = (lbn + 1) - (i * lbnadd);
8434 			if (needj != 0) {
8435 				nfreework = newfreework(ump, freeblks, freework,
8436 				    nlbn, nb, fs->fs_frag, 0, 0);
8437 				freedeps++;
8438 			}
8439 			indir_trunc(nfreework, fsbtodb(fs, nb), nlbn);
8440 		} else {
8441 			struct freedep *freedep;
8442 
8443 			/*
8444 			 * Attempt to aggregate freedep dependencies for
8445 			 * all blocks being released to the same CG.
8446 			 */
8447 			LIST_INIT(&wkhd);
8448 			if (needj != 0 &&
8449 			    (nnb == 0 || (dtog(fs, nb) != dtog(fs, nnb)))) {
8450 				freedep = newfreedep(freework);
8451 				WORKLIST_INSERT_UNLOCKED(&wkhd,
8452 				    &freedep->fd_list);
8453 				freedeps++;
8454 			}
8455 			CTR3(KTR_SUJ,
8456 			    "indir_trunc: ino %jd blkno %jd size %d",
8457 			    freeblks->fb_inum, nb, fs->fs_bsize);
8458 			ffs_blkfree(ump, fs, freeblks->fb_devvp, nb,
8459 			    fs->fs_bsize, freeblks->fb_inum,
8460 			    freeblks->fb_vtype, &wkhd, key);
8461 		}
8462 	}
8463 	ffs_blkrelease_finish(ump, key);
8464 	if (goingaway) {
8465 		bp->b_flags |= B_INVAL | B_NOCACHE;
8466 		brelse(bp);
8467 	}
8468 	freedblocks = 0;
8469 	if (level == 0)
8470 		freedblocks = (nblocks * cnt);
8471 	if (needj == 0)
8472 		freedblocks += nblocks;
8473 	freeblks_free(ump, freeblks, freedblocks);
8474 	/*
8475 	 * If we are journaling set up the ref counts and offset so this
8476 	 * indirect can be completed when its children are free.
8477 	 */
8478 	if (needj) {
8479 		ACQUIRE_LOCK(ump);
8480 		freework->fw_off = i;
8481 		freework->fw_ref += freedeps;
8482 		freework->fw_ref -= NINDIR(fs) + 1;
8483 		if (level == 0)
8484 			freeblks->fb_cgwait += freedeps;
8485 		if (freework->fw_ref == 0)
8486 			freework_freeblock(freework, SINGLETON_KEY);
8487 		FREE_LOCK(ump);
8488 		return;
8489 	}
8490 	/*
8491 	 * If we're not journaling we can free the indirect now.
8492 	 */
8493 	dbn = dbtofsb(fs, dbn);
8494 	CTR3(KTR_SUJ,
8495 	    "indir_trunc 2: ino %jd blkno %jd size %d",
8496 	    freeblks->fb_inum, dbn, fs->fs_bsize);
8497 	ffs_blkfree(ump, fs, freeblks->fb_devvp, dbn, fs->fs_bsize,
8498 	    freeblks->fb_inum, freeblks->fb_vtype, NULL, SINGLETON_KEY);
8499 	/* Non SUJ softdep does single-threaded truncations. */
8500 	if (freework->fw_blkno == dbn) {
8501 		freework->fw_state |= ALLCOMPLETE;
8502 		ACQUIRE_LOCK(ump);
8503 		handle_written_freework(freework);
8504 		FREE_LOCK(ump);
8505 	}
8506 	return;
8507 }
8508 
8509 /*
8510  * Cancel an allocindir when it is removed via truncation.  When bp is not
8511  * NULL the indirect never appeared on disk and is scheduled to be freed
8512  * independently of the indir so we can more easily track journal work.
8513  */
8514 static void
8515 cancel_allocindir(
8516 	struct allocindir *aip,
8517 	struct buf *bp,
8518 	struct freeblks *freeblks,
8519 	int trunc)
8520 {
8521 	struct indirdep *indirdep;
8522 	struct freefrag *freefrag;
8523 	struct newblk *newblk;
8524 
8525 	newblk = (struct newblk *)aip;
8526 	LIST_REMOVE(aip, ai_next);
8527 	/*
8528 	 * We must eliminate the pointer in bp if it must be freed on its
8529 	 * own due to partial truncate or pending journal work.
8530 	 */
8531 	if (bp && (trunc || newblk->nb_jnewblk)) {
8532 		/*
8533 		 * Clear the pointer and mark the aip to be freed
8534 		 * directly if it never existed on disk.
8535 		 */
8536 		aip->ai_state |= DELAYEDFREE;
8537 		indirdep = aip->ai_indirdep;
8538 		if (indirdep->ir_state & UFS1FMT)
8539 			((ufs1_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8540 		else
8541 			((ufs2_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8542 	}
8543 	/*
8544 	 * When truncating the previous pointer will be freed via
8545 	 * savedbp.  Eliminate the freefrag which would dup free.
8546 	 */
8547 	if (trunc && (freefrag = newblk->nb_freefrag) != NULL) {
8548 		newblk->nb_freefrag = NULL;
8549 		if (freefrag->ff_jdep)
8550 			cancel_jfreefrag(
8551 			    WK_JFREEFRAG(freefrag->ff_jdep));
8552 		jwork_move(&freeblks->fb_jwork, &freefrag->ff_jwork);
8553 		WORKITEM_FREE(freefrag, D_FREEFRAG);
8554 	}
8555 	/*
8556 	 * If the journal hasn't been written the jnewblk must be passed
8557 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
8558 	 * this by leaving the journal dependency on the newblk to be freed
8559 	 * when a freework is created in handle_workitem_freeblocks().
8560 	 */
8561 	cancel_newblk(newblk, NULL, &freeblks->fb_jwork);
8562 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
8563 }
8564 
8565 /*
8566  * Create the mkdir dependencies for . and .. in a new directory.  Link them
8567  * in to a newdirblk so any subsequent additions are tracked properly.  The
8568  * caller is responsible for adding the mkdir1 dependency to the journal
8569  * and updating id_mkdiradd.  This function returns with the per-filesystem
8570  * lock held.
8571  */
8572 static struct mkdir *
8573 setup_newdir(
8574 	struct diradd *dap,
8575 	ino_t newinum,
8576 	ino_t dinum,
8577 	struct buf *newdirbp,
8578 	struct mkdir **mkdirp)
8579 {
8580 	struct newblk *newblk;
8581 	struct pagedep *pagedep;
8582 	struct inodedep *inodedep;
8583 	struct newdirblk *newdirblk;
8584 	struct mkdir *mkdir1, *mkdir2;
8585 	struct worklist *wk;
8586 	struct jaddref *jaddref;
8587 	struct ufsmount *ump;
8588 	struct mount *mp;
8589 
8590 	mp = dap->da_list.wk_mp;
8591 	ump = VFSTOUFS(mp);
8592 	newdirblk = malloc(sizeof(struct newdirblk), M_NEWDIRBLK,
8593 	    M_SOFTDEP_FLAGS);
8594 	workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8595 	LIST_INIT(&newdirblk->db_mkdir);
8596 	mkdir1 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8597 	workitem_alloc(&mkdir1->md_list, D_MKDIR, mp);
8598 	mkdir1->md_state = ATTACHED | MKDIR_BODY;
8599 	mkdir1->md_diradd = dap;
8600 	mkdir1->md_jaddref = NULL;
8601 	mkdir2 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8602 	workitem_alloc(&mkdir2->md_list, D_MKDIR, mp);
8603 	mkdir2->md_state = ATTACHED | MKDIR_PARENT;
8604 	mkdir2->md_diradd = dap;
8605 	mkdir2->md_jaddref = NULL;
8606 	if (MOUNTEDSUJ(mp) == 0) {
8607 		mkdir1->md_state |= DEPCOMPLETE;
8608 		mkdir2->md_state |= DEPCOMPLETE;
8609 	}
8610 	/*
8611 	 * Dependency on "." and ".." being written to disk.
8612 	 */
8613 	mkdir1->md_buf = newdirbp;
8614 	ACQUIRE_LOCK(VFSTOUFS(mp));
8615 	LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir1, md_mkdirs);
8616 	/*
8617 	 * We must link the pagedep, allocdirect, and newdirblk for
8618 	 * the initial file page so the pointer to the new directory
8619 	 * is not written until the directory contents are live and
8620 	 * any subsequent additions are not marked live until the
8621 	 * block is reachable via the inode.
8622 	 */
8623 	if (pagedep_lookup(mp, newdirbp, newinum, 0, 0, &pagedep) == 0)
8624 		panic("setup_newdir: lost pagedep");
8625 	LIST_FOREACH(wk, &newdirbp->b_dep, wk_list)
8626 		if (wk->wk_type == D_ALLOCDIRECT)
8627 			break;
8628 	if (wk == NULL)
8629 		panic("setup_newdir: lost allocdirect");
8630 	if (pagedep->pd_state & NEWBLOCK)
8631 		panic("setup_newdir: NEWBLOCK already set");
8632 	newblk = WK_NEWBLK(wk);
8633 	pagedep->pd_state |= NEWBLOCK;
8634 	pagedep->pd_newdirblk = newdirblk;
8635 	newdirblk->db_pagedep = pagedep;
8636 	WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8637 	WORKLIST_INSERT(&newdirblk->db_mkdir, &mkdir1->md_list);
8638 	/*
8639 	 * Look up the inodedep for the parent directory so that we
8640 	 * can link mkdir2 into the pending dotdot jaddref or
8641 	 * the inode write if there is none.  If the inode is
8642 	 * ALLCOMPLETE and no jaddref is present all dependencies have
8643 	 * been satisfied and mkdir2 can be freed.
8644 	 */
8645 	inodedep_lookup(mp, dinum, 0, &inodedep);
8646 	if (MOUNTEDSUJ(mp)) {
8647 		if (inodedep == NULL)
8648 			panic("setup_newdir: Lost parent.");
8649 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8650 		    inoreflst);
8651 		KASSERT(jaddref != NULL && jaddref->ja_parent == newinum &&
8652 		    (jaddref->ja_state & MKDIR_PARENT),
8653 		    ("setup_newdir: bad dotdot jaddref %p", jaddref));
8654 		LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8655 		mkdir2->md_jaddref = jaddref;
8656 		jaddref->ja_mkdir = mkdir2;
8657 	} else if (inodedep == NULL ||
8658 	    (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
8659 		dap->da_state &= ~MKDIR_PARENT;
8660 		WORKITEM_FREE(mkdir2, D_MKDIR);
8661 		mkdir2 = NULL;
8662 	} else {
8663 		LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8664 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir2->md_list);
8665 	}
8666 	*mkdirp = mkdir2;
8667 
8668 	return (mkdir1);
8669 }
8670 
8671 /*
8672  * Directory entry addition dependencies.
8673  *
8674  * When adding a new directory entry, the inode (with its incremented link
8675  * count) must be written to disk before the directory entry's pointer to it.
8676  * Also, if the inode is newly allocated, the corresponding freemap must be
8677  * updated (on disk) before the directory entry's pointer. These requirements
8678  * are met via undo/redo on the directory entry's pointer, which consists
8679  * simply of the inode number.
8680  *
8681  * As directory entries are added and deleted, the free space within a
8682  * directory block can become fragmented.  The ufs filesystem will compact
8683  * a fragmented directory block to make space for a new entry. When this
8684  * occurs, the offsets of previously added entries change. Any "diradd"
8685  * dependency structures corresponding to these entries must be updated with
8686  * the new offsets.
8687  */
8688 
8689 /*
8690  * This routine is called after the in-memory inode's link
8691  * count has been incremented, but before the directory entry's
8692  * pointer to the inode has been set.
8693  */
8694 int
8695 softdep_setup_directory_add(
8696 	struct buf *bp,		/* buffer containing directory block */
8697 	struct inode *dp,	/* inode for directory */
8698 	off_t diroffset,	/* offset of new entry in directory */
8699 	ino_t newinum,		/* inode referenced by new directory entry */
8700 	struct buf *newdirbp,	/* non-NULL => contents of new mkdir */
8701 	int isnewblk)		/* entry is in a newly allocated block */
8702 {
8703 	int offset;		/* offset of new entry within directory block */
8704 	ufs_lbn_t lbn;		/* block in directory containing new entry */
8705 	struct fs *fs;
8706 	struct diradd *dap;
8707 	struct newblk *newblk;
8708 	struct pagedep *pagedep;
8709 	struct inodedep *inodedep;
8710 	struct newdirblk *newdirblk;
8711 	struct mkdir *mkdir1, *mkdir2;
8712 	struct jaddref *jaddref;
8713 	struct ufsmount *ump;
8714 	struct mount *mp;
8715 	int isindir;
8716 
8717 	mp = ITOVFS(dp);
8718 	ump = VFSTOUFS(mp);
8719 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8720 	    ("softdep_setup_directory_add called on non-softdep filesystem"));
8721 	/*
8722 	 * Whiteouts have no dependencies.
8723 	 */
8724 	if (newinum == UFS_WINO) {
8725 		if (newdirbp != NULL)
8726 			bdwrite(newdirbp);
8727 		return (0);
8728 	}
8729 	jaddref = NULL;
8730 	mkdir1 = mkdir2 = NULL;
8731 	fs = ump->um_fs;
8732 	lbn = lblkno(fs, diroffset);
8733 	offset = blkoff(fs, diroffset);
8734 	dap = malloc(sizeof(struct diradd), M_DIRADD,
8735 		M_SOFTDEP_FLAGS|M_ZERO);
8736 	workitem_alloc(&dap->da_list, D_DIRADD, mp);
8737 	dap->da_offset = offset;
8738 	dap->da_newinum = newinum;
8739 	dap->da_state = ATTACHED;
8740 	LIST_INIT(&dap->da_jwork);
8741 	isindir = bp->b_lblkno >= UFS_NDADDR;
8742 	newdirblk = NULL;
8743 	if (isnewblk &&
8744 	    (isindir ? blkoff(fs, diroffset) : fragoff(fs, diroffset)) == 0) {
8745 		newdirblk = malloc(sizeof(struct newdirblk),
8746 		    M_NEWDIRBLK, M_SOFTDEP_FLAGS);
8747 		workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8748 		LIST_INIT(&newdirblk->db_mkdir);
8749 	}
8750 	/*
8751 	 * If we're creating a new directory setup the dependencies and set
8752 	 * the dap state to wait for them.  Otherwise it's COMPLETE and
8753 	 * we can move on.
8754 	 */
8755 	if (newdirbp == NULL) {
8756 		dap->da_state |= DEPCOMPLETE;
8757 		ACQUIRE_LOCK(ump);
8758 	} else {
8759 		dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
8760 		mkdir1 = setup_newdir(dap, newinum, dp->i_number, newdirbp,
8761 		    &mkdir2);
8762 	}
8763 	/*
8764 	 * Link into parent directory pagedep to await its being written.
8765 	 */
8766 	pagedep_lookup(mp, bp, dp->i_number, lbn, DEPALLOC, &pagedep);
8767 #ifdef INVARIANTS
8768 	if (diradd_lookup(pagedep, offset) != NULL)
8769 		panic("softdep_setup_directory_add: %p already at off %d\n",
8770 		    diradd_lookup(pagedep, offset), offset);
8771 #endif
8772 	dap->da_pagedep = pagedep;
8773 	LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
8774 	    da_pdlist);
8775 	inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
8776 	/*
8777 	 * If we're journaling, link the diradd into the jaddref so it
8778 	 * may be completed after the journal entry is written.  Otherwise,
8779 	 * link the diradd into its inodedep.  If the inode is not yet
8780 	 * written place it on the bufwait list, otherwise do the post-inode
8781 	 * write processing to put it on the id_pendinghd list.
8782 	 */
8783 	if (MOUNTEDSUJ(mp)) {
8784 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8785 		    inoreflst);
8786 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
8787 		    ("softdep_setup_directory_add: bad jaddref %p", jaddref));
8788 		jaddref->ja_diroff = diroffset;
8789 		jaddref->ja_diradd = dap;
8790 		add_to_journal(&jaddref->ja_list);
8791 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
8792 		diradd_inode_written(dap, inodedep);
8793 	else
8794 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
8795 	/*
8796 	 * Add the journal entries for . and .. links now that the primary
8797 	 * link is written.
8798 	 */
8799 	if (mkdir1 != NULL && MOUNTEDSUJ(mp)) {
8800 		jaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
8801 		    inoreflst, if_deps);
8802 		KASSERT(jaddref != NULL &&
8803 		    jaddref->ja_ino == jaddref->ja_parent &&
8804 		    (jaddref->ja_state & MKDIR_BODY),
8805 		    ("softdep_setup_directory_add: bad dot jaddref %p",
8806 		    jaddref));
8807 		mkdir1->md_jaddref = jaddref;
8808 		jaddref->ja_mkdir = mkdir1;
8809 		/*
8810 		 * It is important that the dotdot journal entry
8811 		 * is added prior to the dot entry since dot writes
8812 		 * both the dot and dotdot links.  These both must
8813 		 * be added after the primary link for the journal
8814 		 * to remain consistent.
8815 		 */
8816 		add_to_journal(&mkdir2->md_jaddref->ja_list);
8817 		add_to_journal(&jaddref->ja_list);
8818 	}
8819 	/*
8820 	 * If we are adding a new directory remember this diradd so that if
8821 	 * we rename it we can keep the dot and dotdot dependencies.  If
8822 	 * we are adding a new name for an inode that has a mkdiradd we
8823 	 * must be in rename and we have to move the dot and dotdot
8824 	 * dependencies to this new name.  The old name is being orphaned
8825 	 * soon.
8826 	 */
8827 	if (mkdir1 != NULL) {
8828 		if (inodedep->id_mkdiradd != NULL)
8829 			panic("softdep_setup_directory_add: Existing mkdir");
8830 		inodedep->id_mkdiradd = dap;
8831 	} else if (inodedep->id_mkdiradd)
8832 		merge_diradd(inodedep, dap);
8833 	if (newdirblk != NULL) {
8834 		/*
8835 		 * There is nothing to do if we are already tracking
8836 		 * this block.
8837 		 */
8838 		if ((pagedep->pd_state & NEWBLOCK) != 0) {
8839 			WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
8840 			FREE_LOCK(ump);
8841 			return (0);
8842 		}
8843 		if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk)
8844 		    == 0)
8845 			panic("softdep_setup_directory_add: lost entry");
8846 		WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8847 		pagedep->pd_state |= NEWBLOCK;
8848 		pagedep->pd_newdirblk = newdirblk;
8849 		newdirblk->db_pagedep = pagedep;
8850 		FREE_LOCK(ump);
8851 		/*
8852 		 * If we extended into an indirect signal direnter to sync.
8853 		 */
8854 		if (isindir)
8855 			return (1);
8856 		return (0);
8857 	}
8858 	FREE_LOCK(ump);
8859 	return (0);
8860 }
8861 
8862 /*
8863  * This procedure is called to change the offset of a directory
8864  * entry when compacting a directory block which must be owned
8865  * exclusively by the caller. Note that the actual entry movement
8866  * must be done in this procedure to ensure that no I/O completions
8867  * occur while the move is in progress.
8868  */
8869 void
8870 softdep_change_directoryentry_offset(
8871 	struct buf *bp,		/* Buffer holding directory block. */
8872 	struct inode *dp,	/* inode for directory */
8873 	caddr_t base,		/* address of dp->i_offset */
8874 	caddr_t oldloc,		/* address of old directory location */
8875 	caddr_t newloc,		/* address of new directory location */
8876 	int entrysize)		/* size of directory entry */
8877 {
8878 	int offset, oldoffset, newoffset;
8879 	struct pagedep *pagedep;
8880 	struct jmvref *jmvref;
8881 	struct diradd *dap;
8882 	struct direct *de;
8883 	struct mount *mp;
8884 	struct ufsmount *ump;
8885 	ufs_lbn_t lbn;
8886 	int flags;
8887 
8888 	mp = ITOVFS(dp);
8889 	ump = VFSTOUFS(mp);
8890 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8891 	    ("softdep_change_directoryentry_offset called on "
8892 	     "non-softdep filesystem"));
8893 	de = (struct direct *)oldloc;
8894 	jmvref = NULL;
8895 	flags = 0;
8896 	/*
8897 	 * Moves are always journaled as it would be too complex to
8898 	 * determine if any affected adds or removes are present in the
8899 	 * journal.
8900 	 */
8901 	if (MOUNTEDSUJ(mp)) {
8902 		flags = DEPALLOC;
8903 		jmvref = newjmvref(dp, de->d_ino,
8904 		    I_OFFSET(dp) + (oldloc - base),
8905 		    I_OFFSET(dp) + (newloc - base));
8906 	}
8907 	lbn = lblkno(ump->um_fs, I_OFFSET(dp));
8908 	offset = blkoff(ump->um_fs, I_OFFSET(dp));
8909 	oldoffset = offset + (oldloc - base);
8910 	newoffset = offset + (newloc - base);
8911 	ACQUIRE_LOCK(ump);
8912 	if (pagedep_lookup(mp, bp, dp->i_number, lbn, flags, &pagedep) == 0)
8913 		goto done;
8914 	dap = diradd_lookup(pagedep, oldoffset);
8915 	if (dap) {
8916 		dap->da_offset = newoffset;
8917 		newoffset = DIRADDHASH(newoffset);
8918 		oldoffset = DIRADDHASH(oldoffset);
8919 		if ((dap->da_state & ALLCOMPLETE) != ALLCOMPLETE &&
8920 		    newoffset != oldoffset) {
8921 			LIST_REMOVE(dap, da_pdlist);
8922 			LIST_INSERT_HEAD(&pagedep->pd_diraddhd[newoffset],
8923 			    dap, da_pdlist);
8924 		}
8925 	}
8926 done:
8927 	if (jmvref) {
8928 		jmvref->jm_pagedep = pagedep;
8929 		LIST_INSERT_HEAD(&pagedep->pd_jmvrefhd, jmvref, jm_deps);
8930 		add_to_journal(&jmvref->jm_list);
8931 	}
8932 	bcopy(oldloc, newloc, entrysize);
8933 	FREE_LOCK(ump);
8934 }
8935 
8936 /*
8937  * Move the mkdir dependencies and journal work from one diradd to another
8938  * when renaming a directory.  The new name must depend on the mkdir deps
8939  * completing as the old name did.  Directories can only have one valid link
8940  * at a time so one must be canonical.
8941  */
8942 static void
8943 merge_diradd(struct inodedep *inodedep, struct diradd *newdap)
8944 {
8945 	struct diradd *olddap;
8946 	struct mkdir *mkdir, *nextmd;
8947 	struct ufsmount *ump;
8948 	short state;
8949 
8950 	olddap = inodedep->id_mkdiradd;
8951 	inodedep->id_mkdiradd = newdap;
8952 	if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8953 		newdap->da_state &= ~DEPCOMPLETE;
8954 		ump = VFSTOUFS(inodedep->id_list.wk_mp);
8955 		for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
8956 		     mkdir = nextmd) {
8957 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
8958 			if (mkdir->md_diradd != olddap)
8959 				continue;
8960 			mkdir->md_diradd = newdap;
8961 			state = mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY);
8962 			newdap->da_state |= state;
8963 			olddap->da_state &= ~state;
8964 			if ((olddap->da_state &
8965 			    (MKDIR_PARENT | MKDIR_BODY)) == 0)
8966 				break;
8967 		}
8968 		if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8969 			panic("merge_diradd: unfound ref");
8970 	}
8971 	/*
8972 	 * Any mkdir related journal items are not safe to be freed until
8973 	 * the new name is stable.
8974 	 */
8975 	jwork_move(&newdap->da_jwork, &olddap->da_jwork);
8976 	olddap->da_state |= DEPCOMPLETE;
8977 	complete_diradd(olddap);
8978 }
8979 
8980 /*
8981  * Move the diradd to the pending list when all diradd dependencies are
8982  * complete.
8983  */
8984 static void
8985 complete_diradd(struct diradd *dap)
8986 {
8987 	struct pagedep *pagedep;
8988 
8989 	if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
8990 		if (dap->da_state & DIRCHG)
8991 			pagedep = dap->da_previous->dm_pagedep;
8992 		else
8993 			pagedep = dap->da_pagedep;
8994 		LIST_REMOVE(dap, da_pdlist);
8995 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
8996 	}
8997 }
8998 
8999 /*
9000  * Cancel a diradd when a dirrem overlaps with it.  We must cancel the journal
9001  * add entries and conditionally journal the remove.
9002  */
9003 static void
9004 cancel_diradd(
9005 	struct diradd *dap,
9006 	struct dirrem *dirrem,
9007 	struct jremref *jremref,
9008 	struct jremref *dotremref,
9009 	struct jremref *dotdotremref)
9010 {
9011 	struct inodedep *inodedep;
9012 	struct jaddref *jaddref;
9013 	struct inoref *inoref;
9014 	struct ufsmount *ump;
9015 	struct mkdir *mkdir;
9016 
9017 	/*
9018 	 * If no remove references were allocated we're on a non-journaled
9019 	 * filesystem and can skip the cancel step.
9020 	 */
9021 	if (jremref == NULL) {
9022 		free_diradd(dap, NULL);
9023 		return;
9024 	}
9025 	/*
9026 	 * Cancel the primary name an free it if it does not require
9027 	 * journaling.
9028 	 */
9029 	if (inodedep_lookup(dap->da_list.wk_mp, dap->da_newinum,
9030 	    0, &inodedep) != 0) {
9031 		/* Abort the addref that reference this diradd.  */
9032 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
9033 			if (inoref->if_list.wk_type != D_JADDREF)
9034 				continue;
9035 			jaddref = (struct jaddref *)inoref;
9036 			if (jaddref->ja_diradd != dap)
9037 				continue;
9038 			if (cancel_jaddref(jaddref, inodedep,
9039 			    &dirrem->dm_jwork) == 0) {
9040 				free_jremref(jremref);
9041 				jremref = NULL;
9042 			}
9043 			break;
9044 		}
9045 	}
9046 	/*
9047 	 * Cancel subordinate names and free them if they do not require
9048 	 * journaling.
9049 	 */
9050 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
9051 		ump = VFSTOUFS(dap->da_list.wk_mp);
9052 		LIST_FOREACH(mkdir, &ump->softdep_mkdirlisthd, md_mkdirs) {
9053 			if (mkdir->md_diradd != dap)
9054 				continue;
9055 			if ((jaddref = mkdir->md_jaddref) == NULL)
9056 				continue;
9057 			mkdir->md_jaddref = NULL;
9058 			if (mkdir->md_state & MKDIR_PARENT) {
9059 				if (cancel_jaddref(jaddref, NULL,
9060 				    &dirrem->dm_jwork) == 0) {
9061 					free_jremref(dotdotremref);
9062 					dotdotremref = NULL;
9063 				}
9064 			} else {
9065 				if (cancel_jaddref(jaddref, inodedep,
9066 				    &dirrem->dm_jwork) == 0) {
9067 					free_jremref(dotremref);
9068 					dotremref = NULL;
9069 				}
9070 			}
9071 		}
9072 	}
9073 
9074 	if (jremref)
9075 		journal_jremref(dirrem, jremref, inodedep);
9076 	if (dotremref)
9077 		journal_jremref(dirrem, dotremref, inodedep);
9078 	if (dotdotremref)
9079 		journal_jremref(dirrem, dotdotremref, NULL);
9080 	jwork_move(&dirrem->dm_jwork, &dap->da_jwork);
9081 	free_diradd(dap, &dirrem->dm_jwork);
9082 }
9083 
9084 /*
9085  * Free a diradd dependency structure.
9086  */
9087 static void
9088 free_diradd(struct diradd *dap, struct workhead *wkhd)
9089 {
9090 	struct dirrem *dirrem;
9091 	struct pagedep *pagedep;
9092 	struct inodedep *inodedep;
9093 	struct mkdir *mkdir, *nextmd;
9094 	struct ufsmount *ump;
9095 
9096 	ump = VFSTOUFS(dap->da_list.wk_mp);
9097 	LOCK_OWNED(ump);
9098 	LIST_REMOVE(dap, da_pdlist);
9099 	if (dap->da_state & ONWORKLIST)
9100 		WORKLIST_REMOVE(&dap->da_list);
9101 	if ((dap->da_state & DIRCHG) == 0) {
9102 		pagedep = dap->da_pagedep;
9103 	} else {
9104 		dirrem = dap->da_previous;
9105 		pagedep = dirrem->dm_pagedep;
9106 		dirrem->dm_dirinum = pagedep->pd_ino;
9107 		dirrem->dm_state |= COMPLETE;
9108 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9109 			add_to_worklist(&dirrem->dm_list, 0);
9110 	}
9111 	if (inodedep_lookup(pagedep->pd_list.wk_mp, dap->da_newinum,
9112 	    0, &inodedep) != 0)
9113 		if (inodedep->id_mkdiradd == dap)
9114 			inodedep->id_mkdiradd = NULL;
9115 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
9116 		for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
9117 		     mkdir = nextmd) {
9118 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
9119 			if (mkdir->md_diradd != dap)
9120 				continue;
9121 			dap->da_state &=
9122 			    ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
9123 			LIST_REMOVE(mkdir, md_mkdirs);
9124 			if (mkdir->md_state & ONWORKLIST)
9125 				WORKLIST_REMOVE(&mkdir->md_list);
9126 			if (mkdir->md_jaddref != NULL)
9127 				panic("free_diradd: Unexpected jaddref");
9128 			WORKITEM_FREE(mkdir, D_MKDIR);
9129 			if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
9130 				break;
9131 		}
9132 		if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
9133 			panic("free_diradd: unfound ref");
9134 	}
9135 	if (inodedep)
9136 		free_inodedep(inodedep);
9137 	/*
9138 	 * Free any journal segments waiting for the directory write.
9139 	 */
9140 	handle_jwork(&dap->da_jwork);
9141 	WORKITEM_FREE(dap, D_DIRADD);
9142 }
9143 
9144 /*
9145  * Directory entry removal dependencies.
9146  *
9147  * When removing a directory entry, the entry's inode pointer must be
9148  * zero'ed on disk before the corresponding inode's link count is decremented
9149  * (possibly freeing the inode for re-use). This dependency is handled by
9150  * updating the directory entry but delaying the inode count reduction until
9151  * after the directory block has been written to disk. After this point, the
9152  * inode count can be decremented whenever it is convenient.
9153  */
9154 
9155 /*
9156  * This routine should be called immediately after removing
9157  * a directory entry.  The inode's link count should not be
9158  * decremented by the calling procedure -- the soft updates
9159  * code will do this task when it is safe.
9160  */
9161 void
9162 softdep_setup_remove(
9163 	struct buf *bp,		/* buffer containing directory block */
9164 	struct inode *dp,	/* inode for the directory being modified */
9165 	struct inode *ip,	/* inode for directory entry being removed */
9166 	int isrmdir)		/* indicates if doing RMDIR */
9167 {
9168 	struct dirrem *dirrem, *prevdirrem;
9169 	struct inodedep *inodedep;
9170 	struct ufsmount *ump;
9171 	int direct;
9172 
9173 	ump = ITOUMP(ip);
9174 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9175 	    ("softdep_setup_remove called on non-softdep filesystem"));
9176 	/*
9177 	 * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.  We want
9178 	 * newdirrem() to setup the full directory remove which requires
9179 	 * isrmdir > 1.
9180 	 */
9181 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9182 	/*
9183 	 * Add the dirrem to the inodedep's pending remove list for quick
9184 	 * discovery later.
9185 	 */
9186 	if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0)
9187 		panic("softdep_setup_remove: Lost inodedep.");
9188 	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
9189 	dirrem->dm_state |= ONDEPLIST;
9190 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9191 
9192 	/*
9193 	 * If the COMPLETE flag is clear, then there were no active
9194 	 * entries and we want to roll back to a zeroed entry until
9195 	 * the new inode is committed to disk. If the COMPLETE flag is
9196 	 * set then we have deleted an entry that never made it to
9197 	 * disk. If the entry we deleted resulted from a name change,
9198 	 * then the old name still resides on disk. We cannot delete
9199 	 * its inode (returned to us in prevdirrem) until the zeroed
9200 	 * directory entry gets to disk. The new inode has never been
9201 	 * referenced on the disk, so can be deleted immediately.
9202 	 */
9203 	if ((dirrem->dm_state & COMPLETE) == 0) {
9204 		LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
9205 		    dm_next);
9206 		FREE_LOCK(ump);
9207 	} else {
9208 		if (prevdirrem != NULL)
9209 			LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
9210 			    prevdirrem, dm_next);
9211 		dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
9212 		direct = LIST_EMPTY(&dirrem->dm_jremrefhd);
9213 		FREE_LOCK(ump);
9214 		if (direct)
9215 			handle_workitem_remove(dirrem, 0);
9216 	}
9217 }
9218 
9219 /*
9220  * Check for an entry matching 'offset' on both the pd_dirraddhd list and the
9221  * pd_pendinghd list of a pagedep.
9222  */
9223 static struct diradd *
9224 diradd_lookup(struct pagedep *pagedep, int offset)
9225 {
9226 	struct diradd *dap;
9227 
9228 	LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
9229 		if (dap->da_offset == offset)
9230 			return (dap);
9231 	LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
9232 		if (dap->da_offset == offset)
9233 			return (dap);
9234 	return (NULL);
9235 }
9236 
9237 /*
9238  * Search for a .. diradd dependency in a directory that is being removed.
9239  * If the directory was renamed to a new parent we have a diradd rather
9240  * than a mkdir for the .. entry.  We need to cancel it now before
9241  * it is found in truncate().
9242  */
9243 static struct jremref *
9244 cancel_diradd_dotdot(struct inode *ip,
9245 	struct dirrem *dirrem,
9246 	struct jremref *jremref)
9247 {
9248 	struct pagedep *pagedep;
9249 	struct diradd *dap;
9250 	struct worklist *wk;
9251 
9252 	if (pagedep_lookup(ITOVFS(ip), NULL, ip->i_number, 0, 0, &pagedep) == 0)
9253 		return (jremref);
9254 	dap = diradd_lookup(pagedep, DOTDOT_OFFSET);
9255 	if (dap == NULL)
9256 		return (jremref);
9257 	cancel_diradd(dap, dirrem, jremref, NULL, NULL);
9258 	/*
9259 	 * Mark any journal work as belonging to the parent so it is freed
9260 	 * with the .. reference.
9261 	 */
9262 	LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9263 		wk->wk_state |= MKDIR_PARENT;
9264 	return (NULL);
9265 }
9266 
9267 /*
9268  * Cancel the MKDIR_PARENT mkdir component of a diradd when we're going to
9269  * replace it with a dirrem/diradd pair as a result of re-parenting a
9270  * directory.  This ensures that we don't simultaneously have a mkdir and
9271  * a diradd for the same .. entry.
9272  */
9273 static struct jremref *
9274 cancel_mkdir_dotdot(struct inode *ip,
9275 	struct dirrem *dirrem,
9276 	struct jremref *jremref)
9277 {
9278 	struct inodedep *inodedep;
9279 	struct jaddref *jaddref;
9280 	struct ufsmount *ump;
9281 	struct mkdir *mkdir;
9282 	struct diradd *dap;
9283 	struct mount *mp;
9284 
9285 	mp = ITOVFS(ip);
9286 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9287 		return (jremref);
9288 	dap = inodedep->id_mkdiradd;
9289 	if (dap == NULL || (dap->da_state & MKDIR_PARENT) == 0)
9290 		return (jremref);
9291 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
9292 	for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
9293 	    mkdir = LIST_NEXT(mkdir, md_mkdirs))
9294 		if (mkdir->md_diradd == dap && mkdir->md_state & MKDIR_PARENT)
9295 			break;
9296 	if (mkdir == NULL)
9297 		panic("cancel_mkdir_dotdot: Unable to find mkdir\n");
9298 	if ((jaddref = mkdir->md_jaddref) != NULL) {
9299 		mkdir->md_jaddref = NULL;
9300 		jaddref->ja_state &= ~MKDIR_PARENT;
9301 		if (inodedep_lookup(mp, jaddref->ja_ino, 0, &inodedep) == 0)
9302 			panic("cancel_mkdir_dotdot: Lost parent inodedep");
9303 		if (cancel_jaddref(jaddref, inodedep, &dirrem->dm_jwork)) {
9304 			journal_jremref(dirrem, jremref, inodedep);
9305 			jremref = NULL;
9306 		}
9307 	}
9308 	if (mkdir->md_state & ONWORKLIST)
9309 		WORKLIST_REMOVE(&mkdir->md_list);
9310 	mkdir->md_state |= ALLCOMPLETE;
9311 	complete_mkdir(mkdir);
9312 	return (jremref);
9313 }
9314 
9315 static void
9316 journal_jremref(struct dirrem *dirrem,
9317 	struct jremref *jremref,
9318 	struct inodedep *inodedep)
9319 {
9320 
9321 	if (inodedep == NULL)
9322 		if (inodedep_lookup(jremref->jr_list.wk_mp,
9323 		    jremref->jr_ref.if_ino, 0, &inodedep) == 0)
9324 			panic("journal_jremref: Lost inodedep");
9325 	LIST_INSERT_HEAD(&dirrem->dm_jremrefhd, jremref, jr_deps);
9326 	TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
9327 	add_to_journal(&jremref->jr_list);
9328 }
9329 
9330 static void
9331 dirrem_journal(
9332 	struct dirrem *dirrem,
9333 	struct jremref *jremref,
9334 	struct jremref *dotremref,
9335 	struct jremref *dotdotremref)
9336 {
9337 	struct inodedep *inodedep;
9338 
9339 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino, 0,
9340 	    &inodedep) == 0)
9341 		panic("dirrem_journal: Lost inodedep");
9342 	journal_jremref(dirrem, jremref, inodedep);
9343 	if (dotremref)
9344 		journal_jremref(dirrem, dotremref, inodedep);
9345 	if (dotdotremref)
9346 		journal_jremref(dirrem, dotdotremref, NULL);
9347 }
9348 
9349 /*
9350  * Allocate a new dirrem if appropriate and return it along with
9351  * its associated pagedep. Called without a lock, returns with lock.
9352  */
9353 static struct dirrem *
9354 newdirrem(
9355 	struct buf *bp,		/* buffer containing directory block */
9356 	struct inode *dp,	/* inode for the directory being modified */
9357 	struct inode *ip,	/* inode for directory entry being removed */
9358 	int isrmdir,		/* indicates if doing RMDIR */
9359 	struct dirrem **prevdirremp) /* previously referenced inode, if any */
9360 {
9361 	int offset;
9362 	ufs_lbn_t lbn;
9363 	struct diradd *dap;
9364 	struct dirrem *dirrem;
9365 	struct pagedep *pagedep;
9366 	struct jremref *jremref;
9367 	struct jremref *dotremref;
9368 	struct jremref *dotdotremref;
9369 	struct vnode *dvp;
9370 	struct ufsmount *ump;
9371 
9372 	/*
9373 	 * Whiteouts have no deletion dependencies.
9374 	 */
9375 	if (ip == NULL)
9376 		panic("newdirrem: whiteout");
9377 	dvp = ITOV(dp);
9378 	ump = ITOUMP(dp);
9379 
9380 	/*
9381 	 * If the system is over its limit and our filesystem is
9382 	 * responsible for more than our share of that usage and
9383 	 * we are not a snapshot, request some inodedep cleanup.
9384 	 * Limiting the number of dirrem structures will also limit
9385 	 * the number of freefile and freeblks structures.
9386 	 */
9387 	ACQUIRE_LOCK(ump);
9388 	if (!IS_SNAPSHOT(ip) && softdep_excess_items(ump, D_DIRREM))
9389 		schedule_cleanup(UFSTOVFS(ump));
9390 	else
9391 		FREE_LOCK(ump);
9392 	dirrem = malloc(sizeof(struct dirrem), M_DIRREM, M_SOFTDEP_FLAGS |
9393 	    M_ZERO);
9394 	workitem_alloc(&dirrem->dm_list, D_DIRREM, dvp->v_mount);
9395 	LIST_INIT(&dirrem->dm_jremrefhd);
9396 	LIST_INIT(&dirrem->dm_jwork);
9397 	dirrem->dm_state = isrmdir ? RMDIR : 0;
9398 	dirrem->dm_oldinum = ip->i_number;
9399 	*prevdirremp = NULL;
9400 	/*
9401 	 * Allocate remove reference structures to track journal write
9402 	 * dependencies.  We will always have one for the link and
9403 	 * when doing directories we will always have one more for dot.
9404 	 * When renaming a directory we skip the dotdot link change so
9405 	 * this is not needed.
9406 	 */
9407 	jremref = dotremref = dotdotremref = NULL;
9408 	if (DOINGSUJ(dvp)) {
9409 		if (isrmdir) {
9410 			jremref = newjremref(dirrem, dp, ip, I_OFFSET(dp),
9411 			    ip->i_effnlink + 2);
9412 			dotremref = newjremref(dirrem, ip, ip, DOT_OFFSET,
9413 			    ip->i_effnlink + 1);
9414 			dotdotremref = newjremref(dirrem, ip, dp, DOTDOT_OFFSET,
9415 			    dp->i_effnlink + 1);
9416 			dotdotremref->jr_state |= MKDIR_PARENT;
9417 		} else
9418 			jremref = newjremref(dirrem, dp, ip, I_OFFSET(dp),
9419 			    ip->i_effnlink + 1);
9420 	}
9421 	ACQUIRE_LOCK(ump);
9422 	lbn = lblkno(ump->um_fs, I_OFFSET(dp));
9423 	offset = blkoff(ump->um_fs, I_OFFSET(dp));
9424 	pagedep_lookup(UFSTOVFS(ump), bp, dp->i_number, lbn, DEPALLOC,
9425 	    &pagedep);
9426 	dirrem->dm_pagedep = pagedep;
9427 	dirrem->dm_offset = offset;
9428 	/*
9429 	 * If we're renaming a .. link to a new directory, cancel any
9430 	 * existing MKDIR_PARENT mkdir.  If it has already been canceled
9431 	 * the jremref is preserved for any potential diradd in this
9432 	 * location.  This can not coincide with a rmdir.
9433 	 */
9434 	if (I_OFFSET(dp) == DOTDOT_OFFSET) {
9435 		if (isrmdir)
9436 			panic("newdirrem: .. directory change during remove?");
9437 		jremref = cancel_mkdir_dotdot(dp, dirrem, jremref);
9438 	}
9439 	/*
9440 	 * If we're removing a directory search for the .. dependency now and
9441 	 * cancel it.  Any pending journal work will be added to the dirrem
9442 	 * to be completed when the workitem remove completes.
9443 	 */
9444 	if (isrmdir)
9445 		dotdotremref = cancel_diradd_dotdot(ip, dirrem, dotdotremref);
9446 	/*
9447 	 * Check for a diradd dependency for the same directory entry.
9448 	 * If present, then both dependencies become obsolete and can
9449 	 * be de-allocated.
9450 	 */
9451 	dap = diradd_lookup(pagedep, offset);
9452 	if (dap == NULL) {
9453 		/*
9454 		 * Link the jremref structures into the dirrem so they are
9455 		 * written prior to the pagedep.
9456 		 */
9457 		if (jremref)
9458 			dirrem_journal(dirrem, jremref, dotremref,
9459 			    dotdotremref);
9460 		return (dirrem);
9461 	}
9462 	/*
9463 	 * Must be ATTACHED at this point.
9464 	 */
9465 	if ((dap->da_state & ATTACHED) == 0)
9466 		panic("newdirrem: not ATTACHED");
9467 	if (dap->da_newinum != ip->i_number)
9468 		panic("newdirrem: inum %ju should be %ju",
9469 		    (uintmax_t)ip->i_number, (uintmax_t)dap->da_newinum);
9470 	/*
9471 	 * If we are deleting a changed name that never made it to disk,
9472 	 * then return the dirrem describing the previous inode (which
9473 	 * represents the inode currently referenced from this entry on disk).
9474 	 */
9475 	if ((dap->da_state & DIRCHG) != 0) {
9476 		*prevdirremp = dap->da_previous;
9477 		dap->da_state &= ~DIRCHG;
9478 		dap->da_pagedep = pagedep;
9479 	}
9480 	/*
9481 	 * We are deleting an entry that never made it to disk.
9482 	 * Mark it COMPLETE so we can delete its inode immediately.
9483 	 */
9484 	dirrem->dm_state |= COMPLETE;
9485 	cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref);
9486 #ifdef INVARIANTS
9487 	if (isrmdir == 0) {
9488 		struct worklist *wk;
9489 
9490 		LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9491 			if (wk->wk_state & (MKDIR_BODY | MKDIR_PARENT))
9492 				panic("bad wk %p (0x%X)\n", wk, wk->wk_state);
9493 	}
9494 #endif
9495 
9496 	return (dirrem);
9497 }
9498 
9499 /*
9500  * Directory entry change dependencies.
9501  *
9502  * Changing an existing directory entry requires that an add operation
9503  * be completed first followed by a deletion. The semantics for the addition
9504  * are identical to the description of adding a new entry above except
9505  * that the rollback is to the old inode number rather than zero. Once
9506  * the addition dependency is completed, the removal is done as described
9507  * in the removal routine above.
9508  */
9509 
9510 /*
9511  * This routine should be called immediately after changing
9512  * a directory entry.  The inode's link count should not be
9513  * decremented by the calling procedure -- the soft updates
9514  * code will perform this task when it is safe.
9515  */
9516 void
9517 softdep_setup_directory_change(
9518 	struct buf *bp,		/* buffer containing directory block */
9519 	struct inode *dp,	/* inode for the directory being modified */
9520 	struct inode *ip,	/* inode for directory entry being removed */
9521 	ino_t newinum,		/* new inode number for changed entry */
9522 	int isrmdir)		/* indicates if doing RMDIR */
9523 {
9524 	int offset;
9525 	struct diradd *dap = NULL;
9526 	struct dirrem *dirrem, *prevdirrem;
9527 	struct pagedep *pagedep;
9528 	struct inodedep *inodedep;
9529 	struct jaddref *jaddref;
9530 	struct mount *mp;
9531 	struct ufsmount *ump;
9532 
9533 	mp = ITOVFS(dp);
9534 	ump = VFSTOUFS(mp);
9535 	offset = blkoff(ump->um_fs, I_OFFSET(dp));
9536 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
9537 	   ("softdep_setup_directory_change called on non-softdep filesystem"));
9538 
9539 	/*
9540 	 * Whiteouts do not need diradd dependencies.
9541 	 */
9542 	if (newinum != UFS_WINO) {
9543 		dap = malloc(sizeof(struct diradd),
9544 		    M_DIRADD, M_SOFTDEP_FLAGS|M_ZERO);
9545 		workitem_alloc(&dap->da_list, D_DIRADD, mp);
9546 		dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
9547 		dap->da_offset = offset;
9548 		dap->da_newinum = newinum;
9549 		LIST_INIT(&dap->da_jwork);
9550 	}
9551 
9552 	/*
9553 	 * Allocate a new dirrem and ACQUIRE_LOCK.
9554 	 */
9555 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9556 	pagedep = dirrem->dm_pagedep;
9557 	/*
9558 	 * The possible values for isrmdir:
9559 	 *	0 - non-directory file rename
9560 	 *	1 - directory rename within same directory
9561 	 *   inum - directory rename to new directory of given inode number
9562 	 * When renaming to a new directory, we are both deleting and
9563 	 * creating a new directory entry, so the link count on the new
9564 	 * directory should not change. Thus we do not need the followup
9565 	 * dirrem which is usually done in handle_workitem_remove. We set
9566 	 * the DIRCHG flag to tell handle_workitem_remove to skip the
9567 	 * followup dirrem.
9568 	 */
9569 	if (isrmdir > 1)
9570 		dirrem->dm_state |= DIRCHG;
9571 
9572 	/*
9573 	 * Whiteouts have no additional dependencies,
9574 	 * so just put the dirrem on the correct list.
9575 	 */
9576 	if (newinum == UFS_WINO) {
9577 		if ((dirrem->dm_state & COMPLETE) == 0) {
9578 			LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
9579 			    dm_next);
9580 		} else {
9581 			dirrem->dm_dirinum = pagedep->pd_ino;
9582 			if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9583 				add_to_worklist(&dirrem->dm_list, 0);
9584 		}
9585 		FREE_LOCK(ump);
9586 		return;
9587 	}
9588 	/*
9589 	 * Add the dirrem to the inodedep's pending remove list for quick
9590 	 * discovery later.  A valid nlinkdelta ensures that this lookup
9591 	 * will not fail.
9592 	 */
9593 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9594 		panic("softdep_setup_directory_change: Lost inodedep.");
9595 	dirrem->dm_state |= ONDEPLIST;
9596 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9597 
9598 	/*
9599 	 * If the COMPLETE flag is clear, then there were no active
9600 	 * entries and we want to roll back to the previous inode until
9601 	 * the new inode is committed to disk. If the COMPLETE flag is
9602 	 * set, then we have deleted an entry that never made it to disk.
9603 	 * If the entry we deleted resulted from a name change, then the old
9604 	 * inode reference still resides on disk. Any rollback that we do
9605 	 * needs to be to that old inode (returned to us in prevdirrem). If
9606 	 * the entry we deleted resulted from a create, then there is
9607 	 * no entry on the disk, so we want to roll back to zero rather
9608 	 * than the uncommitted inode. In either of the COMPLETE cases we
9609 	 * want to immediately free the unwritten and unreferenced inode.
9610 	 */
9611 	if ((dirrem->dm_state & COMPLETE) == 0) {
9612 		dap->da_previous = dirrem;
9613 	} else {
9614 		if (prevdirrem != NULL) {
9615 			dap->da_previous = prevdirrem;
9616 		} else {
9617 			dap->da_state &= ~DIRCHG;
9618 			dap->da_pagedep = pagedep;
9619 		}
9620 		dirrem->dm_dirinum = pagedep->pd_ino;
9621 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9622 			add_to_worklist(&dirrem->dm_list, 0);
9623 	}
9624 	/*
9625 	 * Lookup the jaddref for this journal entry.  We must finish
9626 	 * initializing it and make the diradd write dependent on it.
9627 	 * If we're not journaling, put it on the id_bufwait list if the
9628 	 * inode is not yet written. If it is written, do the post-inode
9629 	 * write processing to put it on the id_pendinghd list.
9630 	 */
9631 	inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
9632 	if (MOUNTEDSUJ(mp)) {
9633 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
9634 		    inoreflst);
9635 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
9636 		    ("softdep_setup_directory_change: bad jaddref %p",
9637 		    jaddref));
9638 		jaddref->ja_diroff = I_OFFSET(dp);
9639 		jaddref->ja_diradd = dap;
9640 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9641 		    dap, da_pdlist);
9642 		add_to_journal(&jaddref->ja_list);
9643 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
9644 		dap->da_state |= COMPLETE;
9645 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
9646 		WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
9647 	} else {
9648 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9649 		    dap, da_pdlist);
9650 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
9651 	}
9652 	/*
9653 	 * If we're making a new name for a directory that has not been
9654 	 * committed when need to move the dot and dotdot references to
9655 	 * this new name.
9656 	 */
9657 	if (inodedep->id_mkdiradd && I_OFFSET(dp) != DOTDOT_OFFSET)
9658 		merge_diradd(inodedep, dap);
9659 	FREE_LOCK(ump);
9660 }
9661 
9662 /*
9663  * Called whenever the link count on an inode is changed.
9664  * It creates an inode dependency so that the new reference(s)
9665  * to the inode cannot be committed to disk until the updated
9666  * inode has been written.
9667  */
9668 void
9669 softdep_change_linkcnt(
9670 	struct inode *ip)	/* the inode with the increased link count */
9671 {
9672 	struct inodedep *inodedep;
9673 	struct ufsmount *ump;
9674 
9675 	ump = ITOUMP(ip);
9676 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9677 	    ("softdep_change_linkcnt called on non-softdep filesystem"));
9678 	ACQUIRE_LOCK(ump);
9679 	inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
9680 	if (ip->i_nlink < ip->i_effnlink)
9681 		panic("softdep_change_linkcnt: bad delta");
9682 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9683 	FREE_LOCK(ump);
9684 }
9685 
9686 /*
9687  * Attach a sbdep dependency to the superblock buf so that we can keep
9688  * track of the head of the linked list of referenced but unlinked inodes.
9689  */
9690 void
9691 softdep_setup_sbupdate(
9692 	struct ufsmount *ump,
9693 	struct fs *fs,
9694 	struct buf *bp)
9695 {
9696 	struct sbdep *sbdep;
9697 	struct worklist *wk;
9698 
9699 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9700 	    ("softdep_setup_sbupdate called on non-softdep filesystem"));
9701 	LIST_FOREACH(wk, &bp->b_dep, wk_list)
9702 		if (wk->wk_type == D_SBDEP)
9703 			break;
9704 	if (wk != NULL)
9705 		return;
9706 	sbdep = malloc(sizeof(struct sbdep), M_SBDEP, M_SOFTDEP_FLAGS);
9707 	workitem_alloc(&sbdep->sb_list, D_SBDEP, UFSTOVFS(ump));
9708 	sbdep->sb_fs = fs;
9709 	sbdep->sb_ump = ump;
9710 	ACQUIRE_LOCK(ump);
9711 	WORKLIST_INSERT(&bp->b_dep, &sbdep->sb_list);
9712 	FREE_LOCK(ump);
9713 }
9714 
9715 /*
9716  * Return the first unlinked inodedep which is ready to be the head of the
9717  * list.  The inodedep and all those after it must have valid next pointers.
9718  */
9719 static struct inodedep *
9720 first_unlinked_inodedep(struct ufsmount *ump)
9721 {
9722 	struct inodedep *inodedep;
9723 	struct inodedep *idp;
9724 
9725 	LOCK_OWNED(ump);
9726 	for (inodedep = TAILQ_LAST(&ump->softdep_unlinked, inodedeplst);
9727 	    inodedep; inodedep = idp) {
9728 		if ((inodedep->id_state & UNLINKNEXT) == 0)
9729 			return (NULL);
9730 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9731 		if (idp == NULL || (idp->id_state & UNLINKNEXT) == 0)
9732 			break;
9733 		if ((inodedep->id_state & UNLINKPREV) == 0)
9734 			break;
9735 	}
9736 	return (inodedep);
9737 }
9738 
9739 /*
9740  * Set the sujfree unlinked head pointer prior to writing a superblock.
9741  */
9742 static void
9743 initiate_write_sbdep(struct sbdep *sbdep)
9744 {
9745 	struct inodedep *inodedep;
9746 	struct fs *bpfs;
9747 	struct fs *fs;
9748 
9749 	bpfs = sbdep->sb_fs;
9750 	fs = sbdep->sb_ump->um_fs;
9751 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9752 	if (inodedep) {
9753 		fs->fs_sujfree = inodedep->id_ino;
9754 		inodedep->id_state |= UNLINKPREV;
9755 	} else
9756 		fs->fs_sujfree = 0;
9757 	bpfs->fs_sujfree = fs->fs_sujfree;
9758 	/*
9759 	 * Because we have made changes to the superblock, we need to
9760 	 * recompute its check-hash.
9761 	 */
9762 	bpfs->fs_ckhash = ffs_calc_sbhash(bpfs);
9763 }
9764 
9765 /*
9766  * After a superblock is written determine whether it must be written again
9767  * due to a changing unlinked list head.
9768  */
9769 static int
9770 handle_written_sbdep(struct sbdep *sbdep, struct buf *bp)
9771 {
9772 	struct inodedep *inodedep;
9773 	struct fs *fs;
9774 
9775 	LOCK_OWNED(sbdep->sb_ump);
9776 	fs = sbdep->sb_fs;
9777 	/*
9778 	 * If the superblock doesn't match the in-memory list start over.
9779 	 */
9780 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9781 	if ((inodedep && fs->fs_sujfree != inodedep->id_ino) ||
9782 	    (inodedep == NULL && fs->fs_sujfree != 0)) {
9783 		bdirty(bp);
9784 		return (1);
9785 	}
9786 	WORKITEM_FREE(sbdep, D_SBDEP);
9787 	if (fs->fs_sujfree == 0)
9788 		return (0);
9789 	/*
9790 	 * Now that we have a record of this inode in stable store allow it
9791 	 * to be written to free up pending work.  Inodes may see a lot of
9792 	 * write activity after they are unlinked which we must not hold up.
9793 	 */
9794 	for (; inodedep != NULL; inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
9795 		if ((inodedep->id_state & UNLINKLINKS) != UNLINKLINKS)
9796 			panic("handle_written_sbdep: Bad inodedep %p (0x%X)",
9797 			    inodedep, inodedep->id_state);
9798 		if (inodedep->id_state & UNLINKONLIST)
9799 			break;
9800 		inodedep->id_state |= DEPCOMPLETE | UNLINKONLIST;
9801 	}
9802 
9803 	return (0);
9804 }
9805 
9806 /*
9807  * Mark an inodedep as unlinked and insert it into the in-memory unlinked list.
9808  */
9809 static void
9810 unlinked_inodedep( struct mount *mp, struct inodedep *inodedep)
9811 {
9812 	struct ufsmount *ump;
9813 
9814 	ump = VFSTOUFS(mp);
9815 	LOCK_OWNED(ump);
9816 	if (MOUNTEDSUJ(mp) == 0)
9817 		return;
9818 	ump->um_fs->fs_fmod = 1;
9819 	if (inodedep->id_state & UNLINKED)
9820 		panic("unlinked_inodedep: %p already unlinked\n", inodedep);
9821 	inodedep->id_state |= UNLINKED;
9822 	TAILQ_INSERT_HEAD(&ump->softdep_unlinked, inodedep, id_unlinked);
9823 }
9824 
9825 /*
9826  * Remove an inodedep from the unlinked inodedep list.  This may require
9827  * disk writes if the inode has made it that far.
9828  */
9829 static void
9830 clear_unlinked_inodedep( struct inodedep *inodedep)
9831 {
9832 	struct ufs2_dinode *dip;
9833 	struct ufsmount *ump;
9834 	struct inodedep *idp;
9835 	struct inodedep *idn;
9836 	struct fs *fs, *bpfs;
9837 	struct buf *bp;
9838 	daddr_t dbn;
9839 	ino_t ino;
9840 	ino_t nino;
9841 	ino_t pino;
9842 	int error;
9843 
9844 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
9845 	fs = ump->um_fs;
9846 	ino = inodedep->id_ino;
9847 	error = 0;
9848 	for (;;) {
9849 		LOCK_OWNED(ump);
9850 		KASSERT((inodedep->id_state & UNLINKED) != 0,
9851 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
9852 		    inodedep));
9853 		/*
9854 		 * If nothing has yet been written simply remove us from
9855 		 * the in memory list and return.  This is the most common
9856 		 * case where handle_workitem_remove() loses the final
9857 		 * reference.
9858 		 */
9859 		if ((inodedep->id_state & UNLINKLINKS) == 0)
9860 			break;
9861 		/*
9862 		 * If we have a NEXT pointer and no PREV pointer we can simply
9863 		 * clear NEXT's PREV and remove ourselves from the list.  Be
9864 		 * careful not to clear PREV if the superblock points at
9865 		 * next as well.
9866 		 */
9867 		idn = TAILQ_NEXT(inodedep, id_unlinked);
9868 		if ((inodedep->id_state & UNLINKLINKS) == UNLINKNEXT) {
9869 			if (idn && fs->fs_sujfree != idn->id_ino)
9870 				idn->id_state &= ~UNLINKPREV;
9871 			break;
9872 		}
9873 		/*
9874 		 * Here we have an inodedep which is actually linked into
9875 		 * the list.  We must remove it by forcing a write to the
9876 		 * link before us, whether it be the superblock or an inode.
9877 		 * Unfortunately the list may change while we're waiting
9878 		 * on the buf lock for either resource so we must loop until
9879 		 * we lock the right one.  If both the superblock and an
9880 		 * inode point to this inode we must clear the inode first
9881 		 * followed by the superblock.
9882 		 */
9883 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9884 		pino = 0;
9885 		if (idp && (idp->id_state & UNLINKNEXT))
9886 			pino = idp->id_ino;
9887 		FREE_LOCK(ump);
9888 		if (pino == 0) {
9889 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9890 			    (int)fs->fs_sbsize, 0, 0, 0);
9891 		} else {
9892 			dbn = fsbtodb(fs, ino_to_fsba(fs, pino));
9893 			error = ffs_breadz(ump, ump->um_devvp, dbn, dbn,
9894 			    (int)fs->fs_bsize, NULL, NULL, 0, NOCRED, 0, NULL,
9895 			    &bp);
9896 		}
9897 		ACQUIRE_LOCK(ump);
9898 		if (error)
9899 			break;
9900 		/* If the list has changed restart the loop. */
9901 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9902 		nino = 0;
9903 		if (idp && (idp->id_state & UNLINKNEXT))
9904 			nino = idp->id_ino;
9905 		if (nino != pino ||
9906 		    (inodedep->id_state & UNLINKPREV) != UNLINKPREV) {
9907 			FREE_LOCK(ump);
9908 			brelse(bp);
9909 			ACQUIRE_LOCK(ump);
9910 			continue;
9911 		}
9912 		nino = 0;
9913 		idn = TAILQ_NEXT(inodedep, id_unlinked);
9914 		if (idn)
9915 			nino = idn->id_ino;
9916 		/*
9917 		 * Remove us from the in memory list.  After this we cannot
9918 		 * access the inodedep.
9919 		 */
9920 		KASSERT((inodedep->id_state & UNLINKED) != 0,
9921 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
9922 		    inodedep));
9923 		inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9924 		TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9925 		FREE_LOCK(ump);
9926 		/*
9927 		 * The predecessor's next pointer is manually updated here
9928 		 * so that the NEXT flag is never cleared for an element
9929 		 * that is in the list.
9930 		 */
9931 		if (pino == 0) {
9932 			bcopy((caddr_t)fs, bp->b_data, (uint64_t)fs->fs_sbsize);
9933 			bpfs = (struct fs *)bp->b_data;
9934 			ffs_oldfscompat_write(bpfs, ump);
9935 			softdep_setup_sbupdate(ump, bpfs, bp);
9936 			/*
9937 			 * Because we may have made changes to the superblock,
9938 			 * we need to recompute its check-hash.
9939 			 */
9940 			bpfs->fs_ckhash = ffs_calc_sbhash(bpfs);
9941 		} else if (fs->fs_magic == FS_UFS1_MAGIC) {
9942 			((struct ufs1_dinode *)bp->b_data +
9943 			    ino_to_fsbo(fs, pino))->di_freelink = nino;
9944 		} else {
9945 			dip = (struct ufs2_dinode *)bp->b_data +
9946 			    ino_to_fsbo(fs, pino);
9947 			dip->di_freelink = nino;
9948 			ffs_update_dinode_ckhash(fs, dip);
9949 		}
9950 		/*
9951 		 * If the bwrite fails we have no recourse to recover.  The
9952 		 * filesystem is corrupted already.
9953 		 */
9954 		bwrite(bp);
9955 		ACQUIRE_LOCK(ump);
9956 		/*
9957 		 * If the superblock pointer still needs to be cleared force
9958 		 * a write here.
9959 		 */
9960 		if (fs->fs_sujfree == ino) {
9961 			FREE_LOCK(ump);
9962 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9963 			    (int)fs->fs_sbsize, 0, 0, 0);
9964 			bcopy((caddr_t)fs, bp->b_data, (uint64_t)fs->fs_sbsize);
9965 			bpfs = (struct fs *)bp->b_data;
9966 			ffs_oldfscompat_write(bpfs, ump);
9967 			softdep_setup_sbupdate(ump, bpfs, bp);
9968 			/*
9969 			 * Because we may have made changes to the superblock,
9970 			 * we need to recompute its check-hash.
9971 			 */
9972 			bpfs->fs_ckhash = ffs_calc_sbhash(bpfs);
9973 			bwrite(bp);
9974 			ACQUIRE_LOCK(ump);
9975 		}
9976 
9977 		if (fs->fs_sujfree != ino)
9978 			return;
9979 		panic("clear_unlinked_inodedep: Failed to clear free head");
9980 	}
9981 	if (inodedep->id_ino == fs->fs_sujfree)
9982 		panic("clear_unlinked_inodedep: Freeing head of free list");
9983 	inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9984 	TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9985 	return;
9986 }
9987 
9988 /*
9989  * This workitem decrements the inode's link count.
9990  * If the link count reaches zero, the file is removed.
9991  */
9992 static int
9993 handle_workitem_remove(struct dirrem *dirrem, int flags)
9994 {
9995 	struct inodedep *inodedep;
9996 	struct workhead dotdotwk;
9997 	struct worklist *wk;
9998 	struct ufsmount *ump;
9999 	struct mount *mp;
10000 	struct vnode *vp;
10001 	struct inode *ip;
10002 	ino_t oldinum;
10003 
10004 	if (dirrem->dm_state & ONWORKLIST)
10005 		panic("handle_workitem_remove: dirrem %p still on worklist",
10006 		    dirrem);
10007 	oldinum = dirrem->dm_oldinum;
10008 	mp = dirrem->dm_list.wk_mp;
10009 	ump = VFSTOUFS(mp);
10010 	flags |= LK_EXCLUSIVE;
10011 	if (ffs_vgetf(mp, oldinum, flags, &vp, FFSV_FORCEINSMQ |
10012 	    FFSV_FORCEINODEDEP) != 0)
10013 		return (EBUSY);
10014 	ip = VTOI(vp);
10015 	MPASS(ip->i_mode != 0);
10016 	ACQUIRE_LOCK(ump);
10017 	if ((inodedep_lookup(mp, oldinum, 0, &inodedep)) == 0)
10018 		panic("handle_workitem_remove: lost inodedep");
10019 	if (dirrem->dm_state & ONDEPLIST)
10020 		LIST_REMOVE(dirrem, dm_inonext);
10021 	KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
10022 	    ("handle_workitem_remove:  Journal entries not written."));
10023 
10024 	/*
10025 	 * Move all dependencies waiting on the remove to complete
10026 	 * from the dirrem to the inode inowait list to be completed
10027 	 * after the inode has been updated and written to disk.
10028 	 *
10029 	 * Any marked MKDIR_PARENT are saved to be completed when the
10030 	 * dotdot ref is removed unless DIRCHG is specified.  For
10031 	 * directory change operations there will be no further
10032 	 * directory writes and the jsegdeps need to be moved along
10033 	 * with the rest to be completed when the inode is free or
10034 	 * stable in the inode free list.
10035 	 */
10036 	LIST_INIT(&dotdotwk);
10037 	while ((wk = LIST_FIRST(&dirrem->dm_jwork)) != NULL) {
10038 		WORKLIST_REMOVE(wk);
10039 		if ((dirrem->dm_state & DIRCHG) == 0 &&
10040 		    wk->wk_state & MKDIR_PARENT) {
10041 			wk->wk_state &= ~MKDIR_PARENT;
10042 			WORKLIST_INSERT(&dotdotwk, wk);
10043 			continue;
10044 		}
10045 		WORKLIST_INSERT(&inodedep->id_inowait, wk);
10046 	}
10047 	LIST_SWAP(&dirrem->dm_jwork, &dotdotwk, worklist, wk_list);
10048 	/*
10049 	 * Normal file deletion.
10050 	 */
10051 	if ((dirrem->dm_state & RMDIR) == 0) {
10052 		ip->i_nlink--;
10053 		KASSERT(ip->i_nlink >= 0, ("handle_workitem_remove: file ino "
10054 		    "%ju negative i_nlink %d", (intmax_t)ip->i_number,
10055 		    ip->i_nlink));
10056 		DIP_SET_NLINK(ip, ip->i_nlink);
10057 		UFS_INODE_SET_FLAG(ip, IN_CHANGE);
10058 		if (ip->i_nlink < ip->i_effnlink)
10059 			panic("handle_workitem_remove: bad file delta");
10060 		if (ip->i_nlink == 0)
10061 			unlinked_inodedep(mp, inodedep);
10062 		inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
10063 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
10064 		    ("handle_workitem_remove: worklist not empty. %s",
10065 		    TYPENAME(LIST_FIRST(&dirrem->dm_jwork)->wk_type)));
10066 		WORKITEM_FREE(dirrem, D_DIRREM);
10067 		FREE_LOCK(ump);
10068 		goto out;
10069 	}
10070 	/*
10071 	 * Directory deletion. Decrement reference count for both the
10072 	 * just deleted parent directory entry and the reference for ".".
10073 	 * Arrange to have the reference count on the parent decremented
10074 	 * to account for the loss of "..".
10075 	 */
10076 	ip->i_nlink -= 2;
10077 	KASSERT(ip->i_nlink >= 0, ("handle_workitem_remove: directory ino "
10078 	    "%ju negative i_nlink %d", (intmax_t)ip->i_number, ip->i_nlink));
10079 	DIP_SET_NLINK(ip, ip->i_nlink);
10080 	UFS_INODE_SET_FLAG(ip, IN_CHANGE);
10081 	if (ip->i_nlink < ip->i_effnlink)
10082 		panic("handle_workitem_remove: bad dir delta");
10083 	if (ip->i_nlink == 0)
10084 		unlinked_inodedep(mp, inodedep);
10085 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
10086 	/*
10087 	 * Rename a directory to a new parent. Since, we are both deleting
10088 	 * and creating a new directory entry, the link count on the new
10089 	 * directory should not change. Thus we skip the followup dirrem.
10090 	 */
10091 	if (dirrem->dm_state & DIRCHG) {
10092 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
10093 		    ("handle_workitem_remove: DIRCHG and worklist not empty."));
10094 		WORKITEM_FREE(dirrem, D_DIRREM);
10095 		FREE_LOCK(ump);
10096 		goto out;
10097 	}
10098 	dirrem->dm_state = ONDEPLIST;
10099 	dirrem->dm_oldinum = dirrem->dm_dirinum;
10100 	/*
10101 	 * Place the dirrem on the parent's diremhd list.
10102 	 */
10103 	if (inodedep_lookup(mp, dirrem->dm_oldinum, 0, &inodedep) == 0)
10104 		panic("handle_workitem_remove: lost dir inodedep");
10105 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
10106 	/*
10107 	 * If the allocated inode has never been written to disk, then
10108 	 * the on-disk inode is zero'ed and we can remove the file
10109 	 * immediately.  When journaling if the inode has been marked
10110 	 * unlinked and not DEPCOMPLETE we know it can never be written.
10111 	 */
10112 	inodedep_lookup(mp, oldinum, 0, &inodedep);
10113 	if (inodedep == NULL ||
10114 	    (inodedep->id_state & (DEPCOMPLETE | UNLINKED)) == UNLINKED ||
10115 	    check_inode_unwritten(inodedep)) {
10116 		FREE_LOCK(ump);
10117 		vput(vp);
10118 		return handle_workitem_remove(dirrem, flags);
10119 	}
10120 	WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
10121 	FREE_LOCK(ump);
10122 	UFS_INODE_SET_FLAG(ip, IN_CHANGE);
10123 out:
10124 	ffs_update(vp, 0);
10125 	vput(vp);
10126 	return (0);
10127 }
10128 
10129 /*
10130  * Inode de-allocation dependencies.
10131  *
10132  * When an inode's link count is reduced to zero, it can be de-allocated. We
10133  * found it convenient to postpone de-allocation until after the inode is
10134  * written to disk with its new link count (zero).  At this point, all of the
10135  * on-disk inode's block pointers are nullified and, with careful dependency
10136  * list ordering, all dependencies related to the inode will be satisfied and
10137  * the corresponding dependency structures de-allocated.  So, if/when the
10138  * inode is reused, there will be no mixing of old dependencies with new
10139  * ones.  This artificial dependency is set up by the block de-allocation
10140  * procedure above (softdep_setup_freeblocks) and completed by the
10141  * following procedure.
10142  */
10143 static void
10144 handle_workitem_freefile(struct freefile *freefile)
10145 {
10146 	struct workhead wkhd;
10147 	struct fs *fs;
10148 	struct ufsmount *ump;
10149 	int error;
10150 #ifdef INVARIANTS
10151 	struct inodedep *idp;
10152 #endif
10153 
10154 	ump = VFSTOUFS(freefile->fx_list.wk_mp);
10155 	fs = ump->um_fs;
10156 #ifdef INVARIANTS
10157 	ACQUIRE_LOCK(ump);
10158 	error = inodedep_lookup(UFSTOVFS(ump), freefile->fx_oldinum, 0, &idp);
10159 	FREE_LOCK(ump);
10160 	if (error)
10161 		panic("handle_workitem_freefile: inodedep %p survived", idp);
10162 #endif
10163 	UFS_LOCK(ump);
10164 	fs->fs_pendinginodes -= 1;
10165 	UFS_UNLOCK(ump);
10166 	LIST_INIT(&wkhd);
10167 	LIST_SWAP(&freefile->fx_jwork, &wkhd, worklist, wk_list);
10168 	if ((error = ffs_freefile(ump, fs, freefile->fx_devvp,
10169 	    freefile->fx_oldinum, freefile->fx_mode, &wkhd)) != 0)
10170 		softdep_error("handle_workitem_freefile", error);
10171 	ACQUIRE_LOCK(ump);
10172 	WORKITEM_FREE(freefile, D_FREEFILE);
10173 	FREE_LOCK(ump);
10174 }
10175 
10176 /*
10177  * Helper function which unlinks marker element from work list and returns
10178  * the next element on the list.
10179  */
10180 static __inline struct worklist *
10181 markernext(struct worklist *marker)
10182 {
10183 	struct worklist *next;
10184 
10185 	next = LIST_NEXT(marker, wk_list);
10186 	LIST_REMOVE(marker, wk_list);
10187 	return next;
10188 }
10189 
10190 /*
10191  * Disk writes.
10192  *
10193  * The dependency structures constructed above are most actively used when file
10194  * system blocks are written to disk.  No constraints are placed on when a
10195  * block can be written, but unsatisfied update dependencies are made safe by
10196  * modifying (or replacing) the source memory for the duration of the disk
10197  * write.  When the disk write completes, the memory block is again brought
10198  * up-to-date.
10199  *
10200  * In-core inode structure reclamation.
10201  *
10202  * Because there are a finite number of "in-core" inode structures, they are
10203  * reused regularly.  By transferring all inode-related dependencies to the
10204  * in-memory inode block and indexing them separately (via "inodedep"s), we
10205  * can allow "in-core" inode structures to be reused at any time and avoid
10206  * any increase in contention.
10207  *
10208  * Called just before entering the device driver to initiate a new disk I/O.
10209  * The buffer must be locked, thus, no I/O completion operations can occur
10210  * while we are manipulating its associated dependencies.
10211  */
10212 static void
10213 softdep_disk_io_initiation(
10214 	struct buf *bp)		/* structure describing disk write to occur */
10215 {
10216 	struct worklist *wk;
10217 	struct worklist marker;
10218 	struct inodedep *inodedep;
10219 	struct freeblks *freeblks;
10220 	struct jblkdep *jblkdep;
10221 	struct newblk *newblk;
10222 	struct ufsmount *ump;
10223 
10224 	/*
10225 	 * We only care about write operations. There should never
10226 	 * be dependencies for reads.
10227 	 */
10228 	if (bp->b_iocmd != BIO_WRITE)
10229 		panic("softdep_disk_io_initiation: not write");
10230 
10231 	if (bp->b_vflags & BV_BKGRDINPROG)
10232 		panic("softdep_disk_io_initiation: Writing buffer with "
10233 		    "background write in progress: %p", bp);
10234 
10235 	ump = softdep_bp_to_mp(bp);
10236 	if (ump == NULL)
10237 		return;
10238 
10239 	marker.wk_type = D_LAST + 1;	/* Not a normal workitem */
10240 	ACQUIRE_LOCK(ump);
10241 	/*
10242 	 * Do any necessary pre-I/O processing.
10243 	 */
10244 	for (wk = LIST_FIRST(&bp->b_dep); wk != NULL;
10245 	     wk = markernext(&marker)) {
10246 		LIST_INSERT_AFTER(wk, &marker, wk_list);
10247 		switch (wk->wk_type) {
10248 		case D_PAGEDEP:
10249 			initiate_write_filepage(WK_PAGEDEP(wk), bp);
10250 			continue;
10251 
10252 		case D_INODEDEP:
10253 			inodedep = WK_INODEDEP(wk);
10254 			if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC)
10255 				initiate_write_inodeblock_ufs1(inodedep, bp);
10256 			else
10257 				initiate_write_inodeblock_ufs2(inodedep, bp);
10258 			continue;
10259 
10260 		case D_INDIRDEP:
10261 			initiate_write_indirdep(WK_INDIRDEP(wk), bp);
10262 			continue;
10263 
10264 		case D_BMSAFEMAP:
10265 			initiate_write_bmsafemap(WK_BMSAFEMAP(wk), bp);
10266 			continue;
10267 
10268 		case D_JSEG:
10269 			WK_JSEG(wk)->js_buf = NULL;
10270 			continue;
10271 
10272 		case D_FREEBLKS:
10273 			freeblks = WK_FREEBLKS(wk);
10274 			jblkdep = LIST_FIRST(&freeblks->fb_jblkdephd);
10275 			/*
10276 			 * We have to wait for the freeblks to be journaled
10277 			 * before we can write an inodeblock with updated
10278 			 * pointers.  Be careful to arrange the marker so
10279 			 * we revisit the freeblks if it's not removed by
10280 			 * the first jwait().
10281 			 */
10282 			if (jblkdep != NULL) {
10283 				LIST_REMOVE(&marker, wk_list);
10284 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
10285 				jwait(&jblkdep->jb_list, MNT_WAIT);
10286 			}
10287 			continue;
10288 		case D_ALLOCDIRECT:
10289 		case D_ALLOCINDIR:
10290 			/*
10291 			 * We have to wait for the jnewblk to be journaled
10292 			 * before we can write to a block if the contents
10293 			 * may be confused with an earlier file's indirect
10294 			 * at recovery time.  Handle the marker as described
10295 			 * above.
10296 			 */
10297 			newblk = WK_NEWBLK(wk);
10298 			if (newblk->nb_jnewblk != NULL &&
10299 			    indirblk_lookup(newblk->nb_list.wk_mp,
10300 			    newblk->nb_newblkno)) {
10301 				LIST_REMOVE(&marker, wk_list);
10302 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
10303 				jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
10304 			}
10305 			continue;
10306 
10307 		case D_SBDEP:
10308 			initiate_write_sbdep(WK_SBDEP(wk));
10309 			continue;
10310 
10311 		case D_MKDIR:
10312 		case D_FREEWORK:
10313 		case D_FREEDEP:
10314 		case D_JSEGDEP:
10315 			continue;
10316 
10317 		default:
10318 			panic("handle_disk_io_initiation: Unexpected type %s",
10319 			    TYPENAME(wk->wk_type));
10320 			/* NOTREACHED */
10321 		}
10322 	}
10323 	FREE_LOCK(ump);
10324 }
10325 
10326 /*
10327  * Called from within the procedure above to deal with unsatisfied
10328  * allocation dependencies in a directory. The buffer must be locked,
10329  * thus, no I/O completion operations can occur while we are
10330  * manipulating its associated dependencies.
10331  */
10332 static void
10333 initiate_write_filepage(struct pagedep *pagedep, struct buf *bp)
10334 {
10335 	struct jremref *jremref;
10336 	struct jmvref *jmvref;
10337 	struct dirrem *dirrem;
10338 	struct diradd *dap;
10339 	struct direct *ep;
10340 	int i;
10341 
10342 	if (pagedep->pd_state & IOSTARTED) {
10343 		/*
10344 		 * This can only happen if there is a driver that does not
10345 		 * understand chaining. Here biodone will reissue the call
10346 		 * to strategy for the incomplete buffers.
10347 		 */
10348 		printf("initiate_write_filepage: already started\n");
10349 		return;
10350 	}
10351 	pagedep->pd_state |= IOSTARTED;
10352 	/*
10353 	 * Wait for all journal remove dependencies to hit the disk.
10354 	 * We can not allow any potentially conflicting directory adds
10355 	 * to be visible before removes and rollback is too difficult.
10356 	 * The per-filesystem lock may be dropped and re-acquired, however
10357 	 * we hold the buf locked so the dependency can not go away.
10358 	 */
10359 	LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next)
10360 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL)
10361 			jwait(&jremref->jr_list, MNT_WAIT);
10362 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL)
10363 		jwait(&jmvref->jm_list, MNT_WAIT);
10364 	for (i = 0; i < DAHASHSZ; i++) {
10365 		LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
10366 			ep = (struct direct *)
10367 			    ((char *)bp->b_data + dap->da_offset);
10368 			if (ep->d_ino != dap->da_newinum)
10369 				panic("%s: dir inum %ju != new %ju",
10370 				    "initiate_write_filepage",
10371 				    (uintmax_t)ep->d_ino,
10372 				    (uintmax_t)dap->da_newinum);
10373 			if (dap->da_state & DIRCHG)
10374 				ep->d_ino = dap->da_previous->dm_oldinum;
10375 			else
10376 				ep->d_ino = 0;
10377 			dap->da_state &= ~ATTACHED;
10378 			dap->da_state |= UNDONE;
10379 		}
10380 	}
10381 }
10382 
10383 /*
10384  * Version of initiate_write_inodeblock that handles UFS1 dinodes.
10385  * Note that any bug fixes made to this routine must be done in the
10386  * version found below.
10387  *
10388  * Called from within the procedure above to deal with unsatisfied
10389  * allocation dependencies in an inodeblock. The buffer must be
10390  * locked, thus, no I/O completion operations can occur while we
10391  * are manipulating its associated dependencies.
10392  */
10393 static void
10394 initiate_write_inodeblock_ufs1(
10395 	struct inodedep *inodedep,
10396 	struct buf *bp)			/* The inode block */
10397 {
10398 	struct allocdirect *adp, *lastadp;
10399 	struct ufs1_dinode *dp;
10400 	struct ufs1_dinode *sip;
10401 	struct inoref *inoref;
10402 	struct ufsmount *ump;
10403 	struct fs *fs;
10404 	ufs_lbn_t i;
10405 #ifdef INVARIANTS
10406 	ufs_lbn_t prevlbn = 0;
10407 #endif
10408 	int deplist __diagused;
10409 
10410 	if (inodedep->id_state & IOSTARTED)
10411 		panic("initiate_write_inodeblock_ufs1: already started");
10412 	inodedep->id_state |= IOSTARTED;
10413 	fs = inodedep->id_fs;
10414 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10415 	LOCK_OWNED(ump);
10416 	dp = (struct ufs1_dinode *)bp->b_data +
10417 	    ino_to_fsbo(fs, inodedep->id_ino);
10418 
10419 	/*
10420 	 * If we're on the unlinked list but have not yet written our
10421 	 * next pointer initialize it here.
10422 	 */
10423 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10424 		struct inodedep *inon;
10425 
10426 		inon = TAILQ_NEXT(inodedep, id_unlinked);
10427 		dp->di_freelink = inon ? inon->id_ino : 0;
10428 	}
10429 	/*
10430 	 * If the bitmap is not yet written, then the allocated
10431 	 * inode cannot be written to disk.
10432 	 */
10433 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10434 		if (inodedep->id_savedino1 != NULL)
10435 			panic("initiate_write_inodeblock_ufs1: I/O underway");
10436 		FREE_LOCK(ump);
10437 		sip = malloc(sizeof(struct ufs1_dinode),
10438 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
10439 		ACQUIRE_LOCK(ump);
10440 		inodedep->id_savedino1 = sip;
10441 		*inodedep->id_savedino1 = *dp;
10442 		bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
10443 		dp->di_gen = inodedep->id_savedino1->di_gen;
10444 		dp->di_freelink = inodedep->id_savedino1->di_freelink;
10445 		return;
10446 	}
10447 	/*
10448 	 * If no dependencies, then there is nothing to roll back.
10449 	 */
10450 	inodedep->id_savedsize = dp->di_size;
10451 	inodedep->id_savedextsize = 0;
10452 	inodedep->id_savednlink = dp->di_nlink;
10453 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10454 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
10455 		return;
10456 	/*
10457 	 * Revert the link count to that of the first unwritten journal entry.
10458 	 */
10459 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10460 	if (inoref)
10461 		dp->di_nlink = inoref->if_nlink;
10462 	/*
10463 	 * Set the dependencies to busy.
10464 	 */
10465 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10466 	     adp = TAILQ_NEXT(adp, ad_next)) {
10467 #ifdef INVARIANTS
10468 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10469 			panic("softdep_write_inodeblock: lbn order");
10470 		prevlbn = adp->ad_offset;
10471 		if (adp->ad_offset < UFS_NDADDR &&
10472 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10473 			panic("initiate_write_inodeblock_ufs1: "
10474 			    "direct pointer #%jd mismatch %d != %jd",
10475 			    (intmax_t)adp->ad_offset,
10476 			    dp->di_db[adp->ad_offset],
10477 			    (intmax_t)adp->ad_newblkno);
10478 		if (adp->ad_offset >= UFS_NDADDR &&
10479 		    dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10480 			panic("initiate_write_inodeblock_ufs1: "
10481 			    "indirect pointer #%jd mismatch %d != %jd",
10482 			    (intmax_t)adp->ad_offset - UFS_NDADDR,
10483 			    dp->di_ib[adp->ad_offset - UFS_NDADDR],
10484 			    (intmax_t)adp->ad_newblkno);
10485 		deplist |= 1 << adp->ad_offset;
10486 		if ((adp->ad_state & ATTACHED) == 0)
10487 			panic("initiate_write_inodeblock_ufs1: "
10488 			    "Unknown state 0x%x", adp->ad_state);
10489 #endif /* INVARIANTS */
10490 		adp->ad_state &= ~ATTACHED;
10491 		adp->ad_state |= UNDONE;
10492 	}
10493 	/*
10494 	 * The on-disk inode cannot claim to be any larger than the last
10495 	 * fragment that has been written. Otherwise, the on-disk inode
10496 	 * might have fragments that were not the last block in the file
10497 	 * which would corrupt the filesystem.
10498 	 */
10499 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10500 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10501 		if (adp->ad_offset >= UFS_NDADDR)
10502 			break;
10503 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10504 		/* keep going until hitting a rollback to a frag */
10505 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10506 			continue;
10507 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10508 		for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10509 #ifdef INVARIANTS
10510 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10511 				panic("initiate_write_inodeblock_ufs1: "
10512 				    "lost dep1");
10513 #endif /* INVARIANTS */
10514 			dp->di_db[i] = 0;
10515 		}
10516 		for (i = 0; i < UFS_NIADDR; i++) {
10517 #ifdef INVARIANTS
10518 			if (dp->di_ib[i] != 0 &&
10519 			    (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10520 				panic("initiate_write_inodeblock_ufs1: "
10521 				    "lost dep2");
10522 #endif /* INVARIANTS */
10523 			dp->di_ib[i] = 0;
10524 		}
10525 		return;
10526 	}
10527 	/*
10528 	 * If we have zero'ed out the last allocated block of the file,
10529 	 * roll back the size to the last currently allocated block.
10530 	 * We know that this last allocated block is a full-sized as
10531 	 * we already checked for fragments in the loop above.
10532 	 */
10533 	if (lastadp != NULL &&
10534 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10535 		for (i = lastadp->ad_offset; i >= 0; i--)
10536 			if (dp->di_db[i] != 0)
10537 				break;
10538 		dp->di_size = (i + 1) * fs->fs_bsize;
10539 	}
10540 	/*
10541 	 * The only dependencies are for indirect blocks.
10542 	 *
10543 	 * The file size for indirect block additions is not guaranteed.
10544 	 * Such a guarantee would be non-trivial to achieve. The conventional
10545 	 * synchronous write implementation also does not make this guarantee.
10546 	 * Fsck should catch and fix discrepancies. Arguably, the file size
10547 	 * can be over-estimated without destroying integrity when the file
10548 	 * moves into the indirect blocks (i.e., is large). If we want to
10549 	 * postpone fsck, we are stuck with this argument.
10550 	 */
10551 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10552 		dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10553 }
10554 
10555 /*
10556  * Version of initiate_write_inodeblock that handles UFS2 dinodes.
10557  * Note that any bug fixes made to this routine must be done in the
10558  * version found above.
10559  *
10560  * Called from within the procedure above to deal with unsatisfied
10561  * allocation dependencies in an inodeblock. The buffer must be
10562  * locked, thus, no I/O completion operations can occur while we
10563  * are manipulating its associated dependencies.
10564  */
10565 static void
10566 initiate_write_inodeblock_ufs2(
10567 	struct inodedep *inodedep,
10568 	struct buf *bp)			/* The inode block */
10569 {
10570 	struct allocdirect *adp, *lastadp;
10571 	struct ufs2_dinode *dp;
10572 	struct ufs2_dinode *sip;
10573 	struct inoref *inoref;
10574 	struct ufsmount *ump;
10575 	struct fs *fs;
10576 	ufs_lbn_t i;
10577 #ifdef INVARIANTS
10578 	ufs_lbn_t prevlbn = 0;
10579 #endif
10580 	int deplist __diagused;
10581 
10582 	if (inodedep->id_state & IOSTARTED)
10583 		panic("initiate_write_inodeblock_ufs2: already started");
10584 	inodedep->id_state |= IOSTARTED;
10585 	fs = inodedep->id_fs;
10586 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10587 	LOCK_OWNED(ump);
10588 	dp = (struct ufs2_dinode *)bp->b_data +
10589 	    ino_to_fsbo(fs, inodedep->id_ino);
10590 
10591 	/*
10592 	 * If we're on the unlinked list but have not yet written our
10593 	 * next pointer initialize it here.
10594 	 */
10595 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10596 		struct inodedep *inon;
10597 
10598 		inon = TAILQ_NEXT(inodedep, id_unlinked);
10599 		dp->di_freelink = inon ? inon->id_ino : 0;
10600 		ffs_update_dinode_ckhash(fs, dp);
10601 	}
10602 	/*
10603 	 * If the bitmap is not yet written, then the allocated
10604 	 * inode cannot be written to disk.
10605 	 */
10606 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10607 		if (inodedep->id_savedino2 != NULL)
10608 			panic("initiate_write_inodeblock_ufs2: I/O underway");
10609 		FREE_LOCK(ump);
10610 		sip = malloc(sizeof(struct ufs2_dinode),
10611 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
10612 		ACQUIRE_LOCK(ump);
10613 		inodedep->id_savedino2 = sip;
10614 		*inodedep->id_savedino2 = *dp;
10615 		bzero((caddr_t)dp, sizeof(struct ufs2_dinode));
10616 		dp->di_gen = inodedep->id_savedino2->di_gen;
10617 		dp->di_freelink = inodedep->id_savedino2->di_freelink;
10618 		return;
10619 	}
10620 	/*
10621 	 * If no dependencies, then there is nothing to roll back.
10622 	 */
10623 	inodedep->id_savedsize = dp->di_size;
10624 	inodedep->id_savedextsize = dp->di_extsize;
10625 	inodedep->id_savednlink = dp->di_nlink;
10626 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10627 	    TAILQ_EMPTY(&inodedep->id_extupdt) &&
10628 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
10629 		return;
10630 	/*
10631 	 * Revert the link count to that of the first unwritten journal entry.
10632 	 */
10633 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10634 	if (inoref)
10635 		dp->di_nlink = inoref->if_nlink;
10636 
10637 	/*
10638 	 * Set the ext data dependencies to busy.
10639 	 */
10640 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10641 	     adp = TAILQ_NEXT(adp, ad_next)) {
10642 #ifdef INVARIANTS
10643 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10644 			panic("initiate_write_inodeblock_ufs2: lbn order");
10645 		prevlbn = adp->ad_offset;
10646 		if (dp->di_extb[adp->ad_offset] != adp->ad_newblkno)
10647 			panic("initiate_write_inodeblock_ufs2: "
10648 			    "ext pointer #%jd mismatch %jd != %jd",
10649 			    (intmax_t)adp->ad_offset,
10650 			    (intmax_t)dp->di_extb[adp->ad_offset],
10651 			    (intmax_t)adp->ad_newblkno);
10652 		deplist |= 1 << adp->ad_offset;
10653 		if ((adp->ad_state & ATTACHED) == 0)
10654 			panic("initiate_write_inodeblock_ufs2: Unknown "
10655 			    "state 0x%x", adp->ad_state);
10656 #endif /* INVARIANTS */
10657 		adp->ad_state &= ~ATTACHED;
10658 		adp->ad_state |= UNDONE;
10659 	}
10660 	/*
10661 	 * The on-disk inode cannot claim to be any larger than the last
10662 	 * fragment that has been written. Otherwise, the on-disk inode
10663 	 * might have fragments that were not the last block in the ext
10664 	 * data which would corrupt the filesystem.
10665 	 */
10666 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10667 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10668 		dp->di_extb[adp->ad_offset] = adp->ad_oldblkno;
10669 		/* keep going until hitting a rollback to a frag */
10670 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10671 			continue;
10672 		dp->di_extsize = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10673 		for (i = adp->ad_offset + 1; i < UFS_NXADDR; i++) {
10674 #ifdef INVARIANTS
10675 			if (dp->di_extb[i] != 0 && (deplist & (1 << i)) == 0)
10676 				panic("initiate_write_inodeblock_ufs2: "
10677 				    "lost dep1");
10678 #endif /* INVARIANTS */
10679 			dp->di_extb[i] = 0;
10680 		}
10681 		lastadp = NULL;
10682 		break;
10683 	}
10684 	/*
10685 	 * If we have zero'ed out the last allocated block of the ext
10686 	 * data, roll back the size to the last currently allocated block.
10687 	 * We know that this last allocated block is a full-sized as
10688 	 * we already checked for fragments in the loop above.
10689 	 */
10690 	if (lastadp != NULL &&
10691 	    dp->di_extsize <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10692 		for (i = lastadp->ad_offset; i >= 0; i--)
10693 			if (dp->di_extb[i] != 0)
10694 				break;
10695 		dp->di_extsize = (i + 1) * fs->fs_bsize;
10696 	}
10697 	/*
10698 	 * Set the file data dependencies to busy.
10699 	 */
10700 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10701 	     adp = TAILQ_NEXT(adp, ad_next)) {
10702 #ifdef INVARIANTS
10703 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10704 			panic("softdep_write_inodeblock: lbn order");
10705 		if ((adp->ad_state & ATTACHED) == 0)
10706 			panic("inodedep %p and adp %p not attached", inodedep, adp);
10707 		prevlbn = adp->ad_offset;
10708 		if (!ffs_fsfail_cleanup(ump, 0) &&
10709 		    adp->ad_offset < UFS_NDADDR &&
10710 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10711 			panic("initiate_write_inodeblock_ufs2: "
10712 			    "direct pointer #%jd mismatch %jd != %jd",
10713 			    (intmax_t)adp->ad_offset,
10714 			    (intmax_t)dp->di_db[adp->ad_offset],
10715 			    (intmax_t)adp->ad_newblkno);
10716 		if (!ffs_fsfail_cleanup(ump, 0) &&
10717 		    adp->ad_offset >= UFS_NDADDR &&
10718 		    dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10719 			panic("initiate_write_inodeblock_ufs2: "
10720 			    "indirect pointer #%jd mismatch %jd != %jd",
10721 			    (intmax_t)adp->ad_offset - UFS_NDADDR,
10722 			    (intmax_t)dp->di_ib[adp->ad_offset - UFS_NDADDR],
10723 			    (intmax_t)adp->ad_newblkno);
10724 		deplist |= 1 << adp->ad_offset;
10725 		if ((adp->ad_state & ATTACHED) == 0)
10726 			panic("initiate_write_inodeblock_ufs2: Unknown "
10727 			     "state 0x%x", adp->ad_state);
10728 #endif /* INVARIANTS */
10729 		adp->ad_state &= ~ATTACHED;
10730 		adp->ad_state |= UNDONE;
10731 	}
10732 	/*
10733 	 * The on-disk inode cannot claim to be any larger than the last
10734 	 * fragment that has been written. Otherwise, the on-disk inode
10735 	 * might have fragments that were not the last block in the file
10736 	 * which would corrupt the filesystem.
10737 	 */
10738 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10739 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10740 		if (adp->ad_offset >= UFS_NDADDR)
10741 			break;
10742 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10743 		/* keep going until hitting a rollback to a frag */
10744 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10745 			continue;
10746 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10747 		for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10748 #ifdef INVARIANTS
10749 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10750 				panic("initiate_write_inodeblock_ufs2: "
10751 				    "lost dep2");
10752 #endif /* INVARIANTS */
10753 			dp->di_db[i] = 0;
10754 		}
10755 		for (i = 0; i < UFS_NIADDR; i++) {
10756 #ifdef INVARIANTS
10757 			if (dp->di_ib[i] != 0 &&
10758 			    (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10759 				panic("initiate_write_inodeblock_ufs2: "
10760 				    "lost dep3");
10761 #endif /* INVARIANTS */
10762 			dp->di_ib[i] = 0;
10763 		}
10764 		ffs_update_dinode_ckhash(fs, dp);
10765 		return;
10766 	}
10767 	/*
10768 	 * If we have zero'ed out the last allocated block of the file,
10769 	 * roll back the size to the last currently allocated block.
10770 	 * We know that this last allocated block is a full-sized as
10771 	 * we already checked for fragments in the loop above.
10772 	 */
10773 	if (lastadp != NULL &&
10774 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10775 		for (i = lastadp->ad_offset; i >= 0; i--)
10776 			if (dp->di_db[i] != 0)
10777 				break;
10778 		dp->di_size = (i + 1) * fs->fs_bsize;
10779 	}
10780 	/*
10781 	 * The only dependencies are for indirect blocks.
10782 	 *
10783 	 * The file size for indirect block additions is not guaranteed.
10784 	 * Such a guarantee would be non-trivial to achieve. The conventional
10785 	 * synchronous write implementation also does not make this guarantee.
10786 	 * Fsck should catch and fix discrepancies. Arguably, the file size
10787 	 * can be over-estimated without destroying integrity when the file
10788 	 * moves into the indirect blocks (i.e., is large). If we want to
10789 	 * postpone fsck, we are stuck with this argument.
10790 	 */
10791 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10792 		dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10793 	ffs_update_dinode_ckhash(fs, dp);
10794 }
10795 
10796 /*
10797  * Cancel an indirdep as a result of truncation.  Release all of the
10798  * children allocindirs and place their journal work on the appropriate
10799  * list.
10800  */
10801 static void
10802 cancel_indirdep(
10803 	struct indirdep *indirdep,
10804 	struct buf *bp,
10805 	struct freeblks *freeblks)
10806 {
10807 	struct allocindir *aip;
10808 
10809 	/*
10810 	 * None of the indirect pointers will ever be visible,
10811 	 * so they can simply be tossed. GOINGAWAY ensures
10812 	 * that allocated pointers will be saved in the buffer
10813 	 * cache until they are freed. Note that they will
10814 	 * only be able to be found by their physical address
10815 	 * since the inode mapping the logical address will
10816 	 * be gone. The save buffer used for the safe copy
10817 	 * was allocated in setup_allocindir_phase2 using
10818 	 * the physical address so it could be used for this
10819 	 * purpose. Hence we swap the safe copy with the real
10820 	 * copy, allowing the safe copy to be freed and holding
10821 	 * on to the real copy for later use in indir_trunc.
10822 	 */
10823 	if (indirdep->ir_state & GOINGAWAY)
10824 		panic("cancel_indirdep: already gone");
10825 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
10826 		indirdep->ir_state |= DEPCOMPLETE;
10827 		LIST_REMOVE(indirdep, ir_next);
10828 	}
10829 	indirdep->ir_state |= GOINGAWAY;
10830 	/*
10831 	 * Pass in bp for blocks still have journal writes
10832 	 * pending so we can cancel them on their own.
10833 	 */
10834 	while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != NULL)
10835 		cancel_allocindir(aip, bp, freeblks, 0);
10836 	while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL)
10837 		cancel_allocindir(aip, NULL, freeblks, 0);
10838 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL)
10839 		cancel_allocindir(aip, NULL, freeblks, 0);
10840 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL)
10841 		cancel_allocindir(aip, NULL, freeblks, 0);
10842 	/*
10843 	 * If there are pending partial truncations we need to keep the
10844 	 * old block copy around until they complete.  This is because
10845 	 * the current b_data is not a perfect superset of the available
10846 	 * blocks.
10847 	 */
10848 	if (TAILQ_EMPTY(&indirdep->ir_trunc))
10849 		bcopy(bp->b_data, indirdep->ir_savebp->b_data, bp->b_bcount);
10850 	else
10851 		bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10852 	WORKLIST_REMOVE(&indirdep->ir_list);
10853 	WORKLIST_INSERT(&indirdep->ir_savebp->b_dep, &indirdep->ir_list);
10854 	indirdep->ir_bp = NULL;
10855 	indirdep->ir_freeblks = freeblks;
10856 }
10857 
10858 /*
10859  * Free an indirdep once it no longer has new pointers to track.
10860  */
10861 static void
10862 free_indirdep(struct indirdep *indirdep)
10863 {
10864 
10865 	KASSERT(TAILQ_EMPTY(&indirdep->ir_trunc),
10866 	    ("free_indirdep: Indir trunc list not empty."));
10867 	KASSERT(LIST_EMPTY(&indirdep->ir_completehd),
10868 	    ("free_indirdep: Complete head not empty."));
10869 	KASSERT(LIST_EMPTY(&indirdep->ir_writehd),
10870 	    ("free_indirdep: write head not empty."));
10871 	KASSERT(LIST_EMPTY(&indirdep->ir_donehd),
10872 	    ("free_indirdep: done head not empty."));
10873 	KASSERT(LIST_EMPTY(&indirdep->ir_deplisthd),
10874 	    ("free_indirdep: deplist head not empty."));
10875 	KASSERT((indirdep->ir_state & DEPCOMPLETE),
10876 	    ("free_indirdep: %p still on newblk list.", indirdep));
10877 	KASSERT(indirdep->ir_saveddata == NULL,
10878 	    ("free_indirdep: %p still has saved data.", indirdep));
10879 	KASSERT(indirdep->ir_savebp == NULL,
10880 	    ("free_indirdep: %p still has savebp buffer.", indirdep));
10881 	if (indirdep->ir_state & ONWORKLIST)
10882 		WORKLIST_REMOVE(&indirdep->ir_list);
10883 	WORKITEM_FREE(indirdep, D_INDIRDEP);
10884 }
10885 
10886 /*
10887  * Called before a write to an indirdep.  This routine is responsible for
10888  * rolling back pointers to a safe state which includes only those
10889  * allocindirs which have been completed.
10890  */
10891 static void
10892 initiate_write_indirdep(struct indirdep *indirdep, struct buf *bp)
10893 {
10894 	struct ufsmount *ump;
10895 
10896 	indirdep->ir_state |= IOSTARTED;
10897 	if (indirdep->ir_state & GOINGAWAY)
10898 		panic("disk_io_initiation: indirdep gone");
10899 	/*
10900 	 * If there are no remaining dependencies, this will be writing
10901 	 * the real pointers.
10902 	 */
10903 	if (LIST_EMPTY(&indirdep->ir_deplisthd) &&
10904 	    TAILQ_EMPTY(&indirdep->ir_trunc))
10905 		return;
10906 	/*
10907 	 * Replace up-to-date version with safe version.
10908 	 */
10909 	if (indirdep->ir_saveddata == NULL) {
10910 		ump = VFSTOUFS(indirdep->ir_list.wk_mp);
10911 		LOCK_OWNED(ump);
10912 		FREE_LOCK(ump);
10913 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
10914 		    M_SOFTDEP_FLAGS);
10915 		ACQUIRE_LOCK(ump);
10916 	}
10917 	indirdep->ir_state &= ~ATTACHED;
10918 	indirdep->ir_state |= UNDONE;
10919 	bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10920 	bcopy(indirdep->ir_savebp->b_data, bp->b_data,
10921 	    bp->b_bcount);
10922 }
10923 
10924 /*
10925  * Called when an inode has been cleared in a cg bitmap.  This finally
10926  * eliminates any canceled jaddrefs
10927  */
10928 void
10929 softdep_setup_inofree(struct mount *mp,
10930 	struct buf *bp,
10931 	ino_t ino,
10932 	struct workhead *wkhd,
10933 	bool doingrecovery)
10934 {
10935 	struct worklist *wk, *wkn;
10936 	struct ufsmount *ump;
10937 #ifdef INVARIANTS
10938 	struct inodedep *inodedep;
10939 #endif
10940 
10941 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
10942 	    ("softdep_setup_inofree called on non-softdep filesystem"));
10943 	ump = VFSTOUFS(mp);
10944 	ACQUIRE_LOCK(ump);
10945 	KASSERT(doingrecovery || ffs_fsfail_cleanup(ump, 0) ||
10946 	    isclr(cg_inosused((struct cg *)bp->b_data),
10947 	    ino % ump->um_fs->fs_ipg),
10948 	    ("softdep_setup_inofree: inode %ju not freed.", (uintmax_t)ino));
10949 	KASSERT(inodedep_lookup(mp, ino, 0, &inodedep) == 0,
10950 	    ("softdep_setup_inofree: ino %ju has existing inodedep %p",
10951 	    (uintmax_t)ino, inodedep));
10952 	if (wkhd) {
10953 		LIST_FOREACH_SAFE(wk, wkhd, wk_list, wkn) {
10954 			if (wk->wk_type != D_JADDREF)
10955 				continue;
10956 			WORKLIST_REMOVE(wk);
10957 			/*
10958 			 * We can free immediately even if the jaddref
10959 			 * isn't attached in a background write as now
10960 			 * the bitmaps are reconciled.
10961 			 */
10962 			wk->wk_state |= COMPLETE | ATTACHED;
10963 			free_jaddref(WK_JADDREF(wk));
10964 		}
10965 		jwork_move(&bp->b_dep, wkhd);
10966 	}
10967 	FREE_LOCK(ump);
10968 }
10969 
10970 /*
10971  * Called via ffs_blkfree() after a set of frags has been cleared from a cg
10972  * map.  Any dependencies waiting for the write to clear are added to the
10973  * buf's list and any jnewblks that are being canceled are discarded
10974  * immediately.
10975  */
10976 void
10977 softdep_setup_blkfree(
10978 	struct mount *mp,
10979 	struct buf *bp,
10980 	ufs2_daddr_t blkno,
10981 	int frags,
10982 	struct workhead *wkhd,
10983 	bool doingrecovery)
10984 {
10985 	struct bmsafemap *bmsafemap;
10986 	struct jnewblk *jnewblk;
10987 	struct ufsmount *ump;
10988 	struct worklist *wk;
10989 	struct fs *fs;
10990 #ifdef INVARIANTS
10991 	uint8_t *blksfree;
10992 	struct cg *cgp;
10993 	ufs2_daddr_t jstart;
10994 	ufs2_daddr_t jend;
10995 	ufs2_daddr_t end;
10996 	long bno;
10997 	int i;
10998 #endif
10999 
11000 	CTR3(KTR_SUJ,
11001 	    "softdep_setup_blkfree: blkno %jd frags %d wk head %p",
11002 	    blkno, frags, wkhd);
11003 
11004 	ump = VFSTOUFS(mp);
11005 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
11006 	    ("softdep_setup_blkfree called on non-softdep filesystem"));
11007 	ACQUIRE_LOCK(ump);
11008 	/* Lookup the bmsafemap so we track when it is dirty. */
11009 	fs = ump->um_fs;
11010 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
11011 	/*
11012 	 * Detach any jnewblks which have been canceled.  They must linger
11013 	 * until the bitmap is cleared again by ffs_blkfree() to prevent
11014 	 * an unjournaled allocation from hitting the disk.
11015 	 */
11016 	if (wkhd) {
11017 		while ((wk = LIST_FIRST(wkhd)) != NULL) {
11018 			CTR2(KTR_SUJ,
11019 			    "softdep_setup_blkfree: blkno %jd wk type %d",
11020 			    blkno, wk->wk_type);
11021 			WORKLIST_REMOVE(wk);
11022 			if (wk->wk_type != D_JNEWBLK) {
11023 				WORKLIST_INSERT(&bmsafemap->sm_freehd, wk);
11024 				continue;
11025 			}
11026 			jnewblk = WK_JNEWBLK(wk);
11027 			KASSERT(jnewblk->jn_state & GOINGAWAY,
11028 			    ("softdep_setup_blkfree: jnewblk not canceled."));
11029 #ifdef INVARIANTS
11030 			if (!doingrecovery && !ffs_fsfail_cleanup(ump, 0)) {
11031 				/*
11032 				 * Assert that this block is free in the
11033 				 * bitmap before we discard the jnewblk.
11034 				 */
11035 				cgp = (struct cg *)bp->b_data;
11036 				blksfree = cg_blksfree(cgp);
11037 				bno = dtogd(fs, jnewblk->jn_blkno);
11038 				for (i = jnewblk->jn_oldfrags;
11039 				    i < jnewblk->jn_frags; i++) {
11040 					if (isset(blksfree, bno + i))
11041 						continue;
11042 					panic("softdep_setup_blkfree: block "
11043 					    "%ju not freed.",
11044 					    (uintmax_t)jnewblk->jn_blkno);
11045 				}
11046 			}
11047 #endif
11048 			/*
11049 			 * Even if it's not attached we can free immediately
11050 			 * as the new bitmap is correct.
11051 			 */
11052 			wk->wk_state |= COMPLETE | ATTACHED;
11053 			free_jnewblk(jnewblk);
11054 		}
11055 	}
11056 
11057 #ifdef INVARIANTS
11058 	/*
11059 	 * Assert that we are not freeing a block which has an outstanding
11060 	 * allocation dependency.
11061 	 */
11062 	fs = VFSTOUFS(mp)->um_fs;
11063 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
11064 	end = blkno + frags;
11065 	LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
11066 		/*
11067 		 * Don't match against blocks that will be freed when the
11068 		 * background write is done.
11069 		 */
11070 		if ((jnewblk->jn_state & (ATTACHED | COMPLETE | DEPCOMPLETE)) ==
11071 		    (COMPLETE | DEPCOMPLETE))
11072 			continue;
11073 		jstart = jnewblk->jn_blkno + jnewblk->jn_oldfrags;
11074 		jend = jnewblk->jn_blkno + jnewblk->jn_frags;
11075 		if ((blkno >= jstart && blkno < jend) ||
11076 		    (end > jstart && end <= jend)) {
11077 			printf("state 0x%X %jd - %d %d dep %p\n",
11078 			    jnewblk->jn_state, jnewblk->jn_blkno,
11079 			    jnewblk->jn_oldfrags, jnewblk->jn_frags,
11080 			    jnewblk->jn_dep);
11081 			panic("softdep_setup_blkfree: "
11082 			    "%jd-%jd(%d) overlaps with %jd-%jd",
11083 			    blkno, end, frags, jstart, jend);
11084 		}
11085 	}
11086 #endif
11087 	FREE_LOCK(ump);
11088 }
11089 
11090 /*
11091  * Revert a block allocation when the journal record that describes it
11092  * is not yet written.
11093  */
11094 static int
11095 jnewblk_rollback(
11096 	struct jnewblk *jnewblk,
11097 	struct fs *fs,
11098 	struct cg *cgp,
11099 	uint8_t *blksfree)
11100 {
11101 	ufs1_daddr_t fragno;
11102 	long cgbno, bbase;
11103 	int frags, blk;
11104 	int i;
11105 
11106 	frags = 0;
11107 	cgbno = dtogd(fs, jnewblk->jn_blkno);
11108 	/*
11109 	 * We have to test which frags need to be rolled back.  We may
11110 	 * be operating on a stale copy when doing background writes.
11111 	 */
11112 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++)
11113 		if (isclr(blksfree, cgbno + i))
11114 			frags++;
11115 	if (frags == 0)
11116 		return (0);
11117 	/*
11118 	 * This is mostly ffs_blkfree() sans some validation and
11119 	 * superblock updates.
11120 	 */
11121 	if (frags == fs->fs_frag) {
11122 		fragno = fragstoblks(fs, cgbno);
11123 		ffs_setblock(fs, blksfree, fragno);
11124 		ffs_clusteracct(fs, cgp, fragno, 1);
11125 		cgp->cg_cs.cs_nbfree++;
11126 	} else {
11127 		cgbno += jnewblk->jn_oldfrags;
11128 		bbase = cgbno - fragnum(fs, cgbno);
11129 		/* Decrement the old frags.  */
11130 		blk = blkmap(fs, blksfree, bbase);
11131 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
11132 		/* Deallocate the fragment */
11133 		for (i = 0; i < frags; i++)
11134 			setbit(blksfree, cgbno + i);
11135 		cgp->cg_cs.cs_nffree += frags;
11136 		/* Add back in counts associated with the new frags */
11137 		blk = blkmap(fs, blksfree, bbase);
11138 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
11139 		/* If a complete block has been reassembled, account for it. */
11140 		fragno = fragstoblks(fs, bbase);
11141 		if (ffs_isblock(fs, blksfree, fragno)) {
11142 			cgp->cg_cs.cs_nffree -= fs->fs_frag;
11143 			ffs_clusteracct(fs, cgp, fragno, 1);
11144 			cgp->cg_cs.cs_nbfree++;
11145 		}
11146 	}
11147 	stat_jnewblk++;
11148 	jnewblk->jn_state &= ~ATTACHED;
11149 	jnewblk->jn_state |= UNDONE;
11150 
11151 	return (frags);
11152 }
11153 
11154 static void
11155 initiate_write_bmsafemap(
11156 	struct bmsafemap *bmsafemap,
11157 	struct buf *bp)			/* The cg block. */
11158 {
11159 	struct jaddref *jaddref;
11160 	struct jnewblk *jnewblk;
11161 	uint8_t *inosused;
11162 	uint8_t *blksfree;
11163 	struct cg *cgp;
11164 	struct fs *fs;
11165 	ino_t ino;
11166 
11167 	/*
11168 	 * If this is a background write, we did this at the time that
11169 	 * the copy was made, so do not need to do it again.
11170 	 */
11171 	if (bmsafemap->sm_state & IOSTARTED)
11172 		return;
11173 	bmsafemap->sm_state |= IOSTARTED;
11174 	/*
11175 	 * Clear any inode allocations which are pending journal writes.
11176 	 */
11177 	if (LIST_FIRST(&bmsafemap->sm_jaddrefhd) != NULL) {
11178 		cgp = (struct cg *)bp->b_data;
11179 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11180 		inosused = cg_inosused(cgp);
11181 		LIST_FOREACH(jaddref, &bmsafemap->sm_jaddrefhd, ja_bmdeps) {
11182 			ino = jaddref->ja_ino % fs->fs_ipg;
11183 			if (isset(inosused, ino)) {
11184 				if ((jaddref->ja_mode & IFMT) == IFDIR)
11185 					cgp->cg_cs.cs_ndir--;
11186 				cgp->cg_cs.cs_nifree++;
11187 				clrbit(inosused, ino);
11188 				jaddref->ja_state &= ~ATTACHED;
11189 				jaddref->ja_state |= UNDONE;
11190 				stat_jaddref++;
11191 			} else
11192 				panic("initiate_write_bmsafemap: inode %ju "
11193 				    "marked free", (uintmax_t)jaddref->ja_ino);
11194 		}
11195 	}
11196 	/*
11197 	 * Clear any block allocations which are pending journal writes.
11198 	 */
11199 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
11200 		cgp = (struct cg *)bp->b_data;
11201 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11202 		blksfree = cg_blksfree(cgp);
11203 		LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
11204 			if (jnewblk_rollback(jnewblk, fs, cgp, blksfree))
11205 				continue;
11206 			panic("initiate_write_bmsafemap: block %jd "
11207 			    "marked free", jnewblk->jn_blkno);
11208 		}
11209 	}
11210 	/*
11211 	 * Move allocation lists to the written lists so they can be
11212 	 * cleared once the block write is complete.
11213 	 */
11214 	LIST_SWAP(&bmsafemap->sm_inodedephd, &bmsafemap->sm_inodedepwr,
11215 	    inodedep, id_deps);
11216 	LIST_SWAP(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
11217 	    newblk, nb_deps);
11218 	LIST_SWAP(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr, worklist,
11219 	    wk_list);
11220 }
11221 
11222 void
11223 softdep_handle_error(struct buf *bp)
11224 {
11225 	struct ufsmount *ump;
11226 
11227 	ump = softdep_bp_to_mp(bp);
11228 	if (ump == NULL)
11229 		return;
11230 
11231 	if (ffs_fsfail_cleanup(ump, bp->b_error)) {
11232 		/*
11233 		 * No future writes will succeed, so the on-disk image is safe.
11234 		 * Pretend that this write succeeded so that the softdep state
11235 		 * will be cleaned up naturally.
11236 		 */
11237 		bp->b_ioflags &= ~BIO_ERROR;
11238 		bp->b_error = 0;
11239 	}
11240 }
11241 
11242 /*
11243  * This routine is called during the completion interrupt
11244  * service routine for a disk write (from the procedure called
11245  * by the device driver to inform the filesystem caches of
11246  * a request completion).  It should be called early in this
11247  * procedure, before the block is made available to other
11248  * processes or other routines are called.
11249  *
11250  */
11251 static void
11252 softdep_disk_write_complete(
11253 	struct buf *bp)		/* describes the completed disk write */
11254 {
11255 	struct worklist *wk;
11256 	struct worklist *owk;
11257 	struct ufsmount *ump;
11258 	struct workhead reattach;
11259 	struct freeblks *freeblks;
11260 	struct buf *sbp;
11261 
11262 	ump = softdep_bp_to_mp(bp);
11263 	KASSERT(LIST_EMPTY(&bp->b_dep) || ump != NULL,
11264 	    ("softdep_disk_write_complete: softdep_bp_to_mp returned NULL "
11265 	     "with outstanding dependencies for buffer %p", bp));
11266 	if (ump == NULL)
11267 		return;
11268 	if ((bp->b_ioflags & BIO_ERROR) != 0)
11269 		softdep_handle_error(bp);
11270 	/*
11271 	 * If an error occurred while doing the write, then the data
11272 	 * has not hit the disk and the dependencies cannot be processed.
11273 	 * But we do have to go through and roll forward any dependencies
11274 	 * that were rolled back before the disk write.
11275 	 */
11276 	sbp = NULL;
11277 	ACQUIRE_LOCK(ump);
11278 	if ((bp->b_ioflags & BIO_ERROR) != 0 && (bp->b_flags & B_INVAL) == 0) {
11279 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
11280 			switch (wk->wk_type) {
11281 			case D_PAGEDEP:
11282 				handle_written_filepage(WK_PAGEDEP(wk), bp, 0);
11283 				continue;
11284 
11285 			case D_INODEDEP:
11286 				handle_written_inodeblock(WK_INODEDEP(wk),
11287 				    bp, 0);
11288 				continue;
11289 
11290 			case D_BMSAFEMAP:
11291 				handle_written_bmsafemap(WK_BMSAFEMAP(wk),
11292 				    bp, 0);
11293 				continue;
11294 
11295 			case D_INDIRDEP:
11296 				handle_written_indirdep(WK_INDIRDEP(wk),
11297 				    bp, &sbp, 0);
11298 				continue;
11299 			default:
11300 				/* nothing to roll forward */
11301 				continue;
11302 			}
11303 		}
11304 		FREE_LOCK(ump);
11305 		if (sbp)
11306 			brelse(sbp);
11307 		return;
11308 	}
11309 	LIST_INIT(&reattach);
11310 
11311 	/*
11312 	 * Ump SU lock must not be released anywhere in this code segment.
11313 	 */
11314 	owk = NULL;
11315 	while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
11316 		WORKLIST_REMOVE(wk);
11317 		atomic_add_long(&dep_write[wk->wk_type], 1);
11318 		if (wk == owk)
11319 			panic("duplicate worklist: %p\n", wk);
11320 		owk = wk;
11321 		switch (wk->wk_type) {
11322 		case D_PAGEDEP:
11323 			if (handle_written_filepage(WK_PAGEDEP(wk), bp,
11324 			    WRITESUCCEEDED))
11325 				WORKLIST_INSERT(&reattach, wk);
11326 			continue;
11327 
11328 		case D_INODEDEP:
11329 			if (handle_written_inodeblock(WK_INODEDEP(wk), bp,
11330 			    WRITESUCCEEDED))
11331 				WORKLIST_INSERT(&reattach, wk);
11332 			continue;
11333 
11334 		case D_BMSAFEMAP:
11335 			if (handle_written_bmsafemap(WK_BMSAFEMAP(wk), bp,
11336 			    WRITESUCCEEDED))
11337 				WORKLIST_INSERT(&reattach, wk);
11338 			continue;
11339 
11340 		case D_MKDIR:
11341 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
11342 			continue;
11343 
11344 		case D_ALLOCDIRECT:
11345 			wk->wk_state |= COMPLETE;
11346 			handle_allocdirect_partdone(WK_ALLOCDIRECT(wk), NULL);
11347 			continue;
11348 
11349 		case D_ALLOCINDIR:
11350 			wk->wk_state |= COMPLETE;
11351 			handle_allocindir_partdone(WK_ALLOCINDIR(wk));
11352 			continue;
11353 
11354 		case D_INDIRDEP:
11355 			if (handle_written_indirdep(WK_INDIRDEP(wk), bp, &sbp,
11356 			    WRITESUCCEEDED))
11357 				WORKLIST_INSERT(&reattach, wk);
11358 			continue;
11359 
11360 		case D_FREEBLKS:
11361 			wk->wk_state |= COMPLETE;
11362 			freeblks = WK_FREEBLKS(wk);
11363 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE &&
11364 			    LIST_EMPTY(&freeblks->fb_jblkdephd))
11365 				add_to_worklist(wk, WK_NODELAY);
11366 			continue;
11367 
11368 		case D_FREEWORK:
11369 			handle_written_freework(WK_FREEWORK(wk));
11370 			break;
11371 
11372 		case D_JSEGDEP:
11373 			free_jsegdep(WK_JSEGDEP(wk));
11374 			continue;
11375 
11376 		case D_JSEG:
11377 			handle_written_jseg(WK_JSEG(wk), bp);
11378 			continue;
11379 
11380 		case D_SBDEP:
11381 			if (handle_written_sbdep(WK_SBDEP(wk), bp))
11382 				WORKLIST_INSERT(&reattach, wk);
11383 			continue;
11384 
11385 		case D_FREEDEP:
11386 			free_freedep(WK_FREEDEP(wk));
11387 			continue;
11388 
11389 		default:
11390 			panic("handle_disk_write_complete: Unknown type %s",
11391 			    TYPENAME(wk->wk_type));
11392 			/* NOTREACHED */
11393 		}
11394 	}
11395 	/*
11396 	 * Reattach any requests that must be redone.
11397 	 */
11398 	while ((wk = LIST_FIRST(&reattach)) != NULL) {
11399 		WORKLIST_REMOVE(wk);
11400 		WORKLIST_INSERT(&bp->b_dep, wk);
11401 	}
11402 	FREE_LOCK(ump);
11403 	if (sbp)
11404 		brelse(sbp);
11405 }
11406 
11407 /*
11408  * Called from within softdep_disk_write_complete above.
11409  */
11410 static void
11411 handle_allocdirect_partdone(
11412 	struct allocdirect *adp,	/* the completed allocdirect */
11413 	struct workhead *wkhd)		/* Work to do when inode is writtne. */
11414 {
11415 	struct allocdirectlst *listhead;
11416 	struct allocdirect *listadp;
11417 	struct inodedep *inodedep;
11418 	long bsize;
11419 
11420 	LOCK_OWNED(VFSTOUFS(adp->ad_block.nb_list.wk_mp));
11421 	if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11422 		return;
11423 	/*
11424 	 * The on-disk inode cannot claim to be any larger than the last
11425 	 * fragment that has been written. Otherwise, the on-disk inode
11426 	 * might have fragments that were not the last block in the file
11427 	 * which would corrupt the filesystem. Thus, we cannot free any
11428 	 * allocdirects after one whose ad_oldblkno claims a fragment as
11429 	 * these blocks must be rolled back to zero before writing the inode.
11430 	 * We check the currently active set of allocdirects in id_inoupdt
11431 	 * or id_extupdt as appropriate.
11432 	 */
11433 	inodedep = adp->ad_inodedep;
11434 	bsize = inodedep->id_fs->fs_bsize;
11435 	if (adp->ad_state & EXTDATA)
11436 		listhead = &inodedep->id_extupdt;
11437 	else
11438 		listhead = &inodedep->id_inoupdt;
11439 	TAILQ_FOREACH(listadp, listhead, ad_next) {
11440 		/* found our block */
11441 		if (listadp == adp)
11442 			break;
11443 		/* continue if ad_oldlbn is not a fragment */
11444 		if (listadp->ad_oldsize == 0 ||
11445 		    listadp->ad_oldsize == bsize)
11446 			continue;
11447 		/* hit a fragment */
11448 		return;
11449 	}
11450 	/*
11451 	 * If we have reached the end of the current list without
11452 	 * finding the just finished dependency, then it must be
11453 	 * on the future dependency list. Future dependencies cannot
11454 	 * be freed until they are moved to the current list.
11455 	 */
11456 	if (listadp == NULL) {
11457 #ifdef INVARIANTS
11458 		if (adp->ad_state & EXTDATA)
11459 			listhead = &inodedep->id_newextupdt;
11460 		else
11461 			listhead = &inodedep->id_newinoupdt;
11462 		TAILQ_FOREACH(listadp, listhead, ad_next)
11463 			/* found our block */
11464 			if (listadp == adp)
11465 				break;
11466 		if (listadp == NULL)
11467 			panic("handle_allocdirect_partdone: lost dep");
11468 #endif /* INVARIANTS */
11469 		return;
11470 	}
11471 	/*
11472 	 * If we have found the just finished dependency, then queue
11473 	 * it along with anything that follows it that is complete.
11474 	 * Since the pointer has not yet been written in the inode
11475 	 * as the dependency prevents it, place the allocdirect on the
11476 	 * bufwait list where it will be freed once the pointer is
11477 	 * valid.
11478 	 */
11479 	if (wkhd == NULL)
11480 		wkhd = &inodedep->id_bufwait;
11481 	for (; adp; adp = listadp) {
11482 		listadp = TAILQ_NEXT(adp, ad_next);
11483 		if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11484 			return;
11485 		TAILQ_REMOVE(listhead, adp, ad_next);
11486 		WORKLIST_INSERT(wkhd, &adp->ad_block.nb_list);
11487 	}
11488 }
11489 
11490 /*
11491  * Called from within softdep_disk_write_complete above.  This routine
11492  * completes successfully written allocindirs.
11493  */
11494 static void
11495 handle_allocindir_partdone(
11496 	struct allocindir *aip)		/* the completed allocindir */
11497 {
11498 	struct indirdep *indirdep;
11499 
11500 	if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
11501 		return;
11502 	indirdep = aip->ai_indirdep;
11503 	LIST_REMOVE(aip, ai_next);
11504 	/*
11505 	 * Don't set a pointer while the buffer is undergoing IO or while
11506 	 * we have active truncations.
11507 	 */
11508 	if (indirdep->ir_state & UNDONE || !TAILQ_EMPTY(&indirdep->ir_trunc)) {
11509 		LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
11510 		return;
11511 	}
11512 	if (indirdep->ir_state & UFS1FMT)
11513 		((ufs1_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11514 		    aip->ai_newblkno;
11515 	else
11516 		((ufs2_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11517 		    aip->ai_newblkno;
11518 	/*
11519 	 * Await the pointer write before freeing the allocindir.
11520 	 */
11521 	LIST_INSERT_HEAD(&indirdep->ir_writehd, aip, ai_next);
11522 }
11523 
11524 /*
11525  * Release segments held on a jwork list.
11526  */
11527 static void
11528 handle_jwork(struct workhead *wkhd)
11529 {
11530 	struct worklist *wk;
11531 
11532 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
11533 		WORKLIST_REMOVE(wk);
11534 		switch (wk->wk_type) {
11535 		case D_JSEGDEP:
11536 			free_jsegdep(WK_JSEGDEP(wk));
11537 			continue;
11538 		case D_FREEDEP:
11539 			free_freedep(WK_FREEDEP(wk));
11540 			continue;
11541 		case D_FREEFRAG:
11542 			rele_jseg(WK_JSEG(WK_FREEFRAG(wk)->ff_jdep));
11543 			WORKITEM_FREE(wk, D_FREEFRAG);
11544 			continue;
11545 		case D_FREEWORK:
11546 			handle_written_freework(WK_FREEWORK(wk));
11547 			continue;
11548 		default:
11549 			panic("handle_jwork: Unknown type %s\n",
11550 			    TYPENAME(wk->wk_type));
11551 		}
11552 	}
11553 }
11554 
11555 /*
11556  * Handle the bufwait list on an inode when it is safe to release items
11557  * held there.  This normally happens after an inode block is written but
11558  * may be delayed and handled later if there are pending journal items that
11559  * are not yet safe to be released.
11560  */
11561 static struct freefile *
11562 handle_bufwait(
11563 	struct inodedep *inodedep,
11564 	struct workhead *refhd)
11565 {
11566 	struct jaddref *jaddref;
11567 	struct freefile *freefile;
11568 	struct worklist *wk;
11569 
11570 	freefile = NULL;
11571 	while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
11572 		WORKLIST_REMOVE(wk);
11573 		switch (wk->wk_type) {
11574 		case D_FREEFILE:
11575 			/*
11576 			 * We defer adding freefile to the worklist
11577 			 * until all other additions have been made to
11578 			 * ensure that it will be done after all the
11579 			 * old blocks have been freed.
11580 			 */
11581 			if (freefile != NULL)
11582 				panic("handle_bufwait: freefile");
11583 			freefile = WK_FREEFILE(wk);
11584 			continue;
11585 
11586 		case D_MKDIR:
11587 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
11588 			continue;
11589 
11590 		case D_DIRADD:
11591 			diradd_inode_written(WK_DIRADD(wk), inodedep);
11592 			continue;
11593 
11594 		case D_FREEFRAG:
11595 			wk->wk_state |= COMPLETE;
11596 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE)
11597 				add_to_worklist(wk, 0);
11598 			continue;
11599 
11600 		case D_DIRREM:
11601 			wk->wk_state |= COMPLETE;
11602 			add_to_worklist(wk, 0);
11603 			continue;
11604 
11605 		case D_ALLOCDIRECT:
11606 		case D_ALLOCINDIR:
11607 			free_newblk(WK_NEWBLK(wk));
11608 			continue;
11609 
11610 		case D_JNEWBLK:
11611 			wk->wk_state |= COMPLETE;
11612 			free_jnewblk(WK_JNEWBLK(wk));
11613 			continue;
11614 
11615 		/*
11616 		 * Save freed journal segments and add references on
11617 		 * the supplied list which will delay their release
11618 		 * until the cg bitmap is cleared on disk.
11619 		 */
11620 		case D_JSEGDEP:
11621 			if (refhd == NULL)
11622 				free_jsegdep(WK_JSEGDEP(wk));
11623 			else
11624 				WORKLIST_INSERT(refhd, wk);
11625 			continue;
11626 
11627 		case D_JADDREF:
11628 			jaddref = WK_JADDREF(wk);
11629 			TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
11630 			    if_deps);
11631 			/*
11632 			 * Transfer any jaddrefs to the list to be freed with
11633 			 * the bitmap if we're handling a removed file.
11634 			 */
11635 			if (refhd == NULL) {
11636 				wk->wk_state |= COMPLETE;
11637 				free_jaddref(jaddref);
11638 			} else
11639 				WORKLIST_INSERT(refhd, wk);
11640 			continue;
11641 
11642 		default:
11643 			panic("handle_bufwait: Unknown type %p(%s)",
11644 			    wk, TYPENAME(wk->wk_type));
11645 			/* NOTREACHED */
11646 		}
11647 	}
11648 	return (freefile);
11649 }
11650 /*
11651  * Called from within softdep_disk_write_complete above to restore
11652  * in-memory inode block contents to their most up-to-date state. Note
11653  * that this routine is always called from interrupt level with further
11654  * interrupts from this device blocked.
11655  *
11656  * If the write did not succeed, we will do all the roll-forward
11657  * operations, but we will not take the actions that will allow its
11658  * dependencies to be processed.
11659  */
11660 static int
11661 handle_written_inodeblock(
11662 	struct inodedep *inodedep,
11663 	struct buf *bp,		/* buffer containing the inode block */
11664 	int flags)
11665 {
11666 	struct freefile *freefile;
11667 	struct allocdirect *adp, *nextadp;
11668 	struct ufs1_dinode *dp1 = NULL;
11669 	struct ufs2_dinode *dp2 = NULL;
11670 	struct workhead wkhd;
11671 	int hadchanges, fstype;
11672 	ino_t freelink;
11673 
11674 	LIST_INIT(&wkhd);
11675 	hadchanges = 0;
11676 	freefile = NULL;
11677 	if ((inodedep->id_state & IOSTARTED) == 0)
11678 		panic("handle_written_inodeblock: not started");
11679 	inodedep->id_state &= ~IOSTARTED;
11680 	if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC) {
11681 		fstype = UFS1;
11682 		dp1 = (struct ufs1_dinode *)bp->b_data +
11683 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11684 		freelink = dp1->di_freelink;
11685 	} else {
11686 		fstype = UFS2;
11687 		dp2 = (struct ufs2_dinode *)bp->b_data +
11688 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11689 		freelink = dp2->di_freelink;
11690 	}
11691 	/*
11692 	 * Leave this inodeblock dirty until it's in the list.
11693 	 */
11694 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) == UNLINKED &&
11695 	    (flags & WRITESUCCEEDED)) {
11696 		struct inodedep *inon;
11697 
11698 		inon = TAILQ_NEXT(inodedep, id_unlinked);
11699 		if ((inon == NULL && freelink == 0) ||
11700 		    (inon && inon->id_ino == freelink)) {
11701 			if (inon)
11702 				inon->id_state |= UNLINKPREV;
11703 			inodedep->id_state |= UNLINKNEXT;
11704 		}
11705 		hadchanges = 1;
11706 	}
11707 	/*
11708 	 * If we had to rollback the inode allocation because of
11709 	 * bitmaps being incomplete, then simply restore it.
11710 	 * Keep the block dirty so that it will not be reclaimed until
11711 	 * all associated dependencies have been cleared and the
11712 	 * corresponding updates written to disk.
11713 	 */
11714 	if (inodedep->id_savedino1 != NULL) {
11715 		hadchanges = 1;
11716 		if (fstype == UFS1)
11717 			*dp1 = *inodedep->id_savedino1;
11718 		else
11719 			*dp2 = *inodedep->id_savedino2;
11720 		free(inodedep->id_savedino1, M_SAVEDINO);
11721 		inodedep->id_savedino1 = NULL;
11722 		if ((bp->b_flags & B_DELWRI) == 0)
11723 			stat_inode_bitmap++;
11724 		bdirty(bp);
11725 		/*
11726 		 * If the inode is clear here and GOINGAWAY it will never
11727 		 * be written.  Process the bufwait and clear any pending
11728 		 * work which may include the freefile.
11729 		 */
11730 		if (inodedep->id_state & GOINGAWAY)
11731 			goto bufwait;
11732 		return (1);
11733 	}
11734 	if (flags & WRITESUCCEEDED)
11735 		inodedep->id_state |= COMPLETE;
11736 	/*
11737 	 * Roll forward anything that had to be rolled back before
11738 	 * the inode could be updated.
11739 	 */
11740 	for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
11741 		nextadp = TAILQ_NEXT(adp, ad_next);
11742 		if (adp->ad_state & ATTACHED)
11743 			panic("handle_written_inodeblock: new entry");
11744 		if (fstype == UFS1) {
11745 			if (adp->ad_offset < UFS_NDADDR) {
11746 				if (dp1->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11747 					panic("%s %s #%jd mismatch %d != %jd",
11748 					    "handle_written_inodeblock:",
11749 					    "direct pointer",
11750 					    (intmax_t)adp->ad_offset,
11751 					    dp1->di_db[adp->ad_offset],
11752 					    (intmax_t)adp->ad_oldblkno);
11753 				dp1->di_db[adp->ad_offset] = adp->ad_newblkno;
11754 			} else {
11755 				if (dp1->di_ib[adp->ad_offset - UFS_NDADDR] !=
11756 				    0)
11757 					panic("%s: %s #%jd allocated as %d",
11758 					    "handle_written_inodeblock",
11759 					    "indirect pointer",
11760 					    (intmax_t)adp->ad_offset -
11761 					    UFS_NDADDR,
11762 					    dp1->di_ib[adp->ad_offset -
11763 					    UFS_NDADDR]);
11764 				dp1->di_ib[adp->ad_offset - UFS_NDADDR] =
11765 				    adp->ad_newblkno;
11766 			}
11767 		} else {
11768 			if (adp->ad_offset < UFS_NDADDR) {
11769 				if (dp2->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11770 					panic("%s: %s #%jd %s %jd != %jd",
11771 					    "handle_written_inodeblock",
11772 					    "direct pointer",
11773 					    (intmax_t)adp->ad_offset, "mismatch",
11774 					    (intmax_t)dp2->di_db[adp->ad_offset],
11775 					    (intmax_t)adp->ad_oldblkno);
11776 				dp2->di_db[adp->ad_offset] = adp->ad_newblkno;
11777 			} else {
11778 				if (dp2->di_ib[adp->ad_offset - UFS_NDADDR] !=
11779 				    0)
11780 					panic("%s: %s #%jd allocated as %jd",
11781 					    "handle_written_inodeblock",
11782 					    "indirect pointer",
11783 					    (intmax_t)adp->ad_offset -
11784 					    UFS_NDADDR,
11785 					    (intmax_t)
11786 					    dp2->di_ib[adp->ad_offset -
11787 					    UFS_NDADDR]);
11788 				dp2->di_ib[adp->ad_offset - UFS_NDADDR] =
11789 				    adp->ad_newblkno;
11790 			}
11791 		}
11792 		adp->ad_state &= ~UNDONE;
11793 		adp->ad_state |= ATTACHED;
11794 		hadchanges = 1;
11795 	}
11796 	for (adp = TAILQ_FIRST(&inodedep->id_extupdt); adp; adp = nextadp) {
11797 		nextadp = TAILQ_NEXT(adp, ad_next);
11798 		if (adp->ad_state & ATTACHED)
11799 			panic("handle_written_inodeblock: new entry");
11800 		if (dp2->di_extb[adp->ad_offset] != adp->ad_oldblkno)
11801 			panic("%s: direct pointers #%jd %s %jd != %jd",
11802 			    "handle_written_inodeblock",
11803 			    (intmax_t)adp->ad_offset, "mismatch",
11804 			    (intmax_t)dp2->di_extb[adp->ad_offset],
11805 			    (intmax_t)adp->ad_oldblkno);
11806 		dp2->di_extb[adp->ad_offset] = adp->ad_newblkno;
11807 		adp->ad_state &= ~UNDONE;
11808 		adp->ad_state |= ATTACHED;
11809 		hadchanges = 1;
11810 	}
11811 	if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
11812 		stat_direct_blk_ptrs++;
11813 	/*
11814 	 * Reset the file size to its most up-to-date value.
11815 	 */
11816 	if (inodedep->id_savedsize == -1 || inodedep->id_savedextsize == -1)
11817 		panic("handle_written_inodeblock: bad size");
11818 	if (inodedep->id_savednlink > UFS_LINK_MAX)
11819 		panic("handle_written_inodeblock: Invalid link count "
11820 		    "%jd for inodedep %p", (uintmax_t)inodedep->id_savednlink,
11821 		    inodedep);
11822 	if (fstype == UFS1) {
11823 		if (dp1->di_nlink != inodedep->id_savednlink) {
11824 			dp1->di_nlink = inodedep->id_savednlink;
11825 			hadchanges = 1;
11826 		}
11827 		if (dp1->di_size != inodedep->id_savedsize) {
11828 			dp1->di_size = inodedep->id_savedsize;
11829 			hadchanges = 1;
11830 		}
11831 	} else {
11832 		if (dp2->di_nlink != inodedep->id_savednlink) {
11833 			dp2->di_nlink = inodedep->id_savednlink;
11834 			hadchanges = 1;
11835 		}
11836 		if (dp2->di_size != inodedep->id_savedsize) {
11837 			dp2->di_size = inodedep->id_savedsize;
11838 			hadchanges = 1;
11839 		}
11840 		if (dp2->di_extsize != inodedep->id_savedextsize) {
11841 			dp2->di_extsize = inodedep->id_savedextsize;
11842 			hadchanges = 1;
11843 		}
11844 	}
11845 	inodedep->id_savedsize = -1;
11846 	inodedep->id_savedextsize = -1;
11847 	inodedep->id_savednlink = -1;
11848 	/*
11849 	 * If there were any rollbacks in the inode block, then it must be
11850 	 * marked dirty so that its will eventually get written back in
11851 	 * its correct form.
11852 	 */
11853 	if (hadchanges) {
11854 		if (fstype == UFS2)
11855 			ffs_update_dinode_ckhash(inodedep->id_fs, dp2);
11856 		bdirty(bp);
11857 	}
11858 bufwait:
11859 	/*
11860 	 * If the write did not succeed, we have done all the roll-forward
11861 	 * operations, but we cannot take the actions that will allow its
11862 	 * dependencies to be processed.
11863 	 */
11864 	if ((flags & WRITESUCCEEDED) == 0)
11865 		return (hadchanges);
11866 	/*
11867 	 * Process any allocdirects that completed during the update.
11868 	 */
11869 	if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
11870 		handle_allocdirect_partdone(adp, &wkhd);
11871 	if ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
11872 		handle_allocdirect_partdone(adp, &wkhd);
11873 	/*
11874 	 * Process deallocations that were held pending until the
11875 	 * inode had been written to disk. Freeing of the inode
11876 	 * is delayed until after all blocks have been freed to
11877 	 * avoid creation of new <vfsid, inum, lbn> triples
11878 	 * before the old ones have been deleted.  Completely
11879 	 * unlinked inodes are not processed until the unlinked
11880 	 * inode list is written or the last reference is removed.
11881 	 */
11882 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) != UNLINKED) {
11883 		freefile = handle_bufwait(inodedep, NULL);
11884 		if (freefile && !LIST_EMPTY(&wkhd)) {
11885 			WORKLIST_INSERT(&wkhd, &freefile->fx_list);
11886 			freefile = NULL;
11887 		}
11888 	}
11889 	/*
11890 	 * Move rolled forward dependency completions to the bufwait list
11891 	 * now that those that were already written have been processed.
11892 	 */
11893 	if (!LIST_EMPTY(&wkhd) && hadchanges == 0)
11894 		panic("handle_written_inodeblock: bufwait but no changes");
11895 	jwork_move(&inodedep->id_bufwait, &wkhd);
11896 
11897 	if (freefile != NULL) {
11898 		/*
11899 		 * If the inode is goingaway it was never written.  Fake up
11900 		 * the state here so free_inodedep() can succeed.
11901 		 */
11902 		if (inodedep->id_state & GOINGAWAY)
11903 			inodedep->id_state |= COMPLETE | DEPCOMPLETE;
11904 		if (free_inodedep(inodedep) == 0)
11905 			panic("handle_written_inodeblock: live inodedep %p",
11906 			    inodedep);
11907 		add_to_worklist(&freefile->fx_list, 0);
11908 		return (0);
11909 	}
11910 
11911 	/*
11912 	 * If no outstanding dependencies, free it.
11913 	 */
11914 	if (free_inodedep(inodedep) ||
11915 	    (TAILQ_FIRST(&inodedep->id_inoreflst) == 0 &&
11916 	     TAILQ_FIRST(&inodedep->id_inoupdt) == 0 &&
11917 	     TAILQ_FIRST(&inodedep->id_extupdt) == 0 &&
11918 	     LIST_FIRST(&inodedep->id_bufwait) == 0))
11919 		return (0);
11920 	return (hadchanges);
11921 }
11922 
11923 /*
11924  * Perform needed roll-forwards and kick off any dependencies that
11925  * can now be processed.
11926  *
11927  * If the write did not succeed, we will do all the roll-forward
11928  * operations, but we will not take the actions that will allow its
11929  * dependencies to be processed.
11930  */
11931 static int
11932 handle_written_indirdep(
11933 	struct indirdep *indirdep,
11934 	struct buf *bp,
11935 	struct buf **bpp,
11936 	int flags)
11937 {
11938 	struct allocindir *aip;
11939 	struct buf *sbp;
11940 	int chgs;
11941 
11942 	if (indirdep->ir_state & GOINGAWAY)
11943 		panic("handle_written_indirdep: indirdep gone");
11944 	if ((indirdep->ir_state & IOSTARTED) == 0)
11945 		panic("handle_written_indirdep: IO not started");
11946 	chgs = 0;
11947 	/*
11948 	 * If there were rollbacks revert them here.
11949 	 */
11950 	if (indirdep->ir_saveddata) {
11951 		bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
11952 		if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11953 			free(indirdep->ir_saveddata, M_INDIRDEP);
11954 			indirdep->ir_saveddata = NULL;
11955 		}
11956 		chgs = 1;
11957 	}
11958 	indirdep->ir_state &= ~(UNDONE | IOSTARTED);
11959 	indirdep->ir_state |= ATTACHED;
11960 	/*
11961 	 * If the write did not succeed, we have done all the roll-forward
11962 	 * operations, but we cannot take the actions that will allow its
11963 	 * dependencies to be processed.
11964 	 */
11965 	if ((flags & WRITESUCCEEDED) == 0) {
11966 		stat_indir_blk_ptrs++;
11967 		bdirty(bp);
11968 		return (1);
11969 	}
11970 	/*
11971 	 * Move allocindirs with written pointers to the completehd if
11972 	 * the indirdep's pointer is not yet written.  Otherwise
11973 	 * free them here.
11974 	 */
11975 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL) {
11976 		LIST_REMOVE(aip, ai_next);
11977 		if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
11978 			LIST_INSERT_HEAD(&indirdep->ir_completehd, aip,
11979 			    ai_next);
11980 			newblk_freefrag(&aip->ai_block);
11981 			continue;
11982 		}
11983 		free_newblk(&aip->ai_block);
11984 	}
11985 	/*
11986 	 * Move allocindirs that have finished dependency processing from
11987 	 * the done list to the write list after updating the pointers.
11988 	 */
11989 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11990 		while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL) {
11991 			handle_allocindir_partdone(aip);
11992 			if (aip == LIST_FIRST(&indirdep->ir_donehd))
11993 				panic("disk_write_complete: not gone");
11994 			chgs = 1;
11995 		}
11996 	}
11997 	/*
11998 	 * Preserve the indirdep if there were any changes or if it is not
11999 	 * yet valid on disk.
12000 	 */
12001 	if (chgs) {
12002 		stat_indir_blk_ptrs++;
12003 		bdirty(bp);
12004 		return (1);
12005 	}
12006 	/*
12007 	 * If there were no changes we can discard the savedbp and detach
12008 	 * ourselves from the buf.  We are only carrying completed pointers
12009 	 * in this case.
12010 	 */
12011 	sbp = indirdep->ir_savebp;
12012 	sbp->b_flags |= B_INVAL | B_NOCACHE;
12013 	indirdep->ir_savebp = NULL;
12014 	indirdep->ir_bp = NULL;
12015 	if (*bpp != NULL)
12016 		panic("handle_written_indirdep: bp already exists.");
12017 	*bpp = sbp;
12018 	/*
12019 	 * The indirdep may not be freed until its parent points at it.
12020 	 */
12021 	if (indirdep->ir_state & DEPCOMPLETE)
12022 		free_indirdep(indirdep);
12023 
12024 	return (0);
12025 }
12026 
12027 /*
12028  * Process a diradd entry after its dependent inode has been written.
12029  */
12030 static void
12031 diradd_inode_written(
12032 	struct diradd *dap,
12033 	struct inodedep *inodedep)
12034 {
12035 
12036 	LOCK_OWNED(VFSTOUFS(dap->da_list.wk_mp));
12037 	dap->da_state |= COMPLETE;
12038 	complete_diradd(dap);
12039 	WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
12040 }
12041 
12042 /*
12043  * Returns true if the bmsafemap will have rollbacks when written.  Must only
12044  * be called with the per-filesystem lock and the buf lock on the cg held.
12045  */
12046 static int
12047 bmsafemap_backgroundwrite(
12048 	struct bmsafemap *bmsafemap,
12049 	struct buf *bp)
12050 {
12051 	int dirty;
12052 
12053 	LOCK_OWNED(VFSTOUFS(bmsafemap->sm_list.wk_mp));
12054 	dirty = !LIST_EMPTY(&bmsafemap->sm_jaddrefhd) |
12055 	    !LIST_EMPTY(&bmsafemap->sm_jnewblkhd);
12056 	/*
12057 	 * If we're initiating a background write we need to process the
12058 	 * rollbacks as they exist now, not as they exist when IO starts.
12059 	 * No other consumers will look at the contents of the shadowed
12060 	 * buf so this is safe to do here.
12061 	 */
12062 	if (bp->b_xflags & BX_BKGRDMARKER)
12063 		initiate_write_bmsafemap(bmsafemap, bp);
12064 
12065 	return (dirty);
12066 }
12067 
12068 /*
12069  * Re-apply an allocation when a cg write is complete.
12070  */
12071 static int
12072 jnewblk_rollforward(
12073 	struct jnewblk *jnewblk,
12074 	struct fs *fs,
12075 	struct cg *cgp,
12076 	uint8_t *blksfree)
12077 {
12078 	ufs1_daddr_t fragno;
12079 	ufs2_daddr_t blkno;
12080 	long cgbno, bbase;
12081 	int frags, blk;
12082 	int i;
12083 
12084 	frags = 0;
12085 	cgbno = dtogd(fs, jnewblk->jn_blkno);
12086 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++) {
12087 		if (isclr(blksfree, cgbno + i))
12088 			panic("jnewblk_rollforward: re-allocated fragment");
12089 		frags++;
12090 	}
12091 	if (frags == fs->fs_frag) {
12092 		blkno = fragstoblks(fs, cgbno);
12093 		ffs_clrblock(fs, blksfree, (long)blkno);
12094 		ffs_clusteracct(fs, cgp, blkno, -1);
12095 		cgp->cg_cs.cs_nbfree--;
12096 	} else {
12097 		bbase = cgbno - fragnum(fs, cgbno);
12098 		cgbno += jnewblk->jn_oldfrags;
12099                 /* If a complete block had been reassembled, account for it. */
12100 		fragno = fragstoblks(fs, bbase);
12101 		if (ffs_isblock(fs, blksfree, fragno)) {
12102 			cgp->cg_cs.cs_nffree += fs->fs_frag;
12103 			ffs_clusteracct(fs, cgp, fragno, -1);
12104 			cgp->cg_cs.cs_nbfree--;
12105 		}
12106 		/* Decrement the old frags.  */
12107 		blk = blkmap(fs, blksfree, bbase);
12108 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
12109 		/* Allocate the fragment */
12110 		for (i = 0; i < frags; i++)
12111 			clrbit(blksfree, cgbno + i);
12112 		cgp->cg_cs.cs_nffree -= frags;
12113 		/* Add back in counts associated with the new frags */
12114 		blk = blkmap(fs, blksfree, bbase);
12115 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
12116 	}
12117 	return (frags);
12118 }
12119 
12120 /*
12121  * Complete a write to a bmsafemap structure.  Roll forward any bitmap
12122  * changes if it's not a background write.  Set all written dependencies
12123  * to DEPCOMPLETE and free the structure if possible.
12124  *
12125  * If the write did not succeed, we will do all the roll-forward
12126  * operations, but we will not take the actions that will allow its
12127  * dependencies to be processed.
12128  */
12129 static int
12130 handle_written_bmsafemap(
12131 	struct bmsafemap *bmsafemap,
12132 	struct buf *bp,
12133 	int flags)
12134 {
12135 	struct newblk *newblk;
12136 	struct inodedep *inodedep;
12137 	struct jaddref *jaddref, *jatmp;
12138 	struct jnewblk *jnewblk, *jntmp;
12139 	struct ufsmount *ump;
12140 	uint8_t *inosused;
12141 	uint8_t *blksfree;
12142 	struct cg *cgp;
12143 	struct fs *fs;
12144 	ino_t ino;
12145 	int foreground;
12146 	int chgs;
12147 
12148 	if ((bmsafemap->sm_state & IOSTARTED) == 0)
12149 		panic("handle_written_bmsafemap: Not started\n");
12150 	ump = VFSTOUFS(bmsafemap->sm_list.wk_mp);
12151 	chgs = 0;
12152 	bmsafemap->sm_state &= ~IOSTARTED;
12153 	foreground = (bp->b_xflags & BX_BKGRDMARKER) == 0;
12154 	/*
12155 	 * If write was successful, release journal work that was waiting
12156 	 * on the write. Otherwise move the work back.
12157 	 */
12158 	if (flags & WRITESUCCEEDED)
12159 		handle_jwork(&bmsafemap->sm_freewr);
12160 	else
12161 		LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
12162 		    worklist, wk_list);
12163 
12164 	/*
12165 	 * Restore unwritten inode allocation pending jaddref writes.
12166 	 */
12167 	if (!LIST_EMPTY(&bmsafemap->sm_jaddrefhd)) {
12168 		cgp = (struct cg *)bp->b_data;
12169 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
12170 		inosused = cg_inosused(cgp);
12171 		LIST_FOREACH_SAFE(jaddref, &bmsafemap->sm_jaddrefhd,
12172 		    ja_bmdeps, jatmp) {
12173 			if ((jaddref->ja_state & UNDONE) == 0)
12174 				continue;
12175 			ino = jaddref->ja_ino % fs->fs_ipg;
12176 			if (isset(inosused, ino))
12177 				panic("handle_written_bmsafemap: "
12178 				    "re-allocated inode");
12179 			/* Do the roll-forward only if it's a real copy. */
12180 			if (foreground) {
12181 				if ((jaddref->ja_mode & IFMT) == IFDIR)
12182 					cgp->cg_cs.cs_ndir++;
12183 				cgp->cg_cs.cs_nifree--;
12184 				setbit(inosused, ino);
12185 				chgs = 1;
12186 			}
12187 			jaddref->ja_state &= ~UNDONE;
12188 			jaddref->ja_state |= ATTACHED;
12189 			free_jaddref(jaddref);
12190 		}
12191 	}
12192 	/*
12193 	 * Restore any block allocations which are pending journal writes.
12194 	 */
12195 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
12196 		cgp = (struct cg *)bp->b_data;
12197 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
12198 		blksfree = cg_blksfree(cgp);
12199 		LIST_FOREACH_SAFE(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps,
12200 		    jntmp) {
12201 			if ((jnewblk->jn_state & UNDONE) == 0)
12202 				continue;
12203 			/* Do the roll-forward only if it's a real copy. */
12204 			if (foreground &&
12205 			    jnewblk_rollforward(jnewblk, fs, cgp, blksfree))
12206 				chgs = 1;
12207 			jnewblk->jn_state &= ~(UNDONE | NEWBLOCK);
12208 			jnewblk->jn_state |= ATTACHED;
12209 			free_jnewblk(jnewblk);
12210 		}
12211 	}
12212 	/*
12213 	 * If the write did not succeed, we have done all the roll-forward
12214 	 * operations, but we cannot take the actions that will allow its
12215 	 * dependencies to be processed.
12216 	 */
12217 	if ((flags & WRITESUCCEEDED) == 0) {
12218 		LIST_CONCAT(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
12219 		    newblk, nb_deps);
12220 		LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
12221 		    worklist, wk_list);
12222 		if (foreground)
12223 			bdirty(bp);
12224 		return (1);
12225 	}
12226 	while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkwr))) {
12227 		newblk->nb_state |= DEPCOMPLETE;
12228 		newblk->nb_state &= ~ONDEPLIST;
12229 		newblk->nb_bmsafemap = NULL;
12230 		LIST_REMOVE(newblk, nb_deps);
12231 		if (newblk->nb_list.wk_type == D_ALLOCDIRECT)
12232 			handle_allocdirect_partdone(
12233 			    WK_ALLOCDIRECT(&newblk->nb_list), NULL);
12234 		else if (newblk->nb_list.wk_type == D_ALLOCINDIR)
12235 			handle_allocindir_partdone(
12236 			    WK_ALLOCINDIR(&newblk->nb_list));
12237 		else if (newblk->nb_list.wk_type != D_NEWBLK)
12238 			panic("handle_written_bmsafemap: Unexpected type: %s",
12239 			    TYPENAME(newblk->nb_list.wk_type));
12240 	}
12241 	while ((inodedep = LIST_FIRST(&bmsafemap->sm_inodedepwr)) != NULL) {
12242 		inodedep->id_state |= DEPCOMPLETE;
12243 		inodedep->id_state &= ~ONDEPLIST;
12244 		LIST_REMOVE(inodedep, id_deps);
12245 		inodedep->id_bmsafemap = NULL;
12246 	}
12247 	LIST_REMOVE(bmsafemap, sm_next);
12248 	if (chgs == 0 && LIST_EMPTY(&bmsafemap->sm_jaddrefhd) &&
12249 	    LIST_EMPTY(&bmsafemap->sm_jnewblkhd) &&
12250 	    LIST_EMPTY(&bmsafemap->sm_newblkhd) &&
12251 	    LIST_EMPTY(&bmsafemap->sm_inodedephd) &&
12252 	    LIST_EMPTY(&bmsafemap->sm_freehd)) {
12253 		LIST_REMOVE(bmsafemap, sm_hash);
12254 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
12255 		return (0);
12256 	}
12257 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
12258 	if (foreground)
12259 		bdirty(bp);
12260 	return (1);
12261 }
12262 
12263 /*
12264  * Try to free a mkdir dependency.
12265  */
12266 static void
12267 complete_mkdir(struct mkdir *mkdir)
12268 {
12269 	struct diradd *dap;
12270 
12271 	if ((mkdir->md_state & ALLCOMPLETE) != ALLCOMPLETE)
12272 		return;
12273 	LIST_REMOVE(mkdir, md_mkdirs);
12274 	dap = mkdir->md_diradd;
12275 	dap->da_state &= ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
12276 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0) {
12277 		dap->da_state |= DEPCOMPLETE;
12278 		complete_diradd(dap);
12279 	}
12280 	WORKITEM_FREE(mkdir, D_MKDIR);
12281 }
12282 
12283 /*
12284  * Handle the completion of a mkdir dependency.
12285  */
12286 static void
12287 handle_written_mkdir(struct mkdir *mkdir, int type)
12288 {
12289 
12290 	if ((mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY)) != type)
12291 		panic("handle_written_mkdir: bad type");
12292 	mkdir->md_state |= COMPLETE;
12293 	complete_mkdir(mkdir);
12294 }
12295 
12296 static int
12297 free_pagedep(struct pagedep *pagedep)
12298 {
12299 	int i;
12300 
12301 	if (pagedep->pd_state & NEWBLOCK)
12302 		return (0);
12303 	if (!LIST_EMPTY(&pagedep->pd_dirremhd))
12304 		return (0);
12305 	for (i = 0; i < DAHASHSZ; i++)
12306 		if (!LIST_EMPTY(&pagedep->pd_diraddhd[i]))
12307 			return (0);
12308 	if (!LIST_EMPTY(&pagedep->pd_pendinghd))
12309 		return (0);
12310 	if (!LIST_EMPTY(&pagedep->pd_jmvrefhd))
12311 		return (0);
12312 	if (pagedep->pd_state & ONWORKLIST)
12313 		WORKLIST_REMOVE(&pagedep->pd_list);
12314 	LIST_REMOVE(pagedep, pd_hash);
12315 	WORKITEM_FREE(pagedep, D_PAGEDEP);
12316 
12317 	return (1);
12318 }
12319 
12320 /*
12321  * Called from within softdep_disk_write_complete above.
12322  * A write operation was just completed. Removed inodes can
12323  * now be freed and associated block pointers may be committed.
12324  * Note that this routine is always called from interrupt level
12325  * with further interrupts from this device blocked.
12326  *
12327  * If the write did not succeed, we will do all the roll-forward
12328  * operations, but we will not take the actions that will allow its
12329  * dependencies to be processed.
12330  */
12331 static int
12332 handle_written_filepage(
12333 	struct pagedep *pagedep,
12334 	struct buf *bp,		/* buffer containing the written page */
12335 	int flags)
12336 {
12337 	struct dirrem *dirrem;
12338 	struct diradd *dap, *nextdap;
12339 	struct direct *ep;
12340 	int i, chgs;
12341 
12342 	if ((pagedep->pd_state & IOSTARTED) == 0)
12343 		panic("handle_written_filepage: not started");
12344 	pagedep->pd_state &= ~IOSTARTED;
12345 	if ((flags & WRITESUCCEEDED) == 0)
12346 		goto rollforward;
12347 	/*
12348 	 * Process any directory removals that have been committed.
12349 	 */
12350 	while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
12351 		LIST_REMOVE(dirrem, dm_next);
12352 		dirrem->dm_state |= COMPLETE;
12353 		dirrem->dm_dirinum = pagedep->pd_ino;
12354 		KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
12355 		    ("handle_written_filepage: Journal entries not written."));
12356 		add_to_worklist(&dirrem->dm_list, 0);
12357 	}
12358 	/*
12359 	 * Free any directory additions that have been committed.
12360 	 * If it is a newly allocated block, we have to wait until
12361 	 * the on-disk directory inode claims the new block.
12362 	 */
12363 	if ((pagedep->pd_state & NEWBLOCK) == 0)
12364 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
12365 			free_diradd(dap, NULL);
12366 rollforward:
12367 	/*
12368 	 * Uncommitted directory entries must be restored.
12369 	 */
12370 	for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
12371 		for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
12372 		     dap = nextdap) {
12373 			nextdap = LIST_NEXT(dap, da_pdlist);
12374 			if (dap->da_state & ATTACHED)
12375 				panic("handle_written_filepage: attached");
12376 			ep = (struct direct *)
12377 			    ((char *)bp->b_data + dap->da_offset);
12378 			ep->d_ino = dap->da_newinum;
12379 			dap->da_state &= ~UNDONE;
12380 			dap->da_state |= ATTACHED;
12381 			chgs = 1;
12382 			/*
12383 			 * If the inode referenced by the directory has
12384 			 * been written out, then the dependency can be
12385 			 * moved to the pending list.
12386 			 */
12387 			if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
12388 				LIST_REMOVE(dap, da_pdlist);
12389 				LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
12390 				    da_pdlist);
12391 			}
12392 		}
12393 	}
12394 	/*
12395 	 * If there were any rollbacks in the directory, then it must be
12396 	 * marked dirty so that its will eventually get written back in
12397 	 * its correct form.
12398 	 */
12399 	if (chgs || (flags & WRITESUCCEEDED) == 0) {
12400 		if ((bp->b_flags & B_DELWRI) == 0)
12401 			stat_dir_entry++;
12402 		bdirty(bp);
12403 		return (1);
12404 	}
12405 	/*
12406 	 * If we are not waiting for a new directory block to be
12407 	 * claimed by its inode, then the pagedep will be freed.
12408 	 * Otherwise it will remain to track any new entries on
12409 	 * the page in case they are fsync'ed.
12410 	 */
12411 	free_pagedep(pagedep);
12412 	return (0);
12413 }
12414 
12415 /*
12416  * Writing back in-core inode structures.
12417  *
12418  * The filesystem only accesses an inode's contents when it occupies an
12419  * "in-core" inode structure.  These "in-core" structures are separate from
12420  * the page frames used to cache inode blocks.  Only the latter are
12421  * transferred to/from the disk.  So, when the updated contents of the
12422  * "in-core" inode structure are copied to the corresponding in-memory inode
12423  * block, the dependencies are also transferred.  The following procedure is
12424  * called when copying a dirty "in-core" inode to a cached inode block.
12425  */
12426 
12427 /*
12428  * Called when an inode is loaded from disk. If the effective link count
12429  * differed from the actual link count when it was last flushed, then we
12430  * need to ensure that the correct effective link count is put back.
12431  */
12432 void
12433 softdep_load_inodeblock(
12434 	struct inode *ip)	/* the "in_core" copy of the inode */
12435 {
12436 	struct inodedep *inodedep;
12437 	struct ufsmount *ump;
12438 
12439 	ump = ITOUMP(ip);
12440 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
12441 	    ("softdep_load_inodeblock called on non-softdep filesystem"));
12442 	/*
12443 	 * Check for alternate nlink count.
12444 	 */
12445 	ip->i_effnlink = ip->i_nlink;
12446 	ACQUIRE_LOCK(ump);
12447 	if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0) {
12448 		FREE_LOCK(ump);
12449 		return;
12450 	}
12451 	if (ip->i_nlink != inodedep->id_nlinkwrote &&
12452 	    inodedep->id_nlinkwrote != -1) {
12453 		KASSERT(ip->i_nlink == 0 &&
12454 		    (ump->um_flags & UM_FSFAIL_CLEANUP) != 0,
12455 		    ("read bad i_nlink value"));
12456 		ip->i_effnlink = ip->i_nlink = inodedep->id_nlinkwrote;
12457 	}
12458 	ip->i_effnlink -= inodedep->id_nlinkdelta;
12459 	KASSERT(ip->i_effnlink >= 0,
12460 	    ("softdep_load_inodeblock: negative i_effnlink"));
12461 	FREE_LOCK(ump);
12462 }
12463 
12464 /*
12465  * This routine is called just before the "in-core" inode
12466  * information is to be copied to the in-memory inode block.
12467  * Recall that an inode block contains several inodes. If
12468  * the force flag is set, then the dependencies will be
12469  * cleared so that the update can always be made. Note that
12470  * the buffer is locked when this routine is called, so we
12471  * will never be in the middle of writing the inode block
12472  * to disk.
12473  */
12474 void
12475 softdep_update_inodeblock(
12476 	struct inode *ip,	/* the "in_core" copy of the inode */
12477 	struct buf *bp,		/* the buffer containing the inode block */
12478 	int waitfor)		/* nonzero => update must be allowed */
12479 {
12480 	struct inodedep *inodedep;
12481 	struct inoref *inoref;
12482 	struct ufsmount *ump;
12483 	struct worklist *wk;
12484 	struct mount *mp;
12485 	struct buf *ibp;
12486 	struct fs *fs;
12487 	int error;
12488 
12489 	ump = ITOUMP(ip);
12490 	mp = UFSTOVFS(ump);
12491 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
12492 	    ("softdep_update_inodeblock called on non-softdep filesystem"));
12493 	fs = ump->um_fs;
12494 	/*
12495 	 * If the effective link count is not equal to the actual link
12496 	 * count, then we must track the difference in an inodedep while
12497 	 * the inode is (potentially) tossed out of the cache. Otherwise,
12498 	 * if there is no existing inodedep, then there are no dependencies
12499 	 * to track.
12500 	 */
12501 	ACQUIRE_LOCK(ump);
12502 again:
12503 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12504 		FREE_LOCK(ump);
12505 		if (ip->i_effnlink != ip->i_nlink)
12506 			panic("softdep_update_inodeblock: bad link count");
12507 		return;
12508 	}
12509 	/*
12510 	 * Preserve the freelink that is on disk.  clear_unlinked_inodedep()
12511 	 * does not have access to the in-core ip so must write directly into
12512 	 * the inode block buffer when setting freelink.
12513 	 */
12514 	if ((inodedep->id_state & UNLINKED) != 0) {
12515 		if (fs->fs_magic == FS_UFS1_MAGIC)
12516 			DIP_SET(ip, i_freelink,
12517 			    ((struct ufs1_dinode *)bp->b_data +
12518 			    ino_to_fsbo(fs, ip->i_number))->di_freelink);
12519 		else
12520 			DIP_SET(ip, i_freelink,
12521 			    ((struct ufs2_dinode *)bp->b_data +
12522 			    ino_to_fsbo(fs, ip->i_number))->di_freelink);
12523 	}
12524 	KASSERT(ip->i_nlink >= inodedep->id_nlinkdelta,
12525 	    ("softdep_update_inodeblock inconsistent ip %p i_nlink %d "
12526 	    "inodedep %p id_nlinkdelta %jd",
12527 	    ip, ip->i_nlink, inodedep, (intmax_t)inodedep->id_nlinkdelta));
12528 	inodedep->id_nlinkwrote = ip->i_nlink;
12529 	if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink)
12530 		panic("softdep_update_inodeblock: bad delta");
12531 	/*
12532 	 * If we're flushing all dependencies we must also move any waiting
12533 	 * for journal writes onto the bufwait list prior to I/O.
12534 	 */
12535 	if (waitfor) {
12536 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12537 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12538 			    == DEPCOMPLETE) {
12539 				jwait(&inoref->if_list, MNT_WAIT);
12540 				goto again;
12541 			}
12542 		}
12543 	}
12544 	/*
12545 	 * Changes have been initiated. Anything depending on these
12546 	 * changes cannot occur until this inode has been written.
12547 	 */
12548 	inodedep->id_state &= ~COMPLETE;
12549 	if ((inodedep->id_state & ONWORKLIST) == 0)
12550 		WORKLIST_INSERT(&bp->b_dep, &inodedep->id_list);
12551 	/*
12552 	 * Any new dependencies associated with the incore inode must
12553 	 * now be moved to the list associated with the buffer holding
12554 	 * the in-memory copy of the inode. Once merged process any
12555 	 * allocdirects that are completed by the merger.
12556 	 */
12557 	merge_inode_lists(&inodedep->id_newinoupdt, &inodedep->id_inoupdt);
12558 	if (!TAILQ_EMPTY(&inodedep->id_inoupdt))
12559 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt),
12560 		    NULL);
12561 	merge_inode_lists(&inodedep->id_newextupdt, &inodedep->id_extupdt);
12562 	if (!TAILQ_EMPTY(&inodedep->id_extupdt))
12563 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_extupdt),
12564 		    NULL);
12565 	/*
12566 	 * Now that the inode has been pushed into the buffer, the
12567 	 * operations dependent on the inode being written to disk
12568 	 * can be moved to the id_bufwait so that they will be
12569 	 * processed when the buffer I/O completes.
12570 	 */
12571 	while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
12572 		WORKLIST_REMOVE(wk);
12573 		WORKLIST_INSERT(&inodedep->id_bufwait, wk);
12574 	}
12575 	/*
12576 	 * Newly allocated inodes cannot be written until the bitmap
12577 	 * that allocates them have been written (indicated by
12578 	 * DEPCOMPLETE being set in id_state). If we are doing a
12579 	 * forced sync (e.g., an fsync on a file), we force the bitmap
12580 	 * to be written so that the update can be done.
12581 	 */
12582 	if (waitfor == 0) {
12583 		FREE_LOCK(ump);
12584 		return;
12585 	}
12586 retry:
12587 	if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) != 0) {
12588 		FREE_LOCK(ump);
12589 		return;
12590 	}
12591 	ibp = inodedep->id_bmsafemap->sm_buf;
12592 	ibp = getdirtybuf(ibp, LOCK_PTR(ump), MNT_WAIT);
12593 	if (ibp == NULL) {
12594 		/*
12595 		 * If ibp came back as NULL, the dependency could have been
12596 		 * freed while we slept.  Look it up again, and check to see
12597 		 * that it has completed.
12598 		 */
12599 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
12600 			goto retry;
12601 		FREE_LOCK(ump);
12602 		return;
12603 	}
12604 	FREE_LOCK(ump);
12605 	if ((error = bwrite(ibp)) != 0)
12606 		softdep_error("softdep_update_inodeblock: bwrite", error);
12607 }
12608 
12609 /*
12610  * Merge the a new inode dependency list (such as id_newinoupdt) into an
12611  * old inode dependency list (such as id_inoupdt).
12612  */
12613 static void
12614 merge_inode_lists(
12615 	struct allocdirectlst *newlisthead,
12616 	struct allocdirectlst *oldlisthead)
12617 {
12618 	struct allocdirect *listadp, *newadp;
12619 
12620 	newadp = TAILQ_FIRST(newlisthead);
12621 	if (newadp != NULL)
12622 		LOCK_OWNED(VFSTOUFS(newadp->ad_block.nb_list.wk_mp));
12623 	for (listadp = TAILQ_FIRST(oldlisthead); listadp && newadp;) {
12624 		if (listadp->ad_offset < newadp->ad_offset) {
12625 			listadp = TAILQ_NEXT(listadp, ad_next);
12626 			continue;
12627 		}
12628 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
12629 		TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
12630 		if (listadp->ad_offset == newadp->ad_offset) {
12631 			allocdirect_merge(oldlisthead, newadp,
12632 			    listadp);
12633 			listadp = newadp;
12634 		}
12635 		newadp = TAILQ_FIRST(newlisthead);
12636 	}
12637 	while ((newadp = TAILQ_FIRST(newlisthead)) != NULL) {
12638 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
12639 		TAILQ_INSERT_TAIL(oldlisthead, newadp, ad_next);
12640 	}
12641 }
12642 
12643 /*
12644  * If we are doing an fsync, then we must ensure that any directory
12645  * entries for the inode have been written after the inode gets to disk.
12646  */
12647 int
12648 softdep_fsync(
12649 	struct vnode *vp)	/* the "in_core" copy of the inode */
12650 {
12651 	struct inodedep *inodedep;
12652 	struct pagedep *pagedep;
12653 	struct inoref *inoref;
12654 	struct ufsmount *ump;
12655 	struct worklist *wk;
12656 	struct diradd *dap;
12657 	struct mount *mp;
12658 	struct vnode *pvp;
12659 	struct inode *ip;
12660 	struct buf *bp;
12661 	struct fs *fs;
12662 	struct thread *td = curthread;
12663 	int error, flushparent, pagedep_new_block;
12664 	ino_t parentino;
12665 	ufs_lbn_t lbn;
12666 
12667 	ip = VTOI(vp);
12668 	mp = vp->v_mount;
12669 	ump = VFSTOUFS(mp);
12670 	fs = ump->um_fs;
12671 	if (MOUNTEDSOFTDEP(mp) == 0)
12672 		return (0);
12673 	ACQUIRE_LOCK(ump);
12674 restart:
12675 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12676 		FREE_LOCK(ump);
12677 		return (0);
12678 	}
12679 	TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12680 		if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12681 		    == DEPCOMPLETE) {
12682 			jwait(&inoref->if_list, MNT_WAIT);
12683 			goto restart;
12684 		}
12685 	}
12686 	if (!LIST_EMPTY(&inodedep->id_inowait) ||
12687 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
12688 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
12689 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
12690 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt))
12691 		panic("softdep_fsync: pending ops %p", inodedep);
12692 	for (error = 0, flushparent = 0; ; ) {
12693 		if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
12694 			break;
12695 		if (wk->wk_type != D_DIRADD)
12696 			panic("softdep_fsync: Unexpected type %s",
12697 			    TYPENAME(wk->wk_type));
12698 		dap = WK_DIRADD(wk);
12699 		/*
12700 		 * Flush our parent if this directory entry has a MKDIR_PARENT
12701 		 * dependency or is contained in a newly allocated block.
12702 		 */
12703 		if (dap->da_state & DIRCHG)
12704 			pagedep = dap->da_previous->dm_pagedep;
12705 		else
12706 			pagedep = dap->da_pagedep;
12707 		parentino = pagedep->pd_ino;
12708 		lbn = pagedep->pd_lbn;
12709 		if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE)
12710 			panic("softdep_fsync: dirty");
12711 		if ((dap->da_state & MKDIR_PARENT) ||
12712 		    (pagedep->pd_state & NEWBLOCK))
12713 			flushparent = 1;
12714 		else
12715 			flushparent = 0;
12716 		/*
12717 		 * If we are being fsync'ed as part of vgone'ing this vnode,
12718 		 * then we will not be able to release and recover the
12719 		 * vnode below, so we just have to give up on writing its
12720 		 * directory entry out. It will eventually be written, just
12721 		 * not now, but then the user was not asking to have it
12722 		 * written, so we are not breaking any promises.
12723 		 */
12724 		if (VN_IS_DOOMED(vp))
12725 			break;
12726 		/*
12727 		 * We prevent deadlock by always fetching inodes from the
12728 		 * root, moving down the directory tree. Thus, when fetching
12729 		 * our parent directory, we first try to get the lock. If
12730 		 * that fails, we must unlock ourselves before requesting
12731 		 * the lock on our parent. See the comment in ufs_lookup
12732 		 * for details on possible races.
12733 		 */
12734 		FREE_LOCK(ump);
12735 		error = get_parent_vp(vp, mp, parentino, NULL, NULL, NULL,
12736 		    &pvp);
12737 		if (error == ERELOOKUP)
12738 			error = 0;
12739 		if (error != 0)
12740 			return (error);
12741 		/*
12742 		 * All MKDIR_PARENT dependencies and all the NEWBLOCK pagedeps
12743 		 * that are contained in direct blocks will be resolved by
12744 		 * doing a ffs_update. Pagedeps contained in indirect blocks
12745 		 * may require a complete sync'ing of the directory. So, we
12746 		 * try the cheap and fast ffs_update first, and if that fails,
12747 		 * then we do the slower ffs_syncvnode of the directory.
12748 		 */
12749 		if (flushparent) {
12750 			int locked;
12751 
12752 			if ((error = ffs_update(pvp, 1)) != 0) {
12753 				vput(pvp);
12754 				return (error);
12755 			}
12756 			ACQUIRE_LOCK(ump);
12757 			locked = 1;
12758 			if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0) {
12759 				if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) != NULL) {
12760 					if (wk->wk_type != D_DIRADD)
12761 						panic("softdep_fsync: Unexpected type %s",
12762 						      TYPENAME(wk->wk_type));
12763 					dap = WK_DIRADD(wk);
12764 					if (dap->da_state & DIRCHG)
12765 						pagedep = dap->da_previous->dm_pagedep;
12766 					else
12767 						pagedep = dap->da_pagedep;
12768 					pagedep_new_block = pagedep->pd_state & NEWBLOCK;
12769 					FREE_LOCK(ump);
12770 					locked = 0;
12771 					if (pagedep_new_block) {
12772 						VOP_UNLOCK(vp);
12773 						error = ffs_syncvnode(pvp,
12774 						    MNT_WAIT, 0);
12775 						if (error == 0)
12776 							error = ERELOOKUP;
12777 						vput(pvp);
12778 						vn_lock(vp, LK_EXCLUSIVE |
12779 						    LK_RETRY);
12780 						return (error);
12781 					}
12782 				}
12783 			}
12784 			if (locked)
12785 				FREE_LOCK(ump);
12786 		}
12787 		/*
12788 		 * Flush directory page containing the inode's name.
12789 		 */
12790 		error = bread(pvp, lbn, blksize(fs, VTOI(pvp), lbn), td->td_ucred,
12791 		    &bp);
12792 		if (error == 0)
12793 			error = bwrite(bp);
12794 		else
12795 			brelse(bp);
12796 		vput(pvp);
12797 		if (!ffs_fsfail_cleanup(ump, error))
12798 			return (error);
12799 		ACQUIRE_LOCK(ump);
12800 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
12801 			break;
12802 	}
12803 	FREE_LOCK(ump);
12804 	return (0);
12805 }
12806 
12807 /*
12808  * Flush all the dirty bitmaps associated with the block device
12809  * before flushing the rest of the dirty blocks so as to reduce
12810  * the number of dependencies that will have to be rolled back.
12811  *
12812  * XXX Unused?
12813  */
12814 void
12815 softdep_fsync_mountdev(struct vnode *vp)
12816 {
12817 	struct buf *bp, *nbp;
12818 	struct worklist *wk;
12819 	struct bufobj *bo;
12820 
12821 	if (!vn_isdisk(vp))
12822 		panic("softdep_fsync_mountdev: vnode not a disk");
12823 	bo = &vp->v_bufobj;
12824 restart:
12825 	BO_LOCK(bo);
12826 	TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
12827 		/*
12828 		 * If it is already scheduled, skip to the next buffer.
12829 		 */
12830 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL))
12831 			continue;
12832 
12833 		if ((bp->b_flags & B_DELWRI) == 0)
12834 			panic("softdep_fsync_mountdev: not dirty");
12835 		/*
12836 		 * We are only interested in bitmaps with outstanding
12837 		 * dependencies.
12838 		 */
12839 		if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
12840 		    wk->wk_type != D_BMSAFEMAP ||
12841 		    (bp->b_vflags & BV_BKGRDINPROG)) {
12842 			BUF_UNLOCK(bp);
12843 			continue;
12844 		}
12845 		BO_UNLOCK(bo);
12846 		bremfree(bp);
12847 		(void) bawrite(bp);
12848 		goto restart;
12849 	}
12850 	drain_output(vp);
12851 	BO_UNLOCK(bo);
12852 }
12853 
12854 /*
12855  * Sync all cylinder groups that were dirty at the time this function is
12856  * called.  Newly dirtied cgs will be inserted before the sentinel.  This
12857  * is used to flush freedep activity that may be holding up writes to a
12858  * indirect block.
12859  */
12860 static int
12861 sync_cgs(struct mount *mp, int waitfor)
12862 {
12863 	struct bmsafemap *bmsafemap;
12864 	struct bmsafemap *sentinel;
12865 	struct ufsmount *ump;
12866 	struct buf *bp;
12867 	int error;
12868 
12869 	sentinel = malloc(sizeof(*sentinel), M_BMSAFEMAP, M_ZERO | M_WAITOK);
12870 	sentinel->sm_cg = -1;
12871 	ump = VFSTOUFS(mp);
12872 	error = 0;
12873 	ACQUIRE_LOCK(ump);
12874 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, sentinel, sm_next);
12875 	for (bmsafemap = LIST_NEXT(sentinel, sm_next); bmsafemap != NULL;
12876 	    bmsafemap = LIST_NEXT(sentinel, sm_next)) {
12877 		/* Skip sentinels and cgs with no work to release. */
12878 		if (bmsafemap->sm_cg == -1 ||
12879 		    (LIST_EMPTY(&bmsafemap->sm_freehd) &&
12880 		    LIST_EMPTY(&bmsafemap->sm_freewr))) {
12881 			LIST_REMOVE(sentinel, sm_next);
12882 			LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12883 			continue;
12884 		}
12885 		/*
12886 		 * If we don't get the lock and we're waiting try again, if
12887 		 * not move on to the next buf and try to sync it.
12888 		 */
12889 		bp = getdirtybuf(bmsafemap->sm_buf, LOCK_PTR(ump), waitfor);
12890 		if (bp == NULL && waitfor == MNT_WAIT)
12891 			continue;
12892 		LIST_REMOVE(sentinel, sm_next);
12893 		LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12894 		if (bp == NULL)
12895 			continue;
12896 		FREE_LOCK(ump);
12897 		if (waitfor == MNT_NOWAIT)
12898 			bawrite(bp);
12899 		else
12900 			error = bwrite(bp);
12901 		ACQUIRE_LOCK(ump);
12902 		if (error)
12903 			break;
12904 	}
12905 	LIST_REMOVE(sentinel, sm_next);
12906 	FREE_LOCK(ump);
12907 	free(sentinel, M_BMSAFEMAP);
12908 	return (error);
12909 }
12910 
12911 /*
12912  * This routine is called when we are trying to synchronously flush a
12913  * file. This routine must eliminate any filesystem metadata dependencies
12914  * so that the syncing routine can succeed.
12915  */
12916 int
12917 softdep_sync_metadata(struct vnode *vp)
12918 {
12919 	struct inode *ip;
12920 	int error;
12921 
12922 	ip = VTOI(vp);
12923 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12924 	    ("softdep_sync_metadata called on non-softdep filesystem"));
12925 	/*
12926 	 * Ensure that any direct block dependencies have been cleared,
12927 	 * truncations are started, and inode references are journaled.
12928 	 */
12929 	ACQUIRE_LOCK(VFSTOUFS(vp->v_mount));
12930 	/*
12931 	 * Write all journal records to prevent rollbacks on devvp.
12932 	 */
12933 	if (vp->v_type == VCHR)
12934 		softdep_flushjournal(vp->v_mount);
12935 	error = flush_inodedep_deps(vp, vp->v_mount, ip->i_number);
12936 	/*
12937 	 * Ensure that all truncates are written so we won't find deps on
12938 	 * indirect blocks.
12939 	 */
12940 	process_truncates(vp);
12941 	FREE_LOCK(VFSTOUFS(vp->v_mount));
12942 
12943 	return (error);
12944 }
12945 
12946 /*
12947  * This routine is called when we are attempting to sync a buf with
12948  * dependencies.  If waitfor is MNT_NOWAIT it attempts to schedule any
12949  * other IO it can but returns EBUSY if the buffer is not yet able to
12950  * be written.  Dependencies which will not cause rollbacks will always
12951  * return 0.
12952  */
12953 int
12954 softdep_sync_buf(struct vnode *vp,
12955 	struct buf *bp,
12956 	int waitfor)
12957 {
12958 	struct indirdep *indirdep;
12959 	struct pagedep *pagedep;
12960 	struct allocindir *aip;
12961 	struct newblk *newblk;
12962 	struct ufsmount *ump;
12963 	struct buf *nbp;
12964 	struct worklist *wk;
12965 	int i, error;
12966 
12967 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12968 	    ("softdep_sync_buf called on non-softdep filesystem"));
12969 	/*
12970 	 * For VCHR we just don't want to force flush any dependencies that
12971 	 * will cause rollbacks.
12972 	 */
12973 	if (vp->v_type == VCHR) {
12974 		if (waitfor == MNT_NOWAIT && softdep_count_dependencies(bp, 0))
12975 			return (EBUSY);
12976 		return (0);
12977 	}
12978 	ump = VFSTOUFS(vp->v_mount);
12979 	ACQUIRE_LOCK(ump);
12980 	/*
12981 	 * As we hold the buffer locked, none of its dependencies
12982 	 * will disappear.
12983 	 */
12984 	error = 0;
12985 top:
12986 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
12987 		switch (wk->wk_type) {
12988 		case D_ALLOCDIRECT:
12989 		case D_ALLOCINDIR:
12990 			newblk = WK_NEWBLK(wk);
12991 			if (newblk->nb_jnewblk != NULL) {
12992 				if (waitfor == MNT_NOWAIT) {
12993 					error = EBUSY;
12994 					goto out_unlock;
12995 				}
12996 				jwait(&newblk->nb_jnewblk->jn_list, waitfor);
12997 				goto top;
12998 			}
12999 			if (newblk->nb_state & DEPCOMPLETE ||
13000 			    waitfor == MNT_NOWAIT)
13001 				continue;
13002 			nbp = newblk->nb_bmsafemap->sm_buf;
13003 			nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
13004 			if (nbp == NULL)
13005 				goto top;
13006 			FREE_LOCK(ump);
13007 			if ((error = bwrite(nbp)) != 0)
13008 				goto out;
13009 			ACQUIRE_LOCK(ump);
13010 			continue;
13011 
13012 		case D_INDIRDEP:
13013 			indirdep = WK_INDIRDEP(wk);
13014 			if (waitfor == MNT_NOWAIT) {
13015 				if (!TAILQ_EMPTY(&indirdep->ir_trunc) ||
13016 				    !LIST_EMPTY(&indirdep->ir_deplisthd)) {
13017 					error = EBUSY;
13018 					goto out_unlock;
13019 				}
13020 			}
13021 			if (!TAILQ_EMPTY(&indirdep->ir_trunc))
13022 				panic("softdep_sync_buf: truncation pending.");
13023 		restart:
13024 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
13025 				newblk = (struct newblk *)aip;
13026 				if (newblk->nb_jnewblk != NULL) {
13027 					jwait(&newblk->nb_jnewblk->jn_list,
13028 					    waitfor);
13029 					goto restart;
13030 				}
13031 				if (newblk->nb_state & DEPCOMPLETE)
13032 					continue;
13033 				nbp = newblk->nb_bmsafemap->sm_buf;
13034 				nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
13035 				if (nbp == NULL)
13036 					goto restart;
13037 				FREE_LOCK(ump);
13038 				if ((error = bwrite(nbp)) != 0)
13039 					goto out;
13040 				ACQUIRE_LOCK(ump);
13041 				goto restart;
13042 			}
13043 			continue;
13044 
13045 		case D_PAGEDEP:
13046 			/*
13047 			 * Only flush directory entries in synchronous passes.
13048 			 */
13049 			if (waitfor != MNT_WAIT) {
13050 				error = EBUSY;
13051 				goto out_unlock;
13052 			}
13053 			/*
13054 			 * While syncing snapshots, we must allow recursive
13055 			 * lookups.
13056 			 */
13057 			BUF_AREC(bp);
13058 			/*
13059 			 * We are trying to sync a directory that may
13060 			 * have dependencies on both its own metadata
13061 			 * and/or dependencies on the inodes of any
13062 			 * recently allocated files. We walk its diradd
13063 			 * lists pushing out the associated inode.
13064 			 */
13065 			pagedep = WK_PAGEDEP(wk);
13066 			for (i = 0; i < DAHASHSZ; i++) {
13067 				if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
13068 					continue;
13069 				error = flush_pagedep_deps(vp, wk->wk_mp,
13070 				    &pagedep->pd_diraddhd[i], bp);
13071 				if (error != 0) {
13072 					if (error != ERELOOKUP)
13073 						BUF_NOREC(bp);
13074 					goto out_unlock;
13075 				}
13076 			}
13077 			BUF_NOREC(bp);
13078 			continue;
13079 
13080 		case D_FREEWORK:
13081 		case D_FREEDEP:
13082 		case D_JSEGDEP:
13083 		case D_JNEWBLK:
13084 			continue;
13085 
13086 		default:
13087 			panic("softdep_sync_buf: Unknown type %s",
13088 			    TYPENAME(wk->wk_type));
13089 			/* NOTREACHED */
13090 		}
13091 	}
13092 out_unlock:
13093 	FREE_LOCK(ump);
13094 out:
13095 	return (error);
13096 }
13097 
13098 /*
13099  * Flush the dependencies associated with an inodedep.
13100  */
13101 static int
13102 flush_inodedep_deps(
13103 	struct vnode *vp,
13104 	struct mount *mp,
13105 	ino_t ino)
13106 {
13107 	struct inodedep *inodedep;
13108 	struct inoref *inoref;
13109 	struct ufsmount *ump;
13110 	int error, waitfor;
13111 
13112 	/*
13113 	 * This work is done in two passes. The first pass grabs most
13114 	 * of the buffers and begins asynchronously writing them. The
13115 	 * only way to wait for these asynchronous writes is to sleep
13116 	 * on the filesystem vnode which may stay busy for a long time
13117 	 * if the filesystem is active. So, instead, we make a second
13118 	 * pass over the dependencies blocking on each write. In the
13119 	 * usual case we will be blocking against a write that we
13120 	 * initiated, so when it is done the dependency will have been
13121 	 * resolved. Thus the second pass is expected to end quickly.
13122 	 * We give a brief window at the top of the loop to allow
13123 	 * any pending I/O to complete.
13124 	 */
13125 	ump = VFSTOUFS(mp);
13126 	LOCK_OWNED(ump);
13127 	for (error = 0, waitfor = MNT_NOWAIT; ; ) {
13128 		if (error)
13129 			return (error);
13130 		FREE_LOCK(ump);
13131 		ACQUIRE_LOCK(ump);
13132 restart:
13133 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
13134 			return (0);
13135 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
13136 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
13137 			    == DEPCOMPLETE) {
13138 				jwait(&inoref->if_list, MNT_WAIT);
13139 				goto restart;
13140 			}
13141 		}
13142 		if (flush_deplist(&inodedep->id_inoupdt, waitfor, &error) ||
13143 		    flush_deplist(&inodedep->id_newinoupdt, waitfor, &error) ||
13144 		    flush_deplist(&inodedep->id_extupdt, waitfor, &error) ||
13145 		    flush_deplist(&inodedep->id_newextupdt, waitfor, &error))
13146 			continue;
13147 		/*
13148 		 * If pass2, we are done, otherwise do pass 2.
13149 		 */
13150 		if (waitfor == MNT_WAIT)
13151 			break;
13152 		waitfor = MNT_WAIT;
13153 	}
13154 	/*
13155 	 * Try freeing inodedep in case all dependencies have been removed.
13156 	 */
13157 	if (inodedep_lookup(mp, ino, 0, &inodedep) != 0)
13158 		(void) free_inodedep(inodedep);
13159 	return (0);
13160 }
13161 
13162 /*
13163  * Flush an inode dependency list.
13164  */
13165 static int
13166 flush_deplist(
13167 	struct allocdirectlst *listhead,
13168 	int waitfor,
13169 	int *errorp)
13170 {
13171 	struct allocdirect *adp;
13172 	struct newblk *newblk;
13173 	struct ufsmount *ump;
13174 	struct buf *bp;
13175 
13176 	if ((adp = TAILQ_FIRST(listhead)) == NULL)
13177 		return (0);
13178 	ump = VFSTOUFS(adp->ad_list.wk_mp);
13179 	LOCK_OWNED(ump);
13180 	TAILQ_FOREACH(adp, listhead, ad_next) {
13181 		newblk = (struct newblk *)adp;
13182 		if (newblk->nb_jnewblk != NULL) {
13183 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
13184 			return (1);
13185 		}
13186 		if (newblk->nb_state & DEPCOMPLETE)
13187 			continue;
13188 		bp = newblk->nb_bmsafemap->sm_buf;
13189 		bp = getdirtybuf(bp, LOCK_PTR(ump), waitfor);
13190 		if (bp == NULL) {
13191 			if (waitfor == MNT_NOWAIT)
13192 				continue;
13193 			return (1);
13194 		}
13195 		FREE_LOCK(ump);
13196 		if (waitfor == MNT_NOWAIT)
13197 			bawrite(bp);
13198 		else
13199 			*errorp = bwrite(bp);
13200 		ACQUIRE_LOCK(ump);
13201 		return (1);
13202 	}
13203 	return (0);
13204 }
13205 
13206 /*
13207  * Flush dependencies associated with an allocdirect block.
13208  */
13209 static int
13210 flush_newblk_dep(
13211 	struct vnode *vp,
13212 	struct mount *mp,
13213 	ufs_lbn_t lbn)
13214 {
13215 	struct newblk *newblk;
13216 	struct ufsmount *ump;
13217 	struct bufobj *bo;
13218 	struct inode *ip;
13219 	struct buf *bp;
13220 	ufs2_daddr_t blkno;
13221 	int error;
13222 
13223 	error = 0;
13224 	bo = &vp->v_bufobj;
13225 	ip = VTOI(vp);
13226 	blkno = DIP(ip, i_db[lbn]);
13227 	if (blkno == 0)
13228 		panic("flush_newblk_dep: Missing block");
13229 	ump = VFSTOUFS(mp);
13230 	ACQUIRE_LOCK(ump);
13231 	/*
13232 	 * Loop until all dependencies related to this block are satisfied.
13233 	 * We must be careful to restart after each sleep in case a write
13234 	 * completes some part of this process for us.
13235 	 */
13236 	for (;;) {
13237 		if (newblk_lookup(mp, blkno, 0, &newblk) == 0) {
13238 			FREE_LOCK(ump);
13239 			break;
13240 		}
13241 		if (newblk->nb_list.wk_type != D_ALLOCDIRECT)
13242 			panic("flush_newblk_dep: Bad newblk %p", newblk);
13243 		/*
13244 		 * Flush the journal.
13245 		 */
13246 		if (newblk->nb_jnewblk != NULL) {
13247 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
13248 			continue;
13249 		}
13250 		/*
13251 		 * Write the bitmap dependency.
13252 		 */
13253 		if ((newblk->nb_state & DEPCOMPLETE) == 0) {
13254 			bp = newblk->nb_bmsafemap->sm_buf;
13255 			bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13256 			if (bp == NULL)
13257 				continue;
13258 			FREE_LOCK(ump);
13259 			error = bwrite(bp);
13260 			if (error)
13261 				break;
13262 			ACQUIRE_LOCK(ump);
13263 			continue;
13264 		}
13265 		/*
13266 		 * Write the buffer.
13267 		 */
13268 		FREE_LOCK(ump);
13269 		BO_LOCK(bo);
13270 		bp = gbincore(bo, lbn);
13271 		if (bp != NULL) {
13272 			error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
13273 			    LK_INTERLOCK, BO_LOCKPTR(bo));
13274 			if (error == ENOLCK) {
13275 				ACQUIRE_LOCK(ump);
13276 				error = 0;
13277 				continue; /* Slept, retry */
13278 			}
13279 			if (error != 0)
13280 				break;	/* Failed */
13281 			if (bp->b_flags & B_DELWRI) {
13282 				bremfree(bp);
13283 				error = bwrite(bp);
13284 				if (error)
13285 					break;
13286 			} else
13287 				BUF_UNLOCK(bp);
13288 		} else
13289 			BO_UNLOCK(bo);
13290 		/*
13291 		 * We have to wait for the direct pointers to
13292 		 * point at the newdirblk before the dependency
13293 		 * will go away.
13294 		 */
13295 		error = ffs_update(vp, 1);
13296 		if (error)
13297 			break;
13298 		ACQUIRE_LOCK(ump);
13299 	}
13300 	return (error);
13301 }
13302 
13303 /*
13304  * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
13305  */
13306 static int
13307 flush_pagedep_deps(
13308 	struct vnode *pvp,
13309 	struct mount *mp,
13310 	struct diraddhd *diraddhdp,
13311 	struct buf *locked_bp)
13312 {
13313 	struct inodedep *inodedep;
13314 	struct inoref *inoref;
13315 	struct ufsmount *ump;
13316 	struct diradd *dap;
13317 	struct vnode *vp;
13318 	int error = 0;
13319 	struct buf *bp;
13320 	ino_t inum;
13321 	struct diraddhd unfinished;
13322 
13323 	LIST_INIT(&unfinished);
13324 	ump = VFSTOUFS(mp);
13325 	LOCK_OWNED(ump);
13326 restart:
13327 	while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
13328 		/*
13329 		 * Flush ourselves if this directory entry
13330 		 * has a MKDIR_PARENT dependency.
13331 		 */
13332 		if (dap->da_state & MKDIR_PARENT) {
13333 			FREE_LOCK(ump);
13334 			if ((error = ffs_update(pvp, 1)) != 0)
13335 				break;
13336 			ACQUIRE_LOCK(ump);
13337 			/*
13338 			 * If that cleared dependencies, go on to next.
13339 			 */
13340 			if (dap != LIST_FIRST(diraddhdp))
13341 				continue;
13342 			/*
13343 			 * All MKDIR_PARENT dependencies and all the
13344 			 * NEWBLOCK pagedeps that are contained in direct
13345 			 * blocks were resolved by doing above ffs_update.
13346 			 * Pagedeps contained in indirect blocks may
13347 			 * require a complete sync'ing of the directory.
13348 			 * We are in the midst of doing a complete sync,
13349 			 * so if they are not resolved in this pass we
13350 			 * defer them for now as they will be sync'ed by
13351 			 * our caller shortly.
13352 			 */
13353 			LIST_REMOVE(dap, da_pdlist);
13354 			LIST_INSERT_HEAD(&unfinished, dap, da_pdlist);
13355 			continue;
13356 		}
13357 		/*
13358 		 * A newly allocated directory must have its "." and
13359 		 * ".." entries written out before its name can be
13360 		 * committed in its parent.
13361 		 */
13362 		inum = dap->da_newinum;
13363 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13364 			panic("flush_pagedep_deps: lost inode1");
13365 		/*
13366 		 * Wait for any pending journal adds to complete so we don't
13367 		 * cause rollbacks while syncing.
13368 		 */
13369 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
13370 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
13371 			    == DEPCOMPLETE) {
13372 				jwait(&inoref->if_list, MNT_WAIT);
13373 				goto restart;
13374 			}
13375 		}
13376 		if (dap->da_state & MKDIR_BODY) {
13377 			FREE_LOCK(ump);
13378 			error = get_parent_vp(pvp, mp, inum, locked_bp,
13379 			    diraddhdp, &unfinished, &vp);
13380 			if (error != 0)
13381 				break;
13382 			error = flush_newblk_dep(vp, mp, 0);
13383 			/*
13384 			 * If we still have the dependency we might need to
13385 			 * update the vnode to sync the new link count to
13386 			 * disk.
13387 			 */
13388 			if (error == 0 && dap == LIST_FIRST(diraddhdp))
13389 				error = ffs_update(vp, 1);
13390 			vput(vp);
13391 			if (error != 0)
13392 				break;
13393 			ACQUIRE_LOCK(ump);
13394 			/*
13395 			 * If that cleared dependencies, go on to next.
13396 			 */
13397 			if (dap != LIST_FIRST(diraddhdp))
13398 				continue;
13399 			if (dap->da_state & MKDIR_BODY) {
13400 				inodedep_lookup(UFSTOVFS(ump), inum, 0,
13401 				    &inodedep);
13402 				panic("flush_pagedep_deps: MKDIR_BODY "
13403 				    "inodedep %p dap %p vp %p",
13404 				    inodedep, dap, vp);
13405 			}
13406 		}
13407 		/*
13408 		 * Flush the inode on which the directory entry depends.
13409 		 * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
13410 		 * the only remaining dependency is that the updated inode
13411 		 * count must get pushed to disk. The inode has already
13412 		 * been pushed into its inode buffer (via VOP_UPDATE) at
13413 		 * the time of the reference count change. So we need only
13414 		 * locate that buffer, ensure that there will be no rollback
13415 		 * caused by a bitmap dependency, then write the inode buffer.
13416 		 */
13417 retry:
13418 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13419 			panic("flush_pagedep_deps: lost inode");
13420 		/*
13421 		 * If the inode still has bitmap dependencies,
13422 		 * push them to disk.
13423 		 */
13424 		if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) == 0) {
13425 			bp = inodedep->id_bmsafemap->sm_buf;
13426 			bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13427 			if (bp == NULL)
13428 				goto retry;
13429 			FREE_LOCK(ump);
13430 			if ((error = bwrite(bp)) != 0)
13431 				break;
13432 			ACQUIRE_LOCK(ump);
13433 			if (dap != LIST_FIRST(diraddhdp))
13434 				continue;
13435 		}
13436 		/*
13437 		 * If the inode is still sitting in a buffer waiting
13438 		 * to be written or waiting for the link count to be
13439 		 * adjusted update it here to flush it to disk.
13440 		 */
13441 		if (dap == LIST_FIRST(diraddhdp)) {
13442 			FREE_LOCK(ump);
13443 			error = get_parent_vp(pvp, mp, inum, locked_bp,
13444 			    diraddhdp, &unfinished, &vp);
13445 			if (error != 0)
13446 				break;
13447 			error = ffs_update(vp, 1);
13448 			vput(vp);
13449 			if (error)
13450 				break;
13451 			ACQUIRE_LOCK(ump);
13452 		}
13453 		/*
13454 		 * If we have failed to get rid of all the dependencies
13455 		 * then something is seriously wrong.
13456 		 */
13457 		if (dap == LIST_FIRST(diraddhdp)) {
13458 			inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep);
13459 			panic("flush_pagedep_deps: failed to flush "
13460 			    "inodedep %p ino %ju dap %p",
13461 			    inodedep, (uintmax_t)inum, dap);
13462 		}
13463 	}
13464 	if (error)
13465 		ACQUIRE_LOCK(ump);
13466 	while ((dap = LIST_FIRST(&unfinished)) != NULL) {
13467 		LIST_REMOVE(dap, da_pdlist);
13468 		LIST_INSERT_HEAD(diraddhdp, dap, da_pdlist);
13469 	}
13470 	return (error);
13471 }
13472 
13473 /*
13474  * A large burst of file addition or deletion activity can drive the
13475  * memory load excessively high. First attempt to slow things down
13476  * using the techniques below. If that fails, this routine requests
13477  * the offending operations to fall back to running synchronously
13478  * until the memory load returns to a reasonable level.
13479  */
13480 int
13481 softdep_slowdown(struct vnode *vp)
13482 {
13483 	struct ufsmount *ump;
13484 	int jlow;
13485 	int max_softdeps_hard;
13486 
13487 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
13488 	    ("softdep_slowdown called on non-softdep filesystem"));
13489 	ump = VFSTOUFS(vp->v_mount);
13490 	ACQUIRE_LOCK(ump);
13491 	jlow = 0;
13492 	/*
13493 	 * Check for journal space if needed.
13494 	 */
13495 	if (DOINGSUJ(vp)) {
13496 		if (journal_space(ump, 0) == 0)
13497 			jlow = 1;
13498 	}
13499 	/*
13500 	 * If the system is under its limits and our filesystem is
13501 	 * not responsible for more than our share of the usage and
13502 	 * we are not low on journal space, then no need to slow down.
13503 	 */
13504 	max_softdeps_hard = max_softdeps * 11 / 10;
13505 	if (dep_current[D_DIRREM] < max_softdeps_hard / 2 &&
13506 	    dep_current[D_INODEDEP] < max_softdeps_hard &&
13507 	    dep_current[D_INDIRDEP] < max_softdeps_hard / 1000 &&
13508 	    dep_current[D_FREEBLKS] < max_softdeps_hard && jlow == 0 &&
13509 	    ump->softdep_curdeps[D_DIRREM] <
13510 	    (max_softdeps_hard / 2) / stat_flush_threads &&
13511 	    ump->softdep_curdeps[D_INODEDEP] <
13512 	    max_softdeps_hard / stat_flush_threads &&
13513 	    ump->softdep_curdeps[D_INDIRDEP] <
13514 	    (max_softdeps_hard / 1000) / stat_flush_threads &&
13515 	    ump->softdep_curdeps[D_FREEBLKS] <
13516 	    max_softdeps_hard / stat_flush_threads) {
13517 		FREE_LOCK(ump);
13518   		return (0);
13519 	}
13520 	/*
13521 	 * If the journal is low or our filesystem is over its limit
13522 	 * then speedup the cleanup.
13523 	 */
13524 	if (ump->softdep_curdeps[D_INDIRDEP] <
13525 	    (max_softdeps_hard / 1000) / stat_flush_threads || jlow)
13526 		softdep_speedup(ump);
13527 	stat_sync_limit_hit += 1;
13528 	FREE_LOCK(ump);
13529 	/*
13530 	 * We only slow down the rate at which new dependencies are
13531 	 * generated if we are not using journaling. With journaling,
13532 	 * the cleanup should always be sufficient to keep things
13533 	 * under control.
13534 	 */
13535 	if (DOINGSUJ(vp))
13536 		return (0);
13537 	return (1);
13538 }
13539 
13540 static int
13541 softdep_request_cleanup_filter(struct vnode *vp, void *arg __unused)
13542 {
13543 	return ((vp->v_iflag & VI_OWEINACT) != 0 && vp->v_usecount == 0 &&
13544 	    ((vp->v_vflag & VV_NOSYNC) != 0 || VTOI(vp)->i_effnlink == 0));
13545 }
13546 
13547 static void
13548 softdep_request_cleanup_inactivate(struct mount *mp)
13549 {
13550 	struct vnode *vp, *mvp;
13551 	int error;
13552 
13553 	MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, softdep_request_cleanup_filter,
13554 	    NULL) {
13555 		vholdl(vp);
13556 		vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK | LK_RETRY);
13557 		VI_LOCK(vp);
13558 		if (IS_UFS(vp) && vp->v_usecount == 0) {
13559 			while ((vp->v_iflag & VI_OWEINACT) != 0) {
13560 				error = vinactive(vp);
13561 				if (error != 0 && error != ERELOOKUP)
13562 					break;
13563 			}
13564 			atomic_add_int(&stat_delayed_inact, 1);
13565 		}
13566 		VOP_UNLOCK(vp);
13567 		vdropl(vp);
13568 	}
13569 }
13570 
13571 /*
13572  * Called by the allocation routines when they are about to fail
13573  * in the hope that we can free up the requested resource (inodes
13574  * or disk space).
13575  *
13576  * First check to see if the work list has anything on it. If it has,
13577  * clean up entries until we successfully free the requested resource.
13578  * Because this process holds inodes locked, we cannot handle any remove
13579  * requests that might block on a locked inode as that could lead to
13580  * deadlock. If the worklist yields none of the requested resource,
13581  * start syncing out vnodes to free up the needed space.
13582  */
13583 int
13584 softdep_request_cleanup(
13585 	struct fs *fs,
13586 	struct vnode *vp,
13587 	struct ucred *cred,
13588 	int resource)
13589 {
13590 	struct ufsmount *ump;
13591 	struct mount *mp;
13592 	long starttime;
13593 	ufs2_daddr_t needed;
13594 	int error, failed_vnode;
13595 
13596 	/*
13597 	 * If we are being called because of a process doing a
13598 	 * copy-on-write, then it is not safe to process any
13599 	 * worklist items as we will recurse into the copyonwrite
13600 	 * routine.  This will result in an incoherent snapshot.
13601 	 * If the vnode that we hold is a snapshot, we must avoid
13602 	 * handling other resources that could cause deadlock.
13603 	 */
13604 	if ((curthread->td_pflags & TDP_COWINPROGRESS) || IS_SNAPSHOT(VTOI(vp)))
13605 		return (0);
13606 
13607 	if (resource == FLUSH_BLOCKS_WAIT)
13608 		stat_cleanup_blkrequests += 1;
13609 	else
13610 		stat_cleanup_inorequests += 1;
13611 
13612 	mp = vp->v_mount;
13613 	ump = VFSTOUFS(mp);
13614 	mtx_assert(UFS_MTX(ump), MA_OWNED);
13615 	UFS_UNLOCK(ump);
13616 	error = ffs_update(vp, 1);
13617 	if (error != 0 || MOUNTEDSOFTDEP(mp) == 0) {
13618 		UFS_LOCK(ump);
13619 		return (0);
13620 	}
13621 	/*
13622 	 * If we are in need of resources, start by cleaning up
13623 	 * any block removals associated with our inode.
13624 	 */
13625 	ACQUIRE_LOCK(ump);
13626 	process_removes(vp);
13627 	process_truncates(vp);
13628 	FREE_LOCK(ump);
13629 	/*
13630 	 * Now clean up at least as many resources as we will need.
13631 	 *
13632 	 * When requested to clean up inodes, the number that are needed
13633 	 * is set by the number of simultaneous writers (mnt_writeopcount)
13634 	 * plus a bit of slop (2) in case some more writers show up while
13635 	 * we are cleaning.
13636 	 *
13637 	 * When requested to free up space, the amount of space that
13638 	 * we need is enough blocks to allocate a full-sized segment
13639 	 * (fs_contigsumsize). The number of such segments that will
13640 	 * be needed is set by the number of simultaneous writers
13641 	 * (mnt_writeopcount) plus a bit of slop (2) in case some more
13642 	 * writers show up while we are cleaning.
13643 	 *
13644 	 * Additionally, if we are unpriviledged and allocating space,
13645 	 * we need to ensure that we clean up enough blocks to get the
13646 	 * needed number of blocks over the threshold of the minimum
13647 	 * number of blocks required to be kept free by the filesystem
13648 	 * (fs_minfree).
13649 	 */
13650 	if (resource == FLUSH_INODES_WAIT) {
13651 		needed = vfs_mount_fetch_counter(vp->v_mount,
13652 		    MNT_COUNT_WRITEOPCOUNT) + 2;
13653 	} else if (resource == FLUSH_BLOCKS_WAIT) {
13654 		needed = (vfs_mount_fetch_counter(vp->v_mount,
13655 		    MNT_COUNT_WRITEOPCOUNT) + 2) * fs->fs_contigsumsize;
13656 		if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE))
13657 			needed += fragstoblks(fs,
13658 			    roundup((fs->fs_dsize * fs->fs_minfree / 100) -
13659 			    fs->fs_cstotal.cs_nffree, fs->fs_frag));
13660 	} else {
13661 		printf("softdep_request_cleanup: Unknown resource type %d\n",
13662 		    resource);
13663 		UFS_LOCK(ump);
13664 		return (0);
13665 	}
13666 	starttime = time_second;
13667 retry:
13668 	if (resource == FLUSH_BLOCKS_WAIT &&
13669 	    fs->fs_cstotal.cs_nbfree <= needed)
13670 		softdep_send_speedup(ump, needed * fs->fs_bsize,
13671 		    BIO_SPEEDUP_TRIM);
13672 	if ((resource == FLUSH_BLOCKS_WAIT && ump->softdep_on_worklist > 0 &&
13673 	    fs->fs_cstotal.cs_nbfree <= needed) ||
13674 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13675 	    fs->fs_cstotal.cs_nifree <= needed)) {
13676 		ACQUIRE_LOCK(ump);
13677 		if (ump->softdep_on_worklist > 0 &&
13678 		    process_worklist_item(UFSTOVFS(ump),
13679 		    ump->softdep_on_worklist, LK_NOWAIT) != 0)
13680 			stat_worklist_push += 1;
13681 		FREE_LOCK(ump);
13682 	}
13683 
13684 	/*
13685 	 * Check that there are vnodes pending inactivation.  As they
13686 	 * have been unlinked, inactivating them will free up their
13687 	 * inodes.
13688 	 */
13689 	ACQUIRE_LOCK(ump);
13690 	if (resource == FLUSH_INODES_WAIT &&
13691 	    fs->fs_cstotal.cs_nifree <= needed &&
13692 	    fs->fs_pendinginodes <= needed) {
13693 		if ((ump->um_softdep->sd_flags & FLUSH_DI_ACTIVE) == 0) {
13694 			ump->um_softdep->sd_flags |= FLUSH_DI_ACTIVE;
13695 			FREE_LOCK(ump);
13696 			softdep_request_cleanup_inactivate(mp);
13697 			ACQUIRE_LOCK(ump);
13698 			ump->um_softdep->sd_flags &= ~FLUSH_DI_ACTIVE;
13699 			wakeup(&ump->um_softdep->sd_flags);
13700 		} else {
13701 			while ((ump->um_softdep->sd_flags &
13702 			    FLUSH_DI_ACTIVE) != 0) {
13703 				msleep(&ump->um_softdep->sd_flags,
13704 				    LOCK_PTR(ump), PVM, "ffsvina", hz);
13705 			}
13706 		}
13707 	}
13708 	FREE_LOCK(ump);
13709 
13710 	/*
13711 	 * If we still need resources and there are no more worklist
13712 	 * entries to process to obtain them, we have to start flushing
13713 	 * the dirty vnodes to force the release of additional requests
13714 	 * to the worklist that we can then process to reap addition
13715 	 * resources. We walk the vnodes associated with the mount point
13716 	 * until we get the needed worklist requests that we can reap.
13717 	 *
13718 	 * If there are several threads all needing to clean the same
13719 	 * mount point, only one is allowed to walk the mount list.
13720 	 * When several threads all try to walk the same mount list,
13721 	 * they end up competing with each other and often end up in
13722 	 * livelock. This approach ensures that forward progress is
13723 	 * made at the cost of occational ENOSPC errors being returned
13724 	 * that might otherwise have been avoided.
13725 	 */
13726 	error = 1;
13727 	if ((resource == FLUSH_BLOCKS_WAIT &&
13728 	     fs->fs_cstotal.cs_nbfree <= needed) ||
13729 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13730 	     fs->fs_cstotal.cs_nifree <= needed)) {
13731 		ACQUIRE_LOCK(ump);
13732 		if ((ump->um_softdep->sd_flags & FLUSH_RC_ACTIVE) == 0) {
13733 			ump->um_softdep->sd_flags |= FLUSH_RC_ACTIVE;
13734 			FREE_LOCK(ump);
13735 			failed_vnode = softdep_request_cleanup_flush(mp, ump);
13736 			ACQUIRE_LOCK(ump);
13737 			ump->um_softdep->sd_flags &= ~FLUSH_RC_ACTIVE;
13738 			wakeup(&ump->um_softdep->sd_flags);
13739 			FREE_LOCK(ump);
13740 			if (ump->softdep_on_worklist > 0) {
13741 				stat_cleanup_retries += 1;
13742 				if (!failed_vnode)
13743 					goto retry;
13744 			}
13745 		} else {
13746 			while ((ump->um_softdep->sd_flags &
13747 			    FLUSH_RC_ACTIVE) != 0) {
13748 				msleep(&ump->um_softdep->sd_flags,
13749 				    LOCK_PTR(ump), PVM, "ffsrca", hz);
13750 			}
13751 			FREE_LOCK(ump);
13752 			error = 0;
13753 		}
13754 		stat_cleanup_failures += 1;
13755 	}
13756 	if (time_second - starttime > stat_cleanup_high_delay)
13757 		stat_cleanup_high_delay = time_second - starttime;
13758 	UFS_LOCK(ump);
13759 	return (error);
13760 }
13761 
13762 /*
13763  * Scan the vnodes for the specified mount point flushing out any
13764  * vnodes that can be locked without waiting. Finally, try to flush
13765  * the device associated with the mount point if it can be locked
13766  * without waiting.
13767  *
13768  * We return 0 if we were able to lock every vnode in our scan.
13769  * If we had to skip one or more vnodes, we return 1.
13770  */
13771 static int
13772 softdep_request_cleanup_flush(struct mount *mp, struct ufsmount *ump)
13773 {
13774 	struct thread *td;
13775 	struct vnode *lvp, *mvp;
13776 	int failed_vnode;
13777 
13778 	failed_vnode = 0;
13779 	td = curthread;
13780 	MNT_VNODE_FOREACH_ALL(lvp, mp, mvp) {
13781 		if (TAILQ_FIRST(&lvp->v_bufobj.bo_dirty.bv_hd) == 0) {
13782 			VI_UNLOCK(lvp);
13783 			continue;
13784 		}
13785 		if (vget(lvp, LK_EXCLUSIVE | LK_INTERLOCK | LK_NOWAIT) != 0) {
13786 			failed_vnode = 1;
13787 			continue;
13788 		}
13789 		if (lvp->v_vflag & VV_NOSYNC) {	/* unlinked */
13790 			vput(lvp);
13791 			continue;
13792 		}
13793 		(void) ffs_syncvnode(lvp, MNT_NOWAIT, 0);
13794 		vput(lvp);
13795 	}
13796 	lvp = ump->um_devvp;
13797 	if (vn_lock(lvp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
13798 		VOP_FSYNC(lvp, MNT_NOWAIT, td);
13799 		VOP_UNLOCK(lvp);
13800 	}
13801 	return (failed_vnode);
13802 }
13803 
13804 static bool
13805 softdep_excess_items(struct ufsmount *ump, int item)
13806 {
13807 
13808 	KASSERT(item >= 0 && item < D_LAST, ("item %d", item));
13809 	return (dep_current[item] > max_softdeps &&
13810 	    ump->softdep_curdeps[item] > max_softdeps /
13811 	    stat_flush_threads);
13812 }
13813 
13814 static void
13815 schedule_cleanup(struct mount *mp)
13816 {
13817 	struct ufsmount *ump;
13818 	struct thread *td;
13819 
13820 	ump = VFSTOUFS(mp);
13821 	LOCK_OWNED(ump);
13822 	FREE_LOCK(ump);
13823 	td = curthread;
13824 	if ((td->td_pflags & TDP_KTHREAD) != 0 &&
13825 	    (td->td_proc->p_flag2 & P2_AST_SU) == 0) {
13826 		/*
13827 		 * No ast is delivered to kernel threads, so nobody
13828 		 * would deref the mp.  Some kernel threads
13829 		 * explicitly check for AST, e.g. NFS daemon does
13830 		 * this in the serving loop.
13831 		 */
13832 		return;
13833 	}
13834 	if (td->td_su != NULL)
13835 		vfs_rel(td->td_su);
13836 	vfs_ref(mp);
13837 	td->td_su = mp;
13838 	ast_sched(td, TDA_UFS);
13839 }
13840 
13841 static void
13842 softdep_ast_cleanup_proc(struct thread *td, int ast __unused)
13843 {
13844 	struct mount *mp;
13845 	struct ufsmount *ump;
13846 	int error;
13847 	bool req;
13848 
13849 	while ((mp = td->td_su) != NULL) {
13850 		td->td_su = NULL;
13851 		error = vfs_busy(mp, MBF_NOWAIT);
13852 		vfs_rel(mp);
13853 		if (error != 0)
13854 			return;
13855 		if (ffs_own_mount(mp) && MOUNTEDSOFTDEP(mp)) {
13856 			ump = VFSTOUFS(mp);
13857 			for (;;) {
13858 				req = false;
13859 				ACQUIRE_LOCK(ump);
13860 				if (softdep_excess_items(ump, D_INODEDEP)) {
13861 					req = true;
13862 					request_cleanup(mp, FLUSH_INODES);
13863 				}
13864 				if (softdep_excess_items(ump, D_DIRREM)) {
13865 					req = true;
13866 					request_cleanup(mp, FLUSH_BLOCKS);
13867 				}
13868 				FREE_LOCK(ump);
13869 				if (softdep_excess_items(ump, D_NEWBLK) ||
13870 				    softdep_excess_items(ump, D_ALLOCDIRECT) ||
13871 				    softdep_excess_items(ump, D_ALLOCINDIR)) {
13872 					error = vn_start_write(NULL, &mp,
13873 					    V_WAIT);
13874 					if (error == 0) {
13875 						req = true;
13876 						VFS_SYNC(mp, MNT_WAIT);
13877 						vn_finished_write(mp);
13878 					}
13879 				}
13880 				if ((td->td_pflags & TDP_KTHREAD) != 0 || !req)
13881 					break;
13882 			}
13883 		}
13884 		vfs_unbusy(mp);
13885 	}
13886 	if ((mp = td->td_su) != NULL) {
13887 		td->td_su = NULL;
13888 		vfs_rel(mp);
13889 	}
13890 }
13891 
13892 /*
13893  * If memory utilization has gotten too high, deliberately slow things
13894  * down and speed up the I/O processing.
13895  */
13896 static int
13897 request_cleanup(struct mount *mp, int resource)
13898 {
13899 	struct thread *td = curthread;
13900 	struct ufsmount *ump;
13901 
13902 	ump = VFSTOUFS(mp);
13903 	LOCK_OWNED(ump);
13904 	/*
13905 	 * We never hold up the filesystem syncer or buf daemon.
13906 	 */
13907 	if (td->td_pflags & (TDP_SOFTDEP|TDP_NORUNNINGBUF))
13908 		return (0);
13909 	/*
13910 	 * First check to see if the work list has gotten backlogged.
13911 	 * If it has, co-opt this process to help clean up two entries.
13912 	 * Because this process may hold inodes locked, we cannot
13913 	 * handle any remove requests that might block on a locked
13914 	 * inode as that could lead to deadlock.  We set TDP_SOFTDEP
13915 	 * to avoid recursively processing the worklist.
13916 	 */
13917 	if (ump->softdep_on_worklist > max_softdeps / 10) {
13918 		td->td_pflags |= TDP_SOFTDEP;
13919 		process_worklist_item(mp, 2, LK_NOWAIT);
13920 		td->td_pflags &= ~TDP_SOFTDEP;
13921 		stat_worklist_push += 2;
13922 		return(1);
13923 	}
13924 	/*
13925 	 * Next, we attempt to speed up the syncer process. If that
13926 	 * is successful, then we allow the process to continue.
13927 	 */
13928 	if (softdep_speedup(ump) &&
13929 	    resource != FLUSH_BLOCKS_WAIT &&
13930 	    resource != FLUSH_INODES_WAIT)
13931 		return(0);
13932 	/*
13933 	 * If we are resource constrained on inode dependencies, try
13934 	 * flushing some dirty inodes. Otherwise, we are constrained
13935 	 * by file deletions, so try accelerating flushes of directories
13936 	 * with removal dependencies. We would like to do the cleanup
13937 	 * here, but we probably hold an inode locked at this point and
13938 	 * that might deadlock against one that we try to clean. So,
13939 	 * the best that we can do is request the syncer daemon to do
13940 	 * the cleanup for us.
13941 	 */
13942 	switch (resource) {
13943 	case FLUSH_INODES:
13944 	case FLUSH_INODES_WAIT:
13945 		ACQUIRE_GBLLOCK(&lk);
13946 		stat_ino_limit_push += 1;
13947 		req_clear_inodedeps += 1;
13948 		FREE_GBLLOCK(&lk);
13949 		stat_countp = &stat_ino_limit_hit;
13950 		break;
13951 
13952 	case FLUSH_BLOCKS:
13953 	case FLUSH_BLOCKS_WAIT:
13954 		ACQUIRE_GBLLOCK(&lk);
13955 		stat_blk_limit_push += 1;
13956 		req_clear_remove += 1;
13957 		FREE_GBLLOCK(&lk);
13958 		stat_countp = &stat_blk_limit_hit;
13959 		break;
13960 
13961 	default:
13962 		panic("request_cleanup: unknown type");
13963 	}
13964 	/*
13965 	 * Hopefully the syncer daemon will catch up and awaken us.
13966 	 * We wait at most tickdelay before proceeding in any case.
13967 	 */
13968 	ACQUIRE_GBLLOCK(&lk);
13969 	FREE_LOCK(ump);
13970 	proc_waiting += 1;
13971 	if (callout_pending(&softdep_callout) == FALSE)
13972 		callout_reset(&softdep_callout, tickdelay > 2 ? tickdelay : 2,
13973 		    pause_timer, 0);
13974 
13975 	if ((td->td_pflags & TDP_KTHREAD) == 0)
13976 		msleep((caddr_t)&proc_waiting, &lk, PPAUSE, "softupdate", 0);
13977 	proc_waiting -= 1;
13978 	FREE_GBLLOCK(&lk);
13979 	ACQUIRE_LOCK(ump);
13980 	return (1);
13981 }
13982 
13983 /*
13984  * Awaken processes pausing in request_cleanup and clear proc_waiting
13985  * to indicate that there is no longer a timer running. Pause_timer
13986  * will be called with the global softdep mutex (&lk) locked.
13987  */
13988 static void
13989 pause_timer(void *arg)
13990 {
13991 
13992 	GBLLOCK_OWNED(&lk);
13993 	/*
13994 	 * The callout_ API has acquired mtx and will hold it around this
13995 	 * function call.
13996 	 */
13997 	*stat_countp += proc_waiting;
13998 	wakeup(&proc_waiting);
13999 }
14000 
14001 /*
14002  * If requested, try removing inode or removal dependencies.
14003  */
14004 static void
14005 check_clear_deps(struct mount *mp)
14006 {
14007 	struct ufsmount *ump;
14008 	bool suj_susp;
14009 
14010 	/*
14011 	 * Tell the lower layers that any TRIM or WRITE transactions that have
14012 	 * been delayed for performance reasons should proceed to help alleviate
14013 	 * the shortage faster. The race between checking req_* and the softdep
14014 	 * mutex (lk) is fine since this is an advisory operation that at most
14015 	 * causes deferred work to be done sooner.
14016 	 */
14017 	ump = VFSTOUFS(mp);
14018 	suj_susp = ump->um_softdep->sd_jblocks != NULL &&
14019 	    ump->softdep_jblocks->jb_suspended;
14020 	if (req_clear_remove || req_clear_inodedeps || suj_susp) {
14021 		FREE_LOCK(ump);
14022 		softdep_send_speedup(ump, 0, BIO_SPEEDUP_TRIM | BIO_SPEEDUP_WRITE);
14023 		ACQUIRE_LOCK(ump);
14024 	}
14025 
14026 	/*
14027 	 * If we are suspended, it may be because of our using
14028 	 * too many inodedeps, so help clear them out.
14029 	 */
14030 	if (suj_susp)
14031 		clear_inodedeps(mp);
14032 
14033 	/*
14034 	 * General requests for cleanup of backed up dependencies
14035 	 */
14036 	ACQUIRE_GBLLOCK(&lk);
14037 	if (req_clear_inodedeps) {
14038 		req_clear_inodedeps -= 1;
14039 		FREE_GBLLOCK(&lk);
14040 		clear_inodedeps(mp);
14041 		ACQUIRE_GBLLOCK(&lk);
14042 		wakeup(&proc_waiting);
14043 	}
14044 	if (req_clear_remove) {
14045 		req_clear_remove -= 1;
14046 		FREE_GBLLOCK(&lk);
14047 		clear_remove(mp);
14048 		ACQUIRE_GBLLOCK(&lk);
14049 		wakeup(&proc_waiting);
14050 	}
14051 	FREE_GBLLOCK(&lk);
14052 }
14053 
14054 /*
14055  * Flush out a directory with at least one removal dependency in an effort to
14056  * reduce the number of dirrem, freefile, and freeblks dependency structures.
14057  */
14058 static void
14059 clear_remove(struct mount *mp)
14060 {
14061 	struct pagedep_hashhead *pagedephd;
14062 	struct pagedep *pagedep;
14063 	struct ufsmount *ump;
14064 	struct vnode *vp;
14065 	struct bufobj *bo;
14066 	int error, cnt;
14067 	ino_t ino;
14068 
14069 	ump = VFSTOUFS(mp);
14070 	LOCK_OWNED(ump);
14071 
14072 	for (cnt = 0; cnt <= ump->pagedep_hash_size; cnt++) {
14073 		pagedephd = &ump->pagedep_hashtbl[ump->pagedep_nextclean++];
14074 		if (ump->pagedep_nextclean > ump->pagedep_hash_size)
14075 			ump->pagedep_nextclean = 0;
14076 		LIST_FOREACH(pagedep, pagedephd, pd_hash) {
14077 			if (LIST_EMPTY(&pagedep->pd_dirremhd))
14078 				continue;
14079 			ino = pagedep->pd_ino;
14080 			if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
14081 				continue;
14082 			FREE_LOCK(ump);
14083 
14084 			/*
14085 			 * Let unmount clear deps
14086 			 */
14087 			error = vfs_busy(mp, MBF_NOWAIT);
14088 			if (error != 0)
14089 				goto finish_write;
14090 			error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
14091 			     FFSV_FORCEINSMQ | FFSV_FORCEINODEDEP);
14092 			vfs_unbusy(mp);
14093 			if (error != 0) {
14094 				softdep_error("clear_remove: vget", error);
14095 				goto finish_write;
14096 			}
14097 			MPASS(VTOI(vp)->i_mode != 0);
14098 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
14099 				softdep_error("clear_remove: fsync", error);
14100 			bo = &vp->v_bufobj;
14101 			BO_LOCK(bo);
14102 			drain_output(vp);
14103 			BO_UNLOCK(bo);
14104 			vput(vp);
14105 		finish_write:
14106 			vn_finished_write(mp);
14107 			ACQUIRE_LOCK(ump);
14108 			return;
14109 		}
14110 	}
14111 }
14112 
14113 /*
14114  * Clear out a block of dirty inodes in an effort to reduce
14115  * the number of inodedep dependency structures.
14116  */
14117 static void
14118 clear_inodedeps(struct mount *mp)
14119 {
14120 	struct inodedep_hashhead *inodedephd;
14121 	struct inodedep *inodedep;
14122 	struct ufsmount *ump;
14123 	struct vnode *vp;
14124 	struct fs *fs;
14125 	int error, cnt;
14126 	ino_t firstino, lastino, ino;
14127 
14128 	ump = VFSTOUFS(mp);
14129 	fs = ump->um_fs;
14130 	LOCK_OWNED(ump);
14131 	/*
14132 	 * Pick a random inode dependency to be cleared.
14133 	 * We will then gather up all the inodes in its block
14134 	 * that have dependencies and flush them out.
14135 	 */
14136 	for (cnt = 0; cnt <= ump->inodedep_hash_size; cnt++) {
14137 		inodedephd = &ump->inodedep_hashtbl[ump->inodedep_nextclean++];
14138 		if (ump->inodedep_nextclean > ump->inodedep_hash_size)
14139 			ump->inodedep_nextclean = 0;
14140 		if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
14141 			break;
14142 	}
14143 	if (inodedep == NULL)
14144 		return;
14145 	/*
14146 	 * Find the last inode in the block with dependencies.
14147 	 */
14148 	firstino = rounddown2(inodedep->id_ino, INOPB(fs));
14149 	for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
14150 		if (inodedep_lookup(mp, lastino, 0, &inodedep) != 0)
14151 			break;
14152 	/*
14153 	 * Asynchronously push all but the last inode with dependencies.
14154 	 * Synchronously push the last inode with dependencies to ensure
14155 	 * that the inode block gets written to free up the inodedeps.
14156 	 */
14157 	for (ino = firstino; ino <= lastino; ino++) {
14158 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
14159 			continue;
14160 		if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
14161 			continue;
14162 		FREE_LOCK(ump);
14163 		error = vfs_busy(mp, MBF_NOWAIT); /* Let unmount clear deps */
14164 		if (error != 0) {
14165 			vn_finished_write(mp);
14166 			ACQUIRE_LOCK(ump);
14167 			return;
14168 		}
14169 		if ((error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
14170 		    FFSV_FORCEINSMQ | FFSV_FORCEINODEDEP)) != 0) {
14171 			softdep_error("clear_inodedeps: vget", error);
14172 			vfs_unbusy(mp);
14173 			vn_finished_write(mp);
14174 			ACQUIRE_LOCK(ump);
14175 			return;
14176 		}
14177 		vfs_unbusy(mp);
14178 		if (VTOI(vp)->i_mode == 0) {
14179 			vgone(vp);
14180 		} else if (ino == lastino) {
14181 			do {
14182 				error = ffs_syncvnode(vp, MNT_WAIT, 0);
14183 			} while (error == ERELOOKUP);
14184 			if (error != 0)
14185 				softdep_error("clear_inodedeps: fsync1", error);
14186 		} else {
14187 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
14188 				softdep_error("clear_inodedeps: fsync2", error);
14189 			BO_LOCK(&vp->v_bufobj);
14190 			drain_output(vp);
14191 			BO_UNLOCK(&vp->v_bufobj);
14192 		}
14193 		vput(vp);
14194 		vn_finished_write(mp);
14195 		ACQUIRE_LOCK(ump);
14196 	}
14197 }
14198 
14199 void
14200 softdep_buf_append(struct buf *bp, struct workhead *wkhd)
14201 {
14202 	struct worklist *wk;
14203 	struct ufsmount *ump;
14204 
14205 	if ((wk = LIST_FIRST(wkhd)) == NULL)
14206 		return;
14207 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
14208 	    ("softdep_buf_append called on non-softdep filesystem"));
14209 	ump = VFSTOUFS(wk->wk_mp);
14210 	ACQUIRE_LOCK(ump);
14211 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
14212 		WORKLIST_REMOVE(wk);
14213 		WORKLIST_INSERT(&bp->b_dep, wk);
14214 	}
14215 	FREE_LOCK(ump);
14216 
14217 }
14218 
14219 void
14220 softdep_inode_append(
14221 	struct inode *ip,
14222 	struct ucred *cred,
14223 	struct workhead *wkhd)
14224 {
14225 	struct buf *bp;
14226 	struct fs *fs;
14227 	struct ufsmount *ump;
14228 	int error;
14229 
14230 	ump = ITOUMP(ip);
14231 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
14232 	    ("softdep_inode_append called on non-softdep filesystem"));
14233 	fs = ump->um_fs;
14234 	error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
14235 	    (int)fs->fs_bsize, cred, &bp);
14236 	if (error) {
14237 		bqrelse(bp);
14238 		softdep_freework(wkhd);
14239 		return;
14240 	}
14241 	softdep_buf_append(bp, wkhd);
14242 	bqrelse(bp);
14243 }
14244 
14245 void
14246 softdep_freework(struct workhead *wkhd)
14247 {
14248 	struct worklist *wk;
14249 	struct ufsmount *ump;
14250 
14251 	if ((wk = LIST_FIRST(wkhd)) == NULL)
14252 		return;
14253 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
14254 	    ("softdep_freework called on non-softdep filesystem"));
14255 	ump = VFSTOUFS(wk->wk_mp);
14256 	ACQUIRE_LOCK(ump);
14257 	handle_jwork(wkhd);
14258 	FREE_LOCK(ump);
14259 }
14260 
14261 static struct ufsmount *
14262 softdep_bp_to_mp(struct buf *bp)
14263 {
14264 	struct mount *mp;
14265 	struct vnode *vp;
14266 
14267 	if (LIST_EMPTY(&bp->b_dep))
14268 		return (NULL);
14269 	vp = bp->b_vp;
14270 	KASSERT(vp != NULL,
14271 	    ("%s, buffer with dependencies lacks vnode", __func__));
14272 
14273 	/*
14274 	 * The ump mount point is stable after we get a correct
14275 	 * pointer, since bp is locked and this prevents unmount from
14276 	 * proceeding.  But to get to it, we cannot dereference bp->b_dep
14277 	 * head wk_mp, because we do not yet own SU ump lock and
14278 	 * workitem might be freed while dereferenced.
14279 	 */
14280 retry:
14281 	switch (vp->v_type) {
14282 	case VCHR:
14283 		VI_LOCK(vp);
14284 		mp = vp->v_type == VCHR ? vp->v_rdev->si_mountpt : NULL;
14285 		VI_UNLOCK(vp);
14286 		if (mp == NULL)
14287 			goto retry;
14288 		break;
14289 	case VREG:
14290 	case VDIR:
14291 	case VLNK:
14292 	case VFIFO:
14293 	case VSOCK:
14294 		mp = vp->v_mount;
14295 		break;
14296 	case VBLK:
14297 		vn_printf(vp, "softdep_bp_to_mp: unexpected block device\n");
14298 		/* FALLTHROUGH */
14299 	case VNON:
14300 	case VBAD:
14301 	case VMARKER:
14302 		mp = NULL;
14303 		break;
14304 	default:
14305 		vn_printf(vp, "unknown vnode type");
14306 		mp = NULL;
14307 		break;
14308 	}
14309 	return (VFSTOUFS(mp));
14310 }
14311 
14312 /*
14313  * Function to determine if the buffer has outstanding dependencies
14314  * that will cause a roll-back if the buffer is written. If wantcount
14315  * is set, return number of dependencies, otherwise just yes or no.
14316  */
14317 static int
14318 softdep_count_dependencies(struct buf *bp, int wantcount)
14319 {
14320 	struct worklist *wk;
14321 	struct ufsmount *ump;
14322 	struct bmsafemap *bmsafemap;
14323 	struct freework *freework;
14324 	struct inodedep *inodedep;
14325 	struct indirdep *indirdep;
14326 	struct freeblks *freeblks;
14327 	struct allocindir *aip;
14328 	struct pagedep *pagedep;
14329 	struct dirrem *dirrem;
14330 	struct newblk *newblk;
14331 	struct mkdir *mkdir;
14332 	struct diradd *dap;
14333 	int i, retval;
14334 
14335 	ump = softdep_bp_to_mp(bp);
14336 	if (ump == NULL)
14337 		return (0);
14338 	retval = 0;
14339 	ACQUIRE_LOCK(ump);
14340 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
14341 		switch (wk->wk_type) {
14342 		case D_INODEDEP:
14343 			inodedep = WK_INODEDEP(wk);
14344 			if ((inodedep->id_state & DEPCOMPLETE) == 0) {
14345 				/* bitmap allocation dependency */
14346 				retval += 1;
14347 				if (!wantcount)
14348 					goto out;
14349 			}
14350 			if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
14351 				/* direct block pointer dependency */
14352 				retval += 1;
14353 				if (!wantcount)
14354 					goto out;
14355 			}
14356 			if (TAILQ_FIRST(&inodedep->id_extupdt)) {
14357 				/* direct block pointer dependency */
14358 				retval += 1;
14359 				if (!wantcount)
14360 					goto out;
14361 			}
14362 			if (TAILQ_FIRST(&inodedep->id_inoreflst)) {
14363 				/* Add reference dependency. */
14364 				retval += 1;
14365 				if (!wantcount)
14366 					goto out;
14367 			}
14368 			continue;
14369 
14370 		case D_INDIRDEP:
14371 			indirdep = WK_INDIRDEP(wk);
14372 
14373 			TAILQ_FOREACH(freework, &indirdep->ir_trunc, fw_next) {
14374 				/* indirect truncation dependency */
14375 				retval += 1;
14376 				if (!wantcount)
14377 					goto out;
14378 			}
14379 
14380 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
14381 				/* indirect block pointer dependency */
14382 				retval += 1;
14383 				if (!wantcount)
14384 					goto out;
14385 			}
14386 			continue;
14387 
14388 		case D_PAGEDEP:
14389 			pagedep = WK_PAGEDEP(wk);
14390 			LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
14391 				if (LIST_FIRST(&dirrem->dm_jremrefhd)) {
14392 					/* Journal remove ref dependency. */
14393 					retval += 1;
14394 					if (!wantcount)
14395 						goto out;
14396 				}
14397 			}
14398 			for (i = 0; i < DAHASHSZ; i++) {
14399 				LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
14400 					/* directory entry dependency */
14401 					retval += 1;
14402 					if (!wantcount)
14403 						goto out;
14404 				}
14405 			}
14406 			continue;
14407 
14408 		case D_BMSAFEMAP:
14409 			bmsafemap = WK_BMSAFEMAP(wk);
14410 			if (LIST_FIRST(&bmsafemap->sm_jaddrefhd)) {
14411 				/* Add reference dependency. */
14412 				retval += 1;
14413 				if (!wantcount)
14414 					goto out;
14415 			}
14416 			if (LIST_FIRST(&bmsafemap->sm_jnewblkhd)) {
14417 				/* Allocate block dependency. */
14418 				retval += 1;
14419 				if (!wantcount)
14420 					goto out;
14421 			}
14422 			continue;
14423 
14424 		case D_FREEBLKS:
14425 			freeblks = WK_FREEBLKS(wk);
14426 			if (LIST_FIRST(&freeblks->fb_jblkdephd)) {
14427 				/* Freeblk journal dependency. */
14428 				retval += 1;
14429 				if (!wantcount)
14430 					goto out;
14431 			}
14432 			continue;
14433 
14434 		case D_ALLOCDIRECT:
14435 		case D_ALLOCINDIR:
14436 			newblk = WK_NEWBLK(wk);
14437 			if (newblk->nb_jnewblk) {
14438 				/* Journal allocate dependency. */
14439 				retval += 1;
14440 				if (!wantcount)
14441 					goto out;
14442 			}
14443 			continue;
14444 
14445 		case D_MKDIR:
14446 			mkdir = WK_MKDIR(wk);
14447 			if (mkdir->md_jaddref) {
14448 				/* Journal reference dependency. */
14449 				retval += 1;
14450 				if (!wantcount)
14451 					goto out;
14452 			}
14453 			continue;
14454 
14455 		case D_FREEWORK:
14456 		case D_FREEDEP:
14457 		case D_JSEGDEP:
14458 		case D_JSEG:
14459 		case D_SBDEP:
14460 			/* never a dependency on these blocks */
14461 			continue;
14462 
14463 		default:
14464 			panic("softdep_count_dependencies: Unexpected type %s",
14465 			    TYPENAME(wk->wk_type));
14466 			/* NOTREACHED */
14467 		}
14468 	}
14469 out:
14470 	FREE_LOCK(ump);
14471 	return (retval);
14472 }
14473 
14474 /*
14475  * Acquire exclusive access to a buffer.
14476  * Must be called with a locked mtx parameter.
14477  * Return acquired buffer or NULL on failure.
14478  */
14479 static struct buf *
14480 getdirtybuf(struct buf *bp,
14481 	struct rwlock *lock,
14482 	int waitfor)
14483 {
14484 	int error;
14485 
14486 	if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0) {
14487 		if (waitfor != MNT_WAIT)
14488 			return (NULL);
14489 		error = BUF_LOCK(bp,
14490 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, lock);
14491 		/*
14492 		 * Even if we successfully acquire bp here, we have dropped
14493 		 * lock, which may violates our guarantee.
14494 		 */
14495 		if (error == 0)
14496 			BUF_UNLOCK(bp);
14497 		else if (error != ENOLCK)
14498 			panic("getdirtybuf: inconsistent lock: %d", error);
14499 		rw_wlock(lock);
14500 		return (NULL);
14501 	}
14502 	if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14503 		if (lock != BO_LOCKPTR(bp->b_bufobj) && waitfor == MNT_WAIT) {
14504 			rw_wunlock(lock);
14505 			BO_LOCK(bp->b_bufobj);
14506 			BUF_UNLOCK(bp);
14507 			if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14508 				bp->b_vflags |= BV_BKGRDWAIT;
14509 				msleep(&bp->b_xflags, BO_LOCKPTR(bp->b_bufobj),
14510 				       PRIBIO | PDROP, "getbuf", 0);
14511 			} else
14512 				BO_UNLOCK(bp->b_bufobj);
14513 			rw_wlock(lock);
14514 			return (NULL);
14515 		}
14516 		BUF_UNLOCK(bp);
14517 		if (waitfor != MNT_WAIT)
14518 			return (NULL);
14519 #ifdef DEBUG_VFS_LOCKS
14520 		if (bp->b_vp->v_type != VCHR)
14521 			ASSERT_BO_WLOCKED(bp->b_bufobj);
14522 #endif
14523 		bp->b_vflags |= BV_BKGRDWAIT;
14524 		rw_sleep(&bp->b_xflags, lock, PRIBIO, "getbuf", 0);
14525 		return (NULL);
14526 	}
14527 	if ((bp->b_flags & B_DELWRI) == 0) {
14528 		BUF_UNLOCK(bp);
14529 		return (NULL);
14530 	}
14531 	bremfree(bp);
14532 	return (bp);
14533 }
14534 
14535 /*
14536  * Check if it is safe to suspend the file system now.  On entry,
14537  * the vnode interlock for devvp should be held.  Return 0 with
14538  * the mount interlock held if the file system can be suspended now,
14539  * otherwise return EAGAIN with the mount interlock held.
14540  */
14541 int
14542 softdep_check_suspend(struct mount *mp,
14543 		      struct vnode *devvp,
14544 		      int softdep_depcnt,
14545 		      int softdep_accdepcnt,
14546 		      int secondary_writes,
14547 		      int secondary_accwrites)
14548 {
14549 	struct buf *bp;
14550 	struct bufobj *bo;
14551 	struct ufsmount *ump;
14552 	struct inodedep *inodedep;
14553 	struct indirdep *indirdep;
14554 	struct worklist *wk, *nextwk;
14555 	int error, unlinked;
14556 
14557 	bo = &devvp->v_bufobj;
14558 	ASSERT_BO_WLOCKED(bo);
14559 
14560 	/*
14561 	 * If we are not running with soft updates, then we need only
14562 	 * deal with secondary writes as we try to suspend.
14563 	 */
14564 	if (MOUNTEDSOFTDEP(mp) == 0) {
14565 		MNT_ILOCK(mp);
14566 		while (mp->mnt_secondary_writes != 0) {
14567 			BO_UNLOCK(bo);
14568 			msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
14569 			    (PUSER - 1) | PDROP, "secwr", 0);
14570 			BO_LOCK(bo);
14571 			MNT_ILOCK(mp);
14572 		}
14573 
14574 		/*
14575 		 * Reasons for needing more work before suspend:
14576 		 * - Dirty buffers on devvp.
14577 		 * - Secondary writes occurred after start of vnode sync loop
14578 		 */
14579 		error = 0;
14580 		if (bo->bo_numoutput > 0 ||
14581 		    bo->bo_dirty.bv_cnt > 0 ||
14582 		    secondary_writes != 0 ||
14583 		    mp->mnt_secondary_writes != 0 ||
14584 		    secondary_accwrites != mp->mnt_secondary_accwrites)
14585 			error = EAGAIN;
14586 		BO_UNLOCK(bo);
14587 		return (error);
14588 	}
14589 
14590 	/*
14591 	 * If we are running with soft updates, then we need to coordinate
14592 	 * with them as we try to suspend.
14593 	 */
14594 	ump = VFSTOUFS(mp);
14595 	for (;;) {
14596 		if (!TRY_ACQUIRE_LOCK(ump)) {
14597 			BO_UNLOCK(bo);
14598 			ACQUIRE_LOCK(ump);
14599 			FREE_LOCK(ump);
14600 			BO_LOCK(bo);
14601 			continue;
14602 		}
14603 		MNT_ILOCK(mp);
14604 		if (mp->mnt_secondary_writes != 0) {
14605 			FREE_LOCK(ump);
14606 			BO_UNLOCK(bo);
14607 			msleep(&mp->mnt_secondary_writes,
14608 			       MNT_MTX(mp),
14609 			       (PUSER - 1) | PDROP, "secwr", 0);
14610 			BO_LOCK(bo);
14611 			continue;
14612 		}
14613 		break;
14614 	}
14615 
14616 	unlinked = 0;
14617 	if (MOUNTEDSUJ(mp)) {
14618 		for (inodedep = TAILQ_FIRST(&ump->softdep_unlinked);
14619 		    inodedep != NULL;
14620 		    inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
14621 			if ((inodedep->id_state & (UNLINKED | UNLINKLINKS |
14622 			    UNLINKONLIST)) != (UNLINKED | UNLINKLINKS |
14623 			    UNLINKONLIST) ||
14624 			    !check_inodedep_free(inodedep))
14625 				continue;
14626 			unlinked++;
14627 		}
14628 	}
14629 
14630 	/*
14631 	 * XXX Check for orphaned indirdep dependency structures.
14632 	 *
14633 	 * During forcible unmount after a disk failure there is a
14634 	 * bug that causes one or more indirdep dependency structures
14635 	 * to fail to be deallocated. We check for them here and clean
14636 	 * them up so that the unmount can succeed.
14637 	 */
14638 	if ((ump->um_flags & UM_FSFAIL_CLEANUP) != 0 && ump->softdep_deps > 0 &&
14639 	    ump->softdep_deps == ump->softdep_curdeps[D_INDIRDEP]) {
14640 		LIST_FOREACH_SAFE(wk, &ump->softdep_alldeps[D_INDIRDEP],
14641 		    wk_all, nextwk) {
14642 			indirdep = WK_INDIRDEP(wk);
14643 			if ((indirdep->ir_state & (GOINGAWAY | DEPCOMPLETE)) !=
14644 			    (GOINGAWAY | DEPCOMPLETE) ||
14645 			    !TAILQ_EMPTY(&indirdep->ir_trunc) ||
14646 			    !LIST_EMPTY(&indirdep->ir_completehd) ||
14647 			    !LIST_EMPTY(&indirdep->ir_writehd) ||
14648 			    !LIST_EMPTY(&indirdep->ir_donehd) ||
14649 			    !LIST_EMPTY(&indirdep->ir_deplisthd) ||
14650 			    indirdep->ir_saveddata != NULL ||
14651 			    indirdep->ir_savebp == NULL) {
14652 				printf("%s: skipping orphaned indirdep %p\n",
14653 				    __FUNCTION__, indirdep);
14654 				continue;
14655 			}
14656 			printf("%s: freeing orphaned indirdep %p\n",
14657 			    __FUNCTION__, indirdep);
14658 			bp = indirdep->ir_savebp;
14659 			indirdep->ir_savebp = NULL;
14660 			free_indirdep(indirdep);
14661 			FREE_LOCK(ump);
14662 			brelse(bp);
14663 			while (!TRY_ACQUIRE_LOCK(ump)) {
14664 				BO_UNLOCK(bo);
14665 				ACQUIRE_LOCK(ump);
14666 				FREE_LOCK(ump);
14667 				BO_LOCK(bo);
14668 			}
14669 		}
14670 	}
14671 
14672 	/*
14673 	 * Reasons for needing more work before suspend:
14674 	 * - Dirty buffers on devvp.
14675 	 * - Dependency structures still exist
14676 	 * - Softdep activity occurred after start of vnode sync loop
14677 	 * - Secondary writes occurred after start of vnode sync loop
14678 	 */
14679 	error = 0;
14680 	if (bo->bo_numoutput > 0 ||
14681 	    bo->bo_dirty.bv_cnt > 0 ||
14682 	    softdep_depcnt != unlinked ||
14683 	    ump->softdep_deps != unlinked ||
14684 	    softdep_accdepcnt != ump->softdep_accdeps ||
14685 	    secondary_writes != 0 ||
14686 	    mp->mnt_secondary_writes != 0 ||
14687 	    secondary_accwrites != mp->mnt_secondary_accwrites)
14688 		error = EAGAIN;
14689 	FREE_LOCK(ump);
14690 	BO_UNLOCK(bo);
14691 	return (error);
14692 }
14693 
14694 /*
14695  * Get the number of dependency structures for the file system, both
14696  * the current number and the total number allocated.  These will
14697  * later be used to detect that softdep processing has occurred.
14698  */
14699 void
14700 softdep_get_depcounts(struct mount *mp,
14701 		      int *softdep_depsp,
14702 		      int *softdep_accdepsp)
14703 {
14704 	struct ufsmount *ump;
14705 
14706 	if (MOUNTEDSOFTDEP(mp) == 0) {
14707 		*softdep_depsp = 0;
14708 		*softdep_accdepsp = 0;
14709 		return;
14710 	}
14711 	ump = VFSTOUFS(mp);
14712 	ACQUIRE_LOCK(ump);
14713 	*softdep_depsp = ump->softdep_deps;
14714 	*softdep_accdepsp = ump->softdep_accdeps;
14715 	FREE_LOCK(ump);
14716 }
14717 
14718 /*
14719  * Wait for pending output on a vnode to complete.
14720  */
14721 static void
14722 drain_output(struct vnode *vp)
14723 {
14724 
14725 	ASSERT_VOP_LOCKED(vp, "drain_output");
14726 	(void)bufobj_wwait(&vp->v_bufobj, 0, 0);
14727 }
14728 
14729 /*
14730  * Called whenever a buffer that is being invalidated or reallocated
14731  * contains dependencies. This should only happen if an I/O error has
14732  * occurred. The routine is called with the buffer locked.
14733  */
14734 static void
14735 softdep_deallocate_dependencies(struct buf *bp)
14736 {
14737 
14738 	if ((bp->b_ioflags & BIO_ERROR) == 0)
14739 		panic("softdep_deallocate_dependencies: dangling deps");
14740 	if (bp->b_vp != NULL && bp->b_vp->v_mount != NULL)
14741 		softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntonname, bp->b_error);
14742 	else
14743 		printf("softdep_deallocate_dependencies: "
14744 		    "got error %d while accessing filesystem\n", bp->b_error);
14745 	if (bp->b_error != ENXIO)
14746 		panic("softdep_deallocate_dependencies: unrecovered I/O error");
14747 }
14748 
14749 /*
14750  * Function to handle asynchronous write errors in the filesystem.
14751  */
14752 static void
14753 softdep_error(char *func, int error)
14754 {
14755 
14756 	/* XXX should do something better! */
14757 	printf("%s: got error %d while accessing filesystem\n", func, error);
14758 }
14759 
14760 #ifdef DDB
14761 
14762 /* exported to ffs_vfsops.c */
14763 extern void db_print_ffs(struct ufsmount *ump);
14764 void
14765 db_print_ffs(struct ufsmount *ump)
14766 {
14767 	db_printf("mp %p (%s) devvp %p\n", ump->um_mountp,
14768 	    ump->um_mountp->mnt_stat.f_mntonname, ump->um_devvp);
14769 	db_printf("    fs %p ", ump->um_fs);
14770 
14771 	if (ump->um_softdep != NULL) {
14772 		db_printf("su_wl %d su_deps %d su_req %d\n",
14773 		    ump->softdep_on_worklist, ump->softdep_deps,
14774 		    ump->softdep_req);
14775 	} else {
14776 		db_printf("su disabled\n");
14777 	}
14778 }
14779 
14780 static void
14781 worklist_print(struct worklist *wk, int verbose)
14782 {
14783 
14784 	if (!verbose) {
14785 		db_printf("%s: %p state 0x%b\n", TYPENAME(wk->wk_type), wk,
14786 		    wk->wk_state, PRINT_SOFTDEP_FLAGS);
14787 		return;
14788 	}
14789 	db_printf("worklist: %p type %s state 0x%b next %p\n    ", wk,
14790 	    TYPENAME(wk->wk_type), wk->wk_state, PRINT_SOFTDEP_FLAGS,
14791 	    LIST_NEXT(wk, wk_list));
14792 	db_print_ffs(VFSTOUFS(wk->wk_mp));
14793 }
14794 
14795 static void
14796 inodedep_print(struct inodedep *inodedep, int verbose)
14797 {
14798 
14799 	worklist_print(&inodedep->id_list, 0);
14800 	db_printf("    fs %p ino %jd inoblk %jd delta %jd nlink %jd\n",
14801 	    inodedep->id_fs,
14802 	    (intmax_t)inodedep->id_ino,
14803 	    (intmax_t)fsbtodb(inodedep->id_fs,
14804 	        ino_to_fsba(inodedep->id_fs, inodedep->id_ino)),
14805 	    (intmax_t)inodedep->id_nlinkdelta,
14806 	    (intmax_t)inodedep->id_savednlink);
14807 
14808 	if (verbose == 0)
14809 		return;
14810 
14811 	db_printf("    bmsafemap %p, mkdiradd %p, inoreflst %p\n",
14812 	    inodedep->id_bmsafemap,
14813 	    inodedep->id_mkdiradd,
14814 	    TAILQ_FIRST(&inodedep->id_inoreflst));
14815 	db_printf("    dirremhd %p, pendinghd %p, bufwait %p\n",
14816 	    LIST_FIRST(&inodedep->id_dirremhd),
14817 	    LIST_FIRST(&inodedep->id_pendinghd),
14818 	    LIST_FIRST(&inodedep->id_bufwait));
14819 	db_printf("    inowait %p, inoupdt %p, newinoupdt %p\n",
14820 	    LIST_FIRST(&inodedep->id_inowait),
14821 	    TAILQ_FIRST(&inodedep->id_inoupdt),
14822 	    TAILQ_FIRST(&inodedep->id_newinoupdt));
14823 	db_printf("    extupdt %p, newextupdt %p, freeblklst %p\n",
14824 	    TAILQ_FIRST(&inodedep->id_extupdt),
14825 	    TAILQ_FIRST(&inodedep->id_newextupdt),
14826 	    TAILQ_FIRST(&inodedep->id_freeblklst));
14827 	db_printf("    saveino %p, savedsize %jd, savedextsize %jd\n",
14828 	    inodedep->id_savedino1,
14829 	    (intmax_t)inodedep->id_savedsize,
14830 	    (intmax_t)inodedep->id_savedextsize);
14831 }
14832 
14833 static void
14834 newblk_print(struct newblk *nbp)
14835 {
14836 
14837 	worklist_print(&nbp->nb_list, 0);
14838 	db_printf("    newblkno %jd\n", (intmax_t)nbp->nb_newblkno);
14839 	db_printf("    jnewblk %p, bmsafemap %p, freefrag %p\n",
14840 	    &nbp->nb_jnewblk,
14841 	    &nbp->nb_bmsafemap,
14842 	    &nbp->nb_freefrag);
14843 	db_printf("    indirdeps %p, newdirblk %p, jwork %p\n",
14844 	    LIST_FIRST(&nbp->nb_indirdeps),
14845 	    LIST_FIRST(&nbp->nb_newdirblk),
14846 	    LIST_FIRST(&nbp->nb_jwork));
14847 }
14848 
14849 static void
14850 allocdirect_print(struct allocdirect *adp)
14851 {
14852 
14853 	newblk_print(&adp->ad_block);
14854 	db_printf("    oldblkno %jd, oldsize %ld, newsize %ld\n",
14855 	    adp->ad_oldblkno, adp->ad_oldsize, adp->ad_newsize);
14856 	db_printf("    offset %d, inodedep %p\n",
14857 	    adp->ad_offset, adp->ad_inodedep);
14858 }
14859 
14860 static void
14861 allocindir_print(struct allocindir *aip)
14862 {
14863 
14864 	newblk_print(&aip->ai_block);
14865 	db_printf("    oldblkno %jd, lbn %jd\n",
14866 	    (intmax_t)aip->ai_oldblkno, (intmax_t)aip->ai_lbn);
14867 	db_printf("    offset %d, indirdep %p\n",
14868 	    aip->ai_offset, aip->ai_indirdep);
14869 }
14870 
14871 static void
14872 mkdir_print(struct mkdir *mkdir)
14873 {
14874 
14875 	worklist_print(&mkdir->md_list, 0);
14876 	db_printf("    diradd %p, jaddref %p, buf %p\n",
14877 		mkdir->md_diradd, mkdir->md_jaddref, mkdir->md_buf);
14878 }
14879 
14880 DB_SHOW_COMMAND(sd_inodedep, db_show_sd_inodedep)
14881 {
14882 
14883 	if (have_addr == 0) {
14884 		db_printf("inodedep address required\n");
14885 		return;
14886 	}
14887 	inodedep_print((struct inodedep*)addr, 1);
14888 }
14889 
14890 DB_SHOW_COMMAND(sd_allinodedeps, db_show_sd_allinodedeps)
14891 {
14892 	struct inodedep_hashhead *inodedephd;
14893 	struct inodedep *inodedep;
14894 	struct ufsmount *ump;
14895 	int cnt;
14896 
14897 	if (have_addr == 0) {
14898 		db_printf("ufsmount address required\n");
14899 		return;
14900 	}
14901 	ump = (struct ufsmount *)addr;
14902 	for (cnt = 0; cnt < ump->inodedep_hash_size; cnt++) {
14903 		inodedephd = &ump->inodedep_hashtbl[cnt];
14904 		LIST_FOREACH(inodedep, inodedephd, id_hash) {
14905 			inodedep_print(inodedep, 0);
14906 		}
14907 	}
14908 }
14909 
14910 DB_SHOW_COMMAND(sd_worklist, db_show_sd_worklist)
14911 {
14912 
14913 	if (have_addr == 0) {
14914 		db_printf("worklist address required\n");
14915 		return;
14916 	}
14917 	worklist_print((struct worklist *)addr, 1);
14918 }
14919 
14920 DB_SHOW_COMMAND(sd_workhead, db_show_sd_workhead)
14921 {
14922 	struct worklist *wk;
14923 	struct workhead *wkhd;
14924 
14925 	if (have_addr == 0) {
14926 		db_printf("worklist address required "
14927 		    "(for example value in bp->b_dep)\n");
14928 		return;
14929 	}
14930 	/*
14931 	 * We often do not have the address of the worklist head but
14932 	 * instead a pointer to its first entry (e.g., we have the
14933 	 * contents of bp->b_dep rather than &bp->b_dep). But the back
14934 	 * pointer of bp->b_dep will point at the head of the list, so
14935 	 * we cheat and use that instead. If we are in the middle of
14936 	 * a list we will still get the same result, so nothing
14937 	 * unexpected will result.
14938 	 */
14939 	wk = (struct worklist *)addr;
14940 	if (wk == NULL)
14941 		return;
14942 	wkhd = (struct workhead *)wk->wk_list.le_prev;
14943 	LIST_FOREACH(wk, wkhd, wk_list) {
14944 		switch(wk->wk_type) {
14945 		case D_INODEDEP:
14946 			inodedep_print(WK_INODEDEP(wk), 0);
14947 			continue;
14948 		case D_ALLOCDIRECT:
14949 			allocdirect_print(WK_ALLOCDIRECT(wk));
14950 			continue;
14951 		case D_ALLOCINDIR:
14952 			allocindir_print(WK_ALLOCINDIR(wk));
14953 			continue;
14954 		case D_MKDIR:
14955 			mkdir_print(WK_MKDIR(wk));
14956 			continue;
14957 		default:
14958 			worklist_print(wk, 0);
14959 			continue;
14960 		}
14961 	}
14962 }
14963 
14964 DB_SHOW_COMMAND(sd_mkdir, db_show_sd_mkdir)
14965 {
14966 	if (have_addr == 0) {
14967 		db_printf("mkdir address required\n");
14968 		return;
14969 	}
14970 	mkdir_print((struct mkdir *)addr);
14971 }
14972 
14973 DB_SHOW_COMMAND(sd_mkdir_list, db_show_sd_mkdir_list)
14974 {
14975 	struct mkdirlist *mkdirlisthd;
14976 	struct mkdir *mkdir;
14977 
14978 	if (have_addr == 0) {
14979 		db_printf("mkdir listhead address required\n");
14980 		return;
14981 	}
14982 	mkdirlisthd = (struct mkdirlist *)addr;
14983 	LIST_FOREACH(mkdir, mkdirlisthd, md_mkdirs) {
14984 		mkdir_print(mkdir);
14985 		if (mkdir->md_diradd != NULL) {
14986 			db_printf("    ");
14987 			worklist_print(&mkdir->md_diradd->da_list, 0);
14988 		}
14989 		if (mkdir->md_jaddref != NULL) {
14990 			db_printf("    ");
14991 			worklist_print(&mkdir->md_jaddref->ja_list, 0);
14992 		}
14993 	}
14994 }
14995 
14996 DB_SHOW_COMMAND(sd_allocdirect, db_show_sd_allocdirect)
14997 {
14998 	if (have_addr == 0) {
14999 		db_printf("allocdirect address required\n");
15000 		return;
15001 	}
15002 	allocdirect_print((struct allocdirect *)addr);
15003 }
15004 
15005 DB_SHOW_COMMAND(sd_allocindir, db_show_sd_allocindir)
15006 {
15007 	if (have_addr == 0) {
15008 		db_printf("allocindir address required\n");
15009 		return;
15010 	}
15011 	allocindir_print((struct allocindir *)addr);
15012 }
15013 
15014 #endif /* DDB */
15015 
15016 #endif /* SOFTUPDATES */
15017