xref: /freebsd/sys/ufs/ffs/ffs_softdep.c (revision e28a4053)
1 /*-
2  * Copyright 1998, 2000 Marshall Kirk McKusick.
3  * Copyright 2009, 2010 Jeffrey W. Roberson <jeff@FreeBSD.org>
4  * All rights reserved.
5  *
6  * The soft updates code is derived from the appendix of a University
7  * of Michigan technical report (Gregory R. Ganger and Yale N. Patt,
8  * "Soft Updates: A Solution to the Metadata Update Problem in File
9  * Systems", CSE-TR-254-95, August 1995).
10  *
11  * Further information about soft updates can be obtained from:
12  *
13  *	Marshall Kirk McKusick		http://www.mckusick.com/softdep/
14  *	1614 Oxford Street		mckusick@mckusick.com
15  *	Berkeley, CA 94709-1608		+1-510-843-9542
16  *	USA
17  *
18  * Redistribution and use in source and binary forms, with or without
19  * modification, are permitted provided that the following conditions
20  * are met:
21  *
22  * 1. Redistributions of source code must retain the above copyright
23  *    notice, this list of conditions and the following disclaimer.
24  * 2. Redistributions in binary form must reproduce the above copyright
25  *    notice, this list of conditions and the following disclaimer in the
26  *    documentation and/or other materials provided with the distribution.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
29  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
30  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
31  * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
32  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
33  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
34  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
35  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
36  * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
37  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38  *
39  *	from: @(#)ffs_softdep.c	9.59 (McKusick) 6/21/00
40  */
41 
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD$");
44 
45 #include "opt_ffs.h"
46 #include "opt_ddb.h"
47 
48 /*
49  * For now we want the safety net that the DEBUG flag provides.
50  */
51 #ifndef DEBUG
52 #define DEBUG
53 #endif
54 
55 #include <sys/param.h>
56 #include <sys/kernel.h>
57 #include <sys/systm.h>
58 #include <sys/bio.h>
59 #include <sys/buf.h>
60 #include <sys/kdb.h>
61 #include <sys/kthread.h>
62 #include <sys/lock.h>
63 #include <sys/malloc.h>
64 #include <sys/mount.h>
65 #include <sys/mutex.h>
66 #include <sys/namei.h>
67 #include <sys/proc.h>
68 #include <sys/stat.h>
69 #include <sys/sysctl.h>
70 #include <sys/syslog.h>
71 #include <sys/vnode.h>
72 #include <sys/conf.h>
73 #include <ufs/ufs/dir.h>
74 #include <ufs/ufs/extattr.h>
75 #include <ufs/ufs/quota.h>
76 #include <ufs/ufs/inode.h>
77 #include <ufs/ufs/ufsmount.h>
78 #include <ufs/ffs/fs.h>
79 #include <ufs/ffs/softdep.h>
80 #include <ufs/ffs/ffs_extern.h>
81 #include <ufs/ufs/ufs_extern.h>
82 
83 #include <vm/vm.h>
84 
85 #include <ddb/ddb.h>
86 
87 #ifndef SOFTUPDATES
88 
89 int
90 softdep_flushfiles(oldmnt, flags, td)
91 	struct mount *oldmnt;
92 	int flags;
93 	struct thread *td;
94 {
95 
96 	panic("softdep_flushfiles called");
97 }
98 
99 int
100 softdep_mount(devvp, mp, fs, cred)
101 	struct vnode *devvp;
102 	struct mount *mp;
103 	struct fs *fs;
104 	struct ucred *cred;
105 {
106 
107 	return (0);
108 }
109 
110 void
111 softdep_initialize()
112 {
113 
114 	return;
115 }
116 
117 void
118 softdep_uninitialize()
119 {
120 
121 	return;
122 }
123 
124 void
125 softdep_unmount(mp)
126 	struct mount *mp;
127 {
128 
129 }
130 
131 void
132 softdep_setup_sbupdate(ump, fs, bp)
133 	struct ufsmount *ump;
134 	struct fs *fs;
135 	struct buf *bp;
136 {
137 }
138 
139 void
140 softdep_setup_inomapdep(bp, ip, newinum)
141 	struct buf *bp;
142 	struct inode *ip;
143 	ino_t newinum;
144 {
145 
146 	panic("softdep_setup_inomapdep called");
147 }
148 
149 void
150 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
151 	struct buf *bp;
152 	struct mount *mp;
153 	ufs2_daddr_t newblkno;
154 	int frags;
155 	int oldfrags;
156 {
157 
158 	panic("softdep_setup_blkmapdep called");
159 }
160 
161 void
162 softdep_setup_allocdirect(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
163 	struct inode *ip;
164 	ufs_lbn_t lbn;
165 	ufs2_daddr_t newblkno;
166 	ufs2_daddr_t oldblkno;
167 	long newsize;
168 	long oldsize;
169 	struct buf *bp;
170 {
171 
172 	panic("softdep_setup_allocdirect called");
173 }
174 
175 void
176 softdep_setup_allocext(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
177 	struct inode *ip;
178 	ufs_lbn_t lbn;
179 	ufs2_daddr_t newblkno;
180 	ufs2_daddr_t oldblkno;
181 	long newsize;
182 	long oldsize;
183 	struct buf *bp;
184 {
185 
186 	panic("softdep_setup_allocext called");
187 }
188 
189 void
190 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
191 	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(nbp, ip, bp, ptrno, newblkno)
205 	struct buf *nbp;
206 	struct inode *ip;
207 	struct buf *bp;
208 	int ptrno;
209 	ufs2_daddr_t newblkno;
210 {
211 
212 	panic("softdep_setup_allocindir_meta called");
213 }
214 
215 void
216 softdep_setup_freeblocks(ip, length, flags)
217 	struct inode *ip;
218 	off_t length;
219 	int flags;
220 {
221 
222 	panic("softdep_setup_freeblocks called");
223 }
224 
225 void
226 softdep_freefile(pvp, ino, mode)
227 		struct vnode *pvp;
228 		ino_t ino;
229 		int mode;
230 {
231 
232 	panic("softdep_freefile called");
233 }
234 
235 int
236 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
237 	struct buf *bp;
238 	struct inode *dp;
239 	off_t diroffset;
240 	ino_t newinum;
241 	struct buf *newdirbp;
242 	int isnewblk;
243 {
244 
245 	panic("softdep_setup_directory_add called");
246 }
247 
248 void
249 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
250 	struct buf *bp;
251 	struct inode *dp;
252 	caddr_t base;
253 	caddr_t oldloc;
254 	caddr_t newloc;
255 	int entrysize;
256 {
257 
258 	panic("softdep_change_directoryentry_offset called");
259 }
260 
261 void
262 softdep_setup_remove(bp, dp, ip, isrmdir)
263 	struct buf *bp;
264 	struct inode *dp;
265 	struct inode *ip;
266 	int isrmdir;
267 {
268 
269 	panic("softdep_setup_remove called");
270 }
271 
272 void
273 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
274 	struct buf *bp;
275 	struct inode *dp;
276 	struct inode *ip;
277 	ino_t newinum;
278 	int isrmdir;
279 {
280 
281 	panic("softdep_setup_directory_change called");
282 }
283 
284 void *
285 softdep_setup_trunc(vp, length, flags)
286 	struct vnode *vp;
287 	off_t length;
288 	int flags;
289 {
290 
291 	panic("%s called", __FUNCTION__);
292 
293 	return (NULL);
294 }
295 
296 int
297 softdep_complete_trunc(vp, cookie)
298 	struct vnode *vp;
299 	void *cookie;
300 {
301 
302 	panic("%s called", __FUNCTION__);
303 
304 	return (0);
305 }
306 
307 void
308 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
309 	struct mount *mp;
310 	struct buf *bp;
311 	ufs2_daddr_t blkno;
312 	int frags;
313 	struct workhead *wkhd;
314 {
315 
316 	panic("%s called", __FUNCTION__);
317 }
318 
319 void
320 softdep_setup_inofree(mp, bp, ino, wkhd)
321 	struct mount *mp;
322 	struct buf *bp;
323 	ino_t ino;
324 	struct workhead *wkhd;
325 {
326 
327 	panic("%s called", __FUNCTION__);
328 }
329 
330 void
331 softdep_setup_unlink(dp, ip)
332 	struct inode *dp;
333 	struct inode *ip;
334 {
335 
336 	panic("%s called", __FUNCTION__);
337 }
338 
339 void
340 softdep_setup_link(dp, ip)
341 	struct inode *dp;
342 	struct inode *ip;
343 {
344 
345 	panic("%s called", __FUNCTION__);
346 }
347 
348 void
349 softdep_revert_link(dp, ip)
350 	struct inode *dp;
351 	struct inode *ip;
352 {
353 
354 	panic("%s called", __FUNCTION__);
355 }
356 
357 void
358 softdep_setup_rmdir(dp, ip)
359 	struct inode *dp;
360 	struct inode *ip;
361 {
362 
363 	panic("%s called", __FUNCTION__);
364 }
365 
366 void
367 softdep_revert_rmdir(dp, ip)
368 	struct inode *dp;
369 	struct inode *ip;
370 {
371 
372 	panic("%s called", __FUNCTION__);
373 }
374 
375 void
376 softdep_setup_create(dp, ip)
377 	struct inode *dp;
378 	struct inode *ip;
379 {
380 
381 	panic("%s called", __FUNCTION__);
382 }
383 
384 void
385 softdep_revert_create(dp, ip)
386 	struct inode *dp;
387 	struct inode *ip;
388 {
389 
390 	panic("%s called", __FUNCTION__);
391 }
392 
393 void
394 softdep_setup_mkdir(dp, ip)
395 	struct inode *dp;
396 	struct inode *ip;
397 {
398 
399 	panic("%s called", __FUNCTION__);
400 }
401 
402 void
403 softdep_revert_mkdir(dp, ip)
404 	struct inode *dp;
405 	struct inode *ip;
406 {
407 
408 	panic("%s called", __FUNCTION__);
409 }
410 
411 void
412 softdep_setup_dotdot_link(dp, ip)
413 	struct inode *dp;
414 	struct inode *ip;
415 {
416 
417 	panic("%s called", __FUNCTION__);
418 }
419 
420 int
421 softdep_prealloc(vp, waitok)
422 	struct vnode *vp;
423 	int waitok;
424 {
425 
426 	panic("%s called", __FUNCTION__);
427 
428 	return (0);
429 }
430 
431 int
432 softdep_journal_lookup(mp, vpp)
433 	struct mount *mp;
434 	struct vnode **vpp;
435 {
436 
437 	return (ENOENT);
438 }
439 
440 void
441 softdep_change_linkcnt(ip)
442 	struct inode *ip;
443 {
444 
445 	panic("softdep_change_linkcnt called");
446 }
447 
448 void
449 softdep_load_inodeblock(ip)
450 	struct inode *ip;
451 {
452 
453 	panic("softdep_load_inodeblock called");
454 }
455 
456 void
457 softdep_update_inodeblock(ip, bp, waitfor)
458 	struct inode *ip;
459 	struct buf *bp;
460 	int waitfor;
461 {
462 
463 	panic("softdep_update_inodeblock called");
464 }
465 
466 int
467 softdep_fsync(vp)
468 	struct vnode *vp;	/* the "in_core" copy of the inode */
469 {
470 
471 	return (0);
472 }
473 
474 void
475 softdep_fsync_mountdev(vp)
476 	struct vnode *vp;
477 {
478 
479 	return;
480 }
481 
482 int
483 softdep_flushworklist(oldmnt, countp, td)
484 	struct mount *oldmnt;
485 	int *countp;
486 	struct thread *td;
487 {
488 
489 	*countp = 0;
490 	return (0);
491 }
492 
493 int
494 softdep_sync_metadata(struct vnode *vp)
495 {
496 
497 	return (0);
498 }
499 
500 int
501 softdep_slowdown(vp)
502 	struct vnode *vp;
503 {
504 
505 	panic("softdep_slowdown called");
506 }
507 
508 void
509 softdep_releasefile(ip)
510 	struct inode *ip;	/* inode with the zero effective link count */
511 {
512 
513 	panic("softdep_releasefile called");
514 }
515 
516 int
517 softdep_request_cleanup(fs, vp)
518 	struct fs *fs;
519 	struct vnode *vp;
520 {
521 
522 	return (0);
523 }
524 
525 int
526 softdep_check_suspend(struct mount *mp,
527 		      struct vnode *devvp,
528 		      int softdep_deps,
529 		      int softdep_accdeps,
530 		      int secondary_writes,
531 		      int secondary_accwrites)
532 {
533 	struct bufobj *bo;
534 	int error;
535 
536 	(void) softdep_deps,
537 	(void) softdep_accdeps;
538 
539 	bo = &devvp->v_bufobj;
540 	ASSERT_BO_LOCKED(bo);
541 
542 	MNT_ILOCK(mp);
543 	while (mp->mnt_secondary_writes != 0) {
544 		BO_UNLOCK(bo);
545 		msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
546 		    (PUSER - 1) | PDROP, "secwr", 0);
547 		BO_LOCK(bo);
548 		MNT_ILOCK(mp);
549 	}
550 
551 	/*
552 	 * Reasons for needing more work before suspend:
553 	 * - Dirty buffers on devvp.
554 	 * - Secondary writes occurred after start of vnode sync loop
555 	 */
556 	error = 0;
557 	if (bo->bo_numoutput > 0 ||
558 	    bo->bo_dirty.bv_cnt > 0 ||
559 	    secondary_writes != 0 ||
560 	    mp->mnt_secondary_writes != 0 ||
561 	    secondary_accwrites != mp->mnt_secondary_accwrites)
562 		error = EAGAIN;
563 	BO_UNLOCK(bo);
564 	return (error);
565 }
566 
567 void
568 softdep_get_depcounts(struct mount *mp,
569 		      int *softdepactivep,
570 		      int *softdepactiveaccp)
571 {
572 	(void) mp;
573 	*softdepactivep = 0;
574 	*softdepactiveaccp = 0;
575 }
576 
577 #else
578 /*
579  * These definitions need to be adapted to the system to which
580  * this file is being ported.
581  */
582 
583 #define M_SOFTDEP_FLAGS	(M_WAITOK)
584 
585 #define	D_PAGEDEP	0
586 #define	D_INODEDEP	1
587 #define	D_BMSAFEMAP	2
588 #define	D_NEWBLK	3
589 #define	D_ALLOCDIRECT	4
590 #define	D_INDIRDEP	5
591 #define	D_ALLOCINDIR	6
592 #define	D_FREEFRAG	7
593 #define	D_FREEBLKS	8
594 #define	D_FREEFILE	9
595 #define	D_DIRADD	10
596 #define	D_MKDIR		11
597 #define	D_DIRREM	12
598 #define	D_NEWDIRBLK	13
599 #define	D_FREEWORK	14
600 #define	D_FREEDEP	15
601 #define	D_JADDREF	16
602 #define	D_JREMREF	17
603 #define	D_JMVREF	18
604 #define	D_JNEWBLK	19
605 #define	D_JFREEBLK	20
606 #define	D_JFREEFRAG	21
607 #define	D_JSEG		22
608 #define	D_JSEGDEP	23
609 #define	D_SBDEP		24
610 #define	D_JTRUNC	25
611 #define	D_LAST		D_JTRUNC
612 
613 unsigned long dep_current[D_LAST + 1];
614 unsigned long dep_total[D_LAST + 1];
615 
616 
617 SYSCTL_NODE(_debug, OID_AUTO, softdep, CTLFLAG_RW, 0, "soft updates stats");
618 SYSCTL_NODE(_debug_softdep, OID_AUTO, total, CTLFLAG_RW, 0,
619     "total dependencies allocated");
620 SYSCTL_NODE(_debug_softdep, OID_AUTO, current, CTLFLAG_RW, 0,
621     "current dependencies allocated");
622 
623 #define	SOFTDEP_TYPE(type, str, long)					\
624     static MALLOC_DEFINE(M_ ## type, #str, long);			\
625     SYSCTL_LONG(_debug_softdep_total, OID_AUTO, str, CTLFLAG_RD,	\
626 	&dep_total[D_ ## type], 0, "");					\
627     SYSCTL_LONG(_debug_softdep_current, OID_AUTO, str, CTLFLAG_RD, 	\
628 	&dep_current[D_ ## type], 0, "");
629 
630 SOFTDEP_TYPE(PAGEDEP, pagedep, "File page dependencies");
631 SOFTDEP_TYPE(INODEDEP, inodedep, "Inode dependencies");
632 SOFTDEP_TYPE(BMSAFEMAP, bmsafemap,
633     "Block or frag allocated from cyl group map");
634 SOFTDEP_TYPE(NEWBLK, newblk, "New block or frag allocation dependency");
635 SOFTDEP_TYPE(ALLOCDIRECT, allocdirect, "Block or frag dependency for an inode");
636 SOFTDEP_TYPE(INDIRDEP, indirdep, "Indirect block dependencies");
637 SOFTDEP_TYPE(ALLOCINDIR, allocindir, "Block dependency for an indirect block");
638 SOFTDEP_TYPE(FREEFRAG, freefrag, "Previously used frag for an inode");
639 SOFTDEP_TYPE(FREEBLKS, freeblks, "Blocks freed from an inode");
640 SOFTDEP_TYPE(FREEFILE, freefile, "Inode deallocated");
641 SOFTDEP_TYPE(DIRADD, diradd, "New directory entry");
642 SOFTDEP_TYPE(MKDIR, mkdir, "New directory");
643 SOFTDEP_TYPE(DIRREM, dirrem, "Directory entry deleted");
644 SOFTDEP_TYPE(NEWDIRBLK, newdirblk, "Unclaimed new directory block");
645 SOFTDEP_TYPE(FREEWORK, freework, "free an inode block");
646 SOFTDEP_TYPE(FREEDEP, freedep, "track a block free");
647 SOFTDEP_TYPE(JADDREF, jaddref, "Journal inode ref add");
648 SOFTDEP_TYPE(JREMREF, jremref, "Journal inode ref remove");
649 SOFTDEP_TYPE(JMVREF, jmvref, "Journal inode ref move");
650 SOFTDEP_TYPE(JNEWBLK, jnewblk, "Journal new block");
651 SOFTDEP_TYPE(JFREEBLK, jfreeblk, "Journal free block");
652 SOFTDEP_TYPE(JFREEFRAG, jfreefrag, "Journal free frag");
653 SOFTDEP_TYPE(JSEG, jseg, "Journal segment");
654 SOFTDEP_TYPE(JSEGDEP, jsegdep, "Journal segment complete");
655 SOFTDEP_TYPE(SBDEP, sbdep, "Superblock write dependency");
656 SOFTDEP_TYPE(JTRUNC, jtrunc, "Journal inode truncation");
657 
658 static MALLOC_DEFINE(M_SAVEDINO, "savedino", "Saved inodes");
659 static MALLOC_DEFINE(M_JBLOCKS, "jblocks", "Journal block locations");
660 
661 /*
662  * translate from workitem type to memory type
663  * MUST match the defines above, such that memtype[D_XXX] == M_XXX
664  */
665 static struct malloc_type *memtype[] = {
666 	M_PAGEDEP,
667 	M_INODEDEP,
668 	M_BMSAFEMAP,
669 	M_NEWBLK,
670 	M_ALLOCDIRECT,
671 	M_INDIRDEP,
672 	M_ALLOCINDIR,
673 	M_FREEFRAG,
674 	M_FREEBLKS,
675 	M_FREEFILE,
676 	M_DIRADD,
677 	M_MKDIR,
678 	M_DIRREM,
679 	M_NEWDIRBLK,
680 	M_FREEWORK,
681 	M_FREEDEP,
682 	M_JADDREF,
683 	M_JREMREF,
684 	M_JMVREF,
685 	M_JNEWBLK,
686 	M_JFREEBLK,
687 	M_JFREEFRAG,
688 	M_JSEG,
689 	M_JSEGDEP,
690 	M_SBDEP,
691 	M_JTRUNC
692 };
693 
694 #define DtoM(type) (memtype[type])
695 
696 /*
697  * Names of malloc types.
698  */
699 #define TYPENAME(type)  \
700 	((unsigned)(type) <= D_LAST ? memtype[type]->ks_shortdesc : "???")
701 /*
702  * End system adaptation definitions.
703  */
704 
705 #define	DOTDOT_OFFSET	offsetof(struct dirtemplate, dotdot_ino)
706 #define	DOT_OFFSET	offsetof(struct dirtemplate, dot_ino)
707 
708 /*
709  * Forward declarations.
710  */
711 struct inodedep_hashhead;
712 struct newblk_hashhead;
713 struct pagedep_hashhead;
714 struct bmsafemap_hashhead;
715 
716 /*
717  * Internal function prototypes.
718  */
719 static	void softdep_error(char *, int);
720 static	void drain_output(struct vnode *);
721 static	struct buf *getdirtybuf(struct buf *, struct mtx *, int);
722 static	void clear_remove(struct thread *);
723 static	void clear_inodedeps(struct thread *);
724 static	void unlinked_inodedep(struct mount *, struct inodedep *);
725 static	void clear_unlinked_inodedep(struct inodedep *);
726 static	struct inodedep *first_unlinked_inodedep(struct ufsmount *);
727 static	int flush_pagedep_deps(struct vnode *, struct mount *,
728 	    struct diraddhd *);
729 static	void free_pagedep(struct pagedep *);
730 static	int flush_newblk_dep(struct vnode *, struct mount *, ufs_lbn_t);
731 static	int flush_inodedep_deps(struct mount *, ino_t);
732 static	int flush_deplist(struct allocdirectlst *, int, int *);
733 static	int handle_written_filepage(struct pagedep *, struct buf *);
734 static	int handle_written_sbdep(struct sbdep *, struct buf *);
735 static	void initiate_write_sbdep(struct sbdep *);
736 static  void diradd_inode_written(struct diradd *, struct inodedep *);
737 static	int handle_written_indirdep(struct indirdep *, struct buf *,
738 	    struct buf**);
739 static	int handle_written_inodeblock(struct inodedep *, struct buf *);
740 static	int handle_written_bmsafemap(struct bmsafemap *, struct buf *);
741 static	void handle_written_jaddref(struct jaddref *);
742 static	void handle_written_jremref(struct jremref *);
743 static	void handle_written_jseg(struct jseg *, struct buf *);
744 static	void handle_written_jnewblk(struct jnewblk *);
745 static	void handle_written_jfreeblk(struct jfreeblk *);
746 static	void handle_written_jfreefrag(struct jfreefrag *);
747 static	void complete_jseg(struct jseg *);
748 static	void jseg_write(struct fs *, struct jblocks *, struct jseg *,
749 	    uint8_t *);
750 static	void jaddref_write(struct jaddref *, struct jseg *, uint8_t *);
751 static	void jremref_write(struct jremref *, struct jseg *, uint8_t *);
752 static	void jmvref_write(struct jmvref *, struct jseg *, uint8_t *);
753 static	void jtrunc_write(struct jtrunc *, struct jseg *, uint8_t *);
754 static	void jnewblk_write(struct jnewblk *, struct jseg *, uint8_t *);
755 static	void jfreeblk_write(struct jfreeblk *, struct jseg *, uint8_t *);
756 static	void jfreefrag_write(struct jfreefrag *, struct jseg *, uint8_t *);
757 static	inline void inoref_write(struct inoref *, struct jseg *,
758 	    struct jrefrec *);
759 static	void handle_allocdirect_partdone(struct allocdirect *,
760 	    struct workhead *);
761 static	void cancel_newblk(struct newblk *, struct workhead *);
762 static	void indirdep_complete(struct indirdep *);
763 static	void handle_allocindir_partdone(struct allocindir *);
764 static	void initiate_write_filepage(struct pagedep *, struct buf *);
765 static	void initiate_write_indirdep(struct indirdep*, struct buf *);
766 static	void handle_written_mkdir(struct mkdir *, int);
767 static	void initiate_write_bmsafemap(struct bmsafemap *, struct buf *);
768 static	void initiate_write_inodeblock_ufs1(struct inodedep *, struct buf *);
769 static	void initiate_write_inodeblock_ufs2(struct inodedep *, struct buf *);
770 static	void handle_workitem_freefile(struct freefile *);
771 static	void handle_workitem_remove(struct dirrem *, struct vnode *);
772 static	struct dirrem *newdirrem(struct buf *, struct inode *,
773 	    struct inode *, int, struct dirrem **);
774 static	void cancel_indirdep(struct indirdep *, struct buf *, struct inodedep *,
775 	    struct freeblks *);
776 static	void free_indirdep(struct indirdep *);
777 static	void free_diradd(struct diradd *, struct workhead *);
778 static	void merge_diradd(struct inodedep *, struct diradd *);
779 static	void complete_diradd(struct diradd *);
780 static	struct diradd *diradd_lookup(struct pagedep *, int);
781 static	struct jremref *cancel_diradd_dotdot(struct inode *, struct dirrem *,
782 	    struct jremref *);
783 static	struct jremref *cancel_mkdir_dotdot(struct inode *, struct dirrem *,
784 	    struct jremref *);
785 static	void cancel_diradd(struct diradd *, struct dirrem *, struct jremref *,
786 	    struct jremref *, struct jremref *);
787 static	void dirrem_journal(struct dirrem *, struct jremref *, struct jremref *,
788 	    struct jremref *);
789 static	void cancel_allocindir(struct allocindir *, struct inodedep *,
790 	    struct freeblks *);
791 static	void complete_mkdir(struct mkdir *);
792 static	void free_newdirblk(struct newdirblk *);
793 static	void free_jremref(struct jremref *);
794 static	void free_jaddref(struct jaddref *);
795 static	void free_jsegdep(struct jsegdep *);
796 static	void free_jseg(struct jseg *);
797 static	void free_jnewblk(struct jnewblk *);
798 static	void free_jfreeblk(struct jfreeblk *);
799 static	void free_jfreefrag(struct jfreefrag *);
800 static	void free_freedep(struct freedep *);
801 static	void journal_jremref(struct dirrem *, struct jremref *,
802 	    struct inodedep *);
803 static	void cancel_jnewblk(struct jnewblk *, struct workhead *);
804 static	int cancel_jaddref(struct jaddref *, struct inodedep *,
805 	    struct workhead *);
806 static	void cancel_jfreefrag(struct jfreefrag *);
807 static	void indir_trunc(struct freework *, ufs2_daddr_t, ufs_lbn_t);
808 static	int deallocate_dependencies(struct buf *, struct inodedep *,
809 	    struct freeblks *);
810 static	void free_newblk(struct newblk *);
811 static	void cancel_allocdirect(struct allocdirectlst *,
812 	    struct allocdirect *, struct freeblks *, int);
813 static	int check_inode_unwritten(struct inodedep *);
814 static	int free_inodedep(struct inodedep *);
815 static	void freework_freeblock(struct freework *);
816 static	void handle_workitem_freeblocks(struct freeblks *, int);
817 static	void handle_complete_freeblocks(struct freeblks *);
818 static	void handle_workitem_indirblk(struct freework *);
819 static	void handle_written_freework(struct freework *);
820 static	void merge_inode_lists(struct allocdirectlst *,struct allocdirectlst *);
821 static	void setup_allocindir_phase2(struct buf *, struct inode *,
822 	    struct inodedep *, struct allocindir *, ufs_lbn_t);
823 static	struct allocindir *newallocindir(struct inode *, int, ufs2_daddr_t,
824 	    ufs2_daddr_t, ufs_lbn_t);
825 static	void handle_workitem_freefrag(struct freefrag *);
826 static	struct freefrag *newfreefrag(struct inode *, ufs2_daddr_t, long,
827 	    ufs_lbn_t);
828 static	void allocdirect_merge(struct allocdirectlst *,
829 	    struct allocdirect *, struct allocdirect *);
830 static	struct freefrag *allocindir_merge(struct allocindir *,
831 	    struct allocindir *);
832 static	int bmsafemap_find(struct bmsafemap_hashhead *, struct mount *, int,
833 	    struct bmsafemap **);
834 static	struct bmsafemap *bmsafemap_lookup(struct mount *, struct buf *,
835 	    int cg);
836 static	int newblk_find(struct newblk_hashhead *, struct mount *, ufs2_daddr_t,
837 	    int, struct newblk **);
838 static	int newblk_lookup(struct mount *, ufs2_daddr_t, int, struct newblk **);
839 static	int inodedep_find(struct inodedep_hashhead *, struct fs *, ino_t,
840 	    struct inodedep **);
841 static	int inodedep_lookup(struct mount *, ino_t, int, struct inodedep **);
842 static	int pagedep_lookup(struct mount *, ino_t, ufs_lbn_t, int,
843 	    struct pagedep **);
844 static	int pagedep_find(struct pagedep_hashhead *, ino_t, ufs_lbn_t,
845 	    struct mount *mp, int, struct pagedep **);
846 static	void pause_timer(void *);
847 static	int request_cleanup(struct mount *, int);
848 static	int process_worklist_item(struct mount *, int);
849 static	void process_removes(struct vnode *);
850 static	void jwork_move(struct workhead *, struct workhead *);
851 static	void add_to_worklist(struct worklist *, int);
852 static	void remove_from_worklist(struct worklist *);
853 static	void softdep_flush(void);
854 static	int softdep_speedup(void);
855 static	void worklist_speedup(void);
856 static	int journal_mount(struct mount *, struct fs *, struct ucred *);
857 static	void journal_unmount(struct mount *);
858 static	int journal_space(struct ufsmount *, int);
859 static	void journal_suspend(struct ufsmount *);
860 static	int journal_unsuspend(struct ufsmount *ump);
861 static	void softdep_prelink(struct vnode *, struct vnode *);
862 static	void add_to_journal(struct worklist *);
863 static	void remove_from_journal(struct worklist *);
864 static	void softdep_process_journal(struct mount *, int);
865 static	struct jremref *newjremref(struct dirrem *, struct inode *,
866 	    struct inode *ip, off_t, nlink_t);
867 static	struct jaddref *newjaddref(struct inode *, ino_t, off_t, int16_t,
868 	    uint16_t);
869 static inline void newinoref(struct inoref *, ino_t, ino_t, off_t, nlink_t,
870 	    uint16_t);
871 static inline struct jsegdep *inoref_jseg(struct inoref *);
872 static	struct jmvref *newjmvref(struct inode *, ino_t, off_t, off_t);
873 static	struct jfreeblk *newjfreeblk(struct freeblks *, ufs_lbn_t,
874 	    ufs2_daddr_t, int);
875 static	struct jfreefrag *newjfreefrag(struct freefrag *, struct inode *,
876 	    ufs2_daddr_t, long, ufs_lbn_t);
877 static	struct freework *newfreework(struct freeblks *, struct freework *,
878 	    ufs_lbn_t, ufs2_daddr_t, int, int);
879 static	void jwait(struct worklist *wk);
880 static	struct inodedep *inodedep_lookup_ip(struct inode *);
881 static	int bmsafemap_rollbacks(struct bmsafemap *);
882 static	struct freefile *handle_bufwait(struct inodedep *, struct workhead *);
883 static	void handle_jwork(struct workhead *);
884 static	struct mkdir *setup_newdir(struct diradd *, ino_t, ino_t, struct buf *,
885 	    struct mkdir **);
886 static	struct jblocks *jblocks_create(void);
887 static	ufs2_daddr_t jblocks_alloc(struct jblocks *, int, int *);
888 static	void jblocks_free(struct jblocks *, struct mount *, int);
889 static	void jblocks_destroy(struct jblocks *);
890 static	void jblocks_add(struct jblocks *, ufs2_daddr_t, int);
891 
892 /*
893  * Exported softdep operations.
894  */
895 static	void softdep_disk_io_initiation(struct buf *);
896 static	void softdep_disk_write_complete(struct buf *);
897 static	void softdep_deallocate_dependencies(struct buf *);
898 static	int softdep_count_dependencies(struct buf *bp, int);
899 
900 static struct mtx lk;
901 MTX_SYSINIT(softdep_lock, &lk, "Softdep Lock", MTX_DEF);
902 
903 #define TRY_ACQUIRE_LOCK(lk)		mtx_trylock(lk)
904 #define ACQUIRE_LOCK(lk)		mtx_lock(lk)
905 #define FREE_LOCK(lk)			mtx_unlock(lk)
906 
907 #define	BUF_AREC(bp)			lockallowrecurse(&(bp)->b_lock)
908 #define	BUF_NOREC(bp)			lockdisablerecurse(&(bp)->b_lock)
909 
910 /*
911  * Worklist queue management.
912  * These routines require that the lock be held.
913  */
914 #ifndef /* NOT */ DEBUG
915 #define WORKLIST_INSERT(head, item) do {	\
916 	(item)->wk_state |= ONWORKLIST;		\
917 	LIST_INSERT_HEAD(head, item, wk_list);	\
918 } while (0)
919 #define WORKLIST_REMOVE(item) do {		\
920 	(item)->wk_state &= ~ONWORKLIST;	\
921 	LIST_REMOVE(item, wk_list);		\
922 } while (0)
923 #define WORKLIST_INSERT_UNLOCKED	WORKLIST_INSERT
924 #define WORKLIST_REMOVE_UNLOCKED	WORKLIST_REMOVE
925 
926 #else /* DEBUG */
927 static	void worklist_insert(struct workhead *, struct worklist *, int);
928 static	void worklist_remove(struct worklist *, int);
929 
930 #define WORKLIST_INSERT(head, item) worklist_insert(head, item, 1)
931 #define WORKLIST_INSERT_UNLOCKED(head, item) worklist_insert(head, item, 0)
932 #define WORKLIST_REMOVE(item) worklist_remove(item, 1)
933 #define WORKLIST_REMOVE_UNLOCKED(item) worklist_remove(item, 0)
934 
935 static void
936 worklist_insert(head, item, locked)
937 	struct workhead *head;
938 	struct worklist *item;
939 	int locked;
940 {
941 
942 	if (locked)
943 		mtx_assert(&lk, MA_OWNED);
944 	if (item->wk_state & ONWORKLIST)
945 		panic("worklist_insert: %p %s(0x%X) already on list",
946 		    item, TYPENAME(item->wk_type), item->wk_state);
947 	item->wk_state |= ONWORKLIST;
948 	LIST_INSERT_HEAD(head, item, wk_list);
949 }
950 
951 static void
952 worklist_remove(item, locked)
953 	struct worklist *item;
954 	int locked;
955 {
956 
957 	if (locked)
958 		mtx_assert(&lk, MA_OWNED);
959 	if ((item->wk_state & ONWORKLIST) == 0)
960 		panic("worklist_remove: %p %s(0x%X) not on list",
961 		    item, TYPENAME(item->wk_type), item->wk_state);
962 	item->wk_state &= ~ONWORKLIST;
963 	LIST_REMOVE(item, wk_list);
964 }
965 #endif /* DEBUG */
966 
967 /*
968  * Merge two jsegdeps keeping only the oldest one as newer references
969  * can't be discarded until after older references.
970  */
971 static inline struct jsegdep *
972 jsegdep_merge(struct jsegdep *one, struct jsegdep *two)
973 {
974 	struct jsegdep *swp;
975 
976 	if (two == NULL)
977 		return (one);
978 
979 	if (one->jd_seg->js_seq > two->jd_seg->js_seq) {
980 		swp = one;
981 		one = two;
982 		two = swp;
983 	}
984 	WORKLIST_REMOVE(&two->jd_list);
985 	free_jsegdep(two);
986 
987 	return (one);
988 }
989 
990 /*
991  * If two freedeps are compatible free one to reduce list size.
992  */
993 static inline struct freedep *
994 freedep_merge(struct freedep *one, struct freedep *two)
995 {
996 	if (two == NULL)
997 		return (one);
998 
999 	if (one->fd_freework == two->fd_freework) {
1000 		WORKLIST_REMOVE(&two->fd_list);
1001 		free_freedep(two);
1002 	}
1003 	return (one);
1004 }
1005 
1006 /*
1007  * Move journal work from one list to another.  Duplicate freedeps and
1008  * jsegdeps are coalesced to keep the lists as small as possible.
1009  */
1010 static void
1011 jwork_move(dst, src)
1012 	struct workhead *dst;
1013 	struct workhead *src;
1014 {
1015 	struct freedep *freedep;
1016 	struct jsegdep *jsegdep;
1017 	struct worklist *wkn;
1018 	struct worklist *wk;
1019 
1020 	KASSERT(dst != src,
1021 	    ("jwork_move: dst == src"));
1022 	freedep = NULL;
1023 	jsegdep = NULL;
1024 	LIST_FOREACH_SAFE(wk, dst, wk_list, wkn) {
1025 		if (wk->wk_type == D_JSEGDEP)
1026 			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1027 		if (wk->wk_type == D_FREEDEP)
1028 			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1029 	}
1030 
1031 	mtx_assert(&lk, MA_OWNED);
1032 	while ((wk = LIST_FIRST(src)) != NULL) {
1033 		WORKLIST_REMOVE(wk);
1034 		WORKLIST_INSERT(dst, wk);
1035 		if (wk->wk_type == D_JSEGDEP) {
1036 			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1037 			continue;
1038 		}
1039 		if (wk->wk_type == D_FREEDEP)
1040 			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1041 	}
1042 }
1043 
1044 /*
1045  * Routines for tracking and managing workitems.
1046  */
1047 static	void workitem_free(struct worklist *, int);
1048 static	void workitem_alloc(struct worklist *, int, struct mount *);
1049 
1050 #define	WORKITEM_FREE(item, type) workitem_free((struct worklist *)(item), (type))
1051 
1052 static void
1053 workitem_free(item, type)
1054 	struct worklist *item;
1055 	int type;
1056 {
1057 	struct ufsmount *ump;
1058 	mtx_assert(&lk, MA_OWNED);
1059 
1060 #ifdef DEBUG
1061 	if (item->wk_state & ONWORKLIST)
1062 		panic("workitem_free: %s(0x%X) still on list",
1063 		    TYPENAME(item->wk_type), item->wk_state);
1064 	if (item->wk_type != type)
1065 		panic("workitem_free: type mismatch %s != %s",
1066 		    TYPENAME(item->wk_type), TYPENAME(type));
1067 #endif
1068 	ump = VFSTOUFS(item->wk_mp);
1069 	if (--ump->softdep_deps == 0 && ump->softdep_req)
1070 		wakeup(&ump->softdep_deps);
1071 	dep_current[type]--;
1072 	free(item, DtoM(type));
1073 }
1074 
1075 static void
1076 workitem_alloc(item, type, mp)
1077 	struct worklist *item;
1078 	int type;
1079 	struct mount *mp;
1080 {
1081 	item->wk_type = type;
1082 	item->wk_mp = mp;
1083 	item->wk_state = 0;
1084 	ACQUIRE_LOCK(&lk);
1085 	dep_current[type]++;
1086 	dep_total[type]++;
1087 	VFSTOUFS(mp)->softdep_deps++;
1088 	VFSTOUFS(mp)->softdep_accdeps++;
1089 	FREE_LOCK(&lk);
1090 }
1091 
1092 /*
1093  * Workitem queue management
1094  */
1095 static int max_softdeps;	/* maximum number of structs before slowdown */
1096 static int maxindirdeps = 50;	/* max number of indirdeps before slowdown */
1097 static int tickdelay = 2;	/* number of ticks to pause during slowdown */
1098 static int proc_waiting;	/* tracks whether we have a timeout posted */
1099 static int *stat_countp;	/* statistic to count in proc_waiting timeout */
1100 static struct callout softdep_callout;
1101 static int req_pending;
1102 static int req_clear_inodedeps;	/* syncer process flush some inodedeps */
1103 #define FLUSH_INODES		1
1104 static int req_clear_remove;	/* syncer process flush some freeblks */
1105 #define FLUSH_REMOVE		2
1106 #define FLUSH_REMOVE_WAIT	3
1107 static long num_freeblkdep;	/* number of freeblks workitems allocated */
1108 
1109 /*
1110  * runtime statistics
1111  */
1112 static int stat_worklist_push;	/* number of worklist cleanups */
1113 static int stat_blk_limit_push;	/* number of times block limit neared */
1114 static int stat_ino_limit_push;	/* number of times inode limit neared */
1115 static int stat_blk_limit_hit;	/* number of times block slowdown imposed */
1116 static int stat_ino_limit_hit;	/* number of times inode slowdown imposed */
1117 static int stat_sync_limit_hit;	/* number of synchronous slowdowns imposed */
1118 static int stat_indir_blk_ptrs;	/* bufs redirtied as indir ptrs not written */
1119 static int stat_inode_bitmap;	/* bufs redirtied as inode bitmap not written */
1120 static int stat_direct_blk_ptrs;/* bufs redirtied as direct ptrs not written */
1121 static int stat_dir_entry;	/* bufs redirtied as dir entry cannot write */
1122 static int stat_jaddref;	/* bufs redirtied as ino bitmap can not write */
1123 static int stat_jnewblk;	/* bufs redirtied as blk bitmap can not write */
1124 static int stat_journal_min;	/* Times hit journal min threshold */
1125 static int stat_journal_low;	/* Times hit journal low threshold */
1126 static int stat_journal_wait;	/* Times blocked in jwait(). */
1127 static int stat_jwait_filepage;	/* Times blocked in jwait() for filepage. */
1128 static int stat_jwait_freeblks;	/* Times blocked in jwait() for freeblks. */
1129 static int stat_jwait_inode;	/* Times blocked in jwait() for inodes. */
1130 static int stat_jwait_newblk;	/* Times blocked in jwait() for newblks. */
1131 
1132 SYSCTL_INT(_debug_softdep, OID_AUTO, max_softdeps, CTLFLAG_RW,
1133     &max_softdeps, 0, "");
1134 SYSCTL_INT(_debug_softdep, OID_AUTO, tickdelay, CTLFLAG_RW,
1135     &tickdelay, 0, "");
1136 SYSCTL_INT(_debug_softdep, OID_AUTO, maxindirdeps, CTLFLAG_RW,
1137     &maxindirdeps, 0, "");
1138 SYSCTL_INT(_debug_softdep, OID_AUTO, worklist_push, CTLFLAG_RW,
1139     &stat_worklist_push, 0,"");
1140 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_push, CTLFLAG_RW,
1141     &stat_blk_limit_push, 0,"");
1142 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_push, CTLFLAG_RW,
1143     &stat_ino_limit_push, 0,"");
1144 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_hit, CTLFLAG_RW,
1145     &stat_blk_limit_hit, 0, "");
1146 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_hit, CTLFLAG_RW,
1147     &stat_ino_limit_hit, 0, "");
1148 SYSCTL_INT(_debug_softdep, OID_AUTO, sync_limit_hit, CTLFLAG_RW,
1149     &stat_sync_limit_hit, 0, "");
1150 SYSCTL_INT(_debug_softdep, OID_AUTO, indir_blk_ptrs, CTLFLAG_RW,
1151     &stat_indir_blk_ptrs, 0, "");
1152 SYSCTL_INT(_debug_softdep, OID_AUTO, inode_bitmap, CTLFLAG_RW,
1153     &stat_inode_bitmap, 0, "");
1154 SYSCTL_INT(_debug_softdep, OID_AUTO, direct_blk_ptrs, CTLFLAG_RW,
1155     &stat_direct_blk_ptrs, 0, "");
1156 SYSCTL_INT(_debug_softdep, OID_AUTO, dir_entry, CTLFLAG_RW,
1157     &stat_dir_entry, 0, "");
1158 SYSCTL_INT(_debug_softdep, OID_AUTO, jaddref_rollback, CTLFLAG_RW,
1159     &stat_jaddref, 0, "");
1160 SYSCTL_INT(_debug_softdep, OID_AUTO, jnewblk_rollback, CTLFLAG_RW,
1161     &stat_jnewblk, 0, "");
1162 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_low, CTLFLAG_RW,
1163     &stat_journal_low, 0, "");
1164 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_min, CTLFLAG_RW,
1165     &stat_journal_min, 0, "");
1166 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_wait, CTLFLAG_RW,
1167     &stat_journal_wait, 0, "");
1168 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_filepage, CTLFLAG_RW,
1169     &stat_jwait_filepage, 0, "");
1170 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_freeblks, CTLFLAG_RW,
1171     &stat_jwait_freeblks, 0, "");
1172 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_inode, CTLFLAG_RW,
1173     &stat_jwait_inode, 0, "");
1174 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_newblk, CTLFLAG_RW,
1175     &stat_jwait_newblk, 0, "");
1176 
1177 SYSCTL_DECL(_vfs_ffs);
1178 
1179 LIST_HEAD(bmsafemap_hashhead, bmsafemap) *bmsafemap_hashtbl;
1180 static u_long	bmsafemap_hash;	/* size of hash table - 1 */
1181 
1182 static int compute_summary_at_mount = 0;	/* Whether to recompute the summary at mount time */
1183 SYSCTL_INT(_vfs_ffs, OID_AUTO, compute_summary_at_mount, CTLFLAG_RW,
1184 	   &compute_summary_at_mount, 0, "Recompute summary at mount");
1185 
1186 static struct proc *softdepproc;
1187 static struct kproc_desc softdep_kp = {
1188 	"softdepflush",
1189 	softdep_flush,
1190 	&softdepproc
1191 };
1192 SYSINIT(sdproc, SI_SUB_KTHREAD_UPDATE, SI_ORDER_ANY, kproc_start,
1193     &softdep_kp);
1194 
1195 static void
1196 softdep_flush(void)
1197 {
1198 	struct mount *nmp;
1199 	struct mount *mp;
1200 	struct ufsmount *ump;
1201 	struct thread *td;
1202 	int remaining;
1203 	int progress;
1204 	int vfslocked;
1205 
1206 	td = curthread;
1207 	td->td_pflags |= TDP_NORUNNINGBUF;
1208 
1209 	for (;;) {
1210 		kproc_suspend_check(softdepproc);
1211 		vfslocked = VFS_LOCK_GIANT((struct mount *)NULL);
1212 		ACQUIRE_LOCK(&lk);
1213 		/*
1214 		 * If requested, try removing inode or removal dependencies.
1215 		 */
1216 		if (req_clear_inodedeps) {
1217 			clear_inodedeps(td);
1218 			req_clear_inodedeps -= 1;
1219 			wakeup_one(&proc_waiting);
1220 		}
1221 		if (req_clear_remove) {
1222 			clear_remove(td);
1223 			req_clear_remove -= 1;
1224 			wakeup_one(&proc_waiting);
1225 		}
1226 		FREE_LOCK(&lk);
1227 		VFS_UNLOCK_GIANT(vfslocked);
1228 		remaining = progress = 0;
1229 		mtx_lock(&mountlist_mtx);
1230 		for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp)  {
1231 			nmp = TAILQ_NEXT(mp, mnt_list);
1232 			if ((mp->mnt_flag & MNT_SOFTDEP) == 0)
1233 				continue;
1234 			if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK))
1235 				continue;
1236 			vfslocked = VFS_LOCK_GIANT(mp);
1237 			progress += softdep_process_worklist(mp, 0);
1238 			ump = VFSTOUFS(mp);
1239 			remaining += ump->softdep_on_worklist -
1240 				ump->softdep_on_worklist_inprogress;
1241 			VFS_UNLOCK_GIANT(vfslocked);
1242 			mtx_lock(&mountlist_mtx);
1243 			nmp = TAILQ_NEXT(mp, mnt_list);
1244 			vfs_unbusy(mp);
1245 		}
1246 		mtx_unlock(&mountlist_mtx);
1247 		if (remaining && progress)
1248 			continue;
1249 		ACQUIRE_LOCK(&lk);
1250 		if (!req_pending)
1251 			msleep(&req_pending, &lk, PVM, "sdflush", hz);
1252 		req_pending = 0;
1253 		FREE_LOCK(&lk);
1254 	}
1255 }
1256 
1257 static void
1258 worklist_speedup(void)
1259 {
1260 	mtx_assert(&lk, MA_OWNED);
1261 	if (req_pending == 0) {
1262 		req_pending = 1;
1263 		wakeup(&req_pending);
1264 	}
1265 }
1266 
1267 static int
1268 softdep_speedup(void)
1269 {
1270 
1271 	worklist_speedup();
1272 	bd_speedup();
1273 	return speedup_syncer();
1274 }
1275 
1276 /*
1277  * Add an item to the end of the work queue.
1278  * This routine requires that the lock be held.
1279  * This is the only routine that adds items to the list.
1280  * The following routine is the only one that removes items
1281  * and does so in order from first to last.
1282  */
1283 static void
1284 add_to_worklist(wk, nodelay)
1285 	struct worklist *wk;
1286 	int nodelay;
1287 {
1288 	struct ufsmount *ump;
1289 
1290 	mtx_assert(&lk, MA_OWNED);
1291 	ump = VFSTOUFS(wk->wk_mp);
1292 	if (wk->wk_state & ONWORKLIST)
1293 		panic("add_to_worklist: %s(0x%X) already on list",
1294 		    TYPENAME(wk->wk_type), wk->wk_state);
1295 	wk->wk_state |= ONWORKLIST;
1296 	if (LIST_EMPTY(&ump->softdep_workitem_pending))
1297 		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1298 	else
1299 		LIST_INSERT_AFTER(ump->softdep_worklist_tail, wk, wk_list);
1300 	ump->softdep_worklist_tail = wk;
1301 	ump->softdep_on_worklist += 1;
1302 	if (nodelay)
1303 		worklist_speedup();
1304 }
1305 
1306 /*
1307  * Remove the item to be processed. If we are removing the last
1308  * item on the list, we need to recalculate the tail pointer.
1309  */
1310 static void
1311 remove_from_worklist(wk)
1312 	struct worklist *wk;
1313 {
1314 	struct ufsmount *ump;
1315 	struct worklist *wkend;
1316 
1317 	ump = VFSTOUFS(wk->wk_mp);
1318 	WORKLIST_REMOVE(wk);
1319 	if (wk == ump->softdep_worklist_tail) {
1320 		LIST_FOREACH(wkend, &ump->softdep_workitem_pending, wk_list)
1321 			if (LIST_NEXT(wkend, wk_list) == NULL)
1322 				break;
1323 		ump->softdep_worklist_tail = wkend;
1324 	}
1325 	ump->softdep_on_worklist -= 1;
1326 }
1327 
1328 /*
1329  * Process that runs once per second to handle items in the background queue.
1330  *
1331  * Note that we ensure that everything is done in the order in which they
1332  * appear in the queue. The code below depends on this property to ensure
1333  * that blocks of a file are freed before the inode itself is freed. This
1334  * ordering ensures that no new <vfsid, inum, lbn> triples will be generated
1335  * until all the old ones have been purged from the dependency lists.
1336  */
1337 int
1338 softdep_process_worklist(mp, full)
1339 	struct mount *mp;
1340 	int full;
1341 {
1342 	struct thread *td = curthread;
1343 	int cnt, matchcnt, loopcount;
1344 	struct ufsmount *ump;
1345 	long starttime;
1346 
1347 	KASSERT(mp != NULL, ("softdep_process_worklist: NULL mp"));
1348 	/*
1349 	 * Record the process identifier of our caller so that we can give
1350 	 * this process preferential treatment in request_cleanup below.
1351 	 */
1352 	matchcnt = 0;
1353 	ump = VFSTOUFS(mp);
1354 	ACQUIRE_LOCK(&lk);
1355 	loopcount = 1;
1356 	starttime = time_second;
1357 	softdep_process_journal(mp, full?MNT_WAIT:0);
1358 	while (ump->softdep_on_worklist > 0) {
1359 		if ((cnt = process_worklist_item(mp, LK_NOWAIT)) == -1)
1360 			break;
1361 		else
1362 			matchcnt += cnt;
1363 		/*
1364 		 * If requested, try removing inode or removal dependencies.
1365 		 */
1366 		if (req_clear_inodedeps) {
1367 			clear_inodedeps(td);
1368 			req_clear_inodedeps -= 1;
1369 			wakeup_one(&proc_waiting);
1370 		}
1371 		if (req_clear_remove) {
1372 			clear_remove(td);
1373 			req_clear_remove -= 1;
1374 			wakeup_one(&proc_waiting);
1375 		}
1376 		/*
1377 		 * We do not generally want to stop for buffer space, but if
1378 		 * we are really being a buffer hog, we will stop and wait.
1379 		 */
1380 		if (loopcount++ % 128 == 0) {
1381 			FREE_LOCK(&lk);
1382 			uio_yield();
1383 			bwillwrite();
1384 			ACQUIRE_LOCK(&lk);
1385 		}
1386 		/*
1387 		 * Never allow processing to run for more than one
1388 		 * second. Otherwise the other mountpoints may get
1389 		 * excessively backlogged.
1390 		 */
1391 		if (!full && starttime != time_second)
1392 			break;
1393 	}
1394 	if (full == 0)
1395 		journal_unsuspend(ump);
1396 	FREE_LOCK(&lk);
1397 	return (matchcnt);
1398 }
1399 
1400 /*
1401  * Process all removes associated with a vnode if we are running out of
1402  * journal space.  Any other process which attempts to flush these will
1403  * be unable as we have the vnodes locked.
1404  */
1405 static void
1406 process_removes(vp)
1407 	struct vnode *vp;
1408 {
1409 	struct inodedep *inodedep;
1410 	struct dirrem *dirrem;
1411 	struct mount *mp;
1412 	ino_t inum;
1413 
1414 	mtx_assert(&lk, MA_OWNED);
1415 
1416 	mp = vp->v_mount;
1417 	inum = VTOI(vp)->i_number;
1418 	for (;;) {
1419 		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1420 			return;
1421 		LIST_FOREACH(dirrem, &inodedep->id_dirremhd, dm_inonext)
1422 			if ((dirrem->dm_state & (COMPLETE | ONWORKLIST)) ==
1423 			    (COMPLETE | ONWORKLIST))
1424 				break;
1425 		if (dirrem == NULL)
1426 			return;
1427 		/*
1428 		 * If another thread is trying to lock this vnode it will
1429 		 * fail but we must wait for it to do so before we can
1430 		 * proceed.
1431 		 */
1432 		if (dirrem->dm_state & INPROGRESS) {
1433 			dirrem->dm_state |= IOWAITING;
1434 			msleep(&dirrem->dm_list, &lk, PVM, "pwrwait", 0);
1435 			continue;
1436 		}
1437 		remove_from_worklist(&dirrem->dm_list);
1438 		FREE_LOCK(&lk);
1439 		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1440 			panic("process_removes: suspended filesystem");
1441 		handle_workitem_remove(dirrem, vp);
1442 		vn_finished_secondary_write(mp);
1443 		ACQUIRE_LOCK(&lk);
1444 	}
1445 }
1446 
1447 /*
1448  * Process one item on the worklist.
1449  */
1450 static int
1451 process_worklist_item(mp, flags)
1452 	struct mount *mp;
1453 	int flags;
1454 {
1455 	struct worklist *wk;
1456 	struct ufsmount *ump;
1457 	struct vnode *vp;
1458 	int matchcnt = 0;
1459 
1460 	mtx_assert(&lk, MA_OWNED);
1461 	KASSERT(mp != NULL, ("process_worklist_item: NULL mp"));
1462 	/*
1463 	 * If we are being called because of a process doing a
1464 	 * copy-on-write, then it is not safe to write as we may
1465 	 * recurse into the copy-on-write routine.
1466 	 */
1467 	if (curthread->td_pflags & TDP_COWINPROGRESS)
1468 		return (-1);
1469 	/*
1470 	 * Normally we just process each item on the worklist in order.
1471 	 * However, if we are in a situation where we cannot lock any
1472 	 * inodes, we have to skip over any dirrem requests whose
1473 	 * vnodes are resident and locked.
1474 	 */
1475 	vp = NULL;
1476 	ump = VFSTOUFS(mp);
1477 	LIST_FOREACH(wk, &ump->softdep_workitem_pending, wk_list) {
1478 		if (wk->wk_state & INPROGRESS)
1479 			continue;
1480 		if ((flags & LK_NOWAIT) == 0 || wk->wk_type != D_DIRREM)
1481 			break;
1482 		wk->wk_state |= INPROGRESS;
1483 		ump->softdep_on_worklist_inprogress++;
1484 		FREE_LOCK(&lk);
1485 		ffs_vgetf(mp, WK_DIRREM(wk)->dm_oldinum,
1486 		    LK_NOWAIT | LK_EXCLUSIVE, &vp, FFSV_FORCEINSMQ);
1487 		ACQUIRE_LOCK(&lk);
1488 		if (wk->wk_state & IOWAITING) {
1489 			wk->wk_state &= ~IOWAITING;
1490 			wakeup(wk);
1491 		}
1492 		wk->wk_state &= ~INPROGRESS;
1493 		ump->softdep_on_worklist_inprogress--;
1494 		if (vp != NULL)
1495 			break;
1496 	}
1497 	if (wk == 0)
1498 		return (-1);
1499 	remove_from_worklist(wk);
1500 	FREE_LOCK(&lk);
1501 	if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1502 		panic("process_worklist_item: suspended filesystem");
1503 	matchcnt++;
1504 	switch (wk->wk_type) {
1505 
1506 	case D_DIRREM:
1507 		/* removal of a directory entry */
1508 		handle_workitem_remove(WK_DIRREM(wk), vp);
1509 		if (vp)
1510 			vput(vp);
1511 		break;
1512 
1513 	case D_FREEBLKS:
1514 		/* releasing blocks and/or fragments from a file */
1515 		handle_workitem_freeblocks(WK_FREEBLKS(wk), flags & LK_NOWAIT);
1516 		break;
1517 
1518 	case D_FREEFRAG:
1519 		/* releasing a fragment when replaced as a file grows */
1520 		handle_workitem_freefrag(WK_FREEFRAG(wk));
1521 		break;
1522 
1523 	case D_FREEFILE:
1524 		/* releasing an inode when its link count drops to 0 */
1525 		handle_workitem_freefile(WK_FREEFILE(wk));
1526 		break;
1527 
1528 	case D_FREEWORK:
1529 		/* Final block in an indirect was freed. */
1530 		handle_workitem_indirblk(WK_FREEWORK(wk));
1531 		break;
1532 
1533 	default:
1534 		panic("%s_process_worklist: Unknown type %s",
1535 		    "softdep", TYPENAME(wk->wk_type));
1536 		/* NOTREACHED */
1537 	}
1538 	vn_finished_secondary_write(mp);
1539 	ACQUIRE_LOCK(&lk);
1540 	return (matchcnt);
1541 }
1542 
1543 /*
1544  * Move dependencies from one buffer to another.
1545  */
1546 int
1547 softdep_move_dependencies(oldbp, newbp)
1548 	struct buf *oldbp;
1549 	struct buf *newbp;
1550 {
1551 	struct worklist *wk, *wktail;
1552 	int dirty;
1553 
1554 	dirty = 0;
1555 	wktail = NULL;
1556 	ACQUIRE_LOCK(&lk);
1557 	while ((wk = LIST_FIRST(&oldbp->b_dep)) != NULL) {
1558 		LIST_REMOVE(wk, wk_list);
1559 		if (wk->wk_type == D_BMSAFEMAP &&
1560 		    bmsafemap_rollbacks(WK_BMSAFEMAP(wk)))
1561 			dirty = 1;
1562 		if (wktail == 0)
1563 			LIST_INSERT_HEAD(&newbp->b_dep, wk, wk_list);
1564 		else
1565 			LIST_INSERT_AFTER(wktail, wk, wk_list);
1566 		wktail = wk;
1567 	}
1568 	FREE_LOCK(&lk);
1569 
1570 	return (dirty);
1571 }
1572 
1573 /*
1574  * Purge the work list of all items associated with a particular mount point.
1575  */
1576 int
1577 softdep_flushworklist(oldmnt, countp, td)
1578 	struct mount *oldmnt;
1579 	int *countp;
1580 	struct thread *td;
1581 {
1582 	struct vnode *devvp;
1583 	int count, error = 0;
1584 	struct ufsmount *ump;
1585 
1586 	/*
1587 	 * Alternately flush the block device associated with the mount
1588 	 * point and process any dependencies that the flushing
1589 	 * creates. We continue until no more worklist dependencies
1590 	 * are found.
1591 	 */
1592 	*countp = 0;
1593 	ump = VFSTOUFS(oldmnt);
1594 	devvp = ump->um_devvp;
1595 	while ((count = softdep_process_worklist(oldmnt, 1)) > 0) {
1596 		*countp += count;
1597 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1598 		error = VOP_FSYNC(devvp, MNT_WAIT, td);
1599 		VOP_UNLOCK(devvp, 0);
1600 		if (error)
1601 			break;
1602 	}
1603 	return (error);
1604 }
1605 
1606 int
1607 softdep_waitidle(struct mount *mp)
1608 {
1609 	struct ufsmount *ump;
1610 	int error;
1611 	int i;
1612 
1613 	ump = VFSTOUFS(mp);
1614 	ACQUIRE_LOCK(&lk);
1615 	for (i = 0; i < 10 && ump->softdep_deps; i++) {
1616 		ump->softdep_req = 1;
1617 		if (ump->softdep_on_worklist)
1618 			panic("softdep_waitidle: work added after flush.");
1619 		msleep(&ump->softdep_deps, &lk, PVM, "softdeps", 1);
1620 	}
1621 	ump->softdep_req = 0;
1622 	FREE_LOCK(&lk);
1623 	error = 0;
1624 	if (i == 10) {
1625 		error = EBUSY;
1626 		printf("softdep_waitidle: Failed to flush worklist for %p\n",
1627 		    mp);
1628 	}
1629 
1630 	return (error);
1631 }
1632 
1633 /*
1634  * Flush all vnodes and worklist items associated with a specified mount point.
1635  */
1636 int
1637 softdep_flushfiles(oldmnt, flags, td)
1638 	struct mount *oldmnt;
1639 	int flags;
1640 	struct thread *td;
1641 {
1642 	int error, depcount, loopcnt, retry_flush_count, retry;
1643 
1644 	loopcnt = 10;
1645 	retry_flush_count = 3;
1646 retry_flush:
1647 	error = 0;
1648 
1649 	/*
1650 	 * Alternately flush the vnodes associated with the mount
1651 	 * point and process any dependencies that the flushing
1652 	 * creates. In theory, this loop can happen at most twice,
1653 	 * but we give it a few extra just to be sure.
1654 	 */
1655 	for (; loopcnt > 0; loopcnt--) {
1656 		/*
1657 		 * Do another flush in case any vnodes were brought in
1658 		 * as part of the cleanup operations.
1659 		 */
1660 		if ((error = ffs_flushfiles(oldmnt, flags, td)) != 0)
1661 			break;
1662 		if ((error = softdep_flushworklist(oldmnt, &depcount, td)) != 0 ||
1663 		    depcount == 0)
1664 			break;
1665 	}
1666 	/*
1667 	 * If we are unmounting then it is an error to fail. If we
1668 	 * are simply trying to downgrade to read-only, then filesystem
1669 	 * activity can keep us busy forever, so we just fail with EBUSY.
1670 	 */
1671 	if (loopcnt == 0) {
1672 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT)
1673 			panic("softdep_flushfiles: looping");
1674 		error = EBUSY;
1675 	}
1676 	if (!error)
1677 		error = softdep_waitidle(oldmnt);
1678 	if (!error) {
1679 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT) {
1680 			retry = 0;
1681 			MNT_ILOCK(oldmnt);
1682 			KASSERT((oldmnt->mnt_kern_flag & MNTK_NOINSMNTQ) != 0,
1683 			    ("softdep_flushfiles: !MNTK_NOINSMNTQ"));
1684 			if (oldmnt->mnt_nvnodelistsize > 0) {
1685 				if (--retry_flush_count > 0) {
1686 					retry = 1;
1687 					loopcnt = 3;
1688 				} else
1689 					error = EBUSY;
1690 			}
1691 			MNT_IUNLOCK(oldmnt);
1692 			if (retry)
1693 				goto retry_flush;
1694 		}
1695 	}
1696 	return (error);
1697 }
1698 
1699 /*
1700  * Structure hashing.
1701  *
1702  * There are three types of structures that can be looked up:
1703  *	1) pagedep structures identified by mount point, inode number,
1704  *	   and logical block.
1705  *	2) inodedep structures identified by mount point and inode number.
1706  *	3) newblk structures identified by mount point and
1707  *	   physical block number.
1708  *
1709  * The "pagedep" and "inodedep" dependency structures are hashed
1710  * separately from the file blocks and inodes to which they correspond.
1711  * This separation helps when the in-memory copy of an inode or
1712  * file block must be replaced. It also obviates the need to access
1713  * an inode or file page when simply updating (or de-allocating)
1714  * dependency structures. Lookup of newblk structures is needed to
1715  * find newly allocated blocks when trying to associate them with
1716  * their allocdirect or allocindir structure.
1717  *
1718  * The lookup routines optionally create and hash a new instance when
1719  * an existing entry is not found.
1720  */
1721 #define DEPALLOC	0x0001	/* allocate structure if lookup fails */
1722 #define NODELAY		0x0002	/* cannot do background work */
1723 
1724 /*
1725  * Structures and routines associated with pagedep caching.
1726  */
1727 LIST_HEAD(pagedep_hashhead, pagedep) *pagedep_hashtbl;
1728 u_long	pagedep_hash;		/* size of hash table - 1 */
1729 #define	PAGEDEP_HASH(mp, inum, lbn) \
1730 	(&pagedep_hashtbl[((((register_t)(mp)) >> 13) + (inum) + (lbn)) & \
1731 	    pagedep_hash])
1732 
1733 static int
1734 pagedep_find(pagedephd, ino, lbn, mp, flags, pagedeppp)
1735 	struct pagedep_hashhead *pagedephd;
1736 	ino_t ino;
1737 	ufs_lbn_t lbn;
1738 	struct mount *mp;
1739 	int flags;
1740 	struct pagedep **pagedeppp;
1741 {
1742 	struct pagedep *pagedep;
1743 
1744 	LIST_FOREACH(pagedep, pagedephd, pd_hash)
1745 		if (ino == pagedep->pd_ino &&
1746 		    lbn == pagedep->pd_lbn &&
1747 		    mp == pagedep->pd_list.wk_mp)
1748 			break;
1749 	if (pagedep) {
1750 		*pagedeppp = pagedep;
1751 		if ((flags & DEPALLOC) != 0 &&
1752 		    (pagedep->pd_state & ONWORKLIST) == 0)
1753 			return (0);
1754 		return (1);
1755 	}
1756 	*pagedeppp = NULL;
1757 	return (0);
1758 }
1759 /*
1760  * Look up a pagedep. Return 1 if found, 0 if not found or found
1761  * when asked to allocate but not associated with any buffer.
1762  * If not found, allocate if DEPALLOC flag is passed.
1763  * Found or allocated entry is returned in pagedeppp.
1764  * This routine must be called with splbio interrupts blocked.
1765  */
1766 static int
1767 pagedep_lookup(mp, ino, lbn, flags, pagedeppp)
1768 	struct mount *mp;
1769 	ino_t ino;
1770 	ufs_lbn_t lbn;
1771 	int flags;
1772 	struct pagedep **pagedeppp;
1773 {
1774 	struct pagedep *pagedep;
1775 	struct pagedep_hashhead *pagedephd;
1776 	int ret;
1777 	int i;
1778 
1779 	mtx_assert(&lk, MA_OWNED);
1780 	pagedephd = PAGEDEP_HASH(mp, ino, lbn);
1781 
1782 	ret = pagedep_find(pagedephd, ino, lbn, mp, flags, pagedeppp);
1783 	if (*pagedeppp || (flags & DEPALLOC) == 0)
1784 		return (ret);
1785 	FREE_LOCK(&lk);
1786 	pagedep = malloc(sizeof(struct pagedep),
1787 	    M_PAGEDEP, M_SOFTDEP_FLAGS|M_ZERO);
1788 	workitem_alloc(&pagedep->pd_list, D_PAGEDEP, mp);
1789 	ACQUIRE_LOCK(&lk);
1790 	ret = pagedep_find(pagedephd, ino, lbn, mp, flags, pagedeppp);
1791 	if (*pagedeppp) {
1792 		WORKITEM_FREE(pagedep, D_PAGEDEP);
1793 		return (ret);
1794 	}
1795 	pagedep->pd_ino = ino;
1796 	pagedep->pd_lbn = lbn;
1797 	LIST_INIT(&pagedep->pd_dirremhd);
1798 	LIST_INIT(&pagedep->pd_pendinghd);
1799 	for (i = 0; i < DAHASHSZ; i++)
1800 		LIST_INIT(&pagedep->pd_diraddhd[i]);
1801 	LIST_INSERT_HEAD(pagedephd, pagedep, pd_hash);
1802 	*pagedeppp = pagedep;
1803 	return (0);
1804 }
1805 
1806 /*
1807  * Structures and routines associated with inodedep caching.
1808  */
1809 LIST_HEAD(inodedep_hashhead, inodedep) *inodedep_hashtbl;
1810 static u_long	inodedep_hash;	/* size of hash table - 1 */
1811 static long	num_inodedep;	/* number of inodedep allocated */
1812 #define	INODEDEP_HASH(fs, inum) \
1813       (&inodedep_hashtbl[((((register_t)(fs)) >> 13) + (inum)) & inodedep_hash])
1814 
1815 static int
1816 inodedep_find(inodedephd, fs, inum, inodedeppp)
1817 	struct inodedep_hashhead *inodedephd;
1818 	struct fs *fs;
1819 	ino_t inum;
1820 	struct inodedep **inodedeppp;
1821 {
1822 	struct inodedep *inodedep;
1823 
1824 	LIST_FOREACH(inodedep, inodedephd, id_hash)
1825 		if (inum == inodedep->id_ino && fs == inodedep->id_fs)
1826 			break;
1827 	if (inodedep) {
1828 		*inodedeppp = inodedep;
1829 		return (1);
1830 	}
1831 	*inodedeppp = NULL;
1832 
1833 	return (0);
1834 }
1835 /*
1836  * Look up an inodedep. Return 1 if found, 0 if not found.
1837  * If not found, allocate if DEPALLOC flag is passed.
1838  * Found or allocated entry is returned in inodedeppp.
1839  * This routine must be called with splbio interrupts blocked.
1840  */
1841 static int
1842 inodedep_lookup(mp, inum, flags, inodedeppp)
1843 	struct mount *mp;
1844 	ino_t inum;
1845 	int flags;
1846 	struct inodedep **inodedeppp;
1847 {
1848 	struct inodedep *inodedep;
1849 	struct inodedep_hashhead *inodedephd;
1850 	struct fs *fs;
1851 
1852 	mtx_assert(&lk, MA_OWNED);
1853 	fs = VFSTOUFS(mp)->um_fs;
1854 	inodedephd = INODEDEP_HASH(fs, inum);
1855 
1856 	if (inodedep_find(inodedephd, fs, inum, inodedeppp))
1857 		return (1);
1858 	if ((flags & DEPALLOC) == 0)
1859 		return (0);
1860 	/*
1861 	 * If we are over our limit, try to improve the situation.
1862 	 */
1863 	if (num_inodedep > max_softdeps && (flags & NODELAY) == 0)
1864 		request_cleanup(mp, FLUSH_INODES);
1865 	FREE_LOCK(&lk);
1866 	inodedep = malloc(sizeof(struct inodedep),
1867 		M_INODEDEP, M_SOFTDEP_FLAGS);
1868 	workitem_alloc(&inodedep->id_list, D_INODEDEP, mp);
1869 	ACQUIRE_LOCK(&lk);
1870 	if (inodedep_find(inodedephd, fs, inum, inodedeppp)) {
1871 		WORKITEM_FREE(inodedep, D_INODEDEP);
1872 		return (1);
1873 	}
1874 	num_inodedep += 1;
1875 	inodedep->id_fs = fs;
1876 	inodedep->id_ino = inum;
1877 	inodedep->id_state = ALLCOMPLETE;
1878 	inodedep->id_nlinkdelta = 0;
1879 	inodedep->id_savedino1 = NULL;
1880 	inodedep->id_savedsize = -1;
1881 	inodedep->id_savedextsize = -1;
1882 	inodedep->id_savednlink = -1;
1883 	inodedep->id_bmsafemap = NULL;
1884 	inodedep->id_mkdiradd = NULL;
1885 	LIST_INIT(&inodedep->id_dirremhd);
1886 	LIST_INIT(&inodedep->id_pendinghd);
1887 	LIST_INIT(&inodedep->id_inowait);
1888 	LIST_INIT(&inodedep->id_bufwait);
1889 	TAILQ_INIT(&inodedep->id_inoreflst);
1890 	TAILQ_INIT(&inodedep->id_inoupdt);
1891 	TAILQ_INIT(&inodedep->id_newinoupdt);
1892 	TAILQ_INIT(&inodedep->id_extupdt);
1893 	TAILQ_INIT(&inodedep->id_newextupdt);
1894 	LIST_INSERT_HEAD(inodedephd, inodedep, id_hash);
1895 	*inodedeppp = inodedep;
1896 	return (0);
1897 }
1898 
1899 /*
1900  * Structures and routines associated with newblk caching.
1901  */
1902 LIST_HEAD(newblk_hashhead, newblk) *newblk_hashtbl;
1903 u_long	newblk_hash;		/* size of hash table - 1 */
1904 #define	NEWBLK_HASH(fs, inum) \
1905 	(&newblk_hashtbl[((((register_t)(fs)) >> 13) + (inum)) & newblk_hash])
1906 
1907 static int
1908 newblk_find(newblkhd, mp, newblkno, flags, newblkpp)
1909 	struct newblk_hashhead *newblkhd;
1910 	struct mount *mp;
1911 	ufs2_daddr_t newblkno;
1912 	int flags;
1913 	struct newblk **newblkpp;
1914 {
1915 	struct newblk *newblk;
1916 
1917 	LIST_FOREACH(newblk, newblkhd, nb_hash) {
1918 		if (newblkno != newblk->nb_newblkno)
1919 			continue;
1920 		if (mp != newblk->nb_list.wk_mp)
1921 			continue;
1922 		/*
1923 		 * If we're creating a new dependency don't match those that
1924 		 * have already been converted to allocdirects.  This is for
1925 		 * a frag extend.
1926 		 */
1927 		if ((flags & DEPALLOC) && newblk->nb_list.wk_type != D_NEWBLK)
1928 			continue;
1929 		break;
1930 	}
1931 	if (newblk) {
1932 		*newblkpp = newblk;
1933 		return (1);
1934 	}
1935 	*newblkpp = NULL;
1936 	return (0);
1937 }
1938 
1939 /*
1940  * Look up a newblk. Return 1 if found, 0 if not found.
1941  * If not found, allocate if DEPALLOC flag is passed.
1942  * Found or allocated entry is returned in newblkpp.
1943  */
1944 static int
1945 newblk_lookup(mp, newblkno, flags, newblkpp)
1946 	struct mount *mp;
1947 	ufs2_daddr_t newblkno;
1948 	int flags;
1949 	struct newblk **newblkpp;
1950 {
1951 	struct newblk *newblk;
1952 	struct newblk_hashhead *newblkhd;
1953 
1954 	newblkhd = NEWBLK_HASH(VFSTOUFS(mp)->um_fs, newblkno);
1955 	if (newblk_find(newblkhd, mp, newblkno, flags, newblkpp))
1956 		return (1);
1957 	if ((flags & DEPALLOC) == 0)
1958 		return (0);
1959 	FREE_LOCK(&lk);
1960 	newblk = malloc(sizeof(union allblk), M_NEWBLK,
1961 	    M_SOFTDEP_FLAGS | M_ZERO);
1962 	workitem_alloc(&newblk->nb_list, D_NEWBLK, mp);
1963 	ACQUIRE_LOCK(&lk);
1964 	if (newblk_find(newblkhd, mp, newblkno, flags, newblkpp)) {
1965 		WORKITEM_FREE(newblk, D_NEWBLK);
1966 		return (1);
1967 	}
1968 	newblk->nb_freefrag = NULL;
1969 	LIST_INIT(&newblk->nb_indirdeps);
1970 	LIST_INIT(&newblk->nb_newdirblk);
1971 	LIST_INIT(&newblk->nb_jwork);
1972 	newblk->nb_state = ATTACHED;
1973 	newblk->nb_newblkno = newblkno;
1974 	LIST_INSERT_HEAD(newblkhd, newblk, nb_hash);
1975 	*newblkpp = newblk;
1976 	return (0);
1977 }
1978 
1979 /*
1980  * Executed during filesystem system initialization before
1981  * mounting any filesystems.
1982  */
1983 void
1984 softdep_initialize()
1985 {
1986 
1987 	LIST_INIT(&mkdirlisthd);
1988 	max_softdeps = desiredvnodes * 4;
1989 	pagedep_hashtbl = hashinit(desiredvnodes / 5, M_PAGEDEP, &pagedep_hash);
1990 	inodedep_hashtbl = hashinit(desiredvnodes, M_INODEDEP, &inodedep_hash);
1991 	newblk_hashtbl = hashinit(desiredvnodes / 5,  M_NEWBLK, &newblk_hash);
1992 	bmsafemap_hashtbl = hashinit(1024, M_BMSAFEMAP, &bmsafemap_hash);
1993 
1994 	/* initialise bioops hack */
1995 	bioops.io_start = softdep_disk_io_initiation;
1996 	bioops.io_complete = softdep_disk_write_complete;
1997 	bioops.io_deallocate = softdep_deallocate_dependencies;
1998 	bioops.io_countdeps = softdep_count_dependencies;
1999 
2000 	/* Initialize the callout with an mtx. */
2001 	callout_init_mtx(&softdep_callout, &lk, 0);
2002 }
2003 
2004 /*
2005  * Executed after all filesystems have been unmounted during
2006  * filesystem module unload.
2007  */
2008 void
2009 softdep_uninitialize()
2010 {
2011 
2012 	callout_drain(&softdep_callout);
2013 	hashdestroy(pagedep_hashtbl, M_PAGEDEP, pagedep_hash);
2014 	hashdestroy(inodedep_hashtbl, M_INODEDEP, inodedep_hash);
2015 	hashdestroy(newblk_hashtbl, M_NEWBLK, newblk_hash);
2016 	hashdestroy(bmsafemap_hashtbl, M_BMSAFEMAP, bmsafemap_hash);
2017 }
2018 
2019 /*
2020  * Called at mount time to notify the dependency code that a
2021  * filesystem wishes to use it.
2022  */
2023 int
2024 softdep_mount(devvp, mp, fs, cred)
2025 	struct vnode *devvp;
2026 	struct mount *mp;
2027 	struct fs *fs;
2028 	struct ucred *cred;
2029 {
2030 	struct csum_total cstotal;
2031 	struct ufsmount *ump;
2032 	struct cg *cgp;
2033 	struct buf *bp;
2034 	int error, cyl;
2035 
2036 	MNT_ILOCK(mp);
2037 	mp->mnt_flag = (mp->mnt_flag & ~MNT_ASYNC) | MNT_SOFTDEP;
2038 	if ((mp->mnt_kern_flag & MNTK_SOFTDEP) == 0) {
2039 		mp->mnt_kern_flag = (mp->mnt_kern_flag & ~MNTK_ASYNC) |
2040 			MNTK_SOFTDEP;
2041 		mp->mnt_noasync++;
2042 	}
2043 	MNT_IUNLOCK(mp);
2044 	ump = VFSTOUFS(mp);
2045 	LIST_INIT(&ump->softdep_workitem_pending);
2046 	LIST_INIT(&ump->softdep_journal_pending);
2047 	TAILQ_INIT(&ump->softdep_unlinked);
2048 	ump->softdep_worklist_tail = NULL;
2049 	ump->softdep_on_worklist = 0;
2050 	ump->softdep_deps = 0;
2051 	if ((fs->fs_flags & FS_SUJ) &&
2052 	    (error = journal_mount(mp, fs, cred)) != 0) {
2053 		printf("Failed to start journal: %d\n", error);
2054 		return (error);
2055 	}
2056 	/*
2057 	 * When doing soft updates, the counters in the
2058 	 * superblock may have gotten out of sync. Recomputation
2059 	 * can take a long time and can be deferred for background
2060 	 * fsck.  However, the old behavior of scanning the cylinder
2061 	 * groups and recalculating them at mount time is available
2062 	 * by setting vfs.ffs.compute_summary_at_mount to one.
2063 	 */
2064 	if (compute_summary_at_mount == 0 || fs->fs_clean != 0)
2065 		return (0);
2066 	bzero(&cstotal, sizeof cstotal);
2067 	for (cyl = 0; cyl < fs->fs_ncg; cyl++) {
2068 		if ((error = bread(devvp, fsbtodb(fs, cgtod(fs, cyl)),
2069 		    fs->fs_cgsize, cred, &bp)) != 0) {
2070 			brelse(bp);
2071 			return (error);
2072 		}
2073 		cgp = (struct cg *)bp->b_data;
2074 		cstotal.cs_nffree += cgp->cg_cs.cs_nffree;
2075 		cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree;
2076 		cstotal.cs_nifree += cgp->cg_cs.cs_nifree;
2077 		cstotal.cs_ndir += cgp->cg_cs.cs_ndir;
2078 		fs->fs_cs(fs, cyl) = cgp->cg_cs;
2079 		brelse(bp);
2080 	}
2081 #ifdef DEBUG
2082 	if (bcmp(&cstotal, &fs->fs_cstotal, sizeof cstotal))
2083 		printf("%s: superblock summary recomputed\n", fs->fs_fsmnt);
2084 #endif
2085 	bcopy(&cstotal, &fs->fs_cstotal, sizeof cstotal);
2086 	return (0);
2087 }
2088 
2089 void
2090 softdep_unmount(mp)
2091 	struct mount *mp;
2092 {
2093 
2094 	if (mp->mnt_kern_flag & MNTK_SUJ)
2095 		journal_unmount(mp);
2096 }
2097 
2098 struct jblocks {
2099 	struct jseglst	jb_segs;	/* TAILQ of current segments. */
2100 	struct jseg	*jb_writeseg;	/* Next write to complete. */
2101 	struct jextent	*jb_extent;	/* Extent array. */
2102 	uint64_t	jb_nextseq;	/* Next sequence number. */
2103 	uint64_t	jb_oldestseq;	/* Oldest active sequence number. */
2104 	int		jb_avail;	/* Available extents. */
2105 	int		jb_used;	/* Last used extent. */
2106 	int		jb_head;	/* Allocator head. */
2107 	int		jb_off;		/* Allocator extent offset. */
2108 	int		jb_blocks;	/* Total disk blocks covered. */
2109 	int		jb_free;	/* Total disk blocks free. */
2110 	int		jb_min;		/* Minimum free space. */
2111 	int		jb_low;		/* Low on space. */
2112 	int		jb_age;		/* Insertion time of oldest rec. */
2113 	int		jb_suspended;	/* Did journal suspend writes? */
2114 };
2115 
2116 struct jextent {
2117 	ufs2_daddr_t	je_daddr;	/* Disk block address. */
2118 	int		je_blocks;	/* Disk block count. */
2119 };
2120 
2121 static struct jblocks *
2122 jblocks_create(void)
2123 {
2124 	struct jblocks *jblocks;
2125 
2126 	jblocks = malloc(sizeof(*jblocks), M_JBLOCKS, M_WAITOK | M_ZERO);
2127 	TAILQ_INIT(&jblocks->jb_segs);
2128 	jblocks->jb_avail = 10;
2129 	jblocks->jb_extent = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2130 	    M_JBLOCKS, M_WAITOK | M_ZERO);
2131 
2132 	return (jblocks);
2133 }
2134 
2135 static ufs2_daddr_t
2136 jblocks_alloc(jblocks, bytes, actual)
2137 	struct jblocks *jblocks;
2138 	int bytes;
2139 	int *actual;
2140 {
2141 	ufs2_daddr_t daddr;
2142 	struct jextent *jext;
2143 	int freecnt;
2144 	int blocks;
2145 
2146 	blocks = bytes / DEV_BSIZE;
2147 	jext = &jblocks->jb_extent[jblocks->jb_head];
2148 	freecnt = jext->je_blocks - jblocks->jb_off;
2149 	if (freecnt == 0) {
2150 		jblocks->jb_off = 0;
2151 		if (++jblocks->jb_head > jblocks->jb_used)
2152 			jblocks->jb_head = 0;
2153 		jext = &jblocks->jb_extent[jblocks->jb_head];
2154 		freecnt = jext->je_blocks;
2155 	}
2156 	if (freecnt > blocks)
2157 		freecnt = blocks;
2158 	*actual = freecnt * DEV_BSIZE;
2159 	daddr = jext->je_daddr + jblocks->jb_off;
2160 	jblocks->jb_off += freecnt;
2161 	jblocks->jb_free -= freecnt;
2162 
2163 	return (daddr);
2164 }
2165 
2166 static void
2167 jblocks_free(jblocks, mp, bytes)
2168 	struct jblocks *jblocks;
2169 	struct mount *mp;
2170 	int bytes;
2171 {
2172 
2173 	jblocks->jb_free += bytes / DEV_BSIZE;
2174 	if (jblocks->jb_suspended)
2175 		worklist_speedup();
2176 	wakeup(jblocks);
2177 }
2178 
2179 static void
2180 jblocks_destroy(jblocks)
2181 	struct jblocks *jblocks;
2182 {
2183 
2184 	if (jblocks->jb_extent)
2185 		free(jblocks->jb_extent, M_JBLOCKS);
2186 	free(jblocks, M_JBLOCKS);
2187 }
2188 
2189 static void
2190 jblocks_add(jblocks, daddr, blocks)
2191 	struct jblocks *jblocks;
2192 	ufs2_daddr_t daddr;
2193 	int blocks;
2194 {
2195 	struct jextent *jext;
2196 
2197 	jblocks->jb_blocks += blocks;
2198 	jblocks->jb_free += blocks;
2199 	jext = &jblocks->jb_extent[jblocks->jb_used];
2200 	/* Adding the first block. */
2201 	if (jext->je_daddr == 0) {
2202 		jext->je_daddr = daddr;
2203 		jext->je_blocks = blocks;
2204 		return;
2205 	}
2206 	/* Extending the last extent. */
2207 	if (jext->je_daddr + jext->je_blocks == daddr) {
2208 		jext->je_blocks += blocks;
2209 		return;
2210 	}
2211 	/* Adding a new extent. */
2212 	if (++jblocks->jb_used == jblocks->jb_avail) {
2213 		jblocks->jb_avail *= 2;
2214 		jext = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2215 		    M_JBLOCKS, M_WAITOK | M_ZERO);
2216 		memcpy(jext, jblocks->jb_extent,
2217 		    sizeof(struct jextent) * jblocks->jb_used);
2218 		free(jblocks->jb_extent, M_JBLOCKS);
2219 		jblocks->jb_extent = jext;
2220 	}
2221 	jext = &jblocks->jb_extent[jblocks->jb_used];
2222 	jext->je_daddr = daddr;
2223 	jext->je_blocks = blocks;
2224 	return;
2225 }
2226 
2227 int
2228 softdep_journal_lookup(mp, vpp)
2229 	struct mount *mp;
2230 	struct vnode **vpp;
2231 {
2232 	struct componentname cnp;
2233 	struct vnode *dvp;
2234 	ino_t sujournal;
2235 	int error;
2236 
2237 	error = VFS_VGET(mp, ROOTINO, LK_EXCLUSIVE, &dvp);
2238 	if (error)
2239 		return (error);
2240 	bzero(&cnp, sizeof(cnp));
2241 	cnp.cn_nameiop = LOOKUP;
2242 	cnp.cn_flags = ISLASTCN;
2243 	cnp.cn_thread = curthread;
2244 	cnp.cn_cred = curthread->td_ucred;
2245 	cnp.cn_pnbuf = SUJ_FILE;
2246 	cnp.cn_nameptr = SUJ_FILE;
2247 	cnp.cn_namelen = strlen(SUJ_FILE);
2248 	error = ufs_lookup_ino(dvp, NULL, &cnp, &sujournal);
2249 	vput(dvp);
2250 	if (error != 0)
2251 		return (error);
2252 	error = VFS_VGET(mp, sujournal, LK_EXCLUSIVE, vpp);
2253 	return (error);
2254 }
2255 
2256 /*
2257  * Open and verify the journal file.
2258  */
2259 static int
2260 journal_mount(mp, fs, cred)
2261 	struct mount *mp;
2262 	struct fs *fs;
2263 	struct ucred *cred;
2264 {
2265 	struct jblocks *jblocks;
2266 	struct vnode *vp;
2267 	struct inode *ip;
2268 	ufs2_daddr_t blkno;
2269 	int bcount;
2270 	int error;
2271 	int i;
2272 
2273 	mp->mnt_kern_flag |= MNTK_SUJ;
2274 	error = softdep_journal_lookup(mp, &vp);
2275 	if (error != 0) {
2276 		printf("Failed to find journal.  Use tunefs to create one\n");
2277 		return (error);
2278 	}
2279 	ip = VTOI(vp);
2280 	if (ip->i_size < SUJ_MIN) {
2281 		error = ENOSPC;
2282 		goto out;
2283 	}
2284 	bcount = lblkno(fs, ip->i_size);	/* Only use whole blocks. */
2285 	jblocks = jblocks_create();
2286 	for (i = 0; i < bcount; i++) {
2287 		error = ufs_bmaparray(vp, i, &blkno, NULL, NULL, NULL);
2288 		if (error)
2289 			break;
2290 		jblocks_add(jblocks, blkno, fsbtodb(fs, fs->fs_frag));
2291 	}
2292 	if (error) {
2293 		jblocks_destroy(jblocks);
2294 		goto out;
2295 	}
2296 	jblocks->jb_low = jblocks->jb_free / 3;	/* Reserve 33%. */
2297 	jblocks->jb_min = jblocks->jb_free / 10; /* Suspend at 10%. */
2298 	/*
2299 	 * Only validate the journal contents if the filesystem is clean,
2300 	 * otherwise we write the logs but they'll never be used.  If the
2301 	 * filesystem was still dirty when we mounted it the journal is
2302 	 * invalid and a new journal can only be valid if it starts from a
2303 	 * clean mount.
2304 	 */
2305 	if (fs->fs_clean) {
2306 		DIP_SET(ip, i_modrev, fs->fs_mtime);
2307 		ip->i_flags |= IN_MODIFIED;
2308 		ffs_update(vp, 1);
2309 	}
2310 	VFSTOUFS(mp)->softdep_jblocks = jblocks;
2311 out:
2312 	vput(vp);
2313 	return (error);
2314 }
2315 
2316 static void
2317 journal_unmount(mp)
2318 	struct mount *mp;
2319 {
2320 	struct ufsmount *ump;
2321 
2322 	ump = VFSTOUFS(mp);
2323 	if (ump->softdep_jblocks)
2324 		jblocks_destroy(ump->softdep_jblocks);
2325 	ump->softdep_jblocks = NULL;
2326 }
2327 
2328 /*
2329  * Called when a journal record is ready to be written.  Space is allocated
2330  * and the journal entry is created when the journal is flushed to stable
2331  * store.
2332  */
2333 static void
2334 add_to_journal(wk)
2335 	struct worklist *wk;
2336 {
2337 	struct ufsmount *ump;
2338 
2339 	mtx_assert(&lk, MA_OWNED);
2340 	ump = VFSTOUFS(wk->wk_mp);
2341 	if (wk->wk_state & ONWORKLIST)
2342 		panic("add_to_journal: %s(0x%X) already on list",
2343 		    TYPENAME(wk->wk_type), wk->wk_state);
2344 	wk->wk_state |= ONWORKLIST | DEPCOMPLETE;
2345 	if (LIST_EMPTY(&ump->softdep_journal_pending)) {
2346 		ump->softdep_jblocks->jb_age = ticks;
2347 		LIST_INSERT_HEAD(&ump->softdep_journal_pending, wk, wk_list);
2348 	} else
2349 		LIST_INSERT_AFTER(ump->softdep_journal_tail, wk, wk_list);
2350 	ump->softdep_journal_tail = wk;
2351 	ump->softdep_on_journal += 1;
2352 }
2353 
2354 /*
2355  * Remove an arbitrary item for the journal worklist maintain the tail
2356  * pointer.  This happens when a new operation obviates the need to
2357  * journal an old operation.
2358  */
2359 static void
2360 remove_from_journal(wk)
2361 	struct worklist *wk;
2362 {
2363 	struct ufsmount *ump;
2364 
2365 	mtx_assert(&lk, MA_OWNED);
2366 	ump = VFSTOUFS(wk->wk_mp);
2367 #ifdef SUJ_DEBUG
2368 	{
2369 		struct worklist *wkn;
2370 
2371 		LIST_FOREACH(wkn, &ump->softdep_journal_pending, wk_list)
2372 			if (wkn == wk)
2373 				break;
2374 		if (wkn == NULL)
2375 			panic("remove_from_journal: %p is not in journal", wk);
2376 	}
2377 #endif
2378 	/*
2379 	 * We emulate a TAILQ to save space in most structures which do not
2380 	 * require TAILQ semantics.  Here we must update the tail position
2381 	 * when removing the tail which is not the final entry. This works
2382 	 * only if the worklist linkage are at the beginning of the structure.
2383 	 */
2384 	if (ump->softdep_journal_tail == wk)
2385 		ump->softdep_journal_tail =
2386 		    (struct worklist *)wk->wk_list.le_prev;
2387 
2388 	WORKLIST_REMOVE(wk);
2389 	ump->softdep_on_journal -= 1;
2390 }
2391 
2392 /*
2393  * Check for journal space as well as dependency limits so the prelink
2394  * code can throttle both journaled and non-journaled filesystems.
2395  * Threshold is 0 for low and 1 for min.
2396  */
2397 static int
2398 journal_space(ump, thresh)
2399 	struct ufsmount *ump;
2400 	int thresh;
2401 {
2402 	struct jblocks *jblocks;
2403 	int avail;
2404 
2405 	jblocks = ump->softdep_jblocks;
2406 	if (jblocks == NULL)
2407 		return (1);
2408 	/*
2409 	 * We use a tighter restriction here to prevent request_cleanup()
2410 	 * running in threads from running into locks we currently hold.
2411 	 */
2412 	if (num_inodedep > (max_softdeps / 10) * 9)
2413 		return (0);
2414 	if (thresh)
2415 		thresh = jblocks->jb_min;
2416 	else
2417 		thresh = jblocks->jb_low;
2418 	avail = (ump->softdep_on_journal * JREC_SIZE) / DEV_BSIZE;
2419 	avail = jblocks->jb_free - avail;
2420 
2421 	return (avail > thresh);
2422 }
2423 
2424 static void
2425 journal_suspend(ump)
2426 	struct ufsmount *ump;
2427 {
2428 	struct jblocks *jblocks;
2429 	struct mount *mp;
2430 
2431 	mp = UFSTOVFS(ump);
2432 	jblocks = ump->softdep_jblocks;
2433 	MNT_ILOCK(mp);
2434 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
2435 		stat_journal_min++;
2436 		mp->mnt_kern_flag |= MNTK_SUSPEND;
2437 		mp->mnt_susp_owner = FIRST_THREAD_IN_PROC(softdepproc);
2438 	}
2439 	jblocks->jb_suspended = 1;
2440 	MNT_IUNLOCK(mp);
2441 }
2442 
2443 static int
2444 journal_unsuspend(struct ufsmount *ump)
2445 {
2446 	struct jblocks *jblocks;
2447 	struct mount *mp;
2448 
2449 	mp = UFSTOVFS(ump);
2450 	jblocks = ump->softdep_jblocks;
2451 
2452 	if (jblocks != NULL && jblocks->jb_suspended &&
2453 	    journal_space(ump, jblocks->jb_min)) {
2454 		jblocks->jb_suspended = 0;
2455 		FREE_LOCK(&lk);
2456 		mp->mnt_susp_owner = curthread;
2457 		vfs_write_resume(mp);
2458 		ACQUIRE_LOCK(&lk);
2459 		return (1);
2460 	}
2461 	return (0);
2462 }
2463 
2464 /*
2465  * Called before any allocation function to be certain that there is
2466  * sufficient space in the journal prior to creating any new records.
2467  * Since in the case of block allocation we may have multiple locked
2468  * buffers at the time of the actual allocation we can not block
2469  * when the journal records are created.  Doing so would create a deadlock
2470  * if any of these buffers needed to be flushed to reclaim space.  Instead
2471  * we require a sufficiently large amount of available space such that
2472  * each thread in the system could have passed this allocation check and
2473  * still have sufficient free space.  With 20% of a minimum journal size
2474  * of 1MB we have 6553 records available.
2475  */
2476 int
2477 softdep_prealloc(vp, waitok)
2478 	struct vnode *vp;
2479 	int waitok;
2480 {
2481 	struct ufsmount *ump;
2482 
2483 	if (DOINGSUJ(vp) == 0)
2484 		return (0);
2485 	ump = VFSTOUFS(vp->v_mount);
2486 	ACQUIRE_LOCK(&lk);
2487 	if (journal_space(ump, 0)) {
2488 		FREE_LOCK(&lk);
2489 		return (0);
2490 	}
2491 	stat_journal_low++;
2492 	FREE_LOCK(&lk);
2493 	if (waitok == MNT_NOWAIT)
2494 		return (ENOSPC);
2495 	/*
2496 	 * Attempt to sync this vnode once to flush any journal
2497 	 * work attached to it.
2498 	 */
2499 	if ((curthread->td_pflags & TDP_COWINPROGRESS) == 0)
2500 		ffs_syncvnode(vp, waitok);
2501 	ACQUIRE_LOCK(&lk);
2502 	process_removes(vp);
2503 	if (journal_space(ump, 0) == 0) {
2504 		softdep_speedup();
2505 		if (journal_space(ump, 1) == 0)
2506 			journal_suspend(ump);
2507 	}
2508 	FREE_LOCK(&lk);
2509 
2510 	return (0);
2511 }
2512 
2513 /*
2514  * Before adjusting a link count on a vnode verify that we have sufficient
2515  * journal space.  If not, process operations that depend on the currently
2516  * locked pair of vnodes to try to flush space as the syncer, buf daemon,
2517  * and softdep flush threads can not acquire these locks to reclaim space.
2518  */
2519 static void
2520 softdep_prelink(dvp, vp)
2521 	struct vnode *dvp;
2522 	struct vnode *vp;
2523 {
2524 	struct ufsmount *ump;
2525 
2526 	ump = VFSTOUFS(dvp->v_mount);
2527 	mtx_assert(&lk, MA_OWNED);
2528 	if (journal_space(ump, 0))
2529 		return;
2530 	stat_journal_low++;
2531 	FREE_LOCK(&lk);
2532 	if (vp)
2533 		ffs_syncvnode(vp, MNT_NOWAIT);
2534 	ffs_syncvnode(dvp, MNT_WAIT);
2535 	ACQUIRE_LOCK(&lk);
2536 	/* Process vp before dvp as it may create .. removes. */
2537 	if (vp)
2538 		process_removes(vp);
2539 	process_removes(dvp);
2540 	softdep_speedup();
2541 	process_worklist_item(UFSTOVFS(ump), LK_NOWAIT);
2542 	process_worklist_item(UFSTOVFS(ump), LK_NOWAIT);
2543 	if (journal_space(ump, 0) == 0) {
2544 		softdep_speedup();
2545 		if (journal_space(ump, 1) == 0)
2546 			journal_suspend(ump);
2547 	}
2548 }
2549 
2550 static void
2551 jseg_write(fs, jblocks, jseg, data)
2552 	struct fs *fs;
2553 	struct jblocks *jblocks;
2554 	struct jseg *jseg;
2555 	uint8_t *data;
2556 {
2557 	struct jsegrec *rec;
2558 
2559 	rec = (struct jsegrec *)data;
2560 	rec->jsr_seq = jseg->js_seq;
2561 	rec->jsr_oldest = jblocks->jb_oldestseq;
2562 	rec->jsr_cnt = jseg->js_cnt;
2563 	rec->jsr_blocks = jseg->js_size / DEV_BSIZE;
2564 	rec->jsr_crc = 0;
2565 	rec->jsr_time = fs->fs_mtime;
2566 }
2567 
2568 static inline void
2569 inoref_write(inoref, jseg, rec)
2570 	struct inoref *inoref;
2571 	struct jseg *jseg;
2572 	struct jrefrec *rec;
2573 {
2574 
2575 	inoref->if_jsegdep->jd_seg = jseg;
2576 	rec->jr_ino = inoref->if_ino;
2577 	rec->jr_parent = inoref->if_parent;
2578 	rec->jr_nlink = inoref->if_nlink;
2579 	rec->jr_mode = inoref->if_mode;
2580 	rec->jr_diroff = inoref->if_diroff;
2581 }
2582 
2583 static void
2584 jaddref_write(jaddref, jseg, data)
2585 	struct jaddref *jaddref;
2586 	struct jseg *jseg;
2587 	uint8_t *data;
2588 {
2589 	struct jrefrec *rec;
2590 
2591 	rec = (struct jrefrec *)data;
2592 	rec->jr_op = JOP_ADDREF;
2593 	inoref_write(&jaddref->ja_ref, jseg, rec);
2594 }
2595 
2596 static void
2597 jremref_write(jremref, jseg, data)
2598 	struct jremref *jremref;
2599 	struct jseg *jseg;
2600 	uint8_t *data;
2601 {
2602 	struct jrefrec *rec;
2603 
2604 	rec = (struct jrefrec *)data;
2605 	rec->jr_op = JOP_REMREF;
2606 	inoref_write(&jremref->jr_ref, jseg, rec);
2607 }
2608 
2609 static void
2610 jmvref_write(jmvref, jseg, data)
2611 	struct jmvref *jmvref;
2612 	struct jseg *jseg;
2613 	uint8_t *data;
2614 {
2615 	struct jmvrec *rec;
2616 
2617 	rec = (struct jmvrec *)data;
2618 	rec->jm_op = JOP_MVREF;
2619 	rec->jm_ino = jmvref->jm_ino;
2620 	rec->jm_parent = jmvref->jm_parent;
2621 	rec->jm_oldoff = jmvref->jm_oldoff;
2622 	rec->jm_newoff = jmvref->jm_newoff;
2623 }
2624 
2625 static void
2626 jnewblk_write(jnewblk, jseg, data)
2627 	struct jnewblk *jnewblk;
2628 	struct jseg *jseg;
2629 	uint8_t *data;
2630 {
2631 	struct jblkrec *rec;
2632 
2633 	jnewblk->jn_jsegdep->jd_seg = jseg;
2634 	rec = (struct jblkrec *)data;
2635 	rec->jb_op = JOP_NEWBLK;
2636 	rec->jb_ino = jnewblk->jn_ino;
2637 	rec->jb_blkno = jnewblk->jn_blkno;
2638 	rec->jb_lbn = jnewblk->jn_lbn;
2639 	rec->jb_frags = jnewblk->jn_frags;
2640 	rec->jb_oldfrags = jnewblk->jn_oldfrags;
2641 }
2642 
2643 static void
2644 jfreeblk_write(jfreeblk, jseg, data)
2645 	struct jfreeblk *jfreeblk;
2646 	struct jseg *jseg;
2647 	uint8_t *data;
2648 {
2649 	struct jblkrec *rec;
2650 
2651 	jfreeblk->jf_jsegdep->jd_seg = jseg;
2652 	rec = (struct jblkrec *)data;
2653 	rec->jb_op = JOP_FREEBLK;
2654 	rec->jb_ino = jfreeblk->jf_ino;
2655 	rec->jb_blkno = jfreeblk->jf_blkno;
2656 	rec->jb_lbn = jfreeblk->jf_lbn;
2657 	rec->jb_frags = jfreeblk->jf_frags;
2658 	rec->jb_oldfrags = 0;
2659 }
2660 
2661 static void
2662 jfreefrag_write(jfreefrag, jseg, data)
2663 	struct jfreefrag *jfreefrag;
2664 	struct jseg *jseg;
2665 	uint8_t *data;
2666 {
2667 	struct jblkrec *rec;
2668 
2669 	jfreefrag->fr_jsegdep->jd_seg = jseg;
2670 	rec = (struct jblkrec *)data;
2671 	rec->jb_op = JOP_FREEBLK;
2672 	rec->jb_ino = jfreefrag->fr_ino;
2673 	rec->jb_blkno = jfreefrag->fr_blkno;
2674 	rec->jb_lbn = jfreefrag->fr_lbn;
2675 	rec->jb_frags = jfreefrag->fr_frags;
2676 	rec->jb_oldfrags = 0;
2677 }
2678 
2679 static void
2680 jtrunc_write(jtrunc, jseg, data)
2681 	struct jtrunc *jtrunc;
2682 	struct jseg *jseg;
2683 	uint8_t *data;
2684 {
2685 	struct jtrncrec *rec;
2686 
2687 	rec = (struct jtrncrec *)data;
2688 	rec->jt_op = JOP_TRUNC;
2689 	rec->jt_ino = jtrunc->jt_ino;
2690 	rec->jt_size = jtrunc->jt_size;
2691 	rec->jt_extsize = jtrunc->jt_extsize;
2692 }
2693 
2694 /*
2695  * Flush some journal records to disk.
2696  */
2697 static void
2698 softdep_process_journal(mp, flags)
2699 	struct mount *mp;
2700 	int flags;
2701 {
2702 	struct jblocks *jblocks;
2703 	struct ufsmount *ump;
2704 	struct worklist *wk;
2705 	struct jseg *jseg;
2706 	struct buf *bp;
2707 	uint8_t *data;
2708 	struct fs *fs;
2709 	int segwritten;
2710 	int jrecmin;	/* Minimum records per block. */
2711 	int jrecmax;	/* Maximum records per block. */
2712 	int size;
2713 	int cnt;
2714 	int off;
2715 
2716 	if ((mp->mnt_kern_flag & MNTK_SUJ) == 0)
2717 		return;
2718 	ump = VFSTOUFS(mp);
2719 	fs = ump->um_fs;
2720 	jblocks = ump->softdep_jblocks;
2721 	/*
2722 	 * We write anywhere between a disk block and fs block.  The upper
2723 	 * bound is picked to prevent buffer cache fragmentation and limit
2724 	 * processing time per I/O.
2725 	 */
2726 	jrecmin = (DEV_BSIZE / JREC_SIZE) - 1; /* -1 for seg header */
2727 	jrecmax = (fs->fs_bsize / DEV_BSIZE) * jrecmin;
2728 	segwritten = 0;
2729 	while ((cnt = ump->softdep_on_journal) != 0) {
2730 		/*
2731 		 * Create a new segment to hold as many as 'cnt' journal
2732 		 * entries and add them to the segment.  Notice cnt is
2733 		 * off by one to account for the space required by the
2734 		 * jsegrec.  If we don't have a full block to log skip it
2735 		 * unless we haven't written anything.
2736 		 */
2737 		cnt++;
2738 		if (cnt < jrecmax && segwritten)
2739 			break;
2740 		/*
2741 		 * Verify some free journal space.  softdep_prealloc() should
2742 	 	 * guarantee that we don't run out so this is indicative of
2743 		 * a problem with the flow control.  Try to recover
2744 		 * gracefully in any event.
2745 		 */
2746 		while (jblocks->jb_free == 0) {
2747 			if (flags != MNT_WAIT)
2748 				break;
2749 			printf("softdep: Out of journal space!\n");
2750 			softdep_speedup();
2751 			msleep(jblocks, &lk, PRIBIO, "jblocks", hz);
2752 		}
2753 		FREE_LOCK(&lk);
2754 		jseg = malloc(sizeof(*jseg), M_JSEG, M_SOFTDEP_FLAGS);
2755 		workitem_alloc(&jseg->js_list, D_JSEG, mp);
2756 		LIST_INIT(&jseg->js_entries);
2757 		jseg->js_state = ATTACHED;
2758 		jseg->js_jblocks = jblocks;
2759 		bp = geteblk(fs->fs_bsize, 0);
2760 		ACQUIRE_LOCK(&lk);
2761 		/*
2762 		 * If there was a race while we were allocating the block
2763 		 * and jseg the entry we care about was likely written.
2764 		 * We bail out in both the WAIT and NOWAIT case and assume
2765 		 * the caller will loop if the entry it cares about is
2766 		 * not written.
2767 		 */
2768 		if (ump->softdep_on_journal == 0 || jblocks->jb_free == 0) {
2769 			bp->b_flags |= B_INVAL | B_NOCACHE;
2770 			WORKITEM_FREE(jseg, D_JSEG);
2771 			FREE_LOCK(&lk);
2772 			brelse(bp);
2773 			ACQUIRE_LOCK(&lk);
2774 			break;
2775 		}
2776 		/*
2777 		 * Calculate the disk block size required for the available
2778 		 * records rounded to the min size.
2779 		 */
2780 		cnt = ump->softdep_on_journal;
2781 		if (cnt < jrecmax)
2782 			size = howmany(cnt, jrecmin) * DEV_BSIZE;
2783 		else
2784 			size = fs->fs_bsize;
2785 		/*
2786 		 * Allocate a disk block for this journal data and account
2787 		 * for truncation of the requested size if enough contiguous
2788 		 * space was not available.
2789 		 */
2790 		bp->b_blkno = jblocks_alloc(jblocks, size, &size);
2791 		bp->b_lblkno = bp->b_blkno;
2792 		bp->b_offset = bp->b_blkno * DEV_BSIZE;
2793 		bp->b_bcount = size;
2794 		bp->b_bufobj = &ump->um_devvp->v_bufobj;
2795 		bp->b_flags &= ~B_INVAL;
2796 		bp->b_flags |= B_VALIDSUSPWRT | B_NOCOPY;
2797 		/*
2798 		 * Initialize our jseg with cnt records.  Assign the next
2799 		 * sequence number to it and link it in-order.
2800 		 */
2801 		cnt = MIN(ump->softdep_on_journal,
2802 		    (size / DEV_BSIZE) * jrecmin);
2803 		jseg->js_buf = bp;
2804 		jseg->js_cnt = cnt;
2805 		jseg->js_refs = cnt + 1;	/* Self ref. */
2806 		jseg->js_size = size;
2807 		jseg->js_seq = jblocks->jb_nextseq++;
2808 		if (TAILQ_EMPTY(&jblocks->jb_segs))
2809 			jblocks->jb_oldestseq = jseg->js_seq;
2810 		TAILQ_INSERT_TAIL(&jblocks->jb_segs, jseg, js_next);
2811 		if (jblocks->jb_writeseg == NULL)
2812 			jblocks->jb_writeseg = jseg;
2813 		/*
2814 		 * Start filling in records from the pending list.
2815 		 */
2816 		data = bp->b_data;
2817 		off = 0;
2818 		while ((wk = LIST_FIRST(&ump->softdep_journal_pending))
2819 		    != NULL) {
2820 			/* Place a segment header on every device block. */
2821 			if ((off % DEV_BSIZE) == 0) {
2822 				jseg_write(fs, jblocks, jseg, data);
2823 				off += JREC_SIZE;
2824 				data = bp->b_data + off;
2825 			}
2826 			remove_from_journal(wk);
2827 			wk->wk_state |= IOSTARTED;
2828 			WORKLIST_INSERT(&jseg->js_entries, wk);
2829 			switch (wk->wk_type) {
2830 			case D_JADDREF:
2831 				jaddref_write(WK_JADDREF(wk), jseg, data);
2832 				break;
2833 			case D_JREMREF:
2834 				jremref_write(WK_JREMREF(wk), jseg, data);
2835 				break;
2836 			case D_JMVREF:
2837 				jmvref_write(WK_JMVREF(wk), jseg, data);
2838 				break;
2839 			case D_JNEWBLK:
2840 				jnewblk_write(WK_JNEWBLK(wk), jseg, data);
2841 				break;
2842 			case D_JFREEBLK:
2843 				jfreeblk_write(WK_JFREEBLK(wk), jseg, data);
2844 				break;
2845 			case D_JFREEFRAG:
2846 				jfreefrag_write(WK_JFREEFRAG(wk), jseg, data);
2847 				break;
2848 			case D_JTRUNC:
2849 				jtrunc_write(WK_JTRUNC(wk), jseg, data);
2850 				break;
2851 			default:
2852 				panic("process_journal: Unknown type %s",
2853 				    TYPENAME(wk->wk_type));
2854 				/* NOTREACHED */
2855 			}
2856 			if (--cnt == 0)
2857 				break;
2858 			off += JREC_SIZE;
2859 			data = bp->b_data + off;
2860 		}
2861 		/*
2862 		 * Write this one buffer and continue.
2863 		 */
2864 		WORKLIST_INSERT(&bp->b_dep, &jseg->js_list);
2865 		FREE_LOCK(&lk);
2866 		BO_LOCK(bp->b_bufobj);
2867 		bgetvp(ump->um_devvp, bp);
2868 		BO_UNLOCK(bp->b_bufobj);
2869 		if (flags == MNT_NOWAIT)
2870 			bawrite(bp);
2871 		else
2872 			bwrite(bp);
2873 		ACQUIRE_LOCK(&lk);
2874 	}
2875 	/*
2876 	 * If we've suspended the filesystem because we ran out of journal
2877 	 * space either try to sync it here to make some progress or
2878 	 * unsuspend it if we already have.
2879 	 */
2880 	if (flags == 0 && jblocks->jb_suspended) {
2881 		if (journal_unsuspend(ump))
2882 			return;
2883 		FREE_LOCK(&lk);
2884 		VFS_SYNC(mp, MNT_NOWAIT);
2885 		ffs_sbupdate(ump, MNT_WAIT, 0);
2886 		ACQUIRE_LOCK(&lk);
2887 	}
2888 }
2889 
2890 /*
2891  * Complete a jseg, allowing all dependencies awaiting journal writes
2892  * to proceed.  Each journal dependency also attaches a jsegdep to dependent
2893  * structures so that the journal segment can be freed to reclaim space.
2894  */
2895 static void
2896 complete_jseg(jseg)
2897 	struct jseg *jseg;
2898 {
2899 	struct worklist *wk;
2900 	struct jmvref *jmvref;
2901 	int waiting;
2902 #ifdef INVARIANTS
2903 	int i = 0;
2904 #endif
2905 
2906 	while ((wk = LIST_FIRST(&jseg->js_entries)) != NULL) {
2907 		WORKLIST_REMOVE(wk);
2908 		waiting = wk->wk_state & IOWAITING;
2909 		wk->wk_state &= ~(IOSTARTED | IOWAITING);
2910 		wk->wk_state |= COMPLETE;
2911 		KASSERT(i++ < jseg->js_cnt,
2912 		    ("handle_written_jseg: overflow %d >= %d",
2913 		    i - 1, jseg->js_cnt));
2914 		switch (wk->wk_type) {
2915 		case D_JADDREF:
2916 			handle_written_jaddref(WK_JADDREF(wk));
2917 			break;
2918 		case D_JREMREF:
2919 			handle_written_jremref(WK_JREMREF(wk));
2920 			break;
2921 		case D_JMVREF:
2922 			/* No jsegdep here. */
2923 			free_jseg(jseg);
2924 			jmvref = WK_JMVREF(wk);
2925 			LIST_REMOVE(jmvref, jm_deps);
2926 			free_pagedep(jmvref->jm_pagedep);
2927 			WORKITEM_FREE(jmvref, D_JMVREF);
2928 			break;
2929 		case D_JNEWBLK:
2930 			handle_written_jnewblk(WK_JNEWBLK(wk));
2931 			break;
2932 		case D_JFREEBLK:
2933 			handle_written_jfreeblk(WK_JFREEBLK(wk));
2934 			break;
2935 		case D_JFREEFRAG:
2936 			handle_written_jfreefrag(WK_JFREEFRAG(wk));
2937 			break;
2938 		case D_JTRUNC:
2939 			WK_JTRUNC(wk)->jt_jsegdep->jd_seg = jseg;
2940 			WORKITEM_FREE(wk, D_JTRUNC);
2941 			break;
2942 		default:
2943 			panic("handle_written_jseg: Unknown type %s",
2944 			    TYPENAME(wk->wk_type));
2945 			/* NOTREACHED */
2946 		}
2947 		if (waiting)
2948 			wakeup(wk);
2949 	}
2950 	/* Release the self reference so the structure may be freed. */
2951 	free_jseg(jseg);
2952 }
2953 
2954 /*
2955  * Mark a jseg as DEPCOMPLETE and throw away the buffer.  Handle jseg
2956  * completions in order only.
2957  */
2958 static void
2959 handle_written_jseg(jseg, bp)
2960 	struct jseg *jseg;
2961 	struct buf *bp;
2962 {
2963 	struct jblocks *jblocks;
2964 	struct jseg *jsegn;
2965 
2966 	if (jseg->js_refs == 0)
2967 		panic("handle_written_jseg: No self-reference on %p", jseg);
2968 	jseg->js_state |= DEPCOMPLETE;
2969 	/*
2970 	 * We'll never need this buffer again, set flags so it will be
2971 	 * discarded.
2972 	 */
2973 	bp->b_flags |= B_INVAL | B_NOCACHE;
2974 	jblocks = jseg->js_jblocks;
2975 	/*
2976 	 * Don't allow out of order completions.  If this isn't the first
2977 	 * block wait for it to write before we're done.
2978 	 */
2979 	if (jseg != jblocks->jb_writeseg)
2980 		return;
2981 	/* Iterate through available jsegs processing their entries. */
2982 	do {
2983 		jsegn = TAILQ_NEXT(jseg, js_next);
2984 		complete_jseg(jseg);
2985 		jseg = jsegn;
2986 	} while (jseg && jseg->js_state & DEPCOMPLETE);
2987 	jblocks->jb_writeseg = jseg;
2988 }
2989 
2990 static inline struct jsegdep *
2991 inoref_jseg(inoref)
2992 	struct inoref *inoref;
2993 {
2994 	struct jsegdep *jsegdep;
2995 
2996 	jsegdep = inoref->if_jsegdep;
2997 	inoref->if_jsegdep = NULL;
2998 
2999 	return (jsegdep);
3000 }
3001 
3002 /*
3003  * Called once a jremref has made it to stable store.  The jremref is marked
3004  * complete and we attempt to free it.  Any pagedeps writes sleeping waiting
3005  * for the jremref to complete will be awoken by free_jremref.
3006  */
3007 static void
3008 handle_written_jremref(jremref)
3009 	struct jremref *jremref;
3010 {
3011 	struct inodedep *inodedep;
3012 	struct jsegdep *jsegdep;
3013 	struct dirrem *dirrem;
3014 
3015 	/* Grab the jsegdep. */
3016 	jsegdep = inoref_jseg(&jremref->jr_ref);
3017 	/*
3018 	 * Remove us from the inoref list.
3019 	 */
3020 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino,
3021 	    0, &inodedep) == 0)
3022 		panic("handle_written_jremref: Lost inodedep");
3023 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
3024 	/*
3025 	 * Complete the dirrem.
3026 	 */
3027 	dirrem = jremref->jr_dirrem;
3028 	jremref->jr_dirrem = NULL;
3029 	LIST_REMOVE(jremref, jr_deps);
3030 	jsegdep->jd_state |= jremref->jr_state & MKDIR_PARENT;
3031 	WORKLIST_INSERT(&dirrem->dm_jwork, &jsegdep->jd_list);
3032 	if (LIST_EMPTY(&dirrem->dm_jremrefhd) &&
3033 	    (dirrem->dm_state & COMPLETE) != 0)
3034 		add_to_worklist(&dirrem->dm_list, 0);
3035 	free_jremref(jremref);
3036 }
3037 
3038 /*
3039  * Called once a jaddref has made it to stable store.  The dependency is
3040  * marked complete and any dependent structures are added to the inode
3041  * bufwait list to be completed as soon as it is written.  If a bitmap write
3042  * depends on this entry we move the inode into the inodedephd of the
3043  * bmsafemap dependency and attempt to remove the jaddref from the bmsafemap.
3044  */
3045 static void
3046 handle_written_jaddref(jaddref)
3047 	struct jaddref *jaddref;
3048 {
3049 	struct jsegdep *jsegdep;
3050 	struct inodedep *inodedep;
3051 	struct diradd *diradd;
3052 	struct mkdir *mkdir;
3053 
3054 	/* Grab the jsegdep. */
3055 	jsegdep = inoref_jseg(&jaddref->ja_ref);
3056 	mkdir = NULL;
3057 	diradd = NULL;
3058 	if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
3059 	    0, &inodedep) == 0)
3060 		panic("handle_written_jaddref: Lost inodedep.");
3061 	if (jaddref->ja_diradd == NULL)
3062 		panic("handle_written_jaddref: No dependency");
3063 	if (jaddref->ja_diradd->da_list.wk_type == D_DIRADD) {
3064 		diradd = jaddref->ja_diradd;
3065 		WORKLIST_INSERT(&inodedep->id_bufwait, &diradd->da_list);
3066 	} else if (jaddref->ja_state & MKDIR_PARENT) {
3067 		mkdir = jaddref->ja_mkdir;
3068 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir->md_list);
3069 	} else if (jaddref->ja_state & MKDIR_BODY)
3070 		mkdir = jaddref->ja_mkdir;
3071 	else
3072 		panic("handle_written_jaddref: Unknown dependency %p",
3073 		    jaddref->ja_diradd);
3074 	jaddref->ja_diradd = NULL;	/* also clears ja_mkdir */
3075 	/*
3076 	 * Remove us from the inode list.
3077 	 */
3078 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref, if_deps);
3079 	/*
3080 	 * The mkdir may be waiting on the jaddref to clear before freeing.
3081 	 */
3082 	if (mkdir) {
3083 		KASSERT(mkdir->md_list.wk_type == D_MKDIR,
3084 		    ("handle_written_jaddref: Incorrect type for mkdir %s",
3085 		    TYPENAME(mkdir->md_list.wk_type)));
3086 		mkdir->md_jaddref = NULL;
3087 		diradd = mkdir->md_diradd;
3088 		mkdir->md_state |= DEPCOMPLETE;
3089 		complete_mkdir(mkdir);
3090 	}
3091 	WORKLIST_INSERT(&diradd->da_jwork, &jsegdep->jd_list);
3092 	if (jaddref->ja_state & NEWBLOCK) {
3093 		inodedep->id_state |= ONDEPLIST;
3094 		LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_inodedephd,
3095 		    inodedep, id_deps);
3096 	}
3097 	free_jaddref(jaddref);
3098 }
3099 
3100 /*
3101  * Called once a jnewblk journal is written.  The allocdirect or allocindir
3102  * is placed in the bmsafemap to await notification of a written bitmap.
3103  */
3104 static void
3105 handle_written_jnewblk(jnewblk)
3106 	struct jnewblk *jnewblk;
3107 {
3108 	struct bmsafemap *bmsafemap;
3109 	struct jsegdep *jsegdep;
3110 	struct newblk *newblk;
3111 
3112 	/* Grab the jsegdep. */
3113 	jsegdep = jnewblk->jn_jsegdep;
3114 	jnewblk->jn_jsegdep = NULL;
3115 	/*
3116 	 * Add the written block to the bmsafemap so it can be notified when
3117 	 * the bitmap is on disk.
3118 	 */
3119 	newblk = jnewblk->jn_newblk;
3120 	jnewblk->jn_newblk = NULL;
3121 	if (newblk == NULL)
3122 		panic("handle_written_jnewblk: No dependency for the segdep.");
3123 
3124 	newblk->nb_jnewblk = NULL;
3125 	bmsafemap = newblk->nb_bmsafemap;
3126 	WORKLIST_INSERT(&newblk->nb_jwork, &jsegdep->jd_list);
3127 	newblk->nb_state |= ONDEPLIST;
3128 	LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
3129 	free_jnewblk(jnewblk);
3130 }
3131 
3132 /*
3133  * Cancel a jfreefrag that won't be needed, probably due to colliding with
3134  * an in-flight allocation that has not yet been committed.  Divorce us
3135  * from the freefrag and mark it DEPCOMPLETE so that it may be added
3136  * to the worklist.
3137  */
3138 static void
3139 cancel_jfreefrag(jfreefrag)
3140 	struct jfreefrag *jfreefrag;
3141 {
3142 	struct freefrag *freefrag;
3143 
3144 	if (jfreefrag->fr_jsegdep) {
3145 		free_jsegdep(jfreefrag->fr_jsegdep);
3146 		jfreefrag->fr_jsegdep = NULL;
3147 	}
3148 	freefrag = jfreefrag->fr_freefrag;
3149 	jfreefrag->fr_freefrag = NULL;
3150 	freefrag->ff_jfreefrag = NULL;
3151 	free_jfreefrag(jfreefrag);
3152 	freefrag->ff_state |= DEPCOMPLETE;
3153 }
3154 
3155 /*
3156  * Free a jfreefrag when the parent freefrag is rendered obsolete.
3157  */
3158 static void
3159 free_jfreefrag(jfreefrag)
3160 	struct jfreefrag *jfreefrag;
3161 {
3162 
3163 	if (jfreefrag->fr_state & IOSTARTED)
3164 		WORKLIST_REMOVE(&jfreefrag->fr_list);
3165 	else if (jfreefrag->fr_state & ONWORKLIST)
3166 		remove_from_journal(&jfreefrag->fr_list);
3167 	if (jfreefrag->fr_freefrag != NULL)
3168 		panic("free_jfreefrag:  Still attached to a freefrag.");
3169 	WORKITEM_FREE(jfreefrag, D_JFREEFRAG);
3170 }
3171 
3172 /*
3173  * Called when the journal write for a jfreefrag completes.  The parent
3174  * freefrag is added to the worklist if this completes its dependencies.
3175  */
3176 static void
3177 handle_written_jfreefrag(jfreefrag)
3178 	struct jfreefrag *jfreefrag;
3179 {
3180 	struct jsegdep *jsegdep;
3181 	struct freefrag *freefrag;
3182 
3183 	/* Grab the jsegdep. */
3184 	jsegdep = jfreefrag->fr_jsegdep;
3185 	jfreefrag->fr_jsegdep = NULL;
3186 	freefrag = jfreefrag->fr_freefrag;
3187 	if (freefrag == NULL)
3188 		panic("handle_written_jfreefrag: No freefrag.");
3189 	freefrag->ff_state |= DEPCOMPLETE;
3190 	freefrag->ff_jfreefrag = NULL;
3191 	WORKLIST_INSERT(&freefrag->ff_jwork, &jsegdep->jd_list);
3192 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
3193 		add_to_worklist(&freefrag->ff_list, 0);
3194 	jfreefrag->fr_freefrag = NULL;
3195 	free_jfreefrag(jfreefrag);
3196 }
3197 
3198 /*
3199  * Called when the journal write for a jfreeblk completes.  The jfreeblk
3200  * is removed from the freeblks list of pending journal writes and the
3201  * jsegdep is moved to the freeblks jwork to be completed when all blocks
3202  * have been reclaimed.
3203  */
3204 static void
3205 handle_written_jfreeblk(jfreeblk)
3206 	struct jfreeblk *jfreeblk;
3207 {
3208 	struct freeblks *freeblks;
3209 	struct jsegdep *jsegdep;
3210 
3211 	/* Grab the jsegdep. */
3212 	jsegdep = jfreeblk->jf_jsegdep;
3213 	jfreeblk->jf_jsegdep = NULL;
3214 	freeblks = jfreeblk->jf_freeblks;
3215 	LIST_REMOVE(jfreeblk, jf_deps);
3216 	WORKLIST_INSERT(&freeblks->fb_jwork, &jsegdep->jd_list);
3217 	/*
3218 	 * If the freeblks is all journaled, we can add it to the worklist.
3219 	 */
3220 	if (LIST_EMPTY(&freeblks->fb_jfreeblkhd) &&
3221 	    (freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE) {
3222 		/* Remove from the b_dep that is waiting on this write. */
3223 		if (freeblks->fb_state & ONWORKLIST)
3224 			WORKLIST_REMOVE(&freeblks->fb_list);
3225 		add_to_worklist(&freeblks->fb_list, 1);
3226 	}
3227 
3228 	free_jfreeblk(jfreeblk);
3229 }
3230 
3231 static struct jsegdep *
3232 newjsegdep(struct worklist *wk)
3233 {
3234 	struct jsegdep *jsegdep;
3235 
3236 	jsegdep = malloc(sizeof(*jsegdep), M_JSEGDEP, M_SOFTDEP_FLAGS);
3237 	workitem_alloc(&jsegdep->jd_list, D_JSEGDEP, wk->wk_mp);
3238 	jsegdep->jd_seg = NULL;
3239 
3240 	return (jsegdep);
3241 }
3242 
3243 static struct jmvref *
3244 newjmvref(dp, ino, oldoff, newoff)
3245 	struct inode *dp;
3246 	ino_t ino;
3247 	off_t oldoff;
3248 	off_t newoff;
3249 {
3250 	struct jmvref *jmvref;
3251 
3252 	jmvref = malloc(sizeof(*jmvref), M_JMVREF, M_SOFTDEP_FLAGS);
3253 	workitem_alloc(&jmvref->jm_list, D_JMVREF, UFSTOVFS(dp->i_ump));
3254 	jmvref->jm_list.wk_state = ATTACHED | DEPCOMPLETE;
3255 	jmvref->jm_parent = dp->i_number;
3256 	jmvref->jm_ino = ino;
3257 	jmvref->jm_oldoff = oldoff;
3258 	jmvref->jm_newoff = newoff;
3259 
3260 	return (jmvref);
3261 }
3262 
3263 /*
3264  * Allocate a new jremref that tracks the removal of ip from dp with the
3265  * directory entry offset of diroff.  Mark the entry as ATTACHED and
3266  * DEPCOMPLETE as we have all the information required for the journal write
3267  * and the directory has already been removed from the buffer.  The caller
3268  * is responsible for linking the jremref into the pagedep and adding it
3269  * to the journal to write.  The MKDIR_PARENT flag is set if we're doing
3270  * a DOTDOT addition so handle_workitem_remove() can properly assign
3271  * the jsegdep when we're done.
3272  */
3273 static struct jremref *
3274 newjremref(struct dirrem *dirrem, struct inode *dp, struct inode *ip,
3275     off_t diroff, nlink_t nlink)
3276 {
3277 	struct jremref *jremref;
3278 
3279 	jremref = malloc(sizeof(*jremref), M_JREMREF, M_SOFTDEP_FLAGS);
3280 	workitem_alloc(&jremref->jr_list, D_JREMREF, UFSTOVFS(dp->i_ump));
3281 	jremref->jr_state = ATTACHED;
3282 	newinoref(&jremref->jr_ref, ip->i_number, dp->i_number, diroff,
3283 	   nlink, ip->i_mode);
3284 	jremref->jr_dirrem = dirrem;
3285 
3286 	return (jremref);
3287 }
3288 
3289 static inline void
3290 newinoref(struct inoref *inoref, ino_t ino, ino_t parent, off_t diroff,
3291     nlink_t nlink, uint16_t mode)
3292 {
3293 
3294 	inoref->if_jsegdep = newjsegdep(&inoref->if_list);
3295 	inoref->if_diroff = diroff;
3296 	inoref->if_ino = ino;
3297 	inoref->if_parent = parent;
3298 	inoref->if_nlink = nlink;
3299 	inoref->if_mode = mode;
3300 }
3301 
3302 /*
3303  * Allocate a new jaddref to track the addition of ino to dp at diroff.  The
3304  * directory offset may not be known until later.  The caller is responsible
3305  * adding the entry to the journal when this information is available.  nlink
3306  * should be the link count prior to the addition and mode is only required
3307  * to have the correct FMT.
3308  */
3309 static struct jaddref *
3310 newjaddref(struct inode *dp, ino_t ino, off_t diroff, int16_t nlink,
3311     uint16_t mode)
3312 {
3313 	struct jaddref *jaddref;
3314 
3315 	jaddref = malloc(sizeof(*jaddref), M_JADDREF, M_SOFTDEP_FLAGS);
3316 	workitem_alloc(&jaddref->ja_list, D_JADDREF, UFSTOVFS(dp->i_ump));
3317 	jaddref->ja_state = ATTACHED;
3318 	jaddref->ja_mkdir = NULL;
3319 	newinoref(&jaddref->ja_ref, ino, dp->i_number, diroff, nlink, mode);
3320 
3321 	return (jaddref);
3322 }
3323 
3324 /*
3325  * Create a new free dependency for a freework.  The caller is responsible
3326  * for adjusting the reference count when it has the lock held.  The freedep
3327  * will track an outstanding bitmap write that will ultimately clear the
3328  * freework to continue.
3329  */
3330 static struct freedep *
3331 newfreedep(struct freework *freework)
3332 {
3333 	struct freedep *freedep;
3334 
3335 	freedep = malloc(sizeof(*freedep), M_FREEDEP, M_SOFTDEP_FLAGS);
3336 	workitem_alloc(&freedep->fd_list, D_FREEDEP, freework->fw_list.wk_mp);
3337 	freedep->fd_freework = freework;
3338 
3339 	return (freedep);
3340 }
3341 
3342 /*
3343  * Free a freedep structure once the buffer it is linked to is written.  If
3344  * this is the last reference to the freework schedule it for completion.
3345  */
3346 static void
3347 free_freedep(freedep)
3348 	struct freedep *freedep;
3349 {
3350 
3351 	if (--freedep->fd_freework->fw_ref == 0)
3352 		add_to_worklist(&freedep->fd_freework->fw_list, 1);
3353 	WORKITEM_FREE(freedep, D_FREEDEP);
3354 }
3355 
3356 /*
3357  * Allocate a new freework structure that may be a level in an indirect
3358  * when parent is not NULL or a top level block when it is.  The top level
3359  * freework structures are allocated without lk held and before the freeblks
3360  * is visible outside of softdep_setup_freeblocks().
3361  */
3362 static struct freework *
3363 newfreework(freeblks, parent, lbn, nb, frags, journal)
3364 	struct freeblks *freeblks;
3365 	struct freework *parent;
3366 	ufs_lbn_t lbn;
3367 	ufs2_daddr_t nb;
3368 	int frags;
3369 	int journal;
3370 {
3371 	struct freework *freework;
3372 
3373 	freework = malloc(sizeof(*freework), M_FREEWORK, M_SOFTDEP_FLAGS);
3374 	workitem_alloc(&freework->fw_list, D_FREEWORK, freeblks->fb_list.wk_mp);
3375 	freework->fw_freeblks = freeblks;
3376 	freework->fw_parent = parent;
3377 	freework->fw_lbn = lbn;
3378 	freework->fw_blkno = nb;
3379 	freework->fw_frags = frags;
3380 	freework->fw_ref = 0;
3381 	freework->fw_off = 0;
3382 	LIST_INIT(&freework->fw_jwork);
3383 
3384 	if (parent == NULL) {
3385 		WORKLIST_INSERT_UNLOCKED(&freeblks->fb_freeworkhd,
3386 		    &freework->fw_list);
3387 		freeblks->fb_ref++;
3388 	}
3389 	if (journal)
3390 		newjfreeblk(freeblks, lbn, nb, frags);
3391 
3392 	return (freework);
3393 }
3394 
3395 /*
3396  * Allocate a new jfreeblk to journal top level block pointer when truncating
3397  * a file.  The caller must add this to the worklist when lk is held.
3398  */
3399 static struct jfreeblk *
3400 newjfreeblk(freeblks, lbn, blkno, frags)
3401 	struct freeblks *freeblks;
3402 	ufs_lbn_t lbn;
3403 	ufs2_daddr_t blkno;
3404 	int frags;
3405 {
3406 	struct jfreeblk *jfreeblk;
3407 
3408 	jfreeblk = malloc(sizeof(*jfreeblk), M_JFREEBLK, M_SOFTDEP_FLAGS);
3409 	workitem_alloc(&jfreeblk->jf_list, D_JFREEBLK, freeblks->fb_list.wk_mp);
3410 	jfreeblk->jf_jsegdep = newjsegdep(&jfreeblk->jf_list);
3411 	jfreeblk->jf_state = ATTACHED | DEPCOMPLETE;
3412 	jfreeblk->jf_ino = freeblks->fb_previousinum;
3413 	jfreeblk->jf_lbn = lbn;
3414 	jfreeblk->jf_blkno = blkno;
3415 	jfreeblk->jf_frags = frags;
3416 	jfreeblk->jf_freeblks = freeblks;
3417 	LIST_INSERT_HEAD(&freeblks->fb_jfreeblkhd, jfreeblk, jf_deps);
3418 
3419 	return (jfreeblk);
3420 }
3421 
3422 static void move_newblock_dep(struct jaddref *, struct inodedep *);
3423 /*
3424  * If we're canceling a new bitmap we have to search for another ref
3425  * to move into the bmsafemap dep.  This might be better expressed
3426  * with another structure.
3427  */
3428 static void
3429 move_newblock_dep(jaddref, inodedep)
3430 	struct jaddref *jaddref;
3431 	struct inodedep *inodedep;
3432 {
3433 	struct inoref *inoref;
3434 	struct jaddref *jaddrefn;
3435 
3436 	jaddrefn = NULL;
3437 	for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
3438 	    inoref = TAILQ_NEXT(inoref, if_deps)) {
3439 		if ((jaddref->ja_state & NEWBLOCK) &&
3440 		    inoref->if_list.wk_type == D_JADDREF) {
3441 			jaddrefn = (struct jaddref *)inoref;
3442 			break;
3443 		}
3444 	}
3445 	if (jaddrefn == NULL)
3446 		return;
3447 	jaddrefn->ja_state &= ~(ATTACHED | UNDONE);
3448 	jaddrefn->ja_state |= jaddref->ja_state &
3449 	    (ATTACHED | UNDONE | NEWBLOCK);
3450 	jaddref->ja_state &= ~(ATTACHED | UNDONE | NEWBLOCK);
3451 	jaddref->ja_state |= ATTACHED;
3452 	LIST_REMOVE(jaddref, ja_bmdeps);
3453 	LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_jaddrefhd, jaddrefn,
3454 	    ja_bmdeps);
3455 }
3456 
3457 /*
3458  * Cancel a jaddref either before it has been written or while it is being
3459  * written.  This happens when a link is removed before the add reaches
3460  * the disk.  The jaddref dependency is kept linked into the bmsafemap
3461  * and inode to prevent the link count or bitmap from reaching the disk
3462  * until handle_workitem_remove() re-adjusts the counts and bitmaps as
3463  * required.
3464  *
3465  * Returns 1 if the canceled addref requires journaling of the remove and
3466  * 0 otherwise.
3467  */
3468 static int
3469 cancel_jaddref(jaddref, inodedep, wkhd)
3470 	struct jaddref *jaddref;
3471 	struct inodedep *inodedep;
3472 	struct workhead *wkhd;
3473 {
3474 	struct inoref *inoref;
3475 	struct jsegdep *jsegdep;
3476 	int needsj;
3477 
3478 	KASSERT((jaddref->ja_state & COMPLETE) == 0,
3479 	    ("cancel_jaddref: Canceling complete jaddref"));
3480 	if (jaddref->ja_state & (IOSTARTED | COMPLETE))
3481 		needsj = 1;
3482 	else
3483 		needsj = 0;
3484 	if (inodedep == NULL)
3485 		if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
3486 		    0, &inodedep) == 0)
3487 			panic("cancel_jaddref: Lost inodedep");
3488 	/*
3489 	 * We must adjust the nlink of any reference operation that follows
3490 	 * us so that it is consistent with the in-memory reference.  This
3491 	 * ensures that inode nlink rollbacks always have the correct link.
3492 	 */
3493 	if (needsj == 0)
3494 		for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
3495 		    inoref = TAILQ_NEXT(inoref, if_deps))
3496 			inoref->if_nlink--;
3497 	jsegdep = inoref_jseg(&jaddref->ja_ref);
3498 	if (jaddref->ja_state & NEWBLOCK)
3499 		move_newblock_dep(jaddref, inodedep);
3500 	if (jaddref->ja_state & IOWAITING) {
3501 		jaddref->ja_state &= ~IOWAITING;
3502 		wakeup(&jaddref->ja_list);
3503 	}
3504 	jaddref->ja_mkdir = NULL;
3505 	if (jaddref->ja_state & IOSTARTED) {
3506 		jaddref->ja_state &= ~IOSTARTED;
3507 		WORKLIST_REMOVE(&jaddref->ja_list);
3508 		WORKLIST_INSERT(wkhd, &jsegdep->jd_list);
3509 	} else {
3510 		free_jsegdep(jsegdep);
3511 		if (jaddref->ja_state & DEPCOMPLETE)
3512 			remove_from_journal(&jaddref->ja_list);
3513 	}
3514 	/*
3515 	 * Leave NEWBLOCK jaddrefs on the inodedep so handle_workitem_remove
3516 	 * can arrange for them to be freed with the bitmap.  Otherwise we
3517 	 * no longer need this addref attached to the inoreflst and it
3518 	 * will incorrectly adjust nlink if we leave it.
3519 	 */
3520 	if ((jaddref->ja_state & NEWBLOCK) == 0) {
3521 		TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
3522 		    if_deps);
3523 		jaddref->ja_state |= COMPLETE;
3524 		free_jaddref(jaddref);
3525 		return (needsj);
3526 	}
3527 	jaddref->ja_state |= GOINGAWAY;
3528 	/*
3529 	 * Leave the head of the list for jsegdeps for fast merging.
3530 	 */
3531 	if (LIST_FIRST(wkhd) != NULL) {
3532 		jaddref->ja_state |= ONWORKLIST;
3533 		LIST_INSERT_AFTER(LIST_FIRST(wkhd), &jaddref->ja_list, wk_list);
3534 	} else
3535 		WORKLIST_INSERT(wkhd, &jaddref->ja_list);
3536 
3537 	return (needsj);
3538 }
3539 
3540 /*
3541  * Attempt to free a jaddref structure when some work completes.  This
3542  * should only succeed once the entry is written and all dependencies have
3543  * been notified.
3544  */
3545 static void
3546 free_jaddref(jaddref)
3547 	struct jaddref *jaddref;
3548 {
3549 
3550 	if ((jaddref->ja_state & ALLCOMPLETE) != ALLCOMPLETE)
3551 		return;
3552 	if (jaddref->ja_ref.if_jsegdep)
3553 		panic("free_jaddref: segdep attached to jaddref %p(0x%X)\n",
3554 		    jaddref, jaddref->ja_state);
3555 	if (jaddref->ja_state & NEWBLOCK)
3556 		LIST_REMOVE(jaddref, ja_bmdeps);
3557 	if (jaddref->ja_state & (IOSTARTED | ONWORKLIST))
3558 		panic("free_jaddref: Bad state %p(0x%X)",
3559 		    jaddref, jaddref->ja_state);
3560 	if (jaddref->ja_mkdir != NULL)
3561 		panic("free_jaddref: Work pending, 0x%X\n", jaddref->ja_state);
3562 	WORKITEM_FREE(jaddref, D_JADDREF);
3563 }
3564 
3565 /*
3566  * Free a jremref structure once it has been written or discarded.
3567  */
3568 static void
3569 free_jremref(jremref)
3570 	struct jremref *jremref;
3571 {
3572 
3573 	if (jremref->jr_ref.if_jsegdep)
3574 		free_jsegdep(jremref->jr_ref.if_jsegdep);
3575 	if (jremref->jr_state & IOSTARTED)
3576 		panic("free_jremref: IO still pending");
3577 	WORKITEM_FREE(jremref, D_JREMREF);
3578 }
3579 
3580 /*
3581  * Free a jnewblk structure.
3582  */
3583 static void
3584 free_jnewblk(jnewblk)
3585 	struct jnewblk *jnewblk;
3586 {
3587 
3588 	if ((jnewblk->jn_state & ALLCOMPLETE) != ALLCOMPLETE)
3589 		return;
3590 	LIST_REMOVE(jnewblk, jn_deps);
3591 	if (jnewblk->jn_newblk != NULL)
3592 		panic("free_jnewblk: Dependency still attached.");
3593 	WORKITEM_FREE(jnewblk, D_JNEWBLK);
3594 }
3595 
3596 /*
3597  * Cancel a jnewblk which has been superseded by a freeblk.  The jnewblk
3598  * is kept linked into the bmsafemap until the free completes, thus
3599  * preventing the modified state from ever reaching disk.  The free
3600  * routine must pass this structure via ffs_blkfree() to
3601  * softdep_setup_freeblks() so there is no race in releasing the space.
3602  */
3603 static void
3604 cancel_jnewblk(jnewblk, wkhd)
3605 	struct jnewblk *jnewblk;
3606 	struct workhead *wkhd;
3607 {
3608 	struct jsegdep *jsegdep;
3609 
3610 	jsegdep = jnewblk->jn_jsegdep;
3611 	jnewblk->jn_jsegdep  = NULL;
3612 	free_jsegdep(jsegdep);
3613 	jnewblk->jn_newblk = NULL;
3614 	jnewblk->jn_state |= GOINGAWAY;
3615 	if (jnewblk->jn_state & IOSTARTED) {
3616 		jnewblk->jn_state &= ~IOSTARTED;
3617 		WORKLIST_REMOVE(&jnewblk->jn_list);
3618 	} else
3619 		remove_from_journal(&jnewblk->jn_list);
3620 	/*
3621 	 * Leave the head of the list for jsegdeps for fast merging.
3622 	 */
3623 	if (LIST_FIRST(wkhd) != NULL) {
3624 		jnewblk->jn_state |= ONWORKLIST;
3625 		LIST_INSERT_AFTER(LIST_FIRST(wkhd), &jnewblk->jn_list, wk_list);
3626 	} else
3627 		WORKLIST_INSERT(wkhd, &jnewblk->jn_list);
3628 	if (jnewblk->jn_state & IOWAITING) {
3629 		jnewblk->jn_state &= ~IOWAITING;
3630 		wakeup(&jnewblk->jn_list);
3631 	}
3632 }
3633 
3634 static void
3635 free_jfreeblk(jfreeblk)
3636 	struct jfreeblk *jfreeblk;
3637 {
3638 
3639 	WORKITEM_FREE(jfreeblk, D_JFREEBLK);
3640 }
3641 
3642 /*
3643  * Release one reference to a jseg and free it if the count reaches 0.  This
3644  * should eventually reclaim journal space as well.
3645  */
3646 static void
3647 free_jseg(jseg)
3648 	struct jseg *jseg;
3649 {
3650 	struct jblocks *jblocks;
3651 
3652 	KASSERT(jseg->js_refs > 0,
3653 	    ("free_jseg: Invalid refcnt %d", jseg->js_refs));
3654 	if (--jseg->js_refs != 0)
3655 		return;
3656 	/*
3657 	 * Free only those jsegs which have none allocated before them to
3658 	 * preserve the journal space ordering.
3659 	 */
3660 	jblocks = jseg->js_jblocks;
3661 	while ((jseg = TAILQ_FIRST(&jblocks->jb_segs)) != NULL) {
3662 		jblocks->jb_oldestseq = jseg->js_seq;
3663 		if (jseg->js_refs != 0)
3664 			break;
3665 		TAILQ_REMOVE(&jblocks->jb_segs, jseg, js_next);
3666 		jblocks_free(jblocks, jseg->js_list.wk_mp, jseg->js_size);
3667 		KASSERT(LIST_EMPTY(&jseg->js_entries),
3668 		    ("free_jseg: Freed jseg has valid entries."));
3669 		WORKITEM_FREE(jseg, D_JSEG);
3670 	}
3671 }
3672 
3673 /*
3674  * Release a jsegdep and decrement the jseg count.
3675  */
3676 static void
3677 free_jsegdep(jsegdep)
3678 	struct jsegdep *jsegdep;
3679 {
3680 
3681 	if (jsegdep->jd_seg)
3682 		free_jseg(jsegdep->jd_seg);
3683 	WORKITEM_FREE(jsegdep, D_JSEGDEP);
3684 }
3685 
3686 /*
3687  * Wait for a journal item to make it to disk.  Initiate journal processing
3688  * if required.
3689  */
3690 static void
3691 jwait(wk)
3692 	struct worklist *wk;
3693 {
3694 
3695 	stat_journal_wait++;
3696 	/*
3697 	 * If IO has not started we process the journal.  We can't mark the
3698 	 * worklist item as IOWAITING because we drop the lock while
3699 	 * processing the journal and the worklist entry may be freed after
3700 	 * this point.  The caller may call back in and re-issue the request.
3701 	 */
3702 	if ((wk->wk_state & IOSTARTED) == 0) {
3703 		softdep_process_journal(wk->wk_mp, MNT_WAIT);
3704 		return;
3705 	}
3706 	wk->wk_state |= IOWAITING;
3707 	msleep(wk, &lk, PRIBIO, "jwait", 0);
3708 }
3709 
3710 /*
3711  * Lookup an inodedep based on an inode pointer and set the nlinkdelta as
3712  * appropriate.  This is a convenience function to reduce duplicate code
3713  * for the setup and revert functions below.
3714  */
3715 static struct inodedep *
3716 inodedep_lookup_ip(ip)
3717 	struct inode *ip;
3718 {
3719 	struct inodedep *inodedep;
3720 
3721 	KASSERT(ip->i_nlink >= ip->i_effnlink,
3722 	    ("inodedep_lookup_ip: bad delta"));
3723 	(void) inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number,
3724 	    DEPALLOC, &inodedep);
3725 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
3726 
3727 	return (inodedep);
3728 }
3729 
3730 /*
3731  * Create a journal entry that describes a truncate that we're about to
3732  * perform.  The inode allocations and frees between here and the completion
3733  * of the operation are done asynchronously and without journaling.  At
3734  * the end of the operation the vnode is sync'd and the journal space
3735  * is released.  Recovery will discover the partially completed truncate
3736  * and complete it.
3737  */
3738 void *
3739 softdep_setup_trunc(vp, length, flags)
3740 	struct vnode *vp;
3741 	off_t length;
3742 	int flags;
3743 {
3744 	struct jsegdep *jsegdep;
3745 	struct jtrunc *jtrunc;
3746 	struct ufsmount *ump;
3747 	struct inode *ip;
3748 
3749 	softdep_prealloc(vp, MNT_WAIT);
3750 	ip = VTOI(vp);
3751 	ump = VFSTOUFS(vp->v_mount);
3752 	jtrunc = malloc(sizeof(*jtrunc), M_JTRUNC, M_SOFTDEP_FLAGS);
3753 	workitem_alloc(&jtrunc->jt_list, D_JTRUNC, vp->v_mount);
3754 	jsegdep = jtrunc->jt_jsegdep = newjsegdep(&jtrunc->jt_list);
3755 	jtrunc->jt_ino = ip->i_number;
3756 	jtrunc->jt_extsize = 0;
3757 	jtrunc->jt_size = length;
3758 	if ((flags & IO_EXT) == 0 && ump->um_fstype == UFS2)
3759 		jtrunc->jt_extsize = ip->i_din2->di_extsize;
3760 	if ((flags & IO_NORMAL) == 0)
3761 		jtrunc->jt_size = DIP(ip, i_size);
3762 	ACQUIRE_LOCK(&lk);
3763 	add_to_journal(&jtrunc->jt_list);
3764 	while (jsegdep->jd_seg == NULL) {
3765 		stat_jwait_freeblks++;
3766 		jwait(&jtrunc->jt_list);
3767 	}
3768 	FREE_LOCK(&lk);
3769 
3770 	return (jsegdep);
3771 }
3772 
3773 /*
3774  * After synchronous truncation is complete we free sync the vnode and
3775  * release the jsegdep so the journal space can be freed.
3776  */
3777 int
3778 softdep_complete_trunc(vp, cookie)
3779 	struct vnode *vp;
3780 	void *cookie;
3781 {
3782 	int error;
3783 
3784 	error = ffs_syncvnode(vp, MNT_WAIT);
3785 	ACQUIRE_LOCK(&lk);
3786 	free_jsegdep((struct jsegdep *)cookie);
3787 	FREE_LOCK(&lk);
3788 
3789 	return (error);
3790 }
3791 
3792 /*
3793  * Called prior to creating a new inode and linking it to a directory.  The
3794  * jaddref structure must already be allocated by softdep_setup_inomapdep
3795  * and it is discovered here so we can initialize the mode and update
3796  * nlinkdelta.
3797  */
3798 void
3799 softdep_setup_create(dp, ip)
3800 	struct inode *dp;
3801 	struct inode *ip;
3802 {
3803 	struct inodedep *inodedep;
3804 	struct jaddref *jaddref;
3805 	struct vnode *dvp;
3806 
3807 	KASSERT(ip->i_nlink == 1,
3808 	    ("softdep_setup_create: Invalid link count."));
3809 	dvp = ITOV(dp);
3810 	ACQUIRE_LOCK(&lk);
3811 	inodedep = inodedep_lookup_ip(ip);
3812 	if (DOINGSUJ(dvp)) {
3813 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
3814 		    inoreflst);
3815 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
3816 		    ("softdep_setup_create: No addref structure present."));
3817 		jaddref->ja_mode = ip->i_mode;
3818 	}
3819 	softdep_prelink(dvp, NULL);
3820 	FREE_LOCK(&lk);
3821 }
3822 
3823 /*
3824  * Create a jaddref structure to track the addition of a DOTDOT link when
3825  * we are reparenting an inode as part of a rename.  This jaddref will be
3826  * found by softdep_setup_directory_change.  Adjusts nlinkdelta for
3827  * non-journaling softdep.
3828  */
3829 void
3830 softdep_setup_dotdot_link(dp, ip)
3831 	struct inode *dp;
3832 	struct inode *ip;
3833 {
3834 	struct inodedep *inodedep;
3835 	struct jaddref *jaddref;
3836 	struct vnode *dvp;
3837 	struct vnode *vp;
3838 
3839 	dvp = ITOV(dp);
3840 	vp = ITOV(ip);
3841 	jaddref = NULL;
3842 	/*
3843 	 * We don't set MKDIR_PARENT as this is not tied to a mkdir and
3844 	 * is used as a normal link would be.
3845 	 */
3846 	if (DOINGSUJ(dvp))
3847 		jaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
3848 		    dp->i_effnlink - 1, dp->i_mode);
3849 	ACQUIRE_LOCK(&lk);
3850 	inodedep = inodedep_lookup_ip(dp);
3851 	if (jaddref)
3852 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
3853 		    if_deps);
3854 	softdep_prelink(dvp, ITOV(ip));
3855 	FREE_LOCK(&lk);
3856 }
3857 
3858 /*
3859  * Create a jaddref structure to track a new link to an inode.  The directory
3860  * offset is not known until softdep_setup_directory_add or
3861  * softdep_setup_directory_change.  Adjusts nlinkdelta for non-journaling
3862  * softdep.
3863  */
3864 void
3865 softdep_setup_link(dp, ip)
3866 	struct inode *dp;
3867 	struct inode *ip;
3868 {
3869 	struct inodedep *inodedep;
3870 	struct jaddref *jaddref;
3871 	struct vnode *dvp;
3872 
3873 	dvp = ITOV(dp);
3874 	jaddref = NULL;
3875 	if (DOINGSUJ(dvp))
3876 		jaddref = newjaddref(dp, ip->i_number, 0, ip->i_effnlink - 1,
3877 		    ip->i_mode);
3878 	ACQUIRE_LOCK(&lk);
3879 	inodedep = inodedep_lookup_ip(ip);
3880 	if (jaddref)
3881 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
3882 		    if_deps);
3883 	softdep_prelink(dvp, ITOV(ip));
3884 	FREE_LOCK(&lk);
3885 }
3886 
3887 /*
3888  * Called to create the jaddref structures to track . and .. references as
3889  * well as lookup and further initialize the incomplete jaddref created
3890  * by softdep_setup_inomapdep when the inode was allocated.  Adjusts
3891  * nlinkdelta for non-journaling softdep.
3892  */
3893 void
3894 softdep_setup_mkdir(dp, ip)
3895 	struct inode *dp;
3896 	struct inode *ip;
3897 {
3898 	struct inodedep *inodedep;
3899 	struct jaddref *dotdotaddref;
3900 	struct jaddref *dotaddref;
3901 	struct jaddref *jaddref;
3902 	struct vnode *dvp;
3903 
3904 	dvp = ITOV(dp);
3905 	dotaddref = dotdotaddref = NULL;
3906 	if (DOINGSUJ(dvp)) {
3907 		dotaddref = newjaddref(ip, ip->i_number, DOT_OFFSET, 1,
3908 		    ip->i_mode);
3909 		dotaddref->ja_state |= MKDIR_BODY;
3910 		dotdotaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
3911 		    dp->i_effnlink - 1, dp->i_mode);
3912 		dotdotaddref->ja_state |= MKDIR_PARENT;
3913 	}
3914 	ACQUIRE_LOCK(&lk);
3915 	inodedep = inodedep_lookup_ip(ip);
3916 	if (DOINGSUJ(dvp)) {
3917 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
3918 		    inoreflst);
3919 		KASSERT(jaddref != NULL,
3920 		    ("softdep_setup_mkdir: No addref structure present."));
3921 		KASSERT(jaddref->ja_parent == dp->i_number,
3922 		    ("softdep_setup_mkdir: bad parent %d",
3923 		    jaddref->ja_parent));
3924 		jaddref->ja_mode = ip->i_mode;
3925 		TAILQ_INSERT_BEFORE(&jaddref->ja_ref, &dotaddref->ja_ref,
3926 		    if_deps);
3927 	}
3928 	inodedep = inodedep_lookup_ip(dp);
3929 	if (DOINGSUJ(dvp))
3930 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst,
3931 		    &dotdotaddref->ja_ref, if_deps);
3932 	softdep_prelink(ITOV(dp), NULL);
3933 	FREE_LOCK(&lk);
3934 }
3935 
3936 /*
3937  * Called to track nlinkdelta of the inode and parent directories prior to
3938  * unlinking a directory.
3939  */
3940 void
3941 softdep_setup_rmdir(dp, ip)
3942 	struct inode *dp;
3943 	struct inode *ip;
3944 {
3945 	struct vnode *dvp;
3946 
3947 	dvp = ITOV(dp);
3948 	ACQUIRE_LOCK(&lk);
3949 	(void) inodedep_lookup_ip(ip);
3950 	(void) inodedep_lookup_ip(dp);
3951 	softdep_prelink(dvp, ITOV(ip));
3952 	FREE_LOCK(&lk);
3953 }
3954 
3955 /*
3956  * Called to track nlinkdelta of the inode and parent directories prior to
3957  * unlink.
3958  */
3959 void
3960 softdep_setup_unlink(dp, ip)
3961 	struct inode *dp;
3962 	struct inode *ip;
3963 {
3964 	struct vnode *dvp;
3965 
3966 	dvp = ITOV(dp);
3967 	ACQUIRE_LOCK(&lk);
3968 	(void) inodedep_lookup_ip(ip);
3969 	(void) inodedep_lookup_ip(dp);
3970 	softdep_prelink(dvp, ITOV(ip));
3971 	FREE_LOCK(&lk);
3972 }
3973 
3974 /*
3975  * Called to release the journal structures created by a failed non-directory
3976  * creation.  Adjusts nlinkdelta for non-journaling softdep.
3977  */
3978 void
3979 softdep_revert_create(dp, ip)
3980 	struct inode *dp;
3981 	struct inode *ip;
3982 {
3983 	struct inodedep *inodedep;
3984 	struct jaddref *jaddref;
3985 	struct vnode *dvp;
3986 
3987 	dvp = ITOV(dp);
3988 	ACQUIRE_LOCK(&lk);
3989 	inodedep = inodedep_lookup_ip(ip);
3990 	if (DOINGSUJ(dvp)) {
3991 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
3992 		    inoreflst);
3993 		KASSERT(jaddref->ja_parent == dp->i_number,
3994 		    ("softdep_revert_create: addref parent mismatch"));
3995 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
3996 	}
3997 	FREE_LOCK(&lk);
3998 }
3999 
4000 /*
4001  * Called to release the journal structures created by a failed dotdot link
4002  * creation.  Adjusts nlinkdelta for non-journaling softdep.
4003  */
4004 void
4005 softdep_revert_dotdot_link(dp, ip)
4006 	struct inode *dp;
4007 	struct inode *ip;
4008 {
4009 	struct inodedep *inodedep;
4010 	struct jaddref *jaddref;
4011 	struct vnode *dvp;
4012 
4013 	dvp = ITOV(dp);
4014 	ACQUIRE_LOCK(&lk);
4015 	inodedep = inodedep_lookup_ip(dp);
4016 	if (DOINGSUJ(dvp)) {
4017 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4018 		    inoreflst);
4019 		KASSERT(jaddref->ja_parent == ip->i_number,
4020 		    ("softdep_revert_dotdot_link: addref parent mismatch"));
4021 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4022 	}
4023 	FREE_LOCK(&lk);
4024 }
4025 
4026 /*
4027  * Called to release the journal structures created by a failed link
4028  * addition.  Adjusts nlinkdelta for non-journaling softdep.
4029  */
4030 void
4031 softdep_revert_link(dp, ip)
4032 	struct inode *dp;
4033 	struct inode *ip;
4034 {
4035 	struct inodedep *inodedep;
4036 	struct jaddref *jaddref;
4037 	struct vnode *dvp;
4038 
4039 	dvp = ITOV(dp);
4040 	ACQUIRE_LOCK(&lk);
4041 	inodedep = inodedep_lookup_ip(ip);
4042 	if (DOINGSUJ(dvp)) {
4043 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4044 		    inoreflst);
4045 		KASSERT(jaddref->ja_parent == dp->i_number,
4046 		    ("softdep_revert_link: addref parent mismatch"));
4047 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4048 	}
4049 	FREE_LOCK(&lk);
4050 }
4051 
4052 /*
4053  * Called to release the journal structures created by a failed mkdir
4054  * attempt.  Adjusts nlinkdelta for non-journaling softdep.
4055  */
4056 void
4057 softdep_revert_mkdir(dp, ip)
4058 	struct inode *dp;
4059 	struct inode *ip;
4060 {
4061 	struct inodedep *inodedep;
4062 	struct jaddref *jaddref;
4063 	struct vnode *dvp;
4064 
4065 	dvp = ITOV(dp);
4066 
4067 	ACQUIRE_LOCK(&lk);
4068 	inodedep = inodedep_lookup_ip(dp);
4069 	if (DOINGSUJ(dvp)) {
4070 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4071 		    inoreflst);
4072 		KASSERT(jaddref->ja_parent == ip->i_number,
4073 		    ("softdep_revert_mkdir: dotdot addref parent mismatch"));
4074 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4075 	}
4076 	inodedep = inodedep_lookup_ip(ip);
4077 	if (DOINGSUJ(dvp)) {
4078 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4079 		    inoreflst);
4080 		KASSERT(jaddref->ja_parent == dp->i_number,
4081 		    ("softdep_revert_mkdir: addref parent mismatch"));
4082 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4083 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4084 		    inoreflst);
4085 		KASSERT(jaddref->ja_parent == ip->i_number,
4086 		    ("softdep_revert_mkdir: dot addref parent mismatch"));
4087 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4088 	}
4089 	FREE_LOCK(&lk);
4090 }
4091 
4092 /*
4093  * Called to correct nlinkdelta after a failed rmdir.
4094  */
4095 void
4096 softdep_revert_rmdir(dp, ip)
4097 	struct inode *dp;
4098 	struct inode *ip;
4099 {
4100 
4101 	ACQUIRE_LOCK(&lk);
4102 	(void) inodedep_lookup_ip(ip);
4103 	(void) inodedep_lookup_ip(dp);
4104 	FREE_LOCK(&lk);
4105 }
4106 
4107 /*
4108  * Protecting the freemaps (or bitmaps).
4109  *
4110  * To eliminate the need to execute fsck before mounting a filesystem
4111  * after a power failure, one must (conservatively) guarantee that the
4112  * on-disk copy of the bitmaps never indicate that a live inode or block is
4113  * free.  So, when a block or inode is allocated, the bitmap should be
4114  * updated (on disk) before any new pointers.  When a block or inode is
4115  * freed, the bitmap should not be updated until all pointers have been
4116  * reset.  The latter dependency is handled by the delayed de-allocation
4117  * approach described below for block and inode de-allocation.  The former
4118  * dependency is handled by calling the following procedure when a block or
4119  * inode is allocated. When an inode is allocated an "inodedep" is created
4120  * with its DEPCOMPLETE flag cleared until its bitmap is written to disk.
4121  * Each "inodedep" is also inserted into the hash indexing structure so
4122  * that any additional link additions can be made dependent on the inode
4123  * allocation.
4124  *
4125  * The ufs filesystem maintains a number of free block counts (e.g., per
4126  * cylinder group, per cylinder and per <cylinder, rotational position> pair)
4127  * in addition to the bitmaps.  These counts are used to improve efficiency
4128  * during allocation and therefore must be consistent with the bitmaps.
4129  * There is no convenient way to guarantee post-crash consistency of these
4130  * counts with simple update ordering, for two main reasons: (1) The counts
4131  * and bitmaps for a single cylinder group block are not in the same disk
4132  * sector.  If a disk write is interrupted (e.g., by power failure), one may
4133  * be written and the other not.  (2) Some of the counts are located in the
4134  * superblock rather than the cylinder group block. So, we focus our soft
4135  * updates implementation on protecting the bitmaps. When mounting a
4136  * filesystem, we recompute the auxiliary counts from the bitmaps.
4137  */
4138 
4139 /*
4140  * Called just after updating the cylinder group block to allocate an inode.
4141  */
4142 void
4143 softdep_setup_inomapdep(bp, ip, newinum)
4144 	struct buf *bp;		/* buffer for cylgroup block with inode map */
4145 	struct inode *ip;	/* inode related to allocation */
4146 	ino_t newinum;		/* new inode number being allocated */
4147 {
4148 	struct inodedep *inodedep;
4149 	struct bmsafemap *bmsafemap;
4150 	struct jaddref *jaddref;
4151 	struct mount *mp;
4152 	struct fs *fs;
4153 
4154 	mp = UFSTOVFS(ip->i_ump);
4155 	fs = ip->i_ump->um_fs;
4156 	jaddref = NULL;
4157 
4158 	/*
4159 	 * Allocate the journal reference add structure so that the bitmap
4160 	 * can be dependent on it.
4161 	 */
4162 	if (mp->mnt_kern_flag & MNTK_SUJ) {
4163 		jaddref = newjaddref(ip, newinum, 0, 0, 0);
4164 		jaddref->ja_state |= NEWBLOCK;
4165 	}
4166 
4167 	/*
4168 	 * Create a dependency for the newly allocated inode.
4169 	 * Panic if it already exists as something is seriously wrong.
4170 	 * Otherwise add it to the dependency list for the buffer holding
4171 	 * the cylinder group map from which it was allocated.
4172 	 */
4173 	ACQUIRE_LOCK(&lk);
4174 	if ((inodedep_lookup(mp, newinum, DEPALLOC|NODELAY, &inodedep)))
4175 		panic("softdep_setup_inomapdep: dependency %p for new"
4176 		    "inode already exists", inodedep);
4177 	bmsafemap = bmsafemap_lookup(mp, bp, ino_to_cg(fs, newinum));
4178 	if (jaddref) {
4179 		LIST_INSERT_HEAD(&bmsafemap->sm_jaddrefhd, jaddref, ja_bmdeps);
4180 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4181 		    if_deps);
4182 	} else {
4183 		inodedep->id_state |= ONDEPLIST;
4184 		LIST_INSERT_HEAD(&bmsafemap->sm_inodedephd, inodedep, id_deps);
4185 	}
4186 	inodedep->id_bmsafemap = bmsafemap;
4187 	inodedep->id_state &= ~DEPCOMPLETE;
4188 	FREE_LOCK(&lk);
4189 }
4190 
4191 /*
4192  * Called just after updating the cylinder group block to
4193  * allocate block or fragment.
4194  */
4195 void
4196 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
4197 	struct buf *bp;		/* buffer for cylgroup block with block map */
4198 	struct mount *mp;	/* filesystem doing allocation */
4199 	ufs2_daddr_t newblkno;	/* number of newly allocated block */
4200 	int frags;		/* Number of fragments. */
4201 	int oldfrags;		/* Previous number of fragments for extend. */
4202 {
4203 	struct newblk *newblk;
4204 	struct bmsafemap *bmsafemap;
4205 	struct jnewblk *jnewblk;
4206 	struct fs *fs;
4207 
4208 	fs = VFSTOUFS(mp)->um_fs;
4209 	jnewblk = NULL;
4210 	/*
4211 	 * Create a dependency for the newly allocated block.
4212 	 * Add it to the dependency list for the buffer holding
4213 	 * the cylinder group map from which it was allocated.
4214 	 */
4215 	if (mp->mnt_kern_flag & MNTK_SUJ) {
4216 		jnewblk = malloc(sizeof(*jnewblk), M_JNEWBLK, M_SOFTDEP_FLAGS);
4217 		workitem_alloc(&jnewblk->jn_list, D_JNEWBLK, mp);
4218 		jnewblk->jn_jsegdep = newjsegdep(&jnewblk->jn_list);
4219 		jnewblk->jn_state = ATTACHED;
4220 		jnewblk->jn_blkno = newblkno;
4221 		jnewblk->jn_frags = frags;
4222 		jnewblk->jn_oldfrags = oldfrags;
4223 #ifdef SUJ_DEBUG
4224 		{
4225 			struct cg *cgp;
4226 			uint8_t *blksfree;
4227 			long bno;
4228 			int i;
4229 
4230 			cgp = (struct cg *)bp->b_data;
4231 			blksfree = cg_blksfree(cgp);
4232 			bno = dtogd(fs, jnewblk->jn_blkno);
4233 			for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags;
4234 			    i++) {
4235 				if (isset(blksfree, bno + i))
4236 					panic("softdep_setup_blkmapdep: "
4237 					    "free fragment %d from %d-%d "
4238 					    "state 0x%X dep %p", i,
4239 					    jnewblk->jn_oldfrags,
4240 					    jnewblk->jn_frags,
4241 					    jnewblk->jn_state,
4242 					    jnewblk->jn_newblk);
4243 			}
4244 		}
4245 #endif
4246 	}
4247 	ACQUIRE_LOCK(&lk);
4248 	if (newblk_lookup(mp, newblkno, DEPALLOC, &newblk) != 0)
4249 		panic("softdep_setup_blkmapdep: found block");
4250 	newblk->nb_bmsafemap = bmsafemap = bmsafemap_lookup(mp, bp,
4251 	    dtog(fs, newblkno));
4252 	if (jnewblk) {
4253 		jnewblk->jn_newblk = newblk;
4254 		LIST_INSERT_HEAD(&bmsafemap->sm_jnewblkhd, jnewblk, jn_deps);
4255 	} else {
4256 		newblk->nb_state |= ONDEPLIST;
4257 		LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
4258 	}
4259 	newblk->nb_bmsafemap = bmsafemap;
4260 	newblk->nb_jnewblk = jnewblk;
4261 	FREE_LOCK(&lk);
4262 }
4263 
4264 #define	BMSAFEMAP_HASH(fs, cg) \
4265       (&bmsafemap_hashtbl[((((register_t)(fs)) >> 13) + (cg)) & bmsafemap_hash])
4266 
4267 static int
4268 bmsafemap_find(bmsafemaphd, mp, cg, bmsafemapp)
4269 	struct bmsafemap_hashhead *bmsafemaphd;
4270 	struct mount *mp;
4271 	int cg;
4272 	struct bmsafemap **bmsafemapp;
4273 {
4274 	struct bmsafemap *bmsafemap;
4275 
4276 	LIST_FOREACH(bmsafemap, bmsafemaphd, sm_hash)
4277 		if (bmsafemap->sm_list.wk_mp == mp && bmsafemap->sm_cg == cg)
4278 			break;
4279 	if (bmsafemap) {
4280 		*bmsafemapp = bmsafemap;
4281 		return (1);
4282 	}
4283 	*bmsafemapp = NULL;
4284 
4285 	return (0);
4286 }
4287 
4288 /*
4289  * Find the bmsafemap associated with a cylinder group buffer.
4290  * If none exists, create one. The buffer must be locked when
4291  * this routine is called and this routine must be called with
4292  * splbio interrupts blocked.
4293  */
4294 static struct bmsafemap *
4295 bmsafemap_lookup(mp, bp, cg)
4296 	struct mount *mp;
4297 	struct buf *bp;
4298 	int cg;
4299 {
4300 	struct bmsafemap_hashhead *bmsafemaphd;
4301 	struct bmsafemap *bmsafemap, *collision;
4302 	struct worklist *wk;
4303 	struct fs *fs;
4304 
4305 	mtx_assert(&lk, MA_OWNED);
4306 	if (bp)
4307 		LIST_FOREACH(wk, &bp->b_dep, wk_list)
4308 			if (wk->wk_type == D_BMSAFEMAP)
4309 				return (WK_BMSAFEMAP(wk));
4310 	fs = VFSTOUFS(mp)->um_fs;
4311 	bmsafemaphd = BMSAFEMAP_HASH(fs, cg);
4312 	if (bmsafemap_find(bmsafemaphd, mp, cg, &bmsafemap) == 1)
4313 		return (bmsafemap);
4314 	FREE_LOCK(&lk);
4315 	bmsafemap = malloc(sizeof(struct bmsafemap),
4316 		M_BMSAFEMAP, M_SOFTDEP_FLAGS);
4317 	workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
4318 	bmsafemap->sm_buf = bp;
4319 	LIST_INIT(&bmsafemap->sm_inodedephd);
4320 	LIST_INIT(&bmsafemap->sm_inodedepwr);
4321 	LIST_INIT(&bmsafemap->sm_newblkhd);
4322 	LIST_INIT(&bmsafemap->sm_newblkwr);
4323 	LIST_INIT(&bmsafemap->sm_jaddrefhd);
4324 	LIST_INIT(&bmsafemap->sm_jnewblkhd);
4325 	ACQUIRE_LOCK(&lk);
4326 	if (bmsafemap_find(bmsafemaphd, mp, cg, &collision) == 1) {
4327 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
4328 		return (collision);
4329 	}
4330 	bmsafemap->sm_cg = cg;
4331 	LIST_INSERT_HEAD(bmsafemaphd, bmsafemap, sm_hash);
4332 	WORKLIST_INSERT(&bp->b_dep, &bmsafemap->sm_list);
4333 	return (bmsafemap);
4334 }
4335 
4336 /*
4337  * Direct block allocation dependencies.
4338  *
4339  * When a new block is allocated, the corresponding disk locations must be
4340  * initialized (with zeros or new data) before the on-disk inode points to
4341  * them.  Also, the freemap from which the block was allocated must be
4342  * updated (on disk) before the inode's pointer. These two dependencies are
4343  * independent of each other and are needed for all file blocks and indirect
4344  * blocks that are pointed to directly by the inode.  Just before the
4345  * "in-core" version of the inode is updated with a newly allocated block
4346  * number, a procedure (below) is called to setup allocation dependency
4347  * structures.  These structures are removed when the corresponding
4348  * dependencies are satisfied or when the block allocation becomes obsolete
4349  * (i.e., the file is deleted, the block is de-allocated, or the block is a
4350  * fragment that gets upgraded).  All of these cases are handled in
4351  * procedures described later.
4352  *
4353  * When a file extension causes a fragment to be upgraded, either to a larger
4354  * fragment or to a full block, the on-disk location may change (if the
4355  * previous fragment could not simply be extended). In this case, the old
4356  * fragment must be de-allocated, but not until after the inode's pointer has
4357  * been updated. In most cases, this is handled by later procedures, which
4358  * will construct a "freefrag" structure to be added to the workitem queue
4359  * when the inode update is complete (or obsolete).  The main exception to
4360  * this is when an allocation occurs while a pending allocation dependency
4361  * (for the same block pointer) remains.  This case is handled in the main
4362  * allocation dependency setup procedure by immediately freeing the
4363  * unreferenced fragments.
4364  */
4365 void
4366 softdep_setup_allocdirect(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
4367 	struct inode *ip;	/* inode to which block is being added */
4368 	ufs_lbn_t off;		/* block pointer within inode */
4369 	ufs2_daddr_t newblkno;	/* disk block number being added */
4370 	ufs2_daddr_t oldblkno;	/* previous block number, 0 unless frag */
4371 	long newsize;		/* size of new block */
4372 	long oldsize;		/* size of new block */
4373 	struct buf *bp;		/* bp for allocated block */
4374 {
4375 	struct allocdirect *adp, *oldadp;
4376 	struct allocdirectlst *adphead;
4377 	struct freefrag *freefrag;
4378 	struct inodedep *inodedep;
4379 	struct pagedep *pagedep;
4380 	struct jnewblk *jnewblk;
4381 	struct newblk *newblk;
4382 	struct mount *mp;
4383 	ufs_lbn_t lbn;
4384 
4385 	lbn = bp->b_lblkno;
4386 	mp = UFSTOVFS(ip->i_ump);
4387 	if (oldblkno && oldblkno != newblkno)
4388 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn);
4389 	else
4390 		freefrag = NULL;
4391 
4392 	ACQUIRE_LOCK(&lk);
4393 	if (off >= NDADDR) {
4394 		if (lbn > 0)
4395 			panic("softdep_setup_allocdirect: bad lbn %jd, off %jd",
4396 			    lbn, off);
4397 		/* allocating an indirect block */
4398 		if (oldblkno != 0)
4399 			panic("softdep_setup_allocdirect: non-zero indir");
4400 	} else {
4401 		if (off != lbn)
4402 			panic("softdep_setup_allocdirect: lbn %jd != off %jd",
4403 			    lbn, off);
4404 		/*
4405 		 * Allocating a direct block.
4406 		 *
4407 		 * If we are allocating a directory block, then we must
4408 		 * allocate an associated pagedep to track additions and
4409 		 * deletions.
4410 		 */
4411 		if ((ip->i_mode & IFMT) == IFDIR &&
4412 		    pagedep_lookup(mp, ip->i_number, off, DEPALLOC,
4413 		    &pagedep) == 0)
4414 			WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
4415 	}
4416 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
4417 		panic("softdep_setup_allocdirect: lost block");
4418 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
4419 	    ("softdep_setup_allocdirect: newblk already initialized"));
4420 	/*
4421 	 * Convert the newblk to an allocdirect.
4422 	 */
4423 	newblk->nb_list.wk_type = D_ALLOCDIRECT;
4424 	adp = (struct allocdirect *)newblk;
4425 	newblk->nb_freefrag = freefrag;
4426 	adp->ad_offset = off;
4427 	adp->ad_oldblkno = oldblkno;
4428 	adp->ad_newsize = newsize;
4429 	adp->ad_oldsize = oldsize;
4430 
4431 	/*
4432 	 * Finish initializing the journal.
4433 	 */
4434 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
4435 		jnewblk->jn_ino = ip->i_number;
4436 		jnewblk->jn_lbn = lbn;
4437 		add_to_journal(&jnewblk->jn_list);
4438 	}
4439 	if (freefrag && freefrag->ff_jfreefrag != NULL)
4440 		add_to_journal(&freefrag->ff_jfreefrag->fr_list);
4441 	inodedep_lookup(mp, ip->i_number, DEPALLOC | NODELAY, &inodedep);
4442 	adp->ad_inodedep = inodedep;
4443 
4444 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
4445 	/*
4446 	 * The list of allocdirects must be kept in sorted and ascending
4447 	 * order so that the rollback routines can quickly determine the
4448 	 * first uncommitted block (the size of the file stored on disk
4449 	 * ends at the end of the lowest committed fragment, or if there
4450 	 * are no fragments, at the end of the highest committed block).
4451 	 * Since files generally grow, the typical case is that the new
4452 	 * block is to be added at the end of the list. We speed this
4453 	 * special case by checking against the last allocdirect in the
4454 	 * list before laboriously traversing the list looking for the
4455 	 * insertion point.
4456 	 */
4457 	adphead = &inodedep->id_newinoupdt;
4458 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
4459 	if (oldadp == NULL || oldadp->ad_offset <= off) {
4460 		/* insert at end of list */
4461 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
4462 		if (oldadp != NULL && oldadp->ad_offset == off)
4463 			allocdirect_merge(adphead, adp, oldadp);
4464 		FREE_LOCK(&lk);
4465 		return;
4466 	}
4467 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
4468 		if (oldadp->ad_offset >= off)
4469 			break;
4470 	}
4471 	if (oldadp == NULL)
4472 		panic("softdep_setup_allocdirect: lost entry");
4473 	/* insert in middle of list */
4474 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
4475 	if (oldadp->ad_offset == off)
4476 		allocdirect_merge(adphead, adp, oldadp);
4477 
4478 	FREE_LOCK(&lk);
4479 }
4480 
4481 /*
4482  * Replace an old allocdirect dependency with a newer one.
4483  * This routine must be called with splbio interrupts blocked.
4484  */
4485 static void
4486 allocdirect_merge(adphead, newadp, oldadp)
4487 	struct allocdirectlst *adphead;	/* head of list holding allocdirects */
4488 	struct allocdirect *newadp;	/* allocdirect being added */
4489 	struct allocdirect *oldadp;	/* existing allocdirect being checked */
4490 {
4491 	struct worklist *wk;
4492 	struct freefrag *freefrag;
4493 	struct newdirblk *newdirblk;
4494 
4495 	freefrag = NULL;
4496 	mtx_assert(&lk, MA_OWNED);
4497 	if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
4498 	    newadp->ad_oldsize != oldadp->ad_newsize ||
4499 	    newadp->ad_offset >= NDADDR)
4500 		panic("%s %jd != new %jd || old size %ld != new %ld",
4501 		    "allocdirect_merge: old blkno",
4502 		    (intmax_t)newadp->ad_oldblkno,
4503 		    (intmax_t)oldadp->ad_newblkno,
4504 		    newadp->ad_oldsize, oldadp->ad_newsize);
4505 	newadp->ad_oldblkno = oldadp->ad_oldblkno;
4506 	newadp->ad_oldsize = oldadp->ad_oldsize;
4507 	/*
4508 	 * If the old dependency had a fragment to free or had never
4509 	 * previously had a block allocated, then the new dependency
4510 	 * can immediately post its freefrag and adopt the old freefrag.
4511 	 * This action is done by swapping the freefrag dependencies.
4512 	 * The new dependency gains the old one's freefrag, and the
4513 	 * old one gets the new one and then immediately puts it on
4514 	 * the worklist when it is freed by free_newblk. It is
4515 	 * not possible to do this swap when the old dependency had a
4516 	 * non-zero size but no previous fragment to free. This condition
4517 	 * arises when the new block is an extension of the old block.
4518 	 * Here, the first part of the fragment allocated to the new
4519 	 * dependency is part of the block currently claimed on disk by
4520 	 * the old dependency, so cannot legitimately be freed until the
4521 	 * conditions for the new dependency are fulfilled.
4522 	 */
4523 	freefrag = newadp->ad_freefrag;
4524 	if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
4525 		newadp->ad_freefrag = oldadp->ad_freefrag;
4526 		oldadp->ad_freefrag = freefrag;
4527 	}
4528 	/*
4529 	 * If we are tracking a new directory-block allocation,
4530 	 * move it from the old allocdirect to the new allocdirect.
4531 	 */
4532 	if ((wk = LIST_FIRST(&oldadp->ad_newdirblk)) != NULL) {
4533 		newdirblk = WK_NEWDIRBLK(wk);
4534 		WORKLIST_REMOVE(&newdirblk->db_list);
4535 		if (!LIST_EMPTY(&oldadp->ad_newdirblk))
4536 			panic("allocdirect_merge: extra newdirblk");
4537 		WORKLIST_INSERT(&newadp->ad_newdirblk, &newdirblk->db_list);
4538 	}
4539 	TAILQ_REMOVE(adphead, oldadp, ad_next);
4540 	/*
4541 	 * We need to move any journal dependencies over to the freefrag
4542 	 * that releases this block if it exists.  Otherwise we are
4543 	 * extending an existing block and we'll wait until that is
4544 	 * complete to release the journal space and extend the
4545 	 * new journal to cover this old space as well.
4546 	 */
4547 	if (freefrag == NULL) {
4548 		struct jnewblk *jnewblk;
4549 		struct jnewblk *njnewblk;
4550 
4551 		if (oldadp->ad_newblkno != newadp->ad_newblkno)
4552 			panic("allocdirect_merge: %jd != %jd",
4553 			    oldadp->ad_newblkno, newadp->ad_newblkno);
4554 		jnewblk = oldadp->ad_block.nb_jnewblk;
4555 		cancel_newblk(&oldadp->ad_block, &newadp->ad_block.nb_jwork);
4556 		/*
4557 		 * We have an unwritten jnewblk, we need to merge the
4558 		 * frag bits with our own.  The newer adp's journal can not
4559 		 * be written prior to the old one so no need to check for
4560 		 * it here.
4561 		 */
4562 		if (jnewblk) {
4563 			njnewblk = newadp->ad_block.nb_jnewblk;
4564 			if (njnewblk == NULL)
4565 				panic("allocdirect_merge: No jnewblk");
4566 			if (jnewblk->jn_state & UNDONE) {
4567 				njnewblk->jn_state |= UNDONE | NEWBLOCK;
4568 				njnewblk->jn_state &= ~ATTACHED;
4569 				jnewblk->jn_state &= ~UNDONE;
4570 			}
4571 			njnewblk->jn_oldfrags = jnewblk->jn_oldfrags;
4572 			WORKLIST_REMOVE(&jnewblk->jn_list);
4573 			jnewblk->jn_state |= ATTACHED | COMPLETE;
4574 			free_jnewblk(jnewblk);
4575 		}
4576 	} else {
4577 		/*
4578 		 * We can skip journaling for this freefrag and just complete
4579 		 * any pending journal work for the allocdirect that is being
4580 		 * removed after the freefrag completes.
4581 		 */
4582 		if (freefrag->ff_jfreefrag)
4583 			cancel_jfreefrag(freefrag->ff_jfreefrag);
4584 		cancel_newblk(&oldadp->ad_block, &freefrag->ff_jwork);
4585 	}
4586 	free_newblk(&oldadp->ad_block);
4587 }
4588 
4589 /*
4590  * Allocate a jfreefrag structure to journal a single block free.
4591  */
4592 static struct jfreefrag *
4593 newjfreefrag(freefrag, ip, blkno, size, lbn)
4594 	struct freefrag *freefrag;
4595 	struct inode *ip;
4596 	ufs2_daddr_t blkno;
4597 	long size;
4598 	ufs_lbn_t lbn;
4599 {
4600 	struct jfreefrag *jfreefrag;
4601 	struct fs *fs;
4602 
4603 	fs = ip->i_fs;
4604 	jfreefrag = malloc(sizeof(struct jfreefrag), M_JFREEFRAG,
4605 	    M_SOFTDEP_FLAGS);
4606 	workitem_alloc(&jfreefrag->fr_list, D_JFREEFRAG, UFSTOVFS(ip->i_ump));
4607 	jfreefrag->fr_jsegdep = newjsegdep(&jfreefrag->fr_list);
4608 	jfreefrag->fr_state = ATTACHED | DEPCOMPLETE;
4609 	jfreefrag->fr_ino = ip->i_number;
4610 	jfreefrag->fr_lbn = lbn;
4611 	jfreefrag->fr_blkno = blkno;
4612 	jfreefrag->fr_frags = numfrags(fs, size);
4613 	jfreefrag->fr_freefrag = freefrag;
4614 
4615 	return (jfreefrag);
4616 }
4617 
4618 /*
4619  * Allocate a new freefrag structure.
4620  */
4621 static struct freefrag *
4622 newfreefrag(ip, blkno, size, lbn)
4623 	struct inode *ip;
4624 	ufs2_daddr_t blkno;
4625 	long size;
4626 	ufs_lbn_t lbn;
4627 {
4628 	struct freefrag *freefrag;
4629 	struct fs *fs;
4630 
4631 	fs = ip->i_fs;
4632 	if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
4633 		panic("newfreefrag: frag size");
4634 	freefrag = malloc(sizeof(struct freefrag),
4635 	    M_FREEFRAG, M_SOFTDEP_FLAGS);
4636 	workitem_alloc(&freefrag->ff_list, D_FREEFRAG, UFSTOVFS(ip->i_ump));
4637 	freefrag->ff_state = ATTACHED;
4638 	LIST_INIT(&freefrag->ff_jwork);
4639 	freefrag->ff_inum = ip->i_number;
4640 	freefrag->ff_blkno = blkno;
4641 	freefrag->ff_fragsize = size;
4642 
4643 	if (fs->fs_flags & FS_SUJ) {
4644 		freefrag->ff_jfreefrag =
4645 		    newjfreefrag(freefrag, ip, blkno, size, lbn);
4646 	} else {
4647 		freefrag->ff_state |= DEPCOMPLETE;
4648 		freefrag->ff_jfreefrag = NULL;
4649 	}
4650 
4651 	return (freefrag);
4652 }
4653 
4654 /*
4655  * This workitem de-allocates fragments that were replaced during
4656  * file block allocation.
4657  */
4658 static void
4659 handle_workitem_freefrag(freefrag)
4660 	struct freefrag *freefrag;
4661 {
4662 	struct ufsmount *ump = VFSTOUFS(freefrag->ff_list.wk_mp);
4663 	struct workhead wkhd;
4664 
4665 	/*
4666 	 * It would be illegal to add new completion items to the
4667 	 * freefrag after it was schedule to be done so it must be
4668 	 * safe to modify the list head here.
4669 	 */
4670 	LIST_INIT(&wkhd);
4671 	LIST_SWAP(&freefrag->ff_jwork, &wkhd, worklist, wk_list);
4672 	ffs_blkfree(ump, ump->um_fs, ump->um_devvp, freefrag->ff_blkno,
4673 	    freefrag->ff_fragsize, freefrag->ff_inum, &wkhd);
4674 	ACQUIRE_LOCK(&lk);
4675 	WORKITEM_FREE(freefrag, D_FREEFRAG);
4676 	FREE_LOCK(&lk);
4677 }
4678 
4679 /*
4680  * Set up a dependency structure for an external attributes data block.
4681  * This routine follows much of the structure of softdep_setup_allocdirect.
4682  * See the description of softdep_setup_allocdirect above for details.
4683  */
4684 void
4685 softdep_setup_allocext(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
4686 	struct inode *ip;
4687 	ufs_lbn_t off;
4688 	ufs2_daddr_t newblkno;
4689 	ufs2_daddr_t oldblkno;
4690 	long newsize;
4691 	long oldsize;
4692 	struct buf *bp;
4693 {
4694 	struct allocdirect *adp, *oldadp;
4695 	struct allocdirectlst *adphead;
4696 	struct freefrag *freefrag;
4697 	struct inodedep *inodedep;
4698 	struct jnewblk *jnewblk;
4699 	struct newblk *newblk;
4700 	struct mount *mp;
4701 	ufs_lbn_t lbn;
4702 
4703 	if (off >= NXADDR)
4704 		panic("softdep_setup_allocext: lbn %lld > NXADDR",
4705 		    (long long)off);
4706 
4707 	lbn = bp->b_lblkno;
4708 	mp = UFSTOVFS(ip->i_ump);
4709 	if (oldblkno && oldblkno != newblkno)
4710 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn);
4711 	else
4712 		freefrag = NULL;
4713 
4714 	ACQUIRE_LOCK(&lk);
4715 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
4716 		panic("softdep_setup_allocext: lost block");
4717 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
4718 	    ("softdep_setup_allocext: newblk already initialized"));
4719 	/*
4720 	 * Convert the newblk to an allocdirect.
4721 	 */
4722 	newblk->nb_list.wk_type = D_ALLOCDIRECT;
4723 	adp = (struct allocdirect *)newblk;
4724 	newblk->nb_freefrag = freefrag;
4725 	adp->ad_offset = off;
4726 	adp->ad_oldblkno = oldblkno;
4727 	adp->ad_newsize = newsize;
4728 	adp->ad_oldsize = oldsize;
4729 	adp->ad_state |=  EXTDATA;
4730 
4731 	/*
4732 	 * Finish initializing the journal.
4733 	 */
4734 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
4735 		jnewblk->jn_ino = ip->i_number;
4736 		jnewblk->jn_lbn = lbn;
4737 		add_to_journal(&jnewblk->jn_list);
4738 	}
4739 	if (freefrag && freefrag->ff_jfreefrag != NULL)
4740 		add_to_journal(&freefrag->ff_jfreefrag->fr_list);
4741 	inodedep_lookup(mp, ip->i_number, DEPALLOC | NODELAY, &inodedep);
4742 	adp->ad_inodedep = inodedep;
4743 
4744 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
4745 	/*
4746 	 * The list of allocdirects must be kept in sorted and ascending
4747 	 * order so that the rollback routines can quickly determine the
4748 	 * first uncommitted block (the size of the file stored on disk
4749 	 * ends at the end of the lowest committed fragment, or if there
4750 	 * are no fragments, at the end of the highest committed block).
4751 	 * Since files generally grow, the typical case is that the new
4752 	 * block is to be added at the end of the list. We speed this
4753 	 * special case by checking against the last allocdirect in the
4754 	 * list before laboriously traversing the list looking for the
4755 	 * insertion point.
4756 	 */
4757 	adphead = &inodedep->id_newextupdt;
4758 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
4759 	if (oldadp == NULL || oldadp->ad_offset <= off) {
4760 		/* insert at end of list */
4761 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
4762 		if (oldadp != NULL && oldadp->ad_offset == off)
4763 			allocdirect_merge(adphead, adp, oldadp);
4764 		FREE_LOCK(&lk);
4765 		return;
4766 	}
4767 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
4768 		if (oldadp->ad_offset >= off)
4769 			break;
4770 	}
4771 	if (oldadp == NULL)
4772 		panic("softdep_setup_allocext: lost entry");
4773 	/* insert in middle of list */
4774 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
4775 	if (oldadp->ad_offset == off)
4776 		allocdirect_merge(adphead, adp, oldadp);
4777 	FREE_LOCK(&lk);
4778 }
4779 
4780 /*
4781  * Indirect block allocation dependencies.
4782  *
4783  * The same dependencies that exist for a direct block also exist when
4784  * a new block is allocated and pointed to by an entry in a block of
4785  * indirect pointers. The undo/redo states described above are also
4786  * used here. Because an indirect block contains many pointers that
4787  * may have dependencies, a second copy of the entire in-memory indirect
4788  * block is kept. The buffer cache copy is always completely up-to-date.
4789  * The second copy, which is used only as a source for disk writes,
4790  * contains only the safe pointers (i.e., those that have no remaining
4791  * update dependencies). The second copy is freed when all pointers
4792  * are safe. The cache is not allowed to replace indirect blocks with
4793  * pending update dependencies. If a buffer containing an indirect
4794  * block with dependencies is written, these routines will mark it
4795  * dirty again. It can only be successfully written once all the
4796  * dependencies are removed. The ffs_fsync routine in conjunction with
4797  * softdep_sync_metadata work together to get all the dependencies
4798  * removed so that a file can be successfully written to disk. Three
4799  * procedures are used when setting up indirect block pointer
4800  * dependencies. The division is necessary because of the organization
4801  * of the "balloc" routine and because of the distinction between file
4802  * pages and file metadata blocks.
4803  */
4804 
4805 /*
4806  * Allocate a new allocindir structure.
4807  */
4808 static struct allocindir *
4809 newallocindir(ip, ptrno, newblkno, oldblkno, lbn)
4810 	struct inode *ip;	/* inode for file being extended */
4811 	int ptrno;		/* offset of pointer in indirect block */
4812 	ufs2_daddr_t newblkno;	/* disk block number being added */
4813 	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
4814 	ufs_lbn_t lbn;
4815 {
4816 	struct newblk *newblk;
4817 	struct allocindir *aip;
4818 	struct freefrag *freefrag;
4819 	struct jnewblk *jnewblk;
4820 
4821 	if (oldblkno)
4822 		freefrag = newfreefrag(ip, oldblkno, ip->i_fs->fs_bsize, lbn);
4823 	else
4824 		freefrag = NULL;
4825 	ACQUIRE_LOCK(&lk);
4826 	if (newblk_lookup(UFSTOVFS(ip->i_ump), newblkno, 0, &newblk) == 0)
4827 		panic("new_allocindir: lost block");
4828 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
4829 	    ("newallocindir: newblk already initialized"));
4830 	newblk->nb_list.wk_type = D_ALLOCINDIR;
4831 	newblk->nb_freefrag = freefrag;
4832 	aip = (struct allocindir *)newblk;
4833 	aip->ai_offset = ptrno;
4834 	aip->ai_oldblkno = oldblkno;
4835 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
4836 		jnewblk->jn_ino = ip->i_number;
4837 		jnewblk->jn_lbn = lbn;
4838 		add_to_journal(&jnewblk->jn_list);
4839 	}
4840 	if (freefrag && freefrag->ff_jfreefrag != NULL)
4841 		add_to_journal(&freefrag->ff_jfreefrag->fr_list);
4842 	return (aip);
4843 }
4844 
4845 /*
4846  * Called just before setting an indirect block pointer
4847  * to a newly allocated file page.
4848  */
4849 void
4850 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
4851 	struct inode *ip;	/* inode for file being extended */
4852 	ufs_lbn_t lbn;		/* allocated block number within file */
4853 	struct buf *bp;		/* buffer with indirect blk referencing page */
4854 	int ptrno;		/* offset of pointer in indirect block */
4855 	ufs2_daddr_t newblkno;	/* disk block number being added */
4856 	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
4857 	struct buf *nbp;	/* buffer holding allocated page */
4858 {
4859 	struct inodedep *inodedep;
4860 	struct allocindir *aip;
4861 	struct pagedep *pagedep;
4862 	struct mount *mp;
4863 
4864 	if (lbn != nbp->b_lblkno)
4865 		panic("softdep_setup_allocindir_page: lbn %jd != lblkno %jd",
4866 		    lbn, bp->b_lblkno);
4867 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_page");
4868 	mp = UFSTOVFS(ip->i_ump);
4869 	aip = newallocindir(ip, ptrno, newblkno, oldblkno, lbn);
4870 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
4871 	/*
4872 	 * If we are allocating a directory page, then we must
4873 	 * allocate an associated pagedep to track additions and
4874 	 * deletions.
4875 	 */
4876 	if ((ip->i_mode & IFMT) == IFDIR &&
4877 	    pagedep_lookup(mp, ip->i_number, lbn, DEPALLOC, &pagedep) == 0)
4878 		WORKLIST_INSERT(&nbp->b_dep, &pagedep->pd_list);
4879 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
4880 	setup_allocindir_phase2(bp, ip, inodedep, aip, lbn);
4881 	FREE_LOCK(&lk);
4882 }
4883 
4884 /*
4885  * Called just before setting an indirect block pointer to a
4886  * newly allocated indirect block.
4887  */
4888 void
4889 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
4890 	struct buf *nbp;	/* newly allocated indirect block */
4891 	struct inode *ip;	/* inode for file being extended */
4892 	struct buf *bp;		/* indirect block referencing allocated block */
4893 	int ptrno;		/* offset of pointer in indirect block */
4894 	ufs2_daddr_t newblkno;	/* disk block number being added */
4895 {
4896 	struct inodedep *inodedep;
4897 	struct allocindir *aip;
4898 	ufs_lbn_t lbn;
4899 
4900 	lbn = nbp->b_lblkno;
4901 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_meta");
4902 	aip = newallocindir(ip, ptrno, newblkno, 0, lbn);
4903 	inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, DEPALLOC, &inodedep);
4904 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
4905 	setup_allocindir_phase2(bp, ip, inodedep, aip, lbn);
4906 	FREE_LOCK(&lk);
4907 }
4908 
4909 static void
4910 indirdep_complete(indirdep)
4911 	struct indirdep *indirdep;
4912 {
4913 	struct allocindir *aip;
4914 
4915 	LIST_REMOVE(indirdep, ir_next);
4916 	indirdep->ir_state &= ~ONDEPLIST;
4917 
4918 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL) {
4919 		LIST_REMOVE(aip, ai_next);
4920 		free_newblk(&aip->ai_block);
4921 	}
4922 	/*
4923 	 * If this indirdep is not attached to a buf it was simply waiting
4924 	 * on completion to clear completehd.  free_indirdep() asserts
4925 	 * that nothing is dangling.
4926 	 */
4927 	if ((indirdep->ir_state & ONWORKLIST) == 0)
4928 		free_indirdep(indirdep);
4929 }
4930 
4931 /*
4932  * Called to finish the allocation of the "aip" allocated
4933  * by one of the two routines above.
4934  */
4935 static void
4936 setup_allocindir_phase2(bp, ip, inodedep, aip, lbn)
4937 	struct buf *bp;		/* in-memory copy of the indirect block */
4938 	struct inode *ip;	/* inode for file being extended */
4939 	struct inodedep *inodedep; /* Inodedep for ip */
4940 	struct allocindir *aip;	/* allocindir allocated by the above routines */
4941 	ufs_lbn_t lbn;		/* Logical block number for this block. */
4942 {
4943 	struct worklist *wk;
4944 	struct fs *fs;
4945 	struct newblk *newblk;
4946 	struct indirdep *indirdep, *newindirdep;
4947 	struct allocindir *oldaip;
4948 	struct freefrag *freefrag;
4949 	struct mount *mp;
4950 	ufs2_daddr_t blkno;
4951 
4952 	mp = UFSTOVFS(ip->i_ump);
4953 	fs = ip->i_fs;
4954 	mtx_assert(&lk, MA_OWNED);
4955 	if (bp->b_lblkno >= 0)
4956 		panic("setup_allocindir_phase2: not indir blk");
4957 	for (freefrag = NULL, indirdep = NULL, newindirdep = NULL; ; ) {
4958 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
4959 			if (wk->wk_type != D_INDIRDEP)
4960 				continue;
4961 			indirdep = WK_INDIRDEP(wk);
4962 			break;
4963 		}
4964 		if (indirdep == NULL && newindirdep) {
4965 			indirdep = newindirdep;
4966 			newindirdep = NULL;
4967 			WORKLIST_INSERT(&bp->b_dep, &indirdep->ir_list);
4968 			if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0,
4969 			    &newblk)) {
4970 				indirdep->ir_state |= ONDEPLIST;
4971 				LIST_INSERT_HEAD(&newblk->nb_indirdeps,
4972 				    indirdep, ir_next);
4973 			} else
4974 				indirdep->ir_state |= DEPCOMPLETE;
4975 		}
4976 		if (indirdep) {
4977 			aip->ai_indirdep = indirdep;
4978 			/*
4979 			 * Check to see if there is an existing dependency
4980 			 * for this block. If there is, merge the old
4981 			 * dependency into the new one.  This happens
4982 			 * as a result of reallocblk only.
4983 			 */
4984 			if (aip->ai_oldblkno == 0)
4985 				oldaip = NULL;
4986 			else
4987 
4988 				LIST_FOREACH(oldaip, &indirdep->ir_deplisthd,
4989 				    ai_next)
4990 					if (oldaip->ai_offset == aip->ai_offset)
4991 						break;
4992 			if (oldaip != NULL)
4993 				freefrag = allocindir_merge(aip, oldaip);
4994 			LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
4995 			KASSERT(aip->ai_offset >= 0 &&
4996 			    aip->ai_offset < NINDIR(ip->i_ump->um_fs),
4997 			    ("setup_allocindir_phase2: Bad offset %d",
4998 			    aip->ai_offset));
4999 			KASSERT(indirdep->ir_savebp != NULL,
5000 			    ("setup_allocindir_phase2 NULL ir_savebp"));
5001 			if (ip->i_ump->um_fstype == UFS1)
5002 				((ufs1_daddr_t *)indirdep->ir_savebp->b_data)
5003 				    [aip->ai_offset] = aip->ai_oldblkno;
5004 			else
5005 				((ufs2_daddr_t *)indirdep->ir_savebp->b_data)
5006 				    [aip->ai_offset] = aip->ai_oldblkno;
5007 			FREE_LOCK(&lk);
5008 			if (freefrag != NULL)
5009 				handle_workitem_freefrag(freefrag);
5010 		} else
5011 			FREE_LOCK(&lk);
5012 		if (newindirdep) {
5013 			newindirdep->ir_savebp->b_flags |= B_INVAL | B_NOCACHE;
5014 			brelse(newindirdep->ir_savebp);
5015 			ACQUIRE_LOCK(&lk);
5016 			WORKITEM_FREE((caddr_t)newindirdep, D_INDIRDEP);
5017 			if (indirdep)
5018 				break;
5019 			FREE_LOCK(&lk);
5020 		}
5021 		if (indirdep) {
5022 			ACQUIRE_LOCK(&lk);
5023 			break;
5024 		}
5025 		newindirdep = malloc(sizeof(struct indirdep),
5026 			M_INDIRDEP, M_SOFTDEP_FLAGS);
5027 		workitem_alloc(&newindirdep->ir_list, D_INDIRDEP, mp);
5028 		newindirdep->ir_state = ATTACHED;
5029 		if (ip->i_ump->um_fstype == UFS1)
5030 			newindirdep->ir_state |= UFS1FMT;
5031 		newindirdep->ir_saveddata = NULL;
5032 		LIST_INIT(&newindirdep->ir_deplisthd);
5033 		LIST_INIT(&newindirdep->ir_donehd);
5034 		LIST_INIT(&newindirdep->ir_writehd);
5035 		LIST_INIT(&newindirdep->ir_completehd);
5036 		LIST_INIT(&newindirdep->ir_jwork);
5037 		if (bp->b_blkno == bp->b_lblkno) {
5038 			ufs_bmaparray(bp->b_vp, bp->b_lblkno, &blkno, bp,
5039 			    NULL, NULL);
5040 			bp->b_blkno = blkno;
5041 		}
5042 		newindirdep->ir_savebp =
5043 		    getblk(ip->i_devvp, bp->b_blkno, bp->b_bcount, 0, 0, 0);
5044 		BUF_KERNPROC(newindirdep->ir_savebp);
5045 		bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
5046 		ACQUIRE_LOCK(&lk);
5047 	}
5048 }
5049 
5050 /*
5051  * Merge two allocindirs which refer to the same block.  Move newblock
5052  * dependencies and setup the freefrags appropriately.
5053  */
5054 static struct freefrag *
5055 allocindir_merge(aip, oldaip)
5056 	struct allocindir *aip;
5057 	struct allocindir *oldaip;
5058 {
5059 	struct newdirblk *newdirblk;
5060 	struct freefrag *freefrag;
5061 	struct worklist *wk;
5062 
5063 	if (oldaip->ai_newblkno != aip->ai_oldblkno)
5064 		panic("allocindir_merge: blkno");
5065 	aip->ai_oldblkno = oldaip->ai_oldblkno;
5066 	freefrag = aip->ai_freefrag;
5067 	aip->ai_freefrag = oldaip->ai_freefrag;
5068 	oldaip->ai_freefrag = NULL;
5069 	KASSERT(freefrag != NULL, ("setup_allocindir_phase2: No freefrag"));
5070 	/*
5071 	 * If we are tracking a new directory-block allocation,
5072 	 * move it from the old allocindir to the new allocindir.
5073 	 */
5074 	if ((wk = LIST_FIRST(&oldaip->ai_newdirblk)) != NULL) {
5075 		newdirblk = WK_NEWDIRBLK(wk);
5076 		WORKLIST_REMOVE(&newdirblk->db_list);
5077 		if (!LIST_EMPTY(&oldaip->ai_newdirblk))
5078 			panic("allocindir_merge: extra newdirblk");
5079 		WORKLIST_INSERT(&aip->ai_newdirblk, &newdirblk->db_list);
5080 	}
5081 	/*
5082 	 * We can skip journaling for this freefrag and just complete
5083 	 * any pending journal work for the allocindir that is being
5084 	 * removed after the freefrag completes.
5085 	 */
5086 	if (freefrag->ff_jfreefrag)
5087 		cancel_jfreefrag(freefrag->ff_jfreefrag);
5088 	LIST_REMOVE(oldaip, ai_next);
5089 	cancel_newblk(&oldaip->ai_block, &freefrag->ff_jwork);
5090 	free_newblk(&oldaip->ai_block);
5091 
5092 	return (freefrag);
5093 }
5094 
5095 /*
5096  * Block de-allocation dependencies.
5097  *
5098  * When blocks are de-allocated, the on-disk pointers must be nullified before
5099  * the blocks are made available for use by other files.  (The true
5100  * requirement is that old pointers must be nullified before new on-disk
5101  * pointers are set.  We chose this slightly more stringent requirement to
5102  * reduce complexity.) Our implementation handles this dependency by updating
5103  * the inode (or indirect block) appropriately but delaying the actual block
5104  * de-allocation (i.e., freemap and free space count manipulation) until
5105  * after the updated versions reach stable storage.  After the disk is
5106  * updated, the blocks can be safely de-allocated whenever it is convenient.
5107  * This implementation handles only the common case of reducing a file's
5108  * length to zero. Other cases are handled by the conventional synchronous
5109  * write approach.
5110  *
5111  * The ffs implementation with which we worked double-checks
5112  * the state of the block pointers and file size as it reduces
5113  * a file's length.  Some of this code is replicated here in our
5114  * soft updates implementation.  The freeblks->fb_chkcnt field is
5115  * used to transfer a part of this information to the procedure
5116  * that eventually de-allocates the blocks.
5117  *
5118  * This routine should be called from the routine that shortens
5119  * a file's length, before the inode's size or block pointers
5120  * are modified. It will save the block pointer information for
5121  * later release and zero the inode so that the calling routine
5122  * can release it.
5123  */
5124 void
5125 softdep_setup_freeblocks(ip, length, flags)
5126 	struct inode *ip;	/* The inode whose length is to be reduced */
5127 	off_t length;		/* The new length for the file */
5128 	int flags;		/* IO_EXT and/or IO_NORMAL */
5129 {
5130 	struct ufs1_dinode *dp1;
5131 	struct ufs2_dinode *dp2;
5132 	struct freeblks *freeblks;
5133 	struct inodedep *inodedep;
5134 	struct allocdirect *adp;
5135 	struct jfreeblk *jfreeblk;
5136 	struct bufobj *bo;
5137 	struct vnode *vp;
5138 	struct buf *bp;
5139 	struct fs *fs;
5140 	ufs2_daddr_t extblocks, datablocks;
5141 	struct mount *mp;
5142 	int i, delay, error;
5143 	ufs2_daddr_t blkno;
5144 	ufs_lbn_t tmpval;
5145 	ufs_lbn_t lbn;
5146 	long oldextsize;
5147 	long oldsize;
5148 	int frags;
5149 	int needj;
5150 
5151 	fs = ip->i_fs;
5152 	mp = UFSTOVFS(ip->i_ump);
5153 	if (length != 0)
5154 		panic("softdep_setup_freeblocks: non-zero length");
5155 	freeblks = malloc(sizeof(struct freeblks),
5156 		M_FREEBLKS, M_SOFTDEP_FLAGS|M_ZERO);
5157 	workitem_alloc(&freeblks->fb_list, D_FREEBLKS, mp);
5158 	LIST_INIT(&freeblks->fb_jfreeblkhd);
5159 	LIST_INIT(&freeblks->fb_jwork);
5160 	freeblks->fb_state = ATTACHED;
5161 	freeblks->fb_uid = ip->i_uid;
5162 	freeblks->fb_previousinum = ip->i_number;
5163 	freeblks->fb_devvp = ip->i_devvp;
5164 	freeblks->fb_chkcnt = 0;
5165 	ACQUIRE_LOCK(&lk);
5166 	/*
5167 	 * If we're truncating a removed file that will never be written
5168 	 * we don't need to journal the block frees.  The canceled journals
5169 	 * for the allocations will suffice.
5170 	 */
5171 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5172 	if ((inodedep->id_state & (UNLINKED | DEPCOMPLETE)) == UNLINKED ||
5173 	    (fs->fs_flags & FS_SUJ) == 0)
5174 		needj = 0;
5175 	else
5176 		needj = 1;
5177 	num_freeblkdep++;
5178 	FREE_LOCK(&lk);
5179 	extblocks = 0;
5180 	if (fs->fs_magic == FS_UFS2_MAGIC)
5181 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
5182 	datablocks = DIP(ip, i_blocks) - extblocks;
5183 	if ((flags & IO_NORMAL) != 0) {
5184 		oldsize = ip->i_size;
5185 		ip->i_size = 0;
5186 		DIP_SET(ip, i_size, 0);
5187 		freeblks->fb_chkcnt = datablocks;
5188 		for (i = 0; i < NDADDR; i++) {
5189 			blkno = DIP(ip, i_db[i]);
5190 			DIP_SET(ip, i_db[i], 0);
5191 			if (blkno == 0)
5192 				continue;
5193 			frags = sblksize(fs, oldsize, i);
5194 			frags = numfrags(fs, frags);
5195 			newfreework(freeblks, NULL, i, blkno, frags, needj);
5196 		}
5197 		for (i = 0, tmpval = NINDIR(fs), lbn = NDADDR; i < NIADDR;
5198 		    i++, tmpval *= NINDIR(fs)) {
5199 			blkno = DIP(ip, i_ib[i]);
5200 			DIP_SET(ip, i_ib[i], 0);
5201 			if (blkno)
5202 				newfreework(freeblks, NULL, -lbn - i, blkno,
5203 				    fs->fs_frag, needj);
5204 			lbn += tmpval;
5205 		}
5206 		UFS_LOCK(ip->i_ump);
5207 		fs->fs_pendingblocks += datablocks;
5208 		UFS_UNLOCK(ip->i_ump);
5209 	}
5210 	if ((flags & IO_EXT) != 0) {
5211 		oldextsize = ip->i_din2->di_extsize;
5212 		ip->i_din2->di_extsize = 0;
5213 		freeblks->fb_chkcnt += extblocks;
5214 		for (i = 0; i < NXADDR; i++) {
5215 			blkno = ip->i_din2->di_extb[i];
5216 			ip->i_din2->di_extb[i] = 0;
5217 			if (blkno == 0)
5218 				continue;
5219 			frags = sblksize(fs, oldextsize, i);
5220 			frags = numfrags(fs, frags);
5221 			newfreework(freeblks, NULL, -1 - i, blkno, frags,
5222 			    needj);
5223 		}
5224 	}
5225 	if (LIST_EMPTY(&freeblks->fb_jfreeblkhd))
5226 		needj = 0;
5227 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - freeblks->fb_chkcnt);
5228 	/*
5229 	 * Push the zero'ed inode to to its disk buffer so that we are free
5230 	 * to delete its dependencies below. Once the dependencies are gone
5231 	 * the buffer can be safely released.
5232 	 */
5233 	if ((error = bread(ip->i_devvp,
5234 	    fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
5235 	    (int)fs->fs_bsize, NOCRED, &bp)) != 0) {
5236 		brelse(bp);
5237 		softdep_error("softdep_setup_freeblocks", error);
5238 	}
5239 	if (ip->i_ump->um_fstype == UFS1) {
5240 		dp1 = ((struct ufs1_dinode *)bp->b_data +
5241 		    ino_to_fsbo(fs, ip->i_number));
5242 		ip->i_din1->di_freelink = dp1->di_freelink;
5243 		*dp1 = *ip->i_din1;
5244 	} else {
5245 		dp2 = ((struct ufs2_dinode *)bp->b_data +
5246 		    ino_to_fsbo(fs, ip->i_number));
5247 		ip->i_din2->di_freelink = dp2->di_freelink;
5248 		*dp2 = *ip->i_din2;
5249 	}
5250 	/*
5251 	 * Find and eliminate any inode dependencies.
5252 	 */
5253 	ACQUIRE_LOCK(&lk);
5254 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5255 	if ((inodedep->id_state & IOSTARTED) != 0)
5256 		panic("softdep_setup_freeblocks: inode busy");
5257 	/*
5258 	 * Add the freeblks structure to the list of operations that
5259 	 * must await the zero'ed inode being written to disk. If we
5260 	 * still have a bitmap dependency (delay == 0), then the inode
5261 	 * has never been written to disk, so we can process the
5262 	 * freeblks below once we have deleted the dependencies.
5263 	 */
5264 	delay = (inodedep->id_state & DEPCOMPLETE);
5265 	if (delay)
5266 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
5267 	else if (needj)
5268 		freeblks->fb_state |= DEPCOMPLETE | COMPLETE;
5269 	/*
5270 	 * Because the file length has been truncated to zero, any
5271 	 * pending block allocation dependency structures associated
5272 	 * with this inode are obsolete and can simply be de-allocated.
5273 	 * We must first merge the two dependency lists to get rid of
5274 	 * any duplicate freefrag structures, then purge the merged list.
5275 	 * If we still have a bitmap dependency, then the inode has never
5276 	 * been written to disk, so we can free any fragments without delay.
5277 	 */
5278 	if (flags & IO_NORMAL) {
5279 		merge_inode_lists(&inodedep->id_newinoupdt,
5280 		    &inodedep->id_inoupdt);
5281 		while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != 0)
5282 			cancel_allocdirect(&inodedep->id_inoupdt, adp,
5283 			    freeblks, delay);
5284 	}
5285 	if (flags & IO_EXT) {
5286 		merge_inode_lists(&inodedep->id_newextupdt,
5287 		    &inodedep->id_extupdt);
5288 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != 0)
5289 			cancel_allocdirect(&inodedep->id_extupdt, adp,
5290 			    freeblks, delay);
5291 	}
5292 	LIST_FOREACH(jfreeblk, &freeblks->fb_jfreeblkhd, jf_deps)
5293 		add_to_journal(&jfreeblk->jf_list);
5294 
5295 	FREE_LOCK(&lk);
5296 	bdwrite(bp);
5297 	/*
5298 	 * We must wait for any I/O in progress to finish so that
5299 	 * all potential buffers on the dirty list will be visible.
5300 	 * Once they are all there, walk the list and get rid of
5301 	 * any dependencies.
5302 	 */
5303 	vp = ITOV(ip);
5304 	bo = &vp->v_bufobj;
5305 	BO_LOCK(bo);
5306 	drain_output(vp);
5307 restart:
5308 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) {
5309 		if (((flags & IO_EXT) == 0 && (bp->b_xflags & BX_ALTDATA)) ||
5310 		    ((flags & IO_NORMAL) == 0 &&
5311 		      (bp->b_xflags & BX_ALTDATA) == 0))
5312 			continue;
5313 		if ((bp = getdirtybuf(bp, BO_MTX(bo), MNT_WAIT)) == NULL)
5314 			goto restart;
5315 		BO_UNLOCK(bo);
5316 		ACQUIRE_LOCK(&lk);
5317 		(void) inodedep_lookup(mp, ip->i_number, 0, &inodedep);
5318 		if (deallocate_dependencies(bp, inodedep, freeblks))
5319 			bp->b_flags |= B_INVAL | B_NOCACHE;
5320 		FREE_LOCK(&lk);
5321 		brelse(bp);
5322 		BO_LOCK(bo);
5323 		goto restart;
5324 	}
5325 	BO_UNLOCK(bo);
5326 	ACQUIRE_LOCK(&lk);
5327 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
5328 		(void) free_inodedep(inodedep);
5329 
5330 	if (delay) {
5331 		freeblks->fb_state |= DEPCOMPLETE;
5332 		/*
5333 		 * If the inode with zeroed block pointers is now on disk
5334 		 * we can start freeing blocks. Add freeblks to the worklist
5335 		 * instead of calling  handle_workitem_freeblocks directly as
5336 		 * it is more likely that additional IO is needed to complete
5337 		 * the request here than in the !delay case.
5338 		 */
5339 		if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
5340 			add_to_worklist(&freeblks->fb_list, 1);
5341 	}
5342 
5343 	FREE_LOCK(&lk);
5344 	/*
5345 	 * If the inode has never been written to disk (delay == 0) and
5346 	 * we're not waiting on any journal writes, then we can process the
5347 	 * freeblks now that we have deleted the dependencies.
5348 	 */
5349 	if (!delay && !needj)
5350 		handle_workitem_freeblocks(freeblks, 0);
5351 }
5352 
5353 /*
5354  * Reclaim any dependency structures from a buffer that is about to
5355  * be reallocated to a new vnode. The buffer must be locked, thus,
5356  * no I/O completion operations can occur while we are manipulating
5357  * its associated dependencies. The mutex is held so that other I/O's
5358  * associated with related dependencies do not occur.  Returns 1 if
5359  * all dependencies were cleared, 0 otherwise.
5360  */
5361 static int
5362 deallocate_dependencies(bp, inodedep, freeblks)
5363 	struct buf *bp;
5364 	struct inodedep *inodedep;
5365 	struct freeblks *freeblks;
5366 {
5367 	struct worklist *wk;
5368 	struct indirdep *indirdep;
5369 	struct newdirblk *newdirblk;
5370 	struct allocindir *aip;
5371 	struct pagedep *pagedep;
5372 	struct jremref *jremref;
5373 	struct jmvref *jmvref;
5374 	struct dirrem *dirrem;
5375 	int i;
5376 
5377 	mtx_assert(&lk, MA_OWNED);
5378 	while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
5379 		switch (wk->wk_type) {
5380 
5381 		case D_INDIRDEP:
5382 			indirdep = WK_INDIRDEP(wk);
5383 			if (bp->b_lblkno >= 0 ||
5384 			    bp->b_blkno != indirdep->ir_savebp->b_lblkno)
5385 				panic("deallocate_dependencies: not indir");
5386 			cancel_indirdep(indirdep, bp, inodedep, freeblks);
5387 			continue;
5388 
5389 		case D_PAGEDEP:
5390 			pagedep = WK_PAGEDEP(wk);
5391 			/*
5392 			 * There should be no directory add dependencies present
5393 			 * as the directory could not be truncated until all
5394 			 * children were removed.
5395 			 */
5396 			KASSERT(LIST_FIRST(&pagedep->pd_pendinghd) == NULL,
5397 			    ("deallocate_dependencies: pendinghd != NULL"));
5398 			for (i = 0; i < DAHASHSZ; i++)
5399 				KASSERT(LIST_FIRST(&pagedep->pd_diraddhd[i]) == NULL,
5400 				    ("deallocate_dependencies: diraddhd != NULL"));
5401 			/*
5402 			 * Copy any directory remove dependencies to the list
5403 			 * to be processed after the zero'ed inode is written.
5404 			 * If the inode has already been written, then they
5405 			 * can be dumped directly onto the work list.
5406 			 */
5407 			LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
5408 				/*
5409 				 * If there are any dirrems we wait for
5410 				 * the journal write to complete and
5411 				 * then restart the buf scan as the lock
5412 				 * has been dropped.
5413 				 */
5414 				while ((jremref =
5415 				    LIST_FIRST(&dirrem->dm_jremrefhd))
5416 				    != NULL) {
5417 					stat_jwait_filepage++;
5418 					jwait(&jremref->jr_list);
5419 					return (0);
5420 				}
5421 				LIST_REMOVE(dirrem, dm_next);
5422 				dirrem->dm_dirinum = pagedep->pd_ino;
5423 				if (inodedep == NULL ||
5424 				    (inodedep->id_state & ALLCOMPLETE) ==
5425 				     ALLCOMPLETE) {
5426 					dirrem->dm_state |= COMPLETE;
5427 					add_to_worklist(&dirrem->dm_list, 0);
5428 				} else
5429 					WORKLIST_INSERT(&inodedep->id_bufwait,
5430 					    &dirrem->dm_list);
5431 			}
5432 			if ((pagedep->pd_state & NEWBLOCK) != 0) {
5433 				newdirblk = pagedep->pd_newdirblk;
5434 				WORKLIST_REMOVE(&newdirblk->db_list);
5435 				free_newdirblk(newdirblk);
5436 			}
5437 			while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd))
5438 			    != NULL) {
5439 				stat_jwait_filepage++;
5440 				jwait(&jmvref->jm_list);
5441 				return (0);
5442 			}
5443 			WORKLIST_REMOVE(&pagedep->pd_list);
5444 			LIST_REMOVE(pagedep, pd_hash);
5445 			WORKITEM_FREE(pagedep, D_PAGEDEP);
5446 			continue;
5447 
5448 		case D_ALLOCINDIR:
5449 			aip = WK_ALLOCINDIR(wk);
5450 			cancel_allocindir(aip, inodedep, freeblks);
5451 			continue;
5452 
5453 		case D_ALLOCDIRECT:
5454 		case D_INODEDEP:
5455 			panic("deallocate_dependencies: Unexpected type %s",
5456 			    TYPENAME(wk->wk_type));
5457 			/* NOTREACHED */
5458 
5459 		default:
5460 			panic("deallocate_dependencies: Unknown type %s",
5461 			    TYPENAME(wk->wk_type));
5462 			/* NOTREACHED */
5463 		}
5464 	}
5465 
5466 	return (1);
5467 }
5468 
5469 /*
5470  * An allocdirect is being canceled due to a truncate.  We must make sure
5471  * the journal entry is released in concert with the blkfree that releases
5472  * the storage.  Completed journal entries must not be released until the
5473  * space is no longer pointed to by the inode or in the bitmap.
5474  */
5475 static void
5476 cancel_allocdirect(adphead, adp, freeblks, delay)
5477 	struct allocdirectlst *adphead;
5478 	struct allocdirect *adp;
5479 	struct freeblks *freeblks;
5480 	int delay;
5481 {
5482 	struct freework *freework;
5483 	struct newblk *newblk;
5484 	struct worklist *wk;
5485 	ufs_lbn_t lbn;
5486 
5487 	TAILQ_REMOVE(adphead, adp, ad_next);
5488 	newblk = (struct newblk *)adp;
5489 	/*
5490 	 * If the journal hasn't been written the jnewblk must be passed
5491 	 * to the call to ffs_freeblk that reclaims the space.  We accomplish
5492 	 * this by linking the journal dependency into the freework to be
5493 	 * freed when freework_freeblock() is called.  If the journal has
5494 	 * been written we can simply reclaim the journal space when the
5495 	 * freeblks work is complete.
5496 	 */
5497 	if (newblk->nb_jnewblk == NULL) {
5498 		cancel_newblk(newblk, &freeblks->fb_jwork);
5499 		goto found;
5500 	}
5501 	lbn = newblk->nb_jnewblk->jn_lbn;
5502 	/*
5503 	 * Find the correct freework structure so it releases the canceled
5504 	 * journal when the bitmap is cleared.  This preserves rollback
5505 	 * until the allocation is reverted.
5506 	 */
5507 	LIST_FOREACH(wk, &freeblks->fb_freeworkhd, wk_list) {
5508 		freework = WK_FREEWORK(wk);
5509 		if (freework->fw_lbn != lbn)
5510 			continue;
5511 		cancel_newblk(newblk, &freework->fw_jwork);
5512 		goto found;
5513 	}
5514 	panic("cancel_allocdirect: Freework not found for lbn %jd\n", lbn);
5515 found:
5516 	if (delay)
5517 		WORKLIST_INSERT(&adp->ad_inodedep->id_bufwait,
5518 		    &newblk->nb_list);
5519 	else
5520 		free_newblk(newblk);
5521 	return;
5522 }
5523 
5524 
5525 static void
5526 cancel_newblk(newblk, wkhd)
5527 	struct newblk *newblk;
5528 	struct workhead *wkhd;
5529 {
5530 	struct indirdep *indirdep;
5531 	struct allocindir *aip;
5532 
5533 	while ((indirdep = LIST_FIRST(&newblk->nb_indirdeps)) != NULL) {
5534 		indirdep->ir_state &= ~ONDEPLIST;
5535 		LIST_REMOVE(indirdep, ir_next);
5536 		/*
5537 		 * If an indirdep is not on the buf worklist we need to
5538 		 * free it here as deallocate_dependencies() will never
5539 		 * find it.  These pointers were never visible on disk and
5540 		 * can be discarded immediately.
5541 		 */
5542 		while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL) {
5543 			LIST_REMOVE(aip, ai_next);
5544 			cancel_newblk(&aip->ai_block, wkhd);
5545 			free_newblk(&aip->ai_block);
5546 		}
5547 		/*
5548 		 * If this indirdep is not attached to a buf it was simply
5549 		 * waiting on completion to clear completehd.  free_indirdep()
5550 		 * asserts that nothing is dangling.
5551 		 */
5552 		if ((indirdep->ir_state & ONWORKLIST) == 0)
5553 			free_indirdep(indirdep);
5554 	}
5555 	if (newblk->nb_state & ONDEPLIST) {
5556 		newblk->nb_state &= ~ONDEPLIST;
5557 		LIST_REMOVE(newblk, nb_deps);
5558 	}
5559 	if (newblk->nb_state & ONWORKLIST)
5560 		WORKLIST_REMOVE(&newblk->nb_list);
5561 	/*
5562 	 * If the journal entry hasn't been written we hold onto the dep
5563 	 * until it is safe to free along with the other journal work.
5564 	 */
5565 	if (newblk->nb_jnewblk != NULL) {
5566 		cancel_jnewblk(newblk->nb_jnewblk, wkhd);
5567 		newblk->nb_jnewblk = NULL;
5568 	}
5569 	if (!LIST_EMPTY(&newblk->nb_jwork))
5570 		jwork_move(wkhd, &newblk->nb_jwork);
5571 }
5572 
5573 /*
5574  * Free a newblk. Generate a new freefrag work request if appropriate.
5575  * This must be called after the inode pointer and any direct block pointers
5576  * are valid or fully removed via truncate or frag extension.
5577  */
5578 static void
5579 free_newblk(newblk)
5580 	struct newblk *newblk;
5581 {
5582 	struct indirdep *indirdep;
5583 	struct newdirblk *newdirblk;
5584 	struct freefrag *freefrag;
5585 	struct worklist *wk;
5586 
5587 	mtx_assert(&lk, MA_OWNED);
5588 	if (newblk->nb_state & ONDEPLIST)
5589 		LIST_REMOVE(newblk, nb_deps);
5590 	if (newblk->nb_state & ONWORKLIST)
5591 		WORKLIST_REMOVE(&newblk->nb_list);
5592 	LIST_REMOVE(newblk, nb_hash);
5593 	if ((freefrag = newblk->nb_freefrag) != NULL) {
5594 		freefrag->ff_state |= COMPLETE;
5595 		if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
5596 			add_to_worklist(&freefrag->ff_list, 0);
5597 	}
5598 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL) {
5599 		newdirblk = WK_NEWDIRBLK(wk);
5600 		WORKLIST_REMOVE(&newdirblk->db_list);
5601 		if (!LIST_EMPTY(&newblk->nb_newdirblk))
5602 			panic("free_newblk: extra newdirblk");
5603 		free_newdirblk(newdirblk);
5604 	}
5605 	while ((indirdep = LIST_FIRST(&newblk->nb_indirdeps)) != NULL) {
5606 		indirdep->ir_state |= DEPCOMPLETE;
5607 		indirdep_complete(indirdep);
5608 	}
5609 	KASSERT(newblk->nb_jnewblk == NULL,
5610 	    ("free_newblk; jnewblk %p still attached", newblk->nb_jnewblk));
5611 	handle_jwork(&newblk->nb_jwork);
5612 	newblk->nb_list.wk_type = D_NEWBLK;
5613 	WORKITEM_FREE(newblk, D_NEWBLK);
5614 }
5615 
5616 /*
5617  * Free a newdirblk. Clear the NEWBLOCK flag on its associated pagedep.
5618  * This routine must be called with splbio interrupts blocked.
5619  */
5620 static void
5621 free_newdirblk(newdirblk)
5622 	struct newdirblk *newdirblk;
5623 {
5624 	struct pagedep *pagedep;
5625 	struct diradd *dap;
5626 	struct worklist *wk;
5627 	int i;
5628 
5629 	mtx_assert(&lk, MA_OWNED);
5630 	/*
5631 	 * If the pagedep is still linked onto the directory buffer
5632 	 * dependency chain, then some of the entries on the
5633 	 * pd_pendinghd list may not be committed to disk yet. In
5634 	 * this case, we will simply clear the NEWBLOCK flag and
5635 	 * let the pd_pendinghd list be processed when the pagedep
5636 	 * is next written. If the pagedep is no longer on the buffer
5637 	 * dependency chain, then all the entries on the pd_pending
5638 	 * list are committed to disk and we can free them here.
5639 	 */
5640 	pagedep = newdirblk->db_pagedep;
5641 	pagedep->pd_state &= ~NEWBLOCK;
5642 	if ((pagedep->pd_state & ONWORKLIST) == 0)
5643 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
5644 			free_diradd(dap, NULL);
5645 	/*
5646 	 * If no dependencies remain, the pagedep will be freed.
5647 	 */
5648 	for (i = 0; i < DAHASHSZ; i++)
5649 		if (!LIST_EMPTY(&pagedep->pd_diraddhd[i]))
5650 			break;
5651 	if (i == DAHASHSZ && (pagedep->pd_state & ONWORKLIST) == 0 &&
5652 	    LIST_EMPTY(&pagedep->pd_jmvrefhd)) {
5653 		KASSERT(LIST_FIRST(&pagedep->pd_dirremhd) == NULL,
5654 		    ("free_newdirblk: Freeing non-free pagedep %p", pagedep));
5655 		LIST_REMOVE(pagedep, pd_hash);
5656 		WORKITEM_FREE(pagedep, D_PAGEDEP);
5657 	}
5658 	/* Should only ever be one item in the list. */
5659 	while ((wk = LIST_FIRST(&newdirblk->db_mkdir)) != NULL) {
5660 		WORKLIST_REMOVE(wk);
5661 		handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
5662 	}
5663 	WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
5664 }
5665 
5666 /*
5667  * Prepare an inode to be freed. The actual free operation is not
5668  * done until the zero'ed inode has been written to disk.
5669  */
5670 void
5671 softdep_freefile(pvp, ino, mode)
5672 	struct vnode *pvp;
5673 	ino_t ino;
5674 	int mode;
5675 {
5676 	struct inode *ip = VTOI(pvp);
5677 	struct inodedep *inodedep;
5678 	struct freefile *freefile;
5679 
5680 	/*
5681 	 * This sets up the inode de-allocation dependency.
5682 	 */
5683 	freefile = malloc(sizeof(struct freefile),
5684 		M_FREEFILE, M_SOFTDEP_FLAGS);
5685 	workitem_alloc(&freefile->fx_list, D_FREEFILE, pvp->v_mount);
5686 	freefile->fx_mode = mode;
5687 	freefile->fx_oldinum = ino;
5688 	freefile->fx_devvp = ip->i_devvp;
5689 	LIST_INIT(&freefile->fx_jwork);
5690 	UFS_LOCK(ip->i_ump);
5691 	ip->i_fs->fs_pendinginodes += 1;
5692 	UFS_UNLOCK(ip->i_ump);
5693 
5694 	/*
5695 	 * If the inodedep does not exist, then the zero'ed inode has
5696 	 * been written to disk. If the allocated inode has never been
5697 	 * written to disk, then the on-disk inode is zero'ed. In either
5698 	 * case we can free the file immediately.  If the journal was
5699 	 * canceled before being written the inode will never make it to
5700 	 * disk and we must send the canceled journal entrys to
5701 	 * ffs_freefile() to be cleared in conjunction with the bitmap.
5702 	 * Any blocks waiting on the inode to write can be safely freed
5703 	 * here as it will never been written.
5704 	 */
5705 	ACQUIRE_LOCK(&lk);
5706 	inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
5707 	/*
5708 	 * Remove this inode from the unlinked list and set
5709 	 * GOINGAWAY as appropriate to indicate that this inode
5710 	 * will never be written.
5711 	 */
5712 	if (inodedep && inodedep->id_state & UNLINKED) {
5713 		/*
5714 		 * Save the journal work to be freed with the bitmap
5715 		 * before we clear UNLINKED.  Otherwise it can be lost
5716 		 * if the inode block is written.
5717 		 */
5718 		handle_bufwait(inodedep, &freefile->fx_jwork);
5719 		clear_unlinked_inodedep(inodedep);
5720 		/* Re-acquire inodedep as we've dropped lk. */
5721 		inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
5722 		if (inodedep && (inodedep->id_state & DEPCOMPLETE) == 0)
5723 			inodedep->id_state |= GOINGAWAY;
5724 	}
5725 	if (inodedep == NULL || check_inode_unwritten(inodedep)) {
5726 		FREE_LOCK(&lk);
5727 		handle_workitem_freefile(freefile);
5728 		return;
5729 	}
5730 	WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
5731 	FREE_LOCK(&lk);
5732 	if (ip->i_number == ino)
5733 		ip->i_flag |= IN_MODIFIED;
5734 }
5735 
5736 /*
5737  * Check to see if an inode has never been written to disk. If
5738  * so free the inodedep and return success, otherwise return failure.
5739  * This routine must be called with splbio interrupts blocked.
5740  *
5741  * If we still have a bitmap dependency, then the inode has never
5742  * been written to disk. Drop the dependency as it is no longer
5743  * necessary since the inode is being deallocated. We set the
5744  * ALLCOMPLETE flags since the bitmap now properly shows that the
5745  * inode is not allocated. Even if the inode is actively being
5746  * written, it has been rolled back to its zero'ed state, so we
5747  * are ensured that a zero inode is what is on the disk. For short
5748  * lived files, this change will usually result in removing all the
5749  * dependencies from the inode so that it can be freed immediately.
5750  */
5751 static int
5752 check_inode_unwritten(inodedep)
5753 	struct inodedep *inodedep;
5754 {
5755 
5756 	mtx_assert(&lk, MA_OWNED);
5757 
5758 	if ((inodedep->id_state & (DEPCOMPLETE | UNLINKED)) != 0 ||
5759 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
5760 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
5761 	    !LIST_EMPTY(&inodedep->id_inowait) ||
5762 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
5763 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
5764 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
5765 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
5766 	    inodedep->id_mkdiradd != NULL ||
5767 	    inodedep->id_nlinkdelta != 0)
5768 		return (0);
5769 	/*
5770 	 * Another process might be in initiate_write_inodeblock_ufs[12]
5771 	 * trying to allocate memory without holding "Softdep Lock".
5772 	 */
5773 	if ((inodedep->id_state & IOSTARTED) != 0 &&
5774 	    inodedep->id_savedino1 == NULL)
5775 		return (0);
5776 
5777 	if (inodedep->id_state & ONDEPLIST)
5778 		LIST_REMOVE(inodedep, id_deps);
5779 	inodedep->id_state &= ~ONDEPLIST;
5780 	inodedep->id_state |= ALLCOMPLETE;
5781 	inodedep->id_bmsafemap = NULL;
5782 	if (inodedep->id_state & ONWORKLIST)
5783 		WORKLIST_REMOVE(&inodedep->id_list);
5784 	if (inodedep->id_savedino1 != NULL) {
5785 		free(inodedep->id_savedino1, M_SAVEDINO);
5786 		inodedep->id_savedino1 = NULL;
5787 	}
5788 	if (free_inodedep(inodedep) == 0)
5789 		panic("check_inode_unwritten: busy inode");
5790 	return (1);
5791 }
5792 
5793 /*
5794  * Try to free an inodedep structure. Return 1 if it could be freed.
5795  */
5796 static int
5797 free_inodedep(inodedep)
5798 	struct inodedep *inodedep;
5799 {
5800 
5801 	mtx_assert(&lk, MA_OWNED);
5802 	if ((inodedep->id_state & (ONWORKLIST | UNLINKED)) != 0 ||
5803 	    (inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
5804 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
5805 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
5806 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
5807 	    !LIST_EMPTY(&inodedep->id_inowait) ||
5808 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
5809 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
5810 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
5811 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
5812 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
5813 	    inodedep->id_mkdiradd != NULL ||
5814 	    inodedep->id_nlinkdelta != 0 ||
5815 	    inodedep->id_savedino1 != NULL)
5816 		return (0);
5817 	if (inodedep->id_state & ONDEPLIST)
5818 		LIST_REMOVE(inodedep, id_deps);
5819 	LIST_REMOVE(inodedep, id_hash);
5820 	WORKITEM_FREE(inodedep, D_INODEDEP);
5821 	num_inodedep -= 1;
5822 	return (1);
5823 }
5824 
5825 /*
5826  * Free the block referenced by a freework structure.  The parent freeblks
5827  * structure is released and completed when the final cg bitmap reaches
5828  * the disk.  This routine may be freeing a jnewblk which never made it to
5829  * disk in which case we do not have to wait as the operation is undone
5830  * in memory immediately.
5831  */
5832 static void
5833 freework_freeblock(freework)
5834 	struct freework *freework;
5835 {
5836 	struct freeblks *freeblks;
5837 	struct ufsmount *ump;
5838 	struct workhead wkhd;
5839 	struct fs *fs;
5840 	int complete;
5841 	int pending;
5842 	int bsize;
5843 	int needj;
5844 
5845 	freeblks = freework->fw_freeblks;
5846 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
5847 	fs = ump->um_fs;
5848 	needj = freeblks->fb_list.wk_mp->mnt_kern_flag & MNTK_SUJ;
5849 	complete = 0;
5850 	LIST_INIT(&wkhd);
5851 	/*
5852 	 * If we are canceling an existing jnewblk pass it to the free
5853 	 * routine, otherwise pass the freeblk which will ultimately
5854 	 * release the freeblks.  If we're not journaling, we can just
5855 	 * free the freeblks immediately.
5856 	 */
5857 	if (!LIST_EMPTY(&freework->fw_jwork)) {
5858 		LIST_SWAP(&wkhd, &freework->fw_jwork, worklist, wk_list);
5859 		complete = 1;
5860 	} else if (needj)
5861 		WORKLIST_INSERT_UNLOCKED(&wkhd, &freework->fw_list);
5862 	bsize = lfragtosize(fs, freework->fw_frags);
5863 	pending = btodb(bsize);
5864 	ACQUIRE_LOCK(&lk);
5865 	freeblks->fb_chkcnt -= pending;
5866 	FREE_LOCK(&lk);
5867 	/*
5868 	 * extattr blocks don't show up in pending blocks.  XXX why?
5869 	 */
5870 	if (freework->fw_lbn >= 0 || freework->fw_lbn <= -NDADDR) {
5871 		UFS_LOCK(ump);
5872 		fs->fs_pendingblocks -= pending;
5873 		UFS_UNLOCK(ump);
5874 	}
5875 	ffs_blkfree(ump, fs, freeblks->fb_devvp, freework->fw_blkno,
5876 	    bsize, freeblks->fb_previousinum, &wkhd);
5877 	if (complete == 0 && needj)
5878 		return;
5879 	/*
5880 	 * The jnewblk will be discarded and the bits in the map never
5881 	 * made it to disk.  We can immediately free the freeblk.
5882 	 */
5883 	ACQUIRE_LOCK(&lk);
5884 	handle_written_freework(freework);
5885 	FREE_LOCK(&lk);
5886 }
5887 
5888 /*
5889  * Start, continue, or finish the process of freeing an indirect block tree.
5890  * The free operation may be paused at any point with fw_off containing the
5891  * offset to restart from.  This enables us to implement some flow control
5892  * for large truncates which may fan out and generate a huge number of
5893  * dependencies.
5894  */
5895 static void
5896 handle_workitem_indirblk(freework)
5897 	struct freework *freework;
5898 {
5899 	struct freeblks *freeblks;
5900 	struct ufsmount *ump;
5901 	struct fs *fs;
5902 
5903 
5904 	freeblks = freework->fw_freeblks;
5905 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
5906 	fs = ump->um_fs;
5907 	if (freework->fw_off == NINDIR(fs))
5908 		freework_freeblock(freework);
5909 	else
5910 		indir_trunc(freework, fsbtodb(fs, freework->fw_blkno),
5911 		    freework->fw_lbn);
5912 }
5913 
5914 /*
5915  * Called when a freework structure attached to a cg buf is written.  The
5916  * ref on either the parent or the freeblks structure is released and
5917  * either may be added to the worklist if it is the final ref.
5918  */
5919 static void
5920 handle_written_freework(freework)
5921 	struct freework *freework;
5922 {
5923 	struct freeblks *freeblks;
5924 	struct freework *parent;
5925 
5926 	freeblks = freework->fw_freeblks;
5927 	parent = freework->fw_parent;
5928 	if (parent) {
5929 		if (--parent->fw_ref != 0)
5930 			parent = NULL;
5931 		freeblks = NULL;
5932 	} else if (--freeblks->fb_ref != 0)
5933 		freeblks = NULL;
5934 	WORKITEM_FREE(freework, D_FREEWORK);
5935 	/*
5936 	 * Don't delay these block frees or it takes an intolerable amount
5937 	 * of time to process truncates and free their journal entries.
5938 	 */
5939 	if (freeblks)
5940 		add_to_worklist(&freeblks->fb_list, 1);
5941 	if (parent)
5942 		add_to_worklist(&parent->fw_list, 1);
5943 }
5944 
5945 /*
5946  * This workitem routine performs the block de-allocation.
5947  * The workitem is added to the pending list after the updated
5948  * inode block has been written to disk.  As mentioned above,
5949  * checks regarding the number of blocks de-allocated (compared
5950  * to the number of blocks allocated for the file) are also
5951  * performed in this function.
5952  */
5953 static void
5954 handle_workitem_freeblocks(freeblks, flags)
5955 	struct freeblks *freeblks;
5956 	int flags;
5957 {
5958 	struct freework *freework;
5959 	struct worklist *wk;
5960 
5961 	KASSERT(LIST_EMPTY(&freeblks->fb_jfreeblkhd),
5962 	    ("handle_workitem_freeblocks: Journal entries not written."));
5963 	if (LIST_EMPTY(&freeblks->fb_freeworkhd)) {
5964 		handle_complete_freeblocks(freeblks);
5965 		return;
5966 	}
5967 	freeblks->fb_ref++;
5968 	while ((wk = LIST_FIRST(&freeblks->fb_freeworkhd)) != NULL) {
5969 		KASSERT(wk->wk_type == D_FREEWORK,
5970 		    ("handle_workitem_freeblocks: Unknown type %s",
5971 		    TYPENAME(wk->wk_type)));
5972 		WORKLIST_REMOVE_UNLOCKED(wk);
5973 		freework = WK_FREEWORK(wk);
5974 		if (freework->fw_lbn <= -NDADDR)
5975 			handle_workitem_indirblk(freework);
5976 		else
5977 			freework_freeblock(freework);
5978 	}
5979 	ACQUIRE_LOCK(&lk);
5980 	if (--freeblks->fb_ref != 0)
5981 		freeblks = NULL;
5982 	FREE_LOCK(&lk);
5983 	if (freeblks)
5984 		handle_complete_freeblocks(freeblks);
5985 }
5986 
5987 /*
5988  * Once all of the freework workitems are complete we can retire the
5989  * freeblocks dependency and any journal work awaiting completion.  This
5990  * can not be called until all other dependencies are stable on disk.
5991  */
5992 static void
5993 handle_complete_freeblocks(freeblks)
5994 	struct freeblks *freeblks;
5995 {
5996 	struct inode *ip;
5997 	struct vnode *vp;
5998 	struct fs *fs;
5999 	struct ufsmount *ump;
6000 	int flags;
6001 
6002 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
6003 	fs = ump->um_fs;
6004 	flags = LK_NOWAIT;
6005 
6006 	/*
6007 	 * If we still have not finished background cleanup, then check
6008 	 * to see if the block count needs to be adjusted.
6009 	 */
6010 	if (freeblks->fb_chkcnt != 0 && (fs->fs_flags & FS_UNCLEAN) != 0 &&
6011 	    ffs_vgetf(freeblks->fb_list.wk_mp, freeblks->fb_previousinum,
6012 	    (flags & LK_NOWAIT) | LK_EXCLUSIVE, &vp, FFSV_FORCEINSMQ) == 0) {
6013 		ip = VTOI(vp);
6014 		DIP_SET(ip, i_blocks, DIP(ip, i_blocks) + freeblks->fb_chkcnt);
6015 		ip->i_flag |= IN_CHANGE;
6016 		vput(vp);
6017 	}
6018 
6019 #ifdef INVARIANTS
6020 	if (freeblks->fb_chkcnt != 0 &&
6021 	    ((fs->fs_flags & FS_UNCLEAN) == 0 || (flags & LK_NOWAIT) != 0))
6022 		printf("handle_workitem_freeblocks: block count\n");
6023 #endif /* INVARIANTS */
6024 
6025 	ACQUIRE_LOCK(&lk);
6026 	/*
6027 	 * All of the freeblock deps must be complete prior to this call
6028 	 * so it's now safe to complete earlier outstanding journal entries.
6029 	 */
6030 	handle_jwork(&freeblks->fb_jwork);
6031 	WORKITEM_FREE(freeblks, D_FREEBLKS);
6032 	num_freeblkdep--;
6033 	FREE_LOCK(&lk);
6034 }
6035 
6036 /*
6037  * Release blocks associated with the inode ip and stored in the indirect
6038  * block dbn. If level is greater than SINGLE, the block is an indirect block
6039  * and recursive calls to indirtrunc must be used to cleanse other indirect
6040  * blocks.
6041  */
6042 static void
6043 indir_trunc(freework, dbn, lbn)
6044 	struct freework *freework;
6045 	ufs2_daddr_t dbn;
6046 	ufs_lbn_t lbn;
6047 {
6048 	struct freework *nfreework;
6049 	struct workhead wkhd;
6050 	struct jnewblk *jnewblk;
6051 	struct freeblks *freeblks;
6052 	struct buf *bp;
6053 	struct fs *fs;
6054 	struct worklist *wkn;
6055 	struct worklist *wk;
6056 	struct indirdep *indirdep;
6057 	struct ufsmount *ump;
6058 	ufs1_daddr_t *bap1 = 0;
6059 	ufs2_daddr_t nb, nnb, *bap2 = 0;
6060 	ufs_lbn_t lbnadd;
6061 	int i, nblocks, ufs1fmt;
6062 	int fs_pendingblocks;
6063 	int freedeps;
6064 	int needj;
6065 	int level;
6066 	int cnt;
6067 
6068 	LIST_INIT(&wkhd);
6069 	level = lbn_level(lbn);
6070 	if (level == -1)
6071 		panic("indir_trunc: Invalid lbn %jd\n", lbn);
6072 	freeblks = freework->fw_freeblks;
6073 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
6074 	fs = ump->um_fs;
6075 	fs_pendingblocks = 0;
6076 	freedeps = 0;
6077 	needj = UFSTOVFS(ump)->mnt_kern_flag & MNTK_SUJ;
6078 	lbnadd = 1;
6079 	for (i = level; i > 0; i--)
6080 		lbnadd *= NINDIR(fs);
6081 	/*
6082 	 * Get buffer of block pointers to be freed. This routine is not
6083 	 * called until the zero'ed inode has been written, so it is safe
6084 	 * to free blocks as they are encountered. Because the inode has
6085 	 * been zero'ed, calls to bmap on these blocks will fail. So, we
6086 	 * have to use the on-disk address and the block device for the
6087 	 * filesystem to look them up. If the file was deleted before its
6088 	 * indirect blocks were all written to disk, the routine that set
6089 	 * us up (deallocate_dependencies) will have arranged to leave
6090 	 * a complete copy of the indirect block in memory for our use.
6091 	 * Otherwise we have to read the blocks in from the disk.
6092 	 */
6093 #ifdef notyet
6094 	bp = getblk(freeblks->fb_devvp, dbn, (int)fs->fs_bsize, 0, 0,
6095 	    GB_NOCREAT);
6096 #else
6097 	bp = incore(&freeblks->fb_devvp->v_bufobj, dbn);
6098 #endif
6099 	ACQUIRE_LOCK(&lk);
6100 	if (bp != NULL && (wk = LIST_FIRST(&bp->b_dep)) != NULL) {
6101 		if (wk->wk_type != D_INDIRDEP ||
6102 		    (wk->wk_state & GOINGAWAY) == 0)
6103 			panic("indir_trunc: lost indirdep %p", wk);
6104 		indirdep = WK_INDIRDEP(wk);
6105 		LIST_SWAP(&wkhd, &indirdep->ir_jwork, worklist, wk_list);
6106 		free_indirdep(indirdep);
6107 		if (!LIST_EMPTY(&bp->b_dep))
6108 			panic("indir_trunc: dangling dep %p",
6109 			    LIST_FIRST(&bp->b_dep));
6110 		ump->um_numindirdeps -= 1;
6111 		FREE_LOCK(&lk);
6112 	} else {
6113 #ifdef notyet
6114 		if (bp)
6115 			brelse(bp);
6116 #endif
6117 		FREE_LOCK(&lk);
6118 		if (bread(freeblks->fb_devvp, dbn, (int)fs->fs_bsize,
6119 		    NOCRED, &bp) != 0) {
6120 			brelse(bp);
6121 			return;
6122 		}
6123 	}
6124 	/*
6125 	 * Recursively free indirect blocks.
6126 	 */
6127 	if (ump->um_fstype == UFS1) {
6128 		ufs1fmt = 1;
6129 		bap1 = (ufs1_daddr_t *)bp->b_data;
6130 	} else {
6131 		ufs1fmt = 0;
6132 		bap2 = (ufs2_daddr_t *)bp->b_data;
6133 	}
6134 	/*
6135 	 * Reclaim indirect blocks which never made it to disk.
6136 	 */
6137 	cnt = 0;
6138 	LIST_FOREACH_SAFE(wk, &wkhd, wk_list, wkn) {
6139 		struct workhead freewk;
6140 		if (wk->wk_type != D_JNEWBLK)
6141 			continue;
6142 		WORKLIST_REMOVE_UNLOCKED(wk);
6143 		LIST_INIT(&freewk);
6144 		WORKLIST_INSERT_UNLOCKED(&freewk, wk);
6145 		jnewblk = WK_JNEWBLK(wk);
6146 		if (jnewblk->jn_lbn > 0)
6147 			i = (jnewblk->jn_lbn - -lbn) / lbnadd;
6148 		else
6149 			i = (jnewblk->jn_lbn - (lbn + 1)) / lbnadd;
6150 		KASSERT(i >= 0 && i < NINDIR(fs),
6151 		    ("indir_trunc: Index out of range %d parent %jd lbn %jd",
6152 		    i, lbn, jnewblk->jn_lbn));
6153 		/* Clear the pointer so it isn't found below. */
6154 		if (ufs1fmt) {
6155 			nb = bap1[i];
6156 			bap1[i] = 0;
6157 		} else {
6158 			nb = bap2[i];
6159 			bap2[i] = 0;
6160 		}
6161 		KASSERT(nb == jnewblk->jn_blkno,
6162 		    ("indir_trunc: Block mismatch %jd != %jd",
6163 		    nb, jnewblk->jn_blkno));
6164 		ffs_blkfree(ump, fs, freeblks->fb_devvp, jnewblk->jn_blkno,
6165 		    fs->fs_bsize, freeblks->fb_previousinum, &freewk);
6166 		cnt++;
6167 	}
6168 	ACQUIRE_LOCK(&lk);
6169 	if (needj)
6170 		freework->fw_ref += NINDIR(fs) + 1;
6171 	/* Any remaining journal work can be completed with freeblks. */
6172 	jwork_move(&freeblks->fb_jwork, &wkhd);
6173 	FREE_LOCK(&lk);
6174 	nblocks = btodb(fs->fs_bsize);
6175 	if (ufs1fmt)
6176 		nb = bap1[0];
6177 	else
6178 		nb = bap2[0];
6179 	nfreework = freework;
6180 	/*
6181 	 * Reclaim on disk blocks.
6182 	 */
6183 	for (i = freework->fw_off; i < NINDIR(fs); i++, nb = nnb) {
6184 		if (i != NINDIR(fs) - 1) {
6185 			if (ufs1fmt)
6186 				nnb = bap1[i+1];
6187 			else
6188 				nnb = bap2[i+1];
6189 		} else
6190 			nnb = 0;
6191 		if (nb == 0)
6192 			continue;
6193 		cnt++;
6194 		if (level != 0) {
6195 			ufs_lbn_t nlbn;
6196 
6197 			nlbn = (lbn + 1) - (i * lbnadd);
6198 			if (needj != 0) {
6199 				nfreework = newfreework(freeblks, freework,
6200 				    nlbn, nb, fs->fs_frag, 0);
6201 				freedeps++;
6202 			}
6203 			indir_trunc(nfreework, fsbtodb(fs, nb), nlbn);
6204 		} else {
6205 			struct freedep *freedep;
6206 
6207 			/*
6208 			 * Attempt to aggregate freedep dependencies for
6209 			 * all blocks being released to the same CG.
6210 			 */
6211 			LIST_INIT(&wkhd);
6212 			if (needj != 0 &&
6213 			    (nnb == 0 || (dtog(fs, nb) != dtog(fs, nnb)))) {
6214 				freedep = newfreedep(freework);
6215 				WORKLIST_INSERT_UNLOCKED(&wkhd,
6216 				    &freedep->fd_list);
6217 				freedeps++;
6218 			}
6219 			ffs_blkfree(ump, fs, freeblks->fb_devvp, nb,
6220 			    fs->fs_bsize, freeblks->fb_previousinum, &wkhd);
6221 		}
6222 	}
6223 	if (level == 0)
6224 		fs_pendingblocks = (nblocks * cnt);
6225 	/*
6226 	 * If we're not journaling we can free the indirect now.  Otherwise
6227 	 * setup the ref counts and offset so this indirect can be completed
6228 	 * when its children are free.
6229 	 */
6230 	if (needj == 0) {
6231 		fs_pendingblocks += nblocks;
6232 		dbn = dbtofsb(fs, dbn);
6233 		ffs_blkfree(ump, fs, freeblks->fb_devvp, dbn, fs->fs_bsize,
6234 		    freeblks->fb_previousinum, NULL);
6235 		ACQUIRE_LOCK(&lk);
6236 		freeblks->fb_chkcnt -= fs_pendingblocks;
6237 		if (freework->fw_blkno == dbn)
6238 			handle_written_freework(freework);
6239 		FREE_LOCK(&lk);
6240 		freework = NULL;
6241 	} else {
6242 		ACQUIRE_LOCK(&lk);
6243 		freework->fw_off = i;
6244 		freework->fw_ref += freedeps;
6245 		freework->fw_ref -= NINDIR(fs) + 1;
6246 		if (freework->fw_ref != 0)
6247 			freework = NULL;
6248 		freeblks->fb_chkcnt -= fs_pendingblocks;
6249 		FREE_LOCK(&lk);
6250 	}
6251 	if (fs_pendingblocks) {
6252 		UFS_LOCK(ump);
6253 		fs->fs_pendingblocks -= fs_pendingblocks;
6254 		UFS_UNLOCK(ump);
6255 	}
6256 	bp->b_flags |= B_INVAL | B_NOCACHE;
6257 	brelse(bp);
6258 	if (freework)
6259 		handle_workitem_indirblk(freework);
6260 	return;
6261 }
6262 
6263 /*
6264  * Cancel an allocindir when it is removed via truncation.
6265  */
6266 static void
6267 cancel_allocindir(aip, inodedep, freeblks)
6268 	struct allocindir *aip;
6269 	struct inodedep *inodedep;
6270 	struct freeblks *freeblks;
6271 {
6272 	struct newblk *newblk;
6273 
6274 	/*
6275 	 * If the journal hasn't been written the jnewblk must be passed
6276 	 * to the call to ffs_freeblk that reclaims the space.  We accomplish
6277 	 * this by linking the journal dependency into the indirdep to be
6278 	 * freed when indir_trunc() is called.  If the journal has already
6279 	 * been written we can simply reclaim the journal space when the
6280 	 * freeblks work is complete.
6281 	 */
6282 	LIST_REMOVE(aip, ai_next);
6283 	newblk = (struct newblk *)aip;
6284 	if (newblk->nb_jnewblk == NULL)
6285 		cancel_newblk(newblk, &freeblks->fb_jwork);
6286 	else
6287 		cancel_newblk(newblk, &aip->ai_indirdep->ir_jwork);
6288 	if (inodedep && inodedep->id_state & DEPCOMPLETE)
6289 		WORKLIST_INSERT(&inodedep->id_bufwait, &newblk->nb_list);
6290 	else
6291 		free_newblk(newblk);
6292 }
6293 
6294 /*
6295  * Create the mkdir dependencies for . and .. in a new directory.  Link them
6296  * in to a newdirblk so any subsequent additions are tracked properly.  The
6297  * caller is responsible for adding the mkdir1 dependency to the journal
6298  * and updating id_mkdiradd.  This function returns with lk held.
6299  */
6300 static struct mkdir *
6301 setup_newdir(dap, newinum, dinum, newdirbp, mkdirp)
6302 	struct diradd *dap;
6303 	ino_t newinum;
6304 	ino_t dinum;
6305 	struct buf *newdirbp;
6306 	struct mkdir **mkdirp;
6307 {
6308 	struct newblk *newblk;
6309 	struct pagedep *pagedep;
6310 	struct inodedep *inodedep;
6311 	struct newdirblk *newdirblk = 0;
6312 	struct mkdir *mkdir1, *mkdir2;
6313 	struct worklist *wk;
6314 	struct jaddref *jaddref;
6315 	struct mount *mp;
6316 
6317 	mp = dap->da_list.wk_mp;
6318 	newdirblk = malloc(sizeof(struct newdirblk), M_NEWDIRBLK,
6319 	    M_SOFTDEP_FLAGS);
6320 	workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
6321 	LIST_INIT(&newdirblk->db_mkdir);
6322 	mkdir1 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
6323 	workitem_alloc(&mkdir1->md_list, D_MKDIR, mp);
6324 	mkdir1->md_state = ATTACHED | MKDIR_BODY;
6325 	mkdir1->md_diradd = dap;
6326 	mkdir1->md_jaddref = NULL;
6327 	mkdir2 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
6328 	workitem_alloc(&mkdir2->md_list, D_MKDIR, mp);
6329 	mkdir2->md_state = ATTACHED | MKDIR_PARENT;
6330 	mkdir2->md_diradd = dap;
6331 	mkdir2->md_jaddref = NULL;
6332 	if ((mp->mnt_kern_flag & MNTK_SUJ) == 0) {
6333 		mkdir1->md_state |= DEPCOMPLETE;
6334 		mkdir2->md_state |= DEPCOMPLETE;
6335 	}
6336 	/*
6337 	 * Dependency on "." and ".." being written to disk.
6338 	 */
6339 	mkdir1->md_buf = newdirbp;
6340 	ACQUIRE_LOCK(&lk);
6341 	LIST_INSERT_HEAD(&mkdirlisthd, mkdir1, md_mkdirs);
6342 	/*
6343 	 * We must link the pagedep, allocdirect, and newdirblk for
6344 	 * the initial file page so the pointer to the new directory
6345 	 * is not written until the directory contents are live and
6346 	 * any subsequent additions are not marked live until the
6347 	 * block is reachable via the inode.
6348 	 */
6349 	if (pagedep_lookup(mp, newinum, 0, 0, &pagedep) == 0)
6350 		panic("setup_newdir: lost pagedep");
6351 	LIST_FOREACH(wk, &newdirbp->b_dep, wk_list)
6352 		if (wk->wk_type == D_ALLOCDIRECT)
6353 			break;
6354 	if (wk == NULL)
6355 		panic("setup_newdir: lost allocdirect");
6356 	newblk = WK_NEWBLK(wk);
6357 	pagedep->pd_state |= NEWBLOCK;
6358 	pagedep->pd_newdirblk = newdirblk;
6359 	newdirblk->db_pagedep = pagedep;
6360 	WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
6361 	WORKLIST_INSERT(&newdirblk->db_mkdir, &mkdir1->md_list);
6362 	/*
6363 	 * Look up the inodedep for the parent directory so that we
6364 	 * can link mkdir2 into the pending dotdot jaddref or
6365 	 * the inode write if there is none.  If the inode is
6366 	 * ALLCOMPLETE and no jaddref is present all dependencies have
6367 	 * been satisfied and mkdir2 can be freed.
6368 	 */
6369 	inodedep_lookup(mp, dinum, 0, &inodedep);
6370 	if (mp->mnt_kern_flag & MNTK_SUJ) {
6371 		if (inodedep == NULL)
6372 			panic("setup_newdir: Lost parent.");
6373 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
6374 		    inoreflst);
6375 		KASSERT(jaddref != NULL && jaddref->ja_parent == newinum &&
6376 		    (jaddref->ja_state & MKDIR_PARENT),
6377 		    ("setup_newdir: bad dotdot jaddref %p", jaddref));
6378 		LIST_INSERT_HEAD(&mkdirlisthd, mkdir2, md_mkdirs);
6379 		mkdir2->md_jaddref = jaddref;
6380 		jaddref->ja_mkdir = mkdir2;
6381 	} else if (inodedep == NULL ||
6382 	    (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
6383 		dap->da_state &= ~MKDIR_PARENT;
6384 		WORKITEM_FREE(mkdir2, D_MKDIR);
6385 	} else {
6386 		LIST_INSERT_HEAD(&mkdirlisthd, mkdir2, md_mkdirs);
6387 		WORKLIST_INSERT(&inodedep->id_bufwait,&mkdir2->md_list);
6388 	}
6389 	*mkdirp = mkdir2;
6390 
6391 	return (mkdir1);
6392 }
6393 
6394 /*
6395  * Directory entry addition dependencies.
6396  *
6397  * When adding a new directory entry, the inode (with its incremented link
6398  * count) must be written to disk before the directory entry's pointer to it.
6399  * Also, if the inode is newly allocated, the corresponding freemap must be
6400  * updated (on disk) before the directory entry's pointer. These requirements
6401  * are met via undo/redo on the directory entry's pointer, which consists
6402  * simply of the inode number.
6403  *
6404  * As directory entries are added and deleted, the free space within a
6405  * directory block can become fragmented.  The ufs filesystem will compact
6406  * a fragmented directory block to make space for a new entry. When this
6407  * occurs, the offsets of previously added entries change. Any "diradd"
6408  * dependency structures corresponding to these entries must be updated with
6409  * the new offsets.
6410  */
6411 
6412 /*
6413  * This routine is called after the in-memory inode's link
6414  * count has been incremented, but before the directory entry's
6415  * pointer to the inode has been set.
6416  */
6417 int
6418 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
6419 	struct buf *bp;		/* buffer containing directory block */
6420 	struct inode *dp;	/* inode for directory */
6421 	off_t diroffset;	/* offset of new entry in directory */
6422 	ino_t newinum;		/* inode referenced by new directory entry */
6423 	struct buf *newdirbp;	/* non-NULL => contents of new mkdir */
6424 	int isnewblk;		/* entry is in a newly allocated block */
6425 {
6426 	int offset;		/* offset of new entry within directory block */
6427 	ufs_lbn_t lbn;		/* block in directory containing new entry */
6428 	struct fs *fs;
6429 	struct diradd *dap;
6430 	struct newblk *newblk;
6431 	struct pagedep *pagedep;
6432 	struct inodedep *inodedep;
6433 	struct newdirblk *newdirblk = 0;
6434 	struct mkdir *mkdir1, *mkdir2;
6435 	struct jaddref *jaddref;
6436 	struct mount *mp;
6437 	int isindir;
6438 
6439 	/*
6440 	 * Whiteouts have no dependencies.
6441 	 */
6442 	if (newinum == WINO) {
6443 		if (newdirbp != NULL)
6444 			bdwrite(newdirbp);
6445 		return (0);
6446 	}
6447 	jaddref = NULL;
6448 	mkdir1 = mkdir2 = NULL;
6449 	mp = UFSTOVFS(dp->i_ump);
6450 	fs = dp->i_fs;
6451 	lbn = lblkno(fs, diroffset);
6452 	offset = blkoff(fs, diroffset);
6453 	dap = malloc(sizeof(struct diradd), M_DIRADD,
6454 		M_SOFTDEP_FLAGS|M_ZERO);
6455 	workitem_alloc(&dap->da_list, D_DIRADD, mp);
6456 	dap->da_offset = offset;
6457 	dap->da_newinum = newinum;
6458 	dap->da_state = ATTACHED;
6459 	LIST_INIT(&dap->da_jwork);
6460 	isindir = bp->b_lblkno >= NDADDR;
6461 	if (isnewblk &&
6462 	    (isindir ? blkoff(fs, diroffset) : fragoff(fs, diroffset)) == 0) {
6463 		newdirblk = malloc(sizeof(struct newdirblk),
6464 		    M_NEWDIRBLK, M_SOFTDEP_FLAGS);
6465 		workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
6466 		LIST_INIT(&newdirblk->db_mkdir);
6467 	}
6468 	/*
6469 	 * If we're creating a new directory setup the dependencies and set
6470 	 * the dap state to wait for them.  Otherwise it's COMPLETE and
6471 	 * we can move on.
6472 	 */
6473 	if (newdirbp == NULL) {
6474 		dap->da_state |= DEPCOMPLETE;
6475 		ACQUIRE_LOCK(&lk);
6476 	} else {
6477 		dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
6478 		mkdir1 = setup_newdir(dap, newinum, dp->i_number, newdirbp,
6479 		    &mkdir2);
6480 	}
6481 	/*
6482 	 * Link into parent directory pagedep to await its being written.
6483 	 */
6484 	if (pagedep_lookup(mp, dp->i_number, lbn, DEPALLOC, &pagedep) == 0)
6485 		WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
6486 #ifdef DEBUG
6487 	if (diradd_lookup(pagedep, offset) != NULL)
6488 		panic("softdep_setup_directory_add: %p already at off %d\n",
6489 		    diradd_lookup(pagedep, offset), offset);
6490 #endif
6491 	dap->da_pagedep = pagedep;
6492 	LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
6493 	    da_pdlist);
6494 	inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
6495 	/*
6496 	 * If we're journaling, link the diradd into the jaddref so it
6497 	 * may be completed after the journal entry is written.  Otherwise,
6498 	 * link the diradd into its inodedep.  If the inode is not yet
6499 	 * written place it on the bufwait list, otherwise do the post-inode
6500 	 * write processing to put it on the id_pendinghd list.
6501 	 */
6502 	if (mp->mnt_kern_flag & MNTK_SUJ) {
6503 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
6504 		    inoreflst);
6505 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
6506 		    ("softdep_setup_directory_add: bad jaddref %p", jaddref));
6507 		jaddref->ja_diroff = diroffset;
6508 		jaddref->ja_diradd = dap;
6509 		add_to_journal(&jaddref->ja_list);
6510 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
6511 		diradd_inode_written(dap, inodedep);
6512 	else
6513 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
6514 	/*
6515 	 * Add the journal entries for . and .. links now that the primary
6516 	 * link is written.
6517 	 */
6518 	if (mkdir1 != NULL && mp->mnt_kern_flag & MNTK_SUJ) {
6519 		jaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
6520 		    inoreflst, if_deps);
6521 		KASSERT(jaddref != NULL &&
6522 		    jaddref->ja_ino == jaddref->ja_parent &&
6523 		    (jaddref->ja_state & MKDIR_BODY),
6524 		    ("softdep_setup_directory_add: bad dot jaddref %p",
6525 		    jaddref));
6526 		mkdir1->md_jaddref = jaddref;
6527 		jaddref->ja_mkdir = mkdir1;
6528 		/*
6529 		 * It is important that the dotdot journal entry
6530 		 * is added prior to the dot entry since dot writes
6531 		 * both the dot and dotdot links.  These both must
6532 		 * be added after the primary link for the journal
6533 		 * to remain consistent.
6534 		 */
6535 		add_to_journal(&mkdir2->md_jaddref->ja_list);
6536 		add_to_journal(&jaddref->ja_list);
6537 	}
6538 	/*
6539 	 * If we are adding a new directory remember this diradd so that if
6540 	 * we rename it we can keep the dot and dotdot dependencies.  If
6541 	 * we are adding a new name for an inode that has a mkdiradd we
6542 	 * must be in rename and we have to move the dot and dotdot
6543 	 * dependencies to this new name.  The old name is being orphaned
6544 	 * soon.
6545 	 */
6546 	if (mkdir1 != NULL) {
6547 		if (inodedep->id_mkdiradd != NULL)
6548 			panic("softdep_setup_directory_add: Existing mkdir");
6549 		inodedep->id_mkdiradd = dap;
6550 	} else if (inodedep->id_mkdiradd)
6551 		merge_diradd(inodedep, dap);
6552 	if (newdirblk) {
6553 		/*
6554 		 * There is nothing to do if we are already tracking
6555 		 * this block.
6556 		 */
6557 		if ((pagedep->pd_state & NEWBLOCK) != 0) {
6558 			WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
6559 			FREE_LOCK(&lk);
6560 			return (0);
6561 		}
6562 		if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk)
6563 		    == 0)
6564 			panic("softdep_setup_directory_add: lost entry");
6565 		WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
6566 		pagedep->pd_state |= NEWBLOCK;
6567 		pagedep->pd_newdirblk = newdirblk;
6568 		newdirblk->db_pagedep = pagedep;
6569 		FREE_LOCK(&lk);
6570 		/*
6571 		 * If we extended into an indirect signal direnter to sync.
6572 		 */
6573 		if (isindir)
6574 			return (1);
6575 		return (0);
6576 	}
6577 	FREE_LOCK(&lk);
6578 	return (0);
6579 }
6580 
6581 /*
6582  * This procedure is called to change the offset of a directory
6583  * entry when compacting a directory block which must be owned
6584  * exclusively by the caller. Note that the actual entry movement
6585  * must be done in this procedure to ensure that no I/O completions
6586  * occur while the move is in progress.
6587  */
6588 void
6589 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
6590 	struct buf *bp;		/* Buffer holding directory block. */
6591 	struct inode *dp;	/* inode for directory */
6592 	caddr_t base;		/* address of dp->i_offset */
6593 	caddr_t oldloc;		/* address of old directory location */
6594 	caddr_t newloc;		/* address of new directory location */
6595 	int entrysize;		/* size of directory entry */
6596 {
6597 	int offset, oldoffset, newoffset;
6598 	struct pagedep *pagedep;
6599 	struct jmvref *jmvref;
6600 	struct diradd *dap;
6601 	struct direct *de;
6602 	struct mount *mp;
6603 	ufs_lbn_t lbn;
6604 	int flags;
6605 
6606 	mp = UFSTOVFS(dp->i_ump);
6607 	de = (struct direct *)oldloc;
6608 	jmvref = NULL;
6609 	flags = 0;
6610 	/*
6611 	 * Moves are always journaled as it would be too complex to
6612 	 * determine if any affected adds or removes are present in the
6613 	 * journal.
6614 	 */
6615 	if (mp->mnt_kern_flag & MNTK_SUJ)  {
6616 		flags = DEPALLOC;
6617 		jmvref = newjmvref(dp, de->d_ino,
6618 		    dp->i_offset + (oldloc - base),
6619 		    dp->i_offset + (newloc - base));
6620 	}
6621 	lbn = lblkno(dp->i_fs, dp->i_offset);
6622 	offset = blkoff(dp->i_fs, dp->i_offset);
6623 	oldoffset = offset + (oldloc - base);
6624 	newoffset = offset + (newloc - base);
6625 	ACQUIRE_LOCK(&lk);
6626 	if (pagedep_lookup(mp, dp->i_number, lbn, flags, &pagedep) == 0) {
6627 		if (pagedep)
6628 			WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
6629 		goto done;
6630 	}
6631 	dap = diradd_lookup(pagedep, oldoffset);
6632 	if (dap) {
6633 		dap->da_offset = newoffset;
6634 		newoffset = DIRADDHASH(newoffset);
6635 		oldoffset = DIRADDHASH(oldoffset);
6636 		if ((dap->da_state & ALLCOMPLETE) != ALLCOMPLETE &&
6637 		    newoffset != oldoffset) {
6638 			LIST_REMOVE(dap, da_pdlist);
6639 			LIST_INSERT_HEAD(&pagedep->pd_diraddhd[newoffset],
6640 			    dap, da_pdlist);
6641 		}
6642 	}
6643 done:
6644 	if (jmvref) {
6645 		jmvref->jm_pagedep = pagedep;
6646 		LIST_INSERT_HEAD(&pagedep->pd_jmvrefhd, jmvref, jm_deps);
6647 		add_to_journal(&jmvref->jm_list);
6648 	}
6649 	bcopy(oldloc, newloc, entrysize);
6650 	FREE_LOCK(&lk);
6651 }
6652 
6653 /*
6654  * Move the mkdir dependencies and journal work from one diradd to another
6655  * when renaming a directory.  The new name must depend on the mkdir deps
6656  * completing as the old name did.  Directories can only have one valid link
6657  * at a time so one must be canonical.
6658  */
6659 static void
6660 merge_diradd(inodedep, newdap)
6661 	struct inodedep *inodedep;
6662 	struct diradd *newdap;
6663 {
6664 	struct diradd *olddap;
6665 	struct mkdir *mkdir, *nextmd;
6666 	short state;
6667 
6668 	olddap = inodedep->id_mkdiradd;
6669 	inodedep->id_mkdiradd = newdap;
6670 	if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
6671 		newdap->da_state &= ~DEPCOMPLETE;
6672 		for (mkdir = LIST_FIRST(&mkdirlisthd); mkdir; mkdir = nextmd) {
6673 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
6674 			if (mkdir->md_diradd != olddap)
6675 				continue;
6676 			mkdir->md_diradd = newdap;
6677 			state = mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY);
6678 			newdap->da_state |= state;
6679 			olddap->da_state &= ~state;
6680 			if ((olddap->da_state &
6681 			    (MKDIR_PARENT | MKDIR_BODY)) == 0)
6682 				break;
6683 		}
6684 		if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
6685 			panic("merge_diradd: unfound ref");
6686 	}
6687 	/*
6688 	 * Any mkdir related journal items are not safe to be freed until
6689 	 * the new name is stable.
6690 	 */
6691 	jwork_move(&newdap->da_jwork, &olddap->da_jwork);
6692 	olddap->da_state |= DEPCOMPLETE;
6693 	complete_diradd(olddap);
6694 }
6695 
6696 /*
6697  * Move the diradd to the pending list when all diradd dependencies are
6698  * complete.
6699  */
6700 static void
6701 complete_diradd(dap)
6702 	struct diradd *dap;
6703 {
6704 	struct pagedep *pagedep;
6705 
6706 	if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
6707 		if (dap->da_state & DIRCHG)
6708 			pagedep = dap->da_previous->dm_pagedep;
6709 		else
6710 			pagedep = dap->da_pagedep;
6711 		LIST_REMOVE(dap, da_pdlist);
6712 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
6713 	}
6714 }
6715 
6716 /*
6717  * Cancel a diradd when a dirrem overlaps with it.  We must cancel the journal
6718  * add entries and conditonally journal the remove.
6719  */
6720 static void
6721 cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref)
6722 	struct diradd *dap;
6723 	struct dirrem *dirrem;
6724 	struct jremref *jremref;
6725 	struct jremref *dotremref;
6726 	struct jremref *dotdotremref;
6727 {
6728 	struct inodedep *inodedep;
6729 	struct jaddref *jaddref;
6730 	struct inoref *inoref;
6731 	struct mkdir *mkdir;
6732 
6733 	/*
6734 	 * If no remove references were allocated we're on a non-journaled
6735 	 * filesystem and can skip the cancel step.
6736 	 */
6737 	if (jremref == NULL) {
6738 		free_diradd(dap, NULL);
6739 		return;
6740 	}
6741 	/*
6742 	 * Cancel the primary name an free it if it does not require
6743 	 * journaling.
6744 	 */
6745 	if (inodedep_lookup(dap->da_list.wk_mp, dap->da_newinum,
6746 	    0, &inodedep) != 0) {
6747 		/* Abort the addref that reference this diradd.  */
6748 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
6749 			if (inoref->if_list.wk_type != D_JADDREF)
6750 				continue;
6751 			jaddref = (struct jaddref *)inoref;
6752 			if (jaddref->ja_diradd != dap)
6753 				continue;
6754 			if (cancel_jaddref(jaddref, inodedep,
6755 			    &dirrem->dm_jwork) == 0) {
6756 				free_jremref(jremref);
6757 				jremref = NULL;
6758 			}
6759 			break;
6760 		}
6761 	}
6762 	/*
6763 	 * Cancel subordinate names and free them if they do not require
6764 	 * journaling.
6765 	 */
6766 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
6767 		LIST_FOREACH(mkdir, &mkdirlisthd, md_mkdirs) {
6768 			if (mkdir->md_diradd != dap)
6769 				continue;
6770 			if ((jaddref = mkdir->md_jaddref) == NULL)
6771 				continue;
6772 			mkdir->md_jaddref = NULL;
6773 			if (mkdir->md_state & MKDIR_PARENT) {
6774 				if (cancel_jaddref(jaddref, NULL,
6775 				    &dirrem->dm_jwork) == 0) {
6776 					free_jremref(dotdotremref);
6777 					dotdotremref = NULL;
6778 				}
6779 			} else {
6780 				if (cancel_jaddref(jaddref, inodedep,
6781 				    &dirrem->dm_jwork) == 0) {
6782 					free_jremref(dotremref);
6783 					dotremref = NULL;
6784 				}
6785 			}
6786 		}
6787 	}
6788 
6789 	if (jremref)
6790 		journal_jremref(dirrem, jremref, inodedep);
6791 	if (dotremref)
6792 		journal_jremref(dirrem, dotremref, inodedep);
6793 	if (dotdotremref)
6794 		journal_jremref(dirrem, dotdotremref, NULL);
6795 	jwork_move(&dirrem->dm_jwork, &dap->da_jwork);
6796 	free_diradd(dap, &dirrem->dm_jwork);
6797 }
6798 
6799 /*
6800  * Free a diradd dependency structure. This routine must be called
6801  * with splbio interrupts blocked.
6802  */
6803 static void
6804 free_diradd(dap, wkhd)
6805 	struct diradd *dap;
6806 	struct workhead *wkhd;
6807 {
6808 	struct dirrem *dirrem;
6809 	struct pagedep *pagedep;
6810 	struct inodedep *inodedep;
6811 	struct mkdir *mkdir, *nextmd;
6812 
6813 	mtx_assert(&lk, MA_OWNED);
6814 	LIST_REMOVE(dap, da_pdlist);
6815 	if (dap->da_state & ONWORKLIST)
6816 		WORKLIST_REMOVE(&dap->da_list);
6817 	if ((dap->da_state & DIRCHG) == 0) {
6818 		pagedep = dap->da_pagedep;
6819 	} else {
6820 		dirrem = dap->da_previous;
6821 		pagedep = dirrem->dm_pagedep;
6822 		dirrem->dm_dirinum = pagedep->pd_ino;
6823 		dirrem->dm_state |= COMPLETE;
6824 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
6825 			add_to_worklist(&dirrem->dm_list, 0);
6826 	}
6827 	if (inodedep_lookup(pagedep->pd_list.wk_mp, dap->da_newinum,
6828 	    0, &inodedep) != 0)
6829 		if (inodedep->id_mkdiradd == dap)
6830 			inodedep->id_mkdiradd = NULL;
6831 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
6832 		for (mkdir = LIST_FIRST(&mkdirlisthd); mkdir; mkdir = nextmd) {
6833 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
6834 			if (mkdir->md_diradd != dap)
6835 				continue;
6836 			dap->da_state &=
6837 			    ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
6838 			LIST_REMOVE(mkdir, md_mkdirs);
6839 			if (mkdir->md_state & ONWORKLIST)
6840 				WORKLIST_REMOVE(&mkdir->md_list);
6841 			if (mkdir->md_jaddref != NULL)
6842 				panic("free_diradd: Unexpected jaddref");
6843 			WORKITEM_FREE(mkdir, D_MKDIR);
6844 			if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
6845 				break;
6846 		}
6847 		if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
6848 			panic("free_diradd: unfound ref");
6849 	}
6850 	if (inodedep)
6851 		free_inodedep(inodedep);
6852 	/*
6853 	 * Free any journal segments waiting for the directory write.
6854 	 */
6855 	handle_jwork(&dap->da_jwork);
6856 	WORKITEM_FREE(dap, D_DIRADD);
6857 }
6858 
6859 /*
6860  * Directory entry removal dependencies.
6861  *
6862  * When removing a directory entry, the entry's inode pointer must be
6863  * zero'ed on disk before the corresponding inode's link count is decremented
6864  * (possibly freeing the inode for re-use). This dependency is handled by
6865  * updating the directory entry but delaying the inode count reduction until
6866  * after the directory block has been written to disk. After this point, the
6867  * inode count can be decremented whenever it is convenient.
6868  */
6869 
6870 /*
6871  * This routine should be called immediately after removing
6872  * a directory entry.  The inode's link count should not be
6873  * decremented by the calling procedure -- the soft updates
6874  * code will do this task when it is safe.
6875  */
6876 void
6877 softdep_setup_remove(bp, dp, ip, isrmdir)
6878 	struct buf *bp;		/* buffer containing directory block */
6879 	struct inode *dp;	/* inode for the directory being modified */
6880 	struct inode *ip;	/* inode for directory entry being removed */
6881 	int isrmdir;		/* indicates if doing RMDIR */
6882 {
6883 	struct dirrem *dirrem, *prevdirrem;
6884 	struct inodedep *inodedep;
6885 	int direct;
6886 
6887 	/*
6888 	 * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.  We want
6889 	 * newdirrem() to setup the full directory remove which requires
6890 	 * isrmdir > 1.
6891 	 */
6892 	dirrem = newdirrem(bp, dp, ip, isrmdir?2:0, &prevdirrem);
6893 	/*
6894 	 * Add the dirrem to the inodedep's pending remove list for quick
6895 	 * discovery later.
6896 	 */
6897 	if (inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, 0,
6898 	    &inodedep) == 0)
6899 		panic("softdep_setup_remove: Lost inodedep.");
6900 	dirrem->dm_state |= ONDEPLIST;
6901 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
6902 
6903 	/*
6904 	 * If the COMPLETE flag is clear, then there were no active
6905 	 * entries and we want to roll back to a zeroed entry until
6906 	 * the new inode is committed to disk. If the COMPLETE flag is
6907 	 * set then we have deleted an entry that never made it to
6908 	 * disk. If the entry we deleted resulted from a name change,
6909 	 * then the old name still resides on disk. We cannot delete
6910 	 * its inode (returned to us in prevdirrem) until the zeroed
6911 	 * directory entry gets to disk. The new inode has never been
6912 	 * referenced on the disk, so can be deleted immediately.
6913 	 */
6914 	if ((dirrem->dm_state & COMPLETE) == 0) {
6915 		LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
6916 		    dm_next);
6917 		FREE_LOCK(&lk);
6918 	} else {
6919 		if (prevdirrem != NULL)
6920 			LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
6921 			    prevdirrem, dm_next);
6922 		dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
6923 		direct = LIST_EMPTY(&dirrem->dm_jremrefhd);
6924 		FREE_LOCK(&lk);
6925 		if (direct)
6926 			handle_workitem_remove(dirrem, NULL);
6927 	}
6928 }
6929 
6930 /*
6931  * Check for an entry matching 'offset' on both the pd_dirraddhd list and the
6932  * pd_pendinghd list of a pagedep.
6933  */
6934 static struct diradd *
6935 diradd_lookup(pagedep, offset)
6936 	struct pagedep *pagedep;
6937 	int offset;
6938 {
6939 	struct diradd *dap;
6940 
6941 	LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
6942 		if (dap->da_offset == offset)
6943 			return (dap);
6944 	LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
6945 		if (dap->da_offset == offset)
6946 			return (dap);
6947 	return (NULL);
6948 }
6949 
6950 /*
6951  * Search for a .. diradd dependency in a directory that is being removed.
6952  * If the directory was renamed to a new parent we have a diradd rather
6953  * than a mkdir for the .. entry.  We need to cancel it now before
6954  * it is found in truncate().
6955  */
6956 static struct jremref *
6957 cancel_diradd_dotdot(ip, dirrem, jremref)
6958 	struct inode *ip;
6959 	struct dirrem *dirrem;
6960 	struct jremref *jremref;
6961 {
6962 	struct pagedep *pagedep;
6963 	struct diradd *dap;
6964 	struct worklist *wk;
6965 
6966 	if (pagedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, 0, 0,
6967 	    &pagedep) == 0)
6968 		return (jremref);
6969 	dap = diradd_lookup(pagedep, DOTDOT_OFFSET);
6970 	if (dap == NULL)
6971 		return (jremref);
6972 	cancel_diradd(dap, dirrem, jremref, NULL, NULL);
6973 	/*
6974 	 * Mark any journal work as belonging to the parent so it is freed
6975 	 * with the .. reference.
6976 	 */
6977 	LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
6978 		wk->wk_state |= MKDIR_PARENT;
6979 	return (NULL);
6980 }
6981 
6982 /*
6983  * Cancel the MKDIR_PARENT mkdir component of a diradd when we're going to
6984  * replace it with a dirrem/diradd pair as a result of re-parenting a
6985  * directory.  This ensures that we don't simultaneously have a mkdir and
6986  * a diradd for the same .. entry.
6987  */
6988 static struct jremref *
6989 cancel_mkdir_dotdot(ip, dirrem, jremref)
6990 	struct inode *ip;
6991 	struct dirrem *dirrem;
6992 	struct jremref *jremref;
6993 {
6994 	struct inodedep *inodedep;
6995 	struct jaddref *jaddref;
6996 	struct mkdir *mkdir;
6997 	struct diradd *dap;
6998 
6999 	if (inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, 0,
7000 	    &inodedep) == 0)
7001 		panic("cancel_mkdir_dotdot: Lost inodedep");
7002 	dap = inodedep->id_mkdiradd;
7003 	if (dap == NULL || (dap->da_state & MKDIR_PARENT) == 0)
7004 		return (jremref);
7005 	for (mkdir = LIST_FIRST(&mkdirlisthd); mkdir;
7006 	    mkdir = LIST_NEXT(mkdir, md_mkdirs))
7007 		if (mkdir->md_diradd == dap && mkdir->md_state & MKDIR_PARENT)
7008 			break;
7009 	if (mkdir == NULL)
7010 		panic("cancel_mkdir_dotdot: Unable to find mkdir\n");
7011 	if ((jaddref = mkdir->md_jaddref) != NULL) {
7012 		mkdir->md_jaddref = NULL;
7013 		jaddref->ja_state &= ~MKDIR_PARENT;
7014 		if (inodedep_lookup(UFSTOVFS(ip->i_ump), jaddref->ja_ino, 0,
7015 		    &inodedep) == 0)
7016 			panic("cancel_mkdir_dotdot: Lost parent inodedep");
7017 		if (cancel_jaddref(jaddref, inodedep, &dirrem->dm_jwork)) {
7018 			journal_jremref(dirrem, jremref, inodedep);
7019 			jremref = NULL;
7020 		}
7021 	}
7022 	if (mkdir->md_state & ONWORKLIST)
7023 		WORKLIST_REMOVE(&mkdir->md_list);
7024 	mkdir->md_state |= ALLCOMPLETE;
7025 	complete_mkdir(mkdir);
7026 	return (jremref);
7027 }
7028 
7029 static void
7030 journal_jremref(dirrem, jremref, inodedep)
7031 	struct dirrem *dirrem;
7032 	struct jremref *jremref;
7033 	struct inodedep *inodedep;
7034 {
7035 
7036 	if (inodedep == NULL)
7037 		if (inodedep_lookup(jremref->jr_list.wk_mp,
7038 		    jremref->jr_ref.if_ino, 0, &inodedep) == 0)
7039 			panic("journal_jremref: Lost inodedep");
7040 	LIST_INSERT_HEAD(&dirrem->dm_jremrefhd, jremref, jr_deps);
7041 	TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
7042 	add_to_journal(&jremref->jr_list);
7043 }
7044 
7045 static void
7046 dirrem_journal(dirrem, jremref, dotremref, dotdotremref)
7047 	struct dirrem *dirrem;
7048 	struct jremref *jremref;
7049 	struct jremref *dotremref;
7050 	struct jremref *dotdotremref;
7051 {
7052 	struct inodedep *inodedep;
7053 
7054 
7055 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino, 0,
7056 	    &inodedep) == 0)
7057 		panic("dirrem_journal: Lost inodedep");
7058 	journal_jremref(dirrem, jremref, inodedep);
7059 	if (dotremref)
7060 		journal_jremref(dirrem, dotremref, inodedep);
7061 	if (dotdotremref)
7062 		journal_jremref(dirrem, dotdotremref, NULL);
7063 }
7064 
7065 /*
7066  * Allocate a new dirrem if appropriate and return it along with
7067  * its associated pagedep. Called without a lock, returns with lock.
7068  */
7069 static long num_dirrem;		/* number of dirrem allocated */
7070 static struct dirrem *
7071 newdirrem(bp, dp, ip, isrmdir, prevdirremp)
7072 	struct buf *bp;		/* buffer containing directory block */
7073 	struct inode *dp;	/* inode for the directory being modified */
7074 	struct inode *ip;	/* inode for directory entry being removed */
7075 	int isrmdir;		/* indicates if doing RMDIR */
7076 	struct dirrem **prevdirremp; /* previously referenced inode, if any */
7077 {
7078 	int offset;
7079 	ufs_lbn_t lbn;
7080 	struct diradd *dap;
7081 	struct dirrem *dirrem;
7082 	struct pagedep *pagedep;
7083 	struct jremref *jremref;
7084 	struct jremref *dotremref;
7085 	struct jremref *dotdotremref;
7086 	struct vnode *dvp;
7087 
7088 	/*
7089 	 * Whiteouts have no deletion dependencies.
7090 	 */
7091 	if (ip == NULL)
7092 		panic("newdirrem: whiteout");
7093 	dvp = ITOV(dp);
7094 	/*
7095 	 * If we are over our limit, try to improve the situation.
7096 	 * Limiting the number of dirrem structures will also limit
7097 	 * the number of freefile and freeblks structures.
7098 	 */
7099 	ACQUIRE_LOCK(&lk);
7100 	if (!(ip->i_flags & SF_SNAPSHOT) && num_dirrem > max_softdeps / 2)
7101 		(void) request_cleanup(ITOV(dp)->v_mount, FLUSH_REMOVE);
7102 	num_dirrem += 1;
7103 	FREE_LOCK(&lk);
7104 	dirrem = malloc(sizeof(struct dirrem),
7105 		M_DIRREM, M_SOFTDEP_FLAGS|M_ZERO);
7106 	workitem_alloc(&dirrem->dm_list, D_DIRREM, dvp->v_mount);
7107 	LIST_INIT(&dirrem->dm_jremrefhd);
7108 	LIST_INIT(&dirrem->dm_jwork);
7109 	dirrem->dm_state = isrmdir ? RMDIR : 0;
7110 	dirrem->dm_oldinum = ip->i_number;
7111 	*prevdirremp = NULL;
7112 	/*
7113 	 * Allocate remove reference structures to track journal write
7114 	 * dependencies.  We will always have one for the link and
7115 	 * when doing directories we will always have one more for dot.
7116 	 * When renaming a directory we skip the dotdot link change so
7117 	 * this is not needed.
7118 	 */
7119 	jremref = dotremref = dotdotremref = NULL;
7120 	if (DOINGSUJ(dvp)) {
7121 		if (isrmdir) {
7122 			jremref = newjremref(dirrem, dp, ip, dp->i_offset,
7123 			    ip->i_effnlink + 2);
7124 			dotremref = newjremref(dirrem, ip, ip, DOT_OFFSET,
7125 			    ip->i_effnlink + 1);
7126 		} else
7127 			jremref = newjremref(dirrem, dp, ip, dp->i_offset,
7128 			    ip->i_effnlink + 1);
7129 		if (isrmdir > 1) {
7130 			dotdotremref = newjremref(dirrem, ip, dp, DOTDOT_OFFSET,
7131 			    dp->i_effnlink + 1);
7132 			dotdotremref->jr_state |= MKDIR_PARENT;
7133 		}
7134 	}
7135 	ACQUIRE_LOCK(&lk);
7136 	lbn = lblkno(dp->i_fs, dp->i_offset);
7137 	offset = blkoff(dp->i_fs, dp->i_offset);
7138 	if (pagedep_lookup(UFSTOVFS(dp->i_ump), dp->i_number, lbn, DEPALLOC,
7139 	    &pagedep) == 0)
7140 		WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
7141 	dirrem->dm_pagedep = pagedep;
7142 	/*
7143 	 * If we're renaming a .. link to a new directory, cancel any
7144 	 * existing MKDIR_PARENT mkdir.  If it has already been canceled
7145 	 * the jremref is preserved for any potential diradd in this
7146 	 * location.  This can not coincide with a rmdir.
7147 	 */
7148 	if (dp->i_offset == DOTDOT_OFFSET) {
7149 		if (isrmdir)
7150 			panic("newdirrem: .. directory change during remove?");
7151 		jremref = cancel_mkdir_dotdot(dp, dirrem, jremref);
7152 	}
7153 	/*
7154 	 * If we're removing a directory search for the .. dependency now and
7155 	 * cancel it.  Any pending journal work will be added to the dirrem
7156 	 * to be completed when the workitem remove completes.
7157 	 */
7158 	if (isrmdir > 1)
7159 		dotdotremref = cancel_diradd_dotdot(ip, dirrem, dotdotremref);
7160 	/*
7161 	 * Check for a diradd dependency for the same directory entry.
7162 	 * If present, then both dependencies become obsolete and can
7163 	 * be de-allocated.
7164 	 */
7165 	dap = diradd_lookup(pagedep, offset);
7166 	if (dap == NULL) {
7167 		/*
7168 		 * Link the jremref structures into the dirrem so they are
7169 		 * written prior to the pagedep.
7170 		 */
7171 		if (jremref)
7172 			dirrem_journal(dirrem, jremref, dotremref,
7173 			    dotdotremref);
7174 		return (dirrem);
7175 	}
7176 	/*
7177 	 * Must be ATTACHED at this point.
7178 	 */
7179 	if ((dap->da_state & ATTACHED) == 0)
7180 		panic("newdirrem: not ATTACHED");
7181 	if (dap->da_newinum != ip->i_number)
7182 		panic("newdirrem: inum %d should be %d",
7183 		    ip->i_number, dap->da_newinum);
7184 	/*
7185 	 * If we are deleting a changed name that never made it to disk,
7186 	 * then return the dirrem describing the previous inode (which
7187 	 * represents the inode currently referenced from this entry on disk).
7188 	 */
7189 	if ((dap->da_state & DIRCHG) != 0) {
7190 		*prevdirremp = dap->da_previous;
7191 		dap->da_state &= ~DIRCHG;
7192 		dap->da_pagedep = pagedep;
7193 	}
7194 	/*
7195 	 * We are deleting an entry that never made it to disk.
7196 	 * Mark it COMPLETE so we can delete its inode immediately.
7197 	 */
7198 	dirrem->dm_state |= COMPLETE;
7199 	cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref);
7200 #ifdef SUJ_DEBUG
7201 	if (isrmdir == 0) {
7202 		struct worklist *wk;
7203 
7204 		LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
7205 			if (wk->wk_state & (MKDIR_BODY | MKDIR_PARENT))
7206 				panic("bad wk %p (0x%X)\n", wk, wk->wk_state);
7207 	}
7208 #endif
7209 
7210 	return (dirrem);
7211 }
7212 
7213 /*
7214  * Directory entry change dependencies.
7215  *
7216  * Changing an existing directory entry requires that an add operation
7217  * be completed first followed by a deletion. The semantics for the addition
7218  * are identical to the description of adding a new entry above except
7219  * that the rollback is to the old inode number rather than zero. Once
7220  * the addition dependency is completed, the removal is done as described
7221  * in the removal routine above.
7222  */
7223 
7224 /*
7225  * This routine should be called immediately after changing
7226  * a directory entry.  The inode's link count should not be
7227  * decremented by the calling procedure -- the soft updates
7228  * code will perform this task when it is safe.
7229  */
7230 void
7231 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
7232 	struct buf *bp;		/* buffer containing directory block */
7233 	struct inode *dp;	/* inode for the directory being modified */
7234 	struct inode *ip;	/* inode for directory entry being removed */
7235 	ino_t newinum;		/* new inode number for changed entry */
7236 	int isrmdir;		/* indicates if doing RMDIR */
7237 {
7238 	int offset;
7239 	struct diradd *dap = NULL;
7240 	struct dirrem *dirrem, *prevdirrem;
7241 	struct pagedep *pagedep;
7242 	struct inodedep *inodedep;
7243 	struct jaddref *jaddref;
7244 	struct mount *mp;
7245 
7246 	offset = blkoff(dp->i_fs, dp->i_offset);
7247 	mp = UFSTOVFS(dp->i_ump);
7248 
7249 	/*
7250 	 * Whiteouts do not need diradd dependencies.
7251 	 */
7252 	if (newinum != WINO) {
7253 		dap = malloc(sizeof(struct diradd),
7254 		    M_DIRADD, M_SOFTDEP_FLAGS|M_ZERO);
7255 		workitem_alloc(&dap->da_list, D_DIRADD, mp);
7256 		dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
7257 		dap->da_offset = offset;
7258 		dap->da_newinum = newinum;
7259 		LIST_INIT(&dap->da_jwork);
7260 	}
7261 
7262 	/*
7263 	 * Allocate a new dirrem and ACQUIRE_LOCK.
7264 	 */
7265 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
7266 	pagedep = dirrem->dm_pagedep;
7267 	/*
7268 	 * The possible values for isrmdir:
7269 	 *	0 - non-directory file rename
7270 	 *	1 - directory rename within same directory
7271 	 *   inum - directory rename to new directory of given inode number
7272 	 * When renaming to a new directory, we are both deleting and
7273 	 * creating a new directory entry, so the link count on the new
7274 	 * directory should not change. Thus we do not need the followup
7275 	 * dirrem which is usually done in handle_workitem_remove. We set
7276 	 * the DIRCHG flag to tell handle_workitem_remove to skip the
7277 	 * followup dirrem.
7278 	 */
7279 	if (isrmdir > 1)
7280 		dirrem->dm_state |= DIRCHG;
7281 
7282 	/*
7283 	 * Whiteouts have no additional dependencies,
7284 	 * so just put the dirrem on the correct list.
7285 	 */
7286 	if (newinum == WINO) {
7287 		if ((dirrem->dm_state & COMPLETE) == 0) {
7288 			LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
7289 			    dm_next);
7290 		} else {
7291 			dirrem->dm_dirinum = pagedep->pd_ino;
7292 			if (LIST_EMPTY(&dirrem->dm_jremrefhd))
7293 				add_to_worklist(&dirrem->dm_list, 0);
7294 		}
7295 		FREE_LOCK(&lk);
7296 		return;
7297 	}
7298 	/*
7299 	 * Add the dirrem to the inodedep's pending remove list for quick
7300 	 * discovery later.  A valid nlinkdelta ensures that this lookup
7301 	 * will not fail.
7302 	 */
7303 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
7304 		panic("softdep_setup_directory_change: Lost inodedep.");
7305 	dirrem->dm_state |= ONDEPLIST;
7306 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
7307 
7308 	/*
7309 	 * If the COMPLETE flag is clear, then there were no active
7310 	 * entries and we want to roll back to the previous inode until
7311 	 * the new inode is committed to disk. If the COMPLETE flag is
7312 	 * set, then we have deleted an entry that never made it to disk.
7313 	 * If the entry we deleted resulted from a name change, then the old
7314 	 * inode reference still resides on disk. Any rollback that we do
7315 	 * needs to be to that old inode (returned to us in prevdirrem). If
7316 	 * the entry we deleted resulted from a create, then there is
7317 	 * no entry on the disk, so we want to roll back to zero rather
7318 	 * than the uncommitted inode. In either of the COMPLETE cases we
7319 	 * want to immediately free the unwritten and unreferenced inode.
7320 	 */
7321 	if ((dirrem->dm_state & COMPLETE) == 0) {
7322 		dap->da_previous = dirrem;
7323 	} else {
7324 		if (prevdirrem != NULL) {
7325 			dap->da_previous = prevdirrem;
7326 		} else {
7327 			dap->da_state &= ~DIRCHG;
7328 			dap->da_pagedep = pagedep;
7329 		}
7330 		dirrem->dm_dirinum = pagedep->pd_ino;
7331 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
7332 			add_to_worklist(&dirrem->dm_list, 0);
7333 	}
7334 	/*
7335 	 * Lookup the jaddref for this journal entry.  We must finish
7336 	 * initializing it and make the diradd write dependent on it.
7337 	 * If we're not journaling Put it on the id_bufwait list if the inode
7338 	 * is not yet written. If it is written, do the post-inode write
7339 	 * processing to put it on the id_pendinghd list.
7340 	 */
7341 	inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
7342 	if (mp->mnt_kern_flag & MNTK_SUJ) {
7343 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
7344 		    inoreflst);
7345 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
7346 		    ("softdep_setup_directory_change: bad jaddref %p",
7347 		    jaddref));
7348 		jaddref->ja_diroff = dp->i_offset;
7349 		jaddref->ja_diradd = dap;
7350 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
7351 		    dap, da_pdlist);
7352 		add_to_journal(&jaddref->ja_list);
7353 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
7354 		dap->da_state |= COMPLETE;
7355 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
7356 		WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
7357 	} else {
7358 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
7359 		    dap, da_pdlist);
7360 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
7361 	}
7362 	/*
7363 	 * If we're making a new name for a directory that has not been
7364 	 * committed when need to move the dot and dotdot references to
7365 	 * this new name.
7366 	 */
7367 	if (inodedep->id_mkdiradd && dp->i_offset != DOTDOT_OFFSET)
7368 		merge_diradd(inodedep, dap);
7369 	FREE_LOCK(&lk);
7370 }
7371 
7372 /*
7373  * Called whenever the link count on an inode is changed.
7374  * It creates an inode dependency so that the new reference(s)
7375  * to the inode cannot be committed to disk until the updated
7376  * inode has been written.
7377  */
7378 void
7379 softdep_change_linkcnt(ip)
7380 	struct inode *ip;	/* the inode with the increased link count */
7381 {
7382 	struct inodedep *inodedep;
7383 
7384 	ACQUIRE_LOCK(&lk);
7385 	inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, DEPALLOC, &inodedep);
7386 	if (ip->i_nlink < ip->i_effnlink)
7387 		panic("softdep_change_linkcnt: bad delta");
7388 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
7389 	FREE_LOCK(&lk);
7390 }
7391 
7392 /*
7393  * Attach a sbdep dependency to the superblock buf so that we can keep
7394  * track of the head of the linked list of referenced but unlinked inodes.
7395  */
7396 void
7397 softdep_setup_sbupdate(ump, fs, bp)
7398 	struct ufsmount *ump;
7399 	struct fs *fs;
7400 	struct buf *bp;
7401 {
7402 	struct sbdep *sbdep;
7403 	struct worklist *wk;
7404 
7405 	if ((fs->fs_flags & FS_SUJ) == 0)
7406 		return;
7407 	LIST_FOREACH(wk, &bp->b_dep, wk_list)
7408 		if (wk->wk_type == D_SBDEP)
7409 			break;
7410 	if (wk != NULL)
7411 		return;
7412 	sbdep = malloc(sizeof(struct sbdep), M_SBDEP, M_SOFTDEP_FLAGS);
7413 	workitem_alloc(&sbdep->sb_list, D_SBDEP, UFSTOVFS(ump));
7414 	sbdep->sb_fs = fs;
7415 	sbdep->sb_ump = ump;
7416 	ACQUIRE_LOCK(&lk);
7417 	WORKLIST_INSERT(&bp->b_dep, &sbdep->sb_list);
7418 	FREE_LOCK(&lk);
7419 }
7420 
7421 /*
7422  * Return the first unlinked inodedep which is ready to be the head of the
7423  * list.  The inodedep and all those after it must have valid next pointers.
7424  */
7425 static struct inodedep *
7426 first_unlinked_inodedep(ump)
7427 	struct ufsmount *ump;
7428 {
7429 	struct inodedep *inodedep;
7430 	struct inodedep *idp;
7431 
7432 	for (inodedep = TAILQ_LAST(&ump->softdep_unlinked, inodedeplst);
7433 	    inodedep; inodedep = idp) {
7434 		if ((inodedep->id_state & UNLINKNEXT) == 0)
7435 			return (NULL);
7436 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
7437 		if (idp == NULL || (idp->id_state & UNLINKNEXT) == 0)
7438 			break;
7439 		if ((inodedep->id_state & UNLINKPREV) == 0)
7440 			panic("first_unlinked_inodedep: prev != next");
7441 	}
7442 	if (inodedep == NULL)
7443 		return (NULL);
7444 
7445 	return (inodedep);
7446 }
7447 
7448 /*
7449  * Set the sujfree unlinked head pointer prior to writing a superblock.
7450  */
7451 static void
7452 initiate_write_sbdep(sbdep)
7453 	struct sbdep *sbdep;
7454 {
7455 	struct inodedep *inodedep;
7456 	struct fs *bpfs;
7457 	struct fs *fs;
7458 
7459 	bpfs = sbdep->sb_fs;
7460 	fs = sbdep->sb_ump->um_fs;
7461 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
7462 	if (inodedep) {
7463 		fs->fs_sujfree = inodedep->id_ino;
7464 		inodedep->id_state |= UNLINKPREV;
7465 	} else
7466 		fs->fs_sujfree = 0;
7467 	bpfs->fs_sujfree = fs->fs_sujfree;
7468 }
7469 
7470 /*
7471  * After a superblock is written determine whether it must be written again
7472  * due to a changing unlinked list head.
7473  */
7474 static int
7475 handle_written_sbdep(sbdep, bp)
7476 	struct sbdep *sbdep;
7477 	struct buf *bp;
7478 {
7479 	struct inodedep *inodedep;
7480 	struct mount *mp;
7481 	struct fs *fs;
7482 
7483 	fs = sbdep->sb_fs;
7484 	mp = UFSTOVFS(sbdep->sb_ump);
7485 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
7486 	if ((inodedep && fs->fs_sujfree != inodedep->id_ino) ||
7487 	    (inodedep == NULL && fs->fs_sujfree != 0)) {
7488 		bdirty(bp);
7489 		return (1);
7490 	}
7491 	WORKITEM_FREE(sbdep, D_SBDEP);
7492 	if (fs->fs_sujfree == 0)
7493 		return (0);
7494 	if (inodedep_lookup(mp, fs->fs_sujfree, 0, &inodedep) == 0)
7495 		panic("handle_written_sbdep: lost inodedep");
7496 	/*
7497 	 * Now that we have a record of this inode in stable store allow it
7498 	 * to be written to free up pending work.  Inodes may see a lot of
7499 	 * write activity after they are unlinked which we must not hold up.
7500 	 */
7501 	for (; inodedep != NULL; inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
7502 		if ((inodedep->id_state & UNLINKLINKS) != UNLINKLINKS)
7503 			panic("handle_written_sbdep: Bad inodedep %p (0x%X)",
7504 			    inodedep, inodedep->id_state);
7505 		if (inodedep->id_state & UNLINKONLIST)
7506 			break;
7507 		inodedep->id_state |= DEPCOMPLETE | UNLINKONLIST;
7508 	}
7509 
7510 	return (0);
7511 }
7512 
7513 /*
7514  * Mark an inodedep as unlinked and insert it into the in-memory unlinked list.
7515  */
7516 static void
7517 unlinked_inodedep(mp, inodedep)
7518 	struct mount *mp;
7519 	struct inodedep *inodedep;
7520 {
7521 	struct ufsmount *ump;
7522 
7523 	if ((mp->mnt_kern_flag & MNTK_SUJ) == 0)
7524 		return;
7525 	ump = VFSTOUFS(mp);
7526 	ump->um_fs->fs_fmod = 1;
7527 	inodedep->id_state |= UNLINKED;
7528 	TAILQ_INSERT_HEAD(&ump->softdep_unlinked, inodedep, id_unlinked);
7529 }
7530 
7531 /*
7532  * Remove an inodedep from the unlinked inodedep list.  This may require
7533  * disk writes if the inode has made it that far.
7534  */
7535 static void
7536 clear_unlinked_inodedep(inodedep)
7537 	struct inodedep *inodedep;
7538 {
7539 	struct ufsmount *ump;
7540 	struct inodedep *idp;
7541 	struct inodedep *idn;
7542 	struct fs *fs;
7543 	struct buf *bp;
7544 	ino_t ino;
7545 	ino_t nino;
7546 	ino_t pino;
7547 	int error;
7548 
7549 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
7550 	fs = ump->um_fs;
7551 	ino = inodedep->id_ino;
7552 	error = 0;
7553 	for (;;) {
7554 		/*
7555 		 * If nothing has yet been written simply remove us from
7556 		 * the in memory list and return.  This is the most common
7557 		 * case where handle_workitem_remove() loses the final
7558 		 * reference.
7559 		 */
7560 		if ((inodedep->id_state & UNLINKLINKS) == 0)
7561 			break;
7562 		/*
7563 		 * If we have a NEXT pointer and no PREV pointer we can simply
7564 		 * clear NEXT's PREV and remove ourselves from the list.  Be
7565 		 * careful not to clear PREV if the superblock points at
7566 		 * next as well.
7567 		 */
7568 		idn = TAILQ_NEXT(inodedep, id_unlinked);
7569 		if ((inodedep->id_state & UNLINKLINKS) == UNLINKNEXT) {
7570 			if (idn && fs->fs_sujfree != idn->id_ino)
7571 				idn->id_state &= ~UNLINKPREV;
7572 			break;
7573 		}
7574 		/*
7575 		 * Here we have an inodedep which is actually linked into
7576 		 * the list.  We must remove it by forcing a write to the
7577 		 * link before us, whether it be the superblock or an inode.
7578 		 * Unfortunately the list may change while we're waiting
7579 		 * on the buf lock for either resource so we must loop until
7580 		 * we lock the right one.  If both the superblock and an
7581 		 * inode point to this inode we must clear the inode first
7582 		 * followed by the superblock.
7583 		 */
7584 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
7585 		pino = 0;
7586 		if (idp && (idp->id_state & UNLINKNEXT))
7587 			pino = idp->id_ino;
7588 		FREE_LOCK(&lk);
7589 		if (pino == 0)
7590 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
7591 			    (int)fs->fs_sbsize, 0, 0, 0);
7592 		else
7593 			error = bread(ump->um_devvp,
7594 			    fsbtodb(fs, ino_to_fsba(fs, pino)),
7595 			    (int)fs->fs_bsize, NOCRED, &bp);
7596 		ACQUIRE_LOCK(&lk);
7597 		if (error)
7598 			break;
7599 		/* If the list has changed restart the loop. */
7600 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
7601 		nino = 0;
7602 		if (idp && (idp->id_state & UNLINKNEXT))
7603 			nino = idp->id_ino;
7604 		if (nino != pino ||
7605 		    (inodedep->id_state & UNLINKPREV) != UNLINKPREV) {
7606 			FREE_LOCK(&lk);
7607 			brelse(bp);
7608 			ACQUIRE_LOCK(&lk);
7609 			continue;
7610 		}
7611 		/*
7612 		 * Remove us from the in memory list.  After this we cannot
7613 		 * access the inodedep.
7614 		 */
7615 		idn = TAILQ_NEXT(inodedep, id_unlinked);
7616 		inodedep->id_state &= ~(UNLINKED | UNLINKLINKS);
7617 		TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
7618 		/*
7619 		 * Determine the next inode number.
7620 		 */
7621 		nino = 0;
7622 		if (idn) {
7623 			/*
7624 			 * If next isn't on the list we can just clear prev's
7625 			 * state and schedule it to be fixed later.  No need
7626 			 * to synchronously write if we're not in the real
7627 			 * list.
7628 			 */
7629 			if ((idn->id_state & UNLINKPREV) == 0 && pino != 0) {
7630 				idp->id_state &= ~UNLINKNEXT;
7631 				if ((idp->id_state & ONWORKLIST) == 0)
7632 					WORKLIST_INSERT(&bp->b_dep,
7633 					    &idp->id_list);
7634 				FREE_LOCK(&lk);
7635 				bawrite(bp);
7636 				ACQUIRE_LOCK(&lk);
7637 				return;
7638 			}
7639 			nino = idn->id_ino;
7640 		}
7641 		FREE_LOCK(&lk);
7642 		/*
7643 		 * The predecessor's next pointer is manually updated here
7644 		 * so that the NEXT flag is never cleared for an element
7645 		 * that is in the list.
7646 		 */
7647 		if (pino == 0) {
7648 			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
7649 			ffs_oldfscompat_write((struct fs *)bp->b_data, ump);
7650 			softdep_setup_sbupdate(ump, (struct fs *)bp->b_data,
7651 			    bp);
7652 		} else if (fs->fs_magic == FS_UFS1_MAGIC)
7653 			((struct ufs1_dinode *)bp->b_data +
7654 			    ino_to_fsbo(fs, pino))->di_freelink = nino;
7655 		else
7656 			((struct ufs2_dinode *)bp->b_data +
7657 			    ino_to_fsbo(fs, pino))->di_freelink = nino;
7658 		/*
7659 		 * If the bwrite fails we have no recourse to recover.  The
7660 		 * filesystem is corrupted already.
7661 		 */
7662 		bwrite(bp);
7663 		ACQUIRE_LOCK(&lk);
7664 		/*
7665 		 * If the superblock pointer still needs to be cleared force
7666 		 * a write here.
7667 		 */
7668 		if (fs->fs_sujfree == ino) {
7669 			FREE_LOCK(&lk);
7670 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
7671 			    (int)fs->fs_sbsize, 0, 0, 0);
7672 			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
7673 			ffs_oldfscompat_write((struct fs *)bp->b_data, ump);
7674 			softdep_setup_sbupdate(ump, (struct fs *)bp->b_data,
7675 			    bp);
7676 			bwrite(bp);
7677 			ACQUIRE_LOCK(&lk);
7678 		}
7679 		if (fs->fs_sujfree != ino)
7680 			return;
7681 		panic("clear_unlinked_inodedep: Failed to clear free head");
7682 	}
7683 	if (inodedep->id_ino == fs->fs_sujfree)
7684 		panic("clear_unlinked_inodedep: Freeing head of free list");
7685 	inodedep->id_state &= ~(UNLINKED | UNLINKLINKS);
7686 	TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
7687 	return;
7688 }
7689 
7690 /*
7691  * This workitem decrements the inode's link count.
7692  * If the link count reaches zero, the file is removed.
7693  */
7694 static void
7695 handle_workitem_remove(dirrem, xp)
7696 	struct dirrem *dirrem;
7697 	struct vnode *xp;
7698 {
7699 	struct inodedep *inodedep;
7700 	struct workhead dotdotwk;
7701 	struct worklist *wk;
7702 	struct ufsmount *ump;
7703 	struct mount *mp;
7704 	struct vnode *vp;
7705 	struct inode *ip;
7706 	ino_t oldinum;
7707 	int error;
7708 
7709 	if (dirrem->dm_state & ONWORKLIST)
7710 		panic("handle_workitem_remove: dirrem %p still on worklist",
7711 		    dirrem);
7712 	oldinum = dirrem->dm_oldinum;
7713 	mp = dirrem->dm_list.wk_mp;
7714 	ump = VFSTOUFS(mp);
7715 	if ((vp = xp) == NULL &&
7716 	    (error = ffs_vgetf(mp, oldinum, LK_EXCLUSIVE, &vp,
7717 	    FFSV_FORCEINSMQ)) != 0) {
7718 		softdep_error("handle_workitem_remove: vget", error);
7719 		return;
7720 	}
7721 	ip = VTOI(vp);
7722 	ACQUIRE_LOCK(&lk);
7723 	if ((inodedep_lookup(mp, oldinum, 0, &inodedep)) == 0)
7724 		panic("handle_workitem_remove: lost inodedep");
7725 	if (dirrem->dm_state & ONDEPLIST)
7726 		LIST_REMOVE(dirrem, dm_inonext);
7727 	KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
7728 	    ("handle_workitem_remove:  Journal entries not written."));
7729 
7730 	/*
7731 	 * Move all dependencies waiting on the remove to complete
7732 	 * from the dirrem to the inode inowait list to be completed
7733 	 * after the inode has been updated and written to disk.  Any
7734 	 * marked MKDIR_PARENT are saved to be completed when the .. ref
7735 	 * is removed.
7736 	 */
7737 	LIST_INIT(&dotdotwk);
7738 	while ((wk = LIST_FIRST(&dirrem->dm_jwork)) != NULL) {
7739 		WORKLIST_REMOVE(wk);
7740 		if (wk->wk_state & MKDIR_PARENT) {
7741 			wk->wk_state &= ~MKDIR_PARENT;
7742 			WORKLIST_INSERT(&dotdotwk, wk);
7743 			continue;
7744 		}
7745 		WORKLIST_INSERT(&inodedep->id_inowait, wk);
7746 	}
7747 	LIST_SWAP(&dirrem->dm_jwork, &dotdotwk, worklist, wk_list);
7748 	/*
7749 	 * Normal file deletion.
7750 	 */
7751 	if ((dirrem->dm_state & RMDIR) == 0) {
7752 		ip->i_nlink--;
7753 		DIP_SET(ip, i_nlink, ip->i_nlink);
7754 		ip->i_flag |= IN_CHANGE;
7755 		if (ip->i_nlink < ip->i_effnlink)
7756 			panic("handle_workitem_remove: bad file delta");
7757 		if (ip->i_nlink == 0)
7758 			unlinked_inodedep(mp, inodedep);
7759 		inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
7760 		num_dirrem -= 1;
7761 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
7762 		    ("handle_workitem_remove: worklist not empty. %s",
7763 		    TYPENAME(LIST_FIRST(&dirrem->dm_jwork)->wk_type)));
7764 		WORKITEM_FREE(dirrem, D_DIRREM);
7765 		FREE_LOCK(&lk);
7766 		goto out;
7767 	}
7768 	/*
7769 	 * Directory deletion. Decrement reference count for both the
7770 	 * just deleted parent directory entry and the reference for ".".
7771 	 * Arrange to have the reference count on the parent decremented
7772 	 * to account for the loss of "..".
7773 	 */
7774 	ip->i_nlink -= 2;
7775 	DIP_SET(ip, i_nlink, ip->i_nlink);
7776 	ip->i_flag |= IN_CHANGE;
7777 	if (ip->i_nlink < ip->i_effnlink)
7778 		panic("handle_workitem_remove: bad dir delta");
7779 	if (ip->i_nlink == 0)
7780 		unlinked_inodedep(mp, inodedep);
7781 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
7782 	/*
7783 	 * Rename a directory to a new parent. Since, we are both deleting
7784 	 * and creating a new directory entry, the link count on the new
7785 	 * directory should not change. Thus we skip the followup dirrem.
7786 	 */
7787 	if (dirrem->dm_state & DIRCHG) {
7788 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
7789 		    ("handle_workitem_remove: DIRCHG and worklist not empty."));
7790 		num_dirrem -= 1;
7791 		WORKITEM_FREE(dirrem, D_DIRREM);
7792 		FREE_LOCK(&lk);
7793 		goto out;
7794 	}
7795 	dirrem->dm_state = ONDEPLIST;
7796 	dirrem->dm_oldinum = dirrem->dm_dirinum;
7797 	/*
7798 	 * Place the dirrem on the parent's diremhd list.
7799 	 */
7800 	if (inodedep_lookup(mp, dirrem->dm_oldinum, 0, &inodedep) == 0)
7801 		panic("handle_workitem_remove: lost dir inodedep");
7802 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
7803 	/*
7804 	 * If the allocated inode has never been written to disk, then
7805 	 * the on-disk inode is zero'ed and we can remove the file
7806 	 * immediately.  When journaling if the inode has been marked
7807 	 * unlinked and not DEPCOMPLETE we know it can never be written.
7808 	 */
7809 	inodedep_lookup(mp, oldinum, 0, &inodedep);
7810 	if (inodedep == NULL ||
7811 	    (inodedep->id_state & (DEPCOMPLETE | UNLINKED)) == UNLINKED ||
7812 	    check_inode_unwritten(inodedep)) {
7813 		if (xp != NULL)
7814 			add_to_worklist(&dirrem->dm_list, 0);
7815 		FREE_LOCK(&lk);
7816 		if (xp == NULL) {
7817 			vput(vp);
7818 			handle_workitem_remove(dirrem, NULL);
7819 		}
7820 		return;
7821 	}
7822 	WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
7823 	FREE_LOCK(&lk);
7824 	ip->i_flag |= IN_CHANGE;
7825 out:
7826 	ffs_update(vp, 0);
7827 	if (xp == NULL)
7828 		vput(vp);
7829 }
7830 
7831 /*
7832  * Inode de-allocation dependencies.
7833  *
7834  * When an inode's link count is reduced to zero, it can be de-allocated. We
7835  * found it convenient to postpone de-allocation until after the inode is
7836  * written to disk with its new link count (zero).  At this point, all of the
7837  * on-disk inode's block pointers are nullified and, with careful dependency
7838  * list ordering, all dependencies related to the inode will be satisfied and
7839  * the corresponding dependency structures de-allocated.  So, if/when the
7840  * inode is reused, there will be no mixing of old dependencies with new
7841  * ones.  This artificial dependency is set up by the block de-allocation
7842  * procedure above (softdep_setup_freeblocks) and completed by the
7843  * following procedure.
7844  */
7845 static void
7846 handle_workitem_freefile(freefile)
7847 	struct freefile *freefile;
7848 {
7849 	struct workhead wkhd;
7850 	struct fs *fs;
7851 	struct inodedep *idp;
7852 	struct ufsmount *ump;
7853 	int error;
7854 
7855 	ump = VFSTOUFS(freefile->fx_list.wk_mp);
7856 	fs = ump->um_fs;
7857 #ifdef DEBUG
7858 	ACQUIRE_LOCK(&lk);
7859 	error = inodedep_lookup(UFSTOVFS(ump), freefile->fx_oldinum, 0, &idp);
7860 	FREE_LOCK(&lk);
7861 	if (error)
7862 		panic("handle_workitem_freefile: inodedep %p survived", idp);
7863 #endif
7864 	UFS_LOCK(ump);
7865 	fs->fs_pendinginodes -= 1;
7866 	UFS_UNLOCK(ump);
7867 	LIST_INIT(&wkhd);
7868 	LIST_SWAP(&freefile->fx_jwork, &wkhd, worklist, wk_list);
7869 	if ((error = ffs_freefile(ump, fs, freefile->fx_devvp,
7870 	    freefile->fx_oldinum, freefile->fx_mode, &wkhd)) != 0)
7871 		softdep_error("handle_workitem_freefile", error);
7872 	ACQUIRE_LOCK(&lk);
7873 	WORKITEM_FREE(freefile, D_FREEFILE);
7874 	FREE_LOCK(&lk);
7875 }
7876 
7877 
7878 /*
7879  * Helper function which unlinks marker element from work list and returns
7880  * the next element on the list.
7881  */
7882 static __inline struct worklist *
7883 markernext(struct worklist *marker)
7884 {
7885 	struct worklist *next;
7886 
7887 	next = LIST_NEXT(marker, wk_list);
7888 	LIST_REMOVE(marker, wk_list);
7889 	return next;
7890 }
7891 
7892 /*
7893  * Disk writes.
7894  *
7895  * The dependency structures constructed above are most actively used when file
7896  * system blocks are written to disk.  No constraints are placed on when a
7897  * block can be written, but unsatisfied update dependencies are made safe by
7898  * modifying (or replacing) the source memory for the duration of the disk
7899  * write.  When the disk write completes, the memory block is again brought
7900  * up-to-date.
7901  *
7902  * In-core inode structure reclamation.
7903  *
7904  * Because there are a finite number of "in-core" inode structures, they are
7905  * reused regularly.  By transferring all inode-related dependencies to the
7906  * in-memory inode block and indexing them separately (via "inodedep"s), we
7907  * can allow "in-core" inode structures to be reused at any time and avoid
7908  * any increase in contention.
7909  *
7910  * Called just before entering the device driver to initiate a new disk I/O.
7911  * The buffer must be locked, thus, no I/O completion operations can occur
7912  * while we are manipulating its associated dependencies.
7913  */
7914 static void
7915 softdep_disk_io_initiation(bp)
7916 	struct buf *bp;		/* structure describing disk write to occur */
7917 {
7918 	struct worklist *wk;
7919 	struct worklist marker;
7920 	struct inodedep *inodedep;
7921 	struct freeblks *freeblks;
7922 	struct jfreeblk *jfreeblk;
7923 	struct newblk *newblk;
7924 
7925 	/*
7926 	 * We only care about write operations. There should never
7927 	 * be dependencies for reads.
7928 	 */
7929 	if (bp->b_iocmd != BIO_WRITE)
7930 		panic("softdep_disk_io_initiation: not write");
7931 
7932 	if (bp->b_vflags & BV_BKGRDINPROG)
7933 		panic("softdep_disk_io_initiation: Writing buffer with "
7934 		    "background write in progress: %p", bp);
7935 
7936 	marker.wk_type = D_LAST + 1;	/* Not a normal workitem */
7937 	PHOLD(curproc);			/* Don't swap out kernel stack */
7938 
7939 	ACQUIRE_LOCK(&lk);
7940 	/*
7941 	 * Do any necessary pre-I/O processing.
7942 	 */
7943 	for (wk = LIST_FIRST(&bp->b_dep); wk != NULL;
7944 	     wk = markernext(&marker)) {
7945 		LIST_INSERT_AFTER(wk, &marker, wk_list);
7946 		switch (wk->wk_type) {
7947 
7948 		case D_PAGEDEP:
7949 			initiate_write_filepage(WK_PAGEDEP(wk), bp);
7950 			continue;
7951 
7952 		case D_INODEDEP:
7953 			inodedep = WK_INODEDEP(wk);
7954 			if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC)
7955 				initiate_write_inodeblock_ufs1(inodedep, bp);
7956 			else
7957 				initiate_write_inodeblock_ufs2(inodedep, bp);
7958 			continue;
7959 
7960 		case D_INDIRDEP:
7961 			initiate_write_indirdep(WK_INDIRDEP(wk), bp);
7962 			continue;
7963 
7964 		case D_BMSAFEMAP:
7965 			initiate_write_bmsafemap(WK_BMSAFEMAP(wk), bp);
7966 			continue;
7967 
7968 		case D_JSEG:
7969 			WK_JSEG(wk)->js_buf = NULL;
7970 			continue;
7971 
7972 		case D_FREEBLKS:
7973 			freeblks = WK_FREEBLKS(wk);
7974 			jfreeblk = LIST_FIRST(&freeblks->fb_jfreeblkhd);
7975 			/*
7976 			 * We have to wait for the jfreeblks to be journaled
7977 			 * before we can write an inodeblock with updated
7978 			 * pointers.  Be careful to arrange the marker so
7979 			 * we revisit the jfreeblk if it's not removed by
7980 			 * the first jwait().
7981 			 */
7982 			if (jfreeblk != NULL) {
7983 				LIST_REMOVE(&marker, wk_list);
7984 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
7985 				jwait(&jfreeblk->jf_list);
7986 			}
7987 			continue;
7988 		case D_ALLOCDIRECT:
7989 		case D_ALLOCINDIR:
7990 			/*
7991 			 * We have to wait for the jnewblk to be journaled
7992 			 * before we can write to a block otherwise the
7993 			 * contents may be confused with an earlier file
7994 			 * at recovery time.  Handle the marker as described
7995 			 * above.
7996 			 */
7997 			newblk = WK_NEWBLK(wk);
7998 			if (newblk->nb_jnewblk != NULL) {
7999 				LIST_REMOVE(&marker, wk_list);
8000 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
8001 				jwait(&newblk->nb_jnewblk->jn_list);
8002 			}
8003 			continue;
8004 
8005 		case D_SBDEP:
8006 			initiate_write_sbdep(WK_SBDEP(wk));
8007 			continue;
8008 
8009 		case D_MKDIR:
8010 		case D_FREEWORK:
8011 		case D_FREEDEP:
8012 		case D_JSEGDEP:
8013 			continue;
8014 
8015 		default:
8016 			panic("handle_disk_io_initiation: Unexpected type %s",
8017 			    TYPENAME(wk->wk_type));
8018 			/* NOTREACHED */
8019 		}
8020 	}
8021 	FREE_LOCK(&lk);
8022 	PRELE(curproc);			/* Allow swapout of kernel stack */
8023 }
8024 
8025 /*
8026  * Called from within the procedure above to deal with unsatisfied
8027  * allocation dependencies in a directory. The buffer must be locked,
8028  * thus, no I/O completion operations can occur while we are
8029  * manipulating its associated dependencies.
8030  */
8031 static void
8032 initiate_write_filepage(pagedep, bp)
8033 	struct pagedep *pagedep;
8034 	struct buf *bp;
8035 {
8036 	struct jremref *jremref;
8037 	struct jmvref *jmvref;
8038 	struct dirrem *dirrem;
8039 	struct diradd *dap;
8040 	struct direct *ep;
8041 	int i;
8042 
8043 	if (pagedep->pd_state & IOSTARTED) {
8044 		/*
8045 		 * This can only happen if there is a driver that does not
8046 		 * understand chaining. Here biodone will reissue the call
8047 		 * to strategy for the incomplete buffers.
8048 		 */
8049 		printf("initiate_write_filepage: already started\n");
8050 		return;
8051 	}
8052 	pagedep->pd_state |= IOSTARTED;
8053 	/*
8054 	 * Wait for all journal remove dependencies to hit the disk.
8055 	 * We can not allow any potentially conflicting directory adds
8056 	 * to be visible before removes and rollback is too difficult.
8057 	 * lk may be dropped and re-acquired, however we hold the buf
8058 	 * locked so the dependency can not go away.
8059 	 */
8060 	LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next)
8061 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL) {
8062 			stat_jwait_filepage++;
8063 			jwait(&jremref->jr_list);
8064 		}
8065 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL) {
8066 		stat_jwait_filepage++;
8067 		jwait(&jmvref->jm_list);
8068 	}
8069 	for (i = 0; i < DAHASHSZ; i++) {
8070 		LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
8071 			ep = (struct direct *)
8072 			    ((char *)bp->b_data + dap->da_offset);
8073 			if (ep->d_ino != dap->da_newinum)
8074 				panic("%s: dir inum %d != new %d",
8075 				    "initiate_write_filepage",
8076 				    ep->d_ino, dap->da_newinum);
8077 			if (dap->da_state & DIRCHG)
8078 				ep->d_ino = dap->da_previous->dm_oldinum;
8079 			else
8080 				ep->d_ino = 0;
8081 			dap->da_state &= ~ATTACHED;
8082 			dap->da_state |= UNDONE;
8083 		}
8084 	}
8085 }
8086 
8087 /*
8088  * Version of initiate_write_inodeblock that handles UFS1 dinodes.
8089  * Note that any bug fixes made to this routine must be done in the
8090  * version found below.
8091  *
8092  * Called from within the procedure above to deal with unsatisfied
8093  * allocation dependencies in an inodeblock. The buffer must be
8094  * locked, thus, no I/O completion operations can occur while we
8095  * are manipulating its associated dependencies.
8096  */
8097 static void
8098 initiate_write_inodeblock_ufs1(inodedep, bp)
8099 	struct inodedep *inodedep;
8100 	struct buf *bp;			/* The inode block */
8101 {
8102 	struct allocdirect *adp, *lastadp;
8103 	struct ufs1_dinode *dp;
8104 	struct ufs1_dinode *sip;
8105 	struct inoref *inoref;
8106 	struct fs *fs;
8107 	ufs_lbn_t i;
8108 #ifdef INVARIANTS
8109 	ufs_lbn_t prevlbn = 0;
8110 #endif
8111 	int deplist;
8112 
8113 	if (inodedep->id_state & IOSTARTED)
8114 		panic("initiate_write_inodeblock_ufs1: already started");
8115 	inodedep->id_state |= IOSTARTED;
8116 	fs = inodedep->id_fs;
8117 	dp = (struct ufs1_dinode *)bp->b_data +
8118 	    ino_to_fsbo(fs, inodedep->id_ino);
8119 
8120 	/*
8121 	 * If we're on the unlinked list but have not yet written our
8122 	 * next pointer initialize it here.
8123 	 */
8124 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
8125 		struct inodedep *inon;
8126 
8127 		inon = TAILQ_NEXT(inodedep, id_unlinked);
8128 		dp->di_freelink = inon ? inon->id_ino : 0;
8129 	}
8130 	/*
8131 	 * If the bitmap is not yet written, then the allocated
8132 	 * inode cannot be written to disk.
8133 	 */
8134 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
8135 		if (inodedep->id_savedino1 != NULL)
8136 			panic("initiate_write_inodeblock_ufs1: I/O underway");
8137 		FREE_LOCK(&lk);
8138 		sip = malloc(sizeof(struct ufs1_dinode),
8139 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
8140 		ACQUIRE_LOCK(&lk);
8141 		inodedep->id_savedino1 = sip;
8142 		*inodedep->id_savedino1 = *dp;
8143 		bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
8144 		dp->di_gen = inodedep->id_savedino1->di_gen;
8145 		dp->di_freelink = inodedep->id_savedino1->di_freelink;
8146 		return;
8147 	}
8148 	/*
8149 	 * If no dependencies, then there is nothing to roll back.
8150 	 */
8151 	inodedep->id_savedsize = dp->di_size;
8152 	inodedep->id_savedextsize = 0;
8153 	inodedep->id_savednlink = dp->di_nlink;
8154 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
8155 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
8156 		return;
8157 	/*
8158 	 * Revert the link count to that of the first unwritten journal entry.
8159 	 */
8160 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
8161 	if (inoref)
8162 		dp->di_nlink = inoref->if_nlink;
8163 	/*
8164 	 * Set the dependencies to busy.
8165 	 */
8166 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
8167 	     adp = TAILQ_NEXT(adp, ad_next)) {
8168 #ifdef INVARIANTS
8169 		if (deplist != 0 && prevlbn >= adp->ad_offset)
8170 			panic("softdep_write_inodeblock: lbn order");
8171 		prevlbn = adp->ad_offset;
8172 		if (adp->ad_offset < NDADDR &&
8173 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
8174 			panic("%s: direct pointer #%jd mismatch %d != %jd",
8175 			    "softdep_write_inodeblock",
8176 			    (intmax_t)adp->ad_offset,
8177 			    dp->di_db[adp->ad_offset],
8178 			    (intmax_t)adp->ad_newblkno);
8179 		if (adp->ad_offset >= NDADDR &&
8180 		    dp->di_ib[adp->ad_offset - NDADDR] != adp->ad_newblkno)
8181 			panic("%s: indirect pointer #%jd mismatch %d != %jd",
8182 			    "softdep_write_inodeblock",
8183 			    (intmax_t)adp->ad_offset - NDADDR,
8184 			    dp->di_ib[adp->ad_offset - NDADDR],
8185 			    (intmax_t)adp->ad_newblkno);
8186 		deplist |= 1 << adp->ad_offset;
8187 		if ((adp->ad_state & ATTACHED) == 0)
8188 			panic("softdep_write_inodeblock: Unknown state 0x%x",
8189 			    adp->ad_state);
8190 #endif /* INVARIANTS */
8191 		adp->ad_state &= ~ATTACHED;
8192 		adp->ad_state |= UNDONE;
8193 	}
8194 	/*
8195 	 * The on-disk inode cannot claim to be any larger than the last
8196 	 * fragment that has been written. Otherwise, the on-disk inode
8197 	 * might have fragments that were not the last block in the file
8198 	 * which would corrupt the filesystem.
8199 	 */
8200 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
8201 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
8202 		if (adp->ad_offset >= NDADDR)
8203 			break;
8204 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
8205 		/* keep going until hitting a rollback to a frag */
8206 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
8207 			continue;
8208 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
8209 		for (i = adp->ad_offset + 1; i < NDADDR; i++) {
8210 #ifdef INVARIANTS
8211 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
8212 				panic("softdep_write_inodeblock: lost dep1");
8213 #endif /* INVARIANTS */
8214 			dp->di_db[i] = 0;
8215 		}
8216 		for (i = 0; i < NIADDR; i++) {
8217 #ifdef INVARIANTS
8218 			if (dp->di_ib[i] != 0 &&
8219 			    (deplist & ((1 << NDADDR) << i)) == 0)
8220 				panic("softdep_write_inodeblock: lost dep2");
8221 #endif /* INVARIANTS */
8222 			dp->di_ib[i] = 0;
8223 		}
8224 		return;
8225 	}
8226 	/*
8227 	 * If we have zero'ed out the last allocated block of the file,
8228 	 * roll back the size to the last currently allocated block.
8229 	 * We know that this last allocated block is a full-sized as
8230 	 * we already checked for fragments in the loop above.
8231 	 */
8232 	if (lastadp != NULL &&
8233 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
8234 		for (i = lastadp->ad_offset; i >= 0; i--)
8235 			if (dp->di_db[i] != 0)
8236 				break;
8237 		dp->di_size = (i + 1) * fs->fs_bsize;
8238 	}
8239 	/*
8240 	 * The only dependencies are for indirect blocks.
8241 	 *
8242 	 * The file size for indirect block additions is not guaranteed.
8243 	 * Such a guarantee would be non-trivial to achieve. The conventional
8244 	 * synchronous write implementation also does not make this guarantee.
8245 	 * Fsck should catch and fix discrepancies. Arguably, the file size
8246 	 * can be over-estimated without destroying integrity when the file
8247 	 * moves into the indirect blocks (i.e., is large). If we want to
8248 	 * postpone fsck, we are stuck with this argument.
8249 	 */
8250 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
8251 		dp->di_ib[adp->ad_offset - NDADDR] = 0;
8252 }
8253 
8254 /*
8255  * Version of initiate_write_inodeblock that handles UFS2 dinodes.
8256  * Note that any bug fixes made to this routine must be done in the
8257  * version found above.
8258  *
8259  * Called from within the procedure above to deal with unsatisfied
8260  * allocation dependencies in an inodeblock. The buffer must be
8261  * locked, thus, no I/O completion operations can occur while we
8262  * are manipulating its associated dependencies.
8263  */
8264 static void
8265 initiate_write_inodeblock_ufs2(inodedep, bp)
8266 	struct inodedep *inodedep;
8267 	struct buf *bp;			/* The inode block */
8268 {
8269 	struct allocdirect *adp, *lastadp;
8270 	struct ufs2_dinode *dp;
8271 	struct ufs2_dinode *sip;
8272 	struct inoref *inoref;
8273 	struct fs *fs;
8274 	ufs_lbn_t i;
8275 #ifdef INVARIANTS
8276 	ufs_lbn_t prevlbn = 0;
8277 #endif
8278 	int deplist;
8279 
8280 	if (inodedep->id_state & IOSTARTED)
8281 		panic("initiate_write_inodeblock_ufs2: already started");
8282 	inodedep->id_state |= IOSTARTED;
8283 	fs = inodedep->id_fs;
8284 	dp = (struct ufs2_dinode *)bp->b_data +
8285 	    ino_to_fsbo(fs, inodedep->id_ino);
8286 
8287 	/*
8288 	 * If we're on the unlinked list but have not yet written our
8289 	 * next pointer initialize it here.
8290 	 */
8291 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
8292 		struct inodedep *inon;
8293 
8294 		inon = TAILQ_NEXT(inodedep, id_unlinked);
8295 		dp->di_freelink = inon ? inon->id_ino : 0;
8296 	}
8297 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) ==
8298 	    (UNLINKED | UNLINKNEXT)) {
8299 		struct inodedep *inon;
8300 		ino_t freelink;
8301 
8302 		inon = TAILQ_NEXT(inodedep, id_unlinked);
8303 		freelink = inon ? inon->id_ino : 0;
8304 		if (freelink != dp->di_freelink)
8305 			panic("ino %p(0x%X) %d, %d != %d",
8306 			    inodedep, inodedep->id_state, inodedep->id_ino,
8307 			    freelink, dp->di_freelink);
8308 	}
8309 	/*
8310 	 * If the bitmap is not yet written, then the allocated
8311 	 * inode cannot be written to disk.
8312 	 */
8313 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
8314 		if (inodedep->id_savedino2 != NULL)
8315 			panic("initiate_write_inodeblock_ufs2: I/O underway");
8316 		FREE_LOCK(&lk);
8317 		sip = malloc(sizeof(struct ufs2_dinode),
8318 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
8319 		ACQUIRE_LOCK(&lk);
8320 		inodedep->id_savedino2 = sip;
8321 		*inodedep->id_savedino2 = *dp;
8322 		bzero((caddr_t)dp, sizeof(struct ufs2_dinode));
8323 		dp->di_gen = inodedep->id_savedino2->di_gen;
8324 		dp->di_freelink = inodedep->id_savedino2->di_freelink;
8325 		return;
8326 	}
8327 	/*
8328 	 * If no dependencies, then there is nothing to roll back.
8329 	 */
8330 	inodedep->id_savedsize = dp->di_size;
8331 	inodedep->id_savedextsize = dp->di_extsize;
8332 	inodedep->id_savednlink = dp->di_nlink;
8333 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
8334 	    TAILQ_EMPTY(&inodedep->id_extupdt) &&
8335 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
8336 		return;
8337 	/*
8338 	 * Revert the link count to that of the first unwritten journal entry.
8339 	 */
8340 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
8341 	if (inoref)
8342 		dp->di_nlink = inoref->if_nlink;
8343 
8344 	/*
8345 	 * Set the ext data dependencies to busy.
8346 	 */
8347 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
8348 	     adp = TAILQ_NEXT(adp, ad_next)) {
8349 #ifdef INVARIANTS
8350 		if (deplist != 0 && prevlbn >= adp->ad_offset)
8351 			panic("softdep_write_inodeblock: lbn order");
8352 		prevlbn = adp->ad_offset;
8353 		if (dp->di_extb[adp->ad_offset] != adp->ad_newblkno)
8354 			panic("%s: direct pointer #%jd mismatch %jd != %jd",
8355 			    "softdep_write_inodeblock",
8356 			    (intmax_t)adp->ad_offset,
8357 			    (intmax_t)dp->di_extb[adp->ad_offset],
8358 			    (intmax_t)adp->ad_newblkno);
8359 		deplist |= 1 << adp->ad_offset;
8360 		if ((adp->ad_state & ATTACHED) == 0)
8361 			panic("softdep_write_inodeblock: Unknown state 0x%x",
8362 			    adp->ad_state);
8363 #endif /* INVARIANTS */
8364 		adp->ad_state &= ~ATTACHED;
8365 		adp->ad_state |= UNDONE;
8366 	}
8367 	/*
8368 	 * The on-disk inode cannot claim to be any larger than the last
8369 	 * fragment that has been written. Otherwise, the on-disk inode
8370 	 * might have fragments that were not the last block in the ext
8371 	 * data which would corrupt the filesystem.
8372 	 */
8373 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
8374 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
8375 		dp->di_extb[adp->ad_offset] = adp->ad_oldblkno;
8376 		/* keep going until hitting a rollback to a frag */
8377 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
8378 			continue;
8379 		dp->di_extsize = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
8380 		for (i = adp->ad_offset + 1; i < NXADDR; i++) {
8381 #ifdef INVARIANTS
8382 			if (dp->di_extb[i] != 0 && (deplist & (1 << i)) == 0)
8383 				panic("softdep_write_inodeblock: lost dep1");
8384 #endif /* INVARIANTS */
8385 			dp->di_extb[i] = 0;
8386 		}
8387 		lastadp = NULL;
8388 		break;
8389 	}
8390 	/*
8391 	 * If we have zero'ed out the last allocated block of the ext
8392 	 * data, roll back the size to the last currently allocated block.
8393 	 * We know that this last allocated block is a full-sized as
8394 	 * we already checked for fragments in the loop above.
8395 	 */
8396 	if (lastadp != NULL &&
8397 	    dp->di_extsize <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
8398 		for (i = lastadp->ad_offset; i >= 0; i--)
8399 			if (dp->di_extb[i] != 0)
8400 				break;
8401 		dp->di_extsize = (i + 1) * fs->fs_bsize;
8402 	}
8403 	/*
8404 	 * Set the file data dependencies to busy.
8405 	 */
8406 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
8407 	     adp = TAILQ_NEXT(adp, ad_next)) {
8408 #ifdef INVARIANTS
8409 		if (deplist != 0 && prevlbn >= adp->ad_offset)
8410 			panic("softdep_write_inodeblock: lbn order");
8411 		prevlbn = adp->ad_offset;
8412 		if (adp->ad_offset < NDADDR &&
8413 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
8414 			panic("%s: direct pointer #%jd mismatch %jd != %jd",
8415 			    "softdep_write_inodeblock",
8416 			    (intmax_t)adp->ad_offset,
8417 			    (intmax_t)dp->di_db[adp->ad_offset],
8418 			    (intmax_t)adp->ad_newblkno);
8419 		if (adp->ad_offset >= NDADDR &&
8420 		    dp->di_ib[adp->ad_offset - NDADDR] != adp->ad_newblkno)
8421 			panic("%s indirect pointer #%jd mismatch %jd != %jd",
8422 			    "softdep_write_inodeblock:",
8423 			    (intmax_t)adp->ad_offset - NDADDR,
8424 			    (intmax_t)dp->di_ib[adp->ad_offset - NDADDR],
8425 			    (intmax_t)adp->ad_newblkno);
8426 		deplist |= 1 << adp->ad_offset;
8427 		if ((adp->ad_state & ATTACHED) == 0)
8428 			panic("softdep_write_inodeblock: Unknown state 0x%x",
8429 			    adp->ad_state);
8430 #endif /* INVARIANTS */
8431 		adp->ad_state &= ~ATTACHED;
8432 		adp->ad_state |= UNDONE;
8433 	}
8434 	/*
8435 	 * The on-disk inode cannot claim to be any larger than the last
8436 	 * fragment that has been written. Otherwise, the on-disk inode
8437 	 * might have fragments that were not the last block in the file
8438 	 * which would corrupt the filesystem.
8439 	 */
8440 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
8441 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
8442 		if (adp->ad_offset >= NDADDR)
8443 			break;
8444 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
8445 		/* keep going until hitting a rollback to a frag */
8446 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
8447 			continue;
8448 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
8449 		for (i = adp->ad_offset + 1; i < NDADDR; i++) {
8450 #ifdef INVARIANTS
8451 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
8452 				panic("softdep_write_inodeblock: lost dep2");
8453 #endif /* INVARIANTS */
8454 			dp->di_db[i] = 0;
8455 		}
8456 		for (i = 0; i < NIADDR; i++) {
8457 #ifdef INVARIANTS
8458 			if (dp->di_ib[i] != 0 &&
8459 			    (deplist & ((1 << NDADDR) << i)) == 0)
8460 				panic("softdep_write_inodeblock: lost dep3");
8461 #endif /* INVARIANTS */
8462 			dp->di_ib[i] = 0;
8463 		}
8464 		return;
8465 	}
8466 	/*
8467 	 * If we have zero'ed out the last allocated block of the file,
8468 	 * roll back the size to the last currently allocated block.
8469 	 * We know that this last allocated block is a full-sized as
8470 	 * we already checked for fragments in the loop above.
8471 	 */
8472 	if (lastadp != NULL &&
8473 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
8474 		for (i = lastadp->ad_offset; i >= 0; i--)
8475 			if (dp->di_db[i] != 0)
8476 				break;
8477 		dp->di_size = (i + 1) * fs->fs_bsize;
8478 	}
8479 	/*
8480 	 * The only dependencies are for indirect blocks.
8481 	 *
8482 	 * The file size for indirect block additions is not guaranteed.
8483 	 * Such a guarantee would be non-trivial to achieve. The conventional
8484 	 * synchronous write implementation also does not make this guarantee.
8485 	 * Fsck should catch and fix discrepancies. Arguably, the file size
8486 	 * can be over-estimated without destroying integrity when the file
8487 	 * moves into the indirect blocks (i.e., is large). If we want to
8488 	 * postpone fsck, we are stuck with this argument.
8489 	 */
8490 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
8491 		dp->di_ib[adp->ad_offset - NDADDR] = 0;
8492 }
8493 
8494 /*
8495  * Cancel an indirdep as a result of truncation.  Release all of the
8496  * children allocindirs and place their journal work on the appropriate
8497  * list.
8498  */
8499 static void
8500 cancel_indirdep(indirdep, bp, inodedep, freeblks)
8501 	struct indirdep *indirdep;
8502 	struct buf *bp;
8503 	struct inodedep *inodedep;
8504 	struct freeblks *freeblks;
8505 {
8506 	struct allocindir *aip;
8507 
8508 	/*
8509 	 * None of the indirect pointers will ever be visible,
8510 	 * so they can simply be tossed. GOINGAWAY ensures
8511 	 * that allocated pointers will be saved in the buffer
8512 	 * cache until they are freed. Note that they will
8513 	 * only be able to be found by their physical address
8514 	 * since the inode mapping the logical address will
8515 	 * be gone. The save buffer used for the safe copy
8516 	 * was allocated in setup_allocindir_phase2 using
8517 	 * the physical address so it could be used for this
8518 	 * purpose. Hence we swap the safe copy with the real
8519 	 * copy, allowing the safe copy to be freed and holding
8520 	 * on to the real copy for later use in indir_trunc.
8521 	 */
8522 	if (indirdep->ir_state & GOINGAWAY)
8523 		panic("cancel_indirdep: already gone");
8524 	if (indirdep->ir_state & ONDEPLIST) {
8525 		indirdep->ir_state &= ~ONDEPLIST;
8526 		LIST_REMOVE(indirdep, ir_next);
8527 	}
8528 	indirdep->ir_state |= GOINGAWAY;
8529 	VFSTOUFS(indirdep->ir_list.wk_mp)->um_numindirdeps += 1;
8530 	while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != 0)
8531 		cancel_allocindir(aip, inodedep, freeblks);
8532 	while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != 0)
8533 		cancel_allocindir(aip, inodedep, freeblks);
8534 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != 0)
8535 		cancel_allocindir(aip, inodedep, freeblks);
8536 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != 0)
8537 		cancel_allocindir(aip, inodedep, freeblks);
8538 	bcopy(bp->b_data, indirdep->ir_savebp->b_data, bp->b_bcount);
8539 	WORKLIST_REMOVE(&indirdep->ir_list);
8540 	WORKLIST_INSERT(&indirdep->ir_savebp->b_dep, &indirdep->ir_list);
8541 	indirdep->ir_savebp = NULL;
8542 }
8543 
8544 /*
8545  * Free an indirdep once it no longer has new pointers to track.
8546  */
8547 static void
8548 free_indirdep(indirdep)
8549 	struct indirdep *indirdep;
8550 {
8551 
8552 	KASSERT(LIST_EMPTY(&indirdep->ir_jwork),
8553 	    ("free_indirdep: Journal work not empty."));
8554 	KASSERT(LIST_EMPTY(&indirdep->ir_completehd),
8555 	    ("free_indirdep: Complete head not empty."));
8556 	KASSERT(LIST_EMPTY(&indirdep->ir_writehd),
8557 	    ("free_indirdep: write head not empty."));
8558 	KASSERT(LIST_EMPTY(&indirdep->ir_donehd),
8559 	    ("free_indirdep: done head not empty."));
8560 	KASSERT(LIST_EMPTY(&indirdep->ir_deplisthd),
8561 	    ("free_indirdep: deplist head not empty."));
8562 	KASSERT(indirdep->ir_savebp == NULL,
8563 	    ("free_indirdep: %p ir_savebp != NULL", indirdep));
8564 	KASSERT((indirdep->ir_state & ONDEPLIST) == 0,
8565 	    ("free_indirdep: %p still on deplist.", indirdep));
8566 	if (indirdep->ir_state & ONWORKLIST)
8567 		WORKLIST_REMOVE(&indirdep->ir_list);
8568 	WORKITEM_FREE(indirdep, D_INDIRDEP);
8569 }
8570 
8571 /*
8572  * Called before a write to an indirdep.  This routine is responsible for
8573  * rolling back pointers to a safe state which includes only those
8574  * allocindirs which have been completed.
8575  */
8576 static void
8577 initiate_write_indirdep(indirdep, bp)
8578 	struct indirdep *indirdep;
8579 	struct buf *bp;
8580 {
8581 
8582 	if (indirdep->ir_state & GOINGAWAY)
8583 		panic("disk_io_initiation: indirdep gone");
8584 
8585 	/*
8586 	 * If there are no remaining dependencies, this will be writing
8587 	 * the real pointers.
8588 	 */
8589 	if (LIST_EMPTY(&indirdep->ir_deplisthd))
8590 		return;
8591 	/*
8592 	 * Replace up-to-date version with safe version.
8593 	 */
8594 	FREE_LOCK(&lk);
8595 	indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
8596 	    M_SOFTDEP_FLAGS);
8597 	ACQUIRE_LOCK(&lk);
8598 	indirdep->ir_state &= ~ATTACHED;
8599 	indirdep->ir_state |= UNDONE;
8600 	bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
8601 	bcopy(indirdep->ir_savebp->b_data, bp->b_data,
8602 	    bp->b_bcount);
8603 }
8604 
8605 /*
8606  * Called when an inode has been cleared in a cg bitmap.  This finally
8607  * eliminates any canceled jaddrefs
8608  */
8609 void
8610 softdep_setup_inofree(mp, bp, ino, wkhd)
8611 	struct mount *mp;
8612 	struct buf *bp;
8613 	ino_t ino;
8614 	struct workhead *wkhd;
8615 {
8616 	struct worklist *wk, *wkn;
8617 	struct inodedep *inodedep;
8618 	uint8_t *inosused;
8619 	struct cg *cgp;
8620 	struct fs *fs;
8621 
8622 	ACQUIRE_LOCK(&lk);
8623 	fs = VFSTOUFS(mp)->um_fs;
8624 	cgp = (struct cg *)bp->b_data;
8625 	inosused = cg_inosused(cgp);
8626 	if (isset(inosused, ino % fs->fs_ipg))
8627 		panic("softdep_setup_inofree: inode %d not freed.", ino);
8628 	if (inodedep_lookup(mp, ino, 0, &inodedep))
8629 		panic("softdep_setup_inofree: ino %d has existing inodedep %p",
8630 		    ino, inodedep);
8631 	if (wkhd) {
8632 		LIST_FOREACH_SAFE(wk, wkhd, wk_list, wkn) {
8633 			if (wk->wk_type != D_JADDREF)
8634 				continue;
8635 			WORKLIST_REMOVE(wk);
8636 			/*
8637 			 * We can free immediately even if the jaddref
8638 			 * isn't attached in a background write as now
8639 			 * the bitmaps are reconciled.
8640 		 	 */
8641 			wk->wk_state |= COMPLETE | ATTACHED;
8642 			free_jaddref(WK_JADDREF(wk));
8643 		}
8644 		jwork_move(&bp->b_dep, wkhd);
8645 	}
8646 	FREE_LOCK(&lk);
8647 }
8648 
8649 
8650 /*
8651  * Called via ffs_blkfree() after a set of frags has been cleared from a cg
8652  * map.  Any dependencies waiting for the write to clear are added to the
8653  * buf's list and any jnewblks that are being canceled are discarded
8654  * immediately.
8655  */
8656 void
8657 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
8658 	struct mount *mp;
8659 	struct buf *bp;
8660 	ufs2_daddr_t blkno;
8661 	int frags;
8662 	struct workhead *wkhd;
8663 {
8664 	struct jnewblk *jnewblk;
8665 	struct worklist *wk, *wkn;
8666 #ifdef SUJ_DEBUG
8667 	struct bmsafemap *bmsafemap;
8668 	struct fs *fs;
8669 	uint8_t *blksfree;
8670 	struct cg *cgp;
8671 	ufs2_daddr_t jstart;
8672 	ufs2_daddr_t jend;
8673 	ufs2_daddr_t end;
8674 	long bno;
8675 	int i;
8676 #endif
8677 
8678 	ACQUIRE_LOCK(&lk);
8679 	/*
8680 	 * Detach any jnewblks which have been canceled.  They must linger
8681 	 * until the bitmap is cleared again by ffs_blkfree() to prevent
8682 	 * an unjournaled allocation from hitting the disk.
8683 	 */
8684 	if (wkhd) {
8685 		LIST_FOREACH_SAFE(wk, wkhd, wk_list, wkn) {
8686 			if (wk->wk_type != D_JNEWBLK)
8687 				continue;
8688 			jnewblk = WK_JNEWBLK(wk);
8689 			KASSERT(jnewblk->jn_state & GOINGAWAY,
8690 			    ("softdep_setup_blkfree: jnewblk not canceled."));
8691 			WORKLIST_REMOVE(wk);
8692 #ifdef SUJ_DEBUG
8693 			/*
8694 			 * Assert that this block is free in the bitmap
8695 			 * before we discard the jnewblk.
8696 			 */
8697 			fs = VFSTOUFS(mp)->um_fs;
8698 			cgp = (struct cg *)bp->b_data;
8699 			blksfree = cg_blksfree(cgp);
8700 			bno = dtogd(fs, jnewblk->jn_blkno);
8701 			for (i = jnewblk->jn_oldfrags;
8702 			    i < jnewblk->jn_frags; i++) {
8703 				if (isset(blksfree, bno + i))
8704 					continue;
8705 				panic("softdep_setup_blkfree: not free");
8706 			}
8707 #endif
8708 			/*
8709 			 * Even if it's not attached we can free immediately
8710 			 * as the new bitmap is correct.
8711 			 */
8712 			wk->wk_state |= COMPLETE | ATTACHED;
8713 			free_jnewblk(jnewblk);
8714 		}
8715 		/*
8716 		 * The buf must be locked by the caller otherwise these could
8717 		 * be added while it's being written and the write would
8718 		 * complete them before they made it to disk.
8719 		 */
8720 		jwork_move(&bp->b_dep, wkhd);
8721 	}
8722 
8723 #ifdef SUJ_DEBUG
8724 	/*
8725 	 * Assert that we are not freeing a block which has an outstanding
8726 	 * allocation dependency.
8727 	 */
8728 	fs = VFSTOUFS(mp)->um_fs;
8729 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno));
8730 	end = blkno + frags;
8731 	LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
8732 		/*
8733 		 * Don't match against blocks that will be freed when the
8734 		 * background write is done.
8735 		 */
8736 		if ((jnewblk->jn_state & (ATTACHED | COMPLETE | DEPCOMPLETE)) ==
8737 		    (COMPLETE | DEPCOMPLETE))
8738 			continue;
8739 		jstart = jnewblk->jn_blkno + jnewblk->jn_oldfrags;
8740 		jend = jnewblk->jn_blkno + jnewblk->jn_frags;
8741 		if ((blkno >= jstart && blkno < jend) ||
8742 		    (end > jstart && end <= jend)) {
8743 			printf("state 0x%X %jd - %d %d dep %p\n",
8744 			    jnewblk->jn_state, jnewblk->jn_blkno,
8745 			    jnewblk->jn_oldfrags, jnewblk->jn_frags,
8746 			    jnewblk->jn_newblk);
8747 			panic("softdep_setup_blkfree: "
8748 			    "%jd-%jd(%d) overlaps with %jd-%jd",
8749 			    blkno, end, frags, jstart, jend);
8750 		}
8751 	}
8752 #endif
8753 	FREE_LOCK(&lk);
8754 }
8755 
8756 static void
8757 initiate_write_bmsafemap(bmsafemap, bp)
8758 	struct bmsafemap *bmsafemap;
8759 	struct buf *bp;			/* The cg block. */
8760 {
8761 	struct jaddref *jaddref;
8762 	struct jnewblk *jnewblk;
8763 	uint8_t *inosused;
8764 	uint8_t *blksfree;
8765 	struct cg *cgp;
8766 	struct fs *fs;
8767 	int cleared;
8768 	ino_t ino;
8769 	long bno;
8770 	int i;
8771 
8772 	if (bmsafemap->sm_state & IOSTARTED)
8773 		panic("initiate_write_bmsafemap: Already started\n");
8774 	bmsafemap->sm_state |= IOSTARTED;
8775 	/*
8776 	 * Clear any inode allocations which are pending journal writes.
8777 	 */
8778 	if (LIST_FIRST(&bmsafemap->sm_jaddrefhd) != NULL) {
8779 		cgp = (struct cg *)bp->b_data;
8780 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
8781 		inosused = cg_inosused(cgp);
8782 		LIST_FOREACH(jaddref, &bmsafemap->sm_jaddrefhd, ja_bmdeps) {
8783 			ino = jaddref->ja_ino % fs->fs_ipg;
8784 			/*
8785 			 * If this is a background copy the inode may not
8786 			 * be marked used yet.
8787 			 */
8788 			if (isset(inosused, ino)) {
8789 				if ((jaddref->ja_mode & IFMT) == IFDIR)
8790 					cgp->cg_cs.cs_ndir--;
8791 				cgp->cg_cs.cs_nifree++;
8792 				clrbit(inosused, ino);
8793 				jaddref->ja_state &= ~ATTACHED;
8794 				jaddref->ja_state |= UNDONE;
8795 				stat_jaddref++;
8796 			} else if ((bp->b_xflags & BX_BKGRDMARKER) == 0)
8797 				panic("initiate_write_bmsafemap: inode %d "
8798 				    "marked free", jaddref->ja_ino);
8799 		}
8800 	}
8801 	/*
8802 	 * Clear any block allocations which are pending journal writes.
8803 	 */
8804 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
8805 		cgp = (struct cg *)bp->b_data;
8806 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
8807 		blksfree = cg_blksfree(cgp);
8808 		LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
8809 			bno = dtogd(fs, jnewblk->jn_blkno);
8810 			cleared = 0;
8811 			for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags;
8812 			    i++) {
8813 				if (isclr(blksfree, bno + i)) {
8814 					cleared = 1;
8815 					setbit(blksfree, bno + i);
8816 				}
8817 			}
8818 			/*
8819 			 * We may not clear the block if it's a background
8820 			 * copy.  In that case there is no reason to detach
8821 			 * it.
8822 			 */
8823 			if (cleared) {
8824 				stat_jnewblk++;
8825 				jnewblk->jn_state &= ~ATTACHED;
8826 				jnewblk->jn_state |= UNDONE;
8827 			} else if ((bp->b_xflags & BX_BKGRDMARKER) == 0)
8828 				panic("initiate_write_bmsafemap: block %jd "
8829 				    "marked free", jnewblk->jn_blkno);
8830 		}
8831 	}
8832 	/*
8833 	 * Move allocation lists to the written lists so they can be
8834 	 * cleared once the block write is complete.
8835 	 */
8836 	LIST_SWAP(&bmsafemap->sm_inodedephd, &bmsafemap->sm_inodedepwr,
8837 	    inodedep, id_deps);
8838 	LIST_SWAP(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
8839 	    newblk, nb_deps);
8840 }
8841 
8842 /*
8843  * This routine is called during the completion interrupt
8844  * service routine for a disk write (from the procedure called
8845  * by the device driver to inform the filesystem caches of
8846  * a request completion).  It should be called early in this
8847  * procedure, before the block is made available to other
8848  * processes or other routines are called.
8849  *
8850  */
8851 static void
8852 softdep_disk_write_complete(bp)
8853 	struct buf *bp;		/* describes the completed disk write */
8854 {
8855 	struct worklist *wk;
8856 	struct worklist *owk;
8857 	struct workhead reattach;
8858 	struct buf *sbp;
8859 
8860 	/*
8861 	 * If an error occurred while doing the write, then the data
8862 	 * has not hit the disk and the dependencies cannot be unrolled.
8863 	 */
8864 	if ((bp->b_ioflags & BIO_ERROR) != 0 && (bp->b_flags & B_INVAL) == 0)
8865 		return;
8866 	LIST_INIT(&reattach);
8867 	/*
8868 	 * This lock must not be released anywhere in this code segment.
8869 	 */
8870 	sbp = NULL;
8871 	owk = NULL;
8872 	ACQUIRE_LOCK(&lk);
8873 	while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
8874 		WORKLIST_REMOVE(wk);
8875 		if (wk == owk)
8876 			panic("duplicate worklist: %p\n", wk);
8877 		owk = wk;
8878 		switch (wk->wk_type) {
8879 
8880 		case D_PAGEDEP:
8881 			if (handle_written_filepage(WK_PAGEDEP(wk), bp))
8882 				WORKLIST_INSERT(&reattach, wk);
8883 			continue;
8884 
8885 		case D_INODEDEP:
8886 			if (handle_written_inodeblock(WK_INODEDEP(wk), bp))
8887 				WORKLIST_INSERT(&reattach, wk);
8888 			continue;
8889 
8890 		case D_BMSAFEMAP:
8891 			if (handle_written_bmsafemap(WK_BMSAFEMAP(wk), bp))
8892 				WORKLIST_INSERT(&reattach, wk);
8893 			continue;
8894 
8895 		case D_MKDIR:
8896 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
8897 			continue;
8898 
8899 		case D_ALLOCDIRECT:
8900 			wk->wk_state |= COMPLETE;
8901 			handle_allocdirect_partdone(WK_ALLOCDIRECT(wk), NULL);
8902 			continue;
8903 
8904 		case D_ALLOCINDIR:
8905 			wk->wk_state |= COMPLETE;
8906 			handle_allocindir_partdone(WK_ALLOCINDIR(wk));
8907 			continue;
8908 
8909 		case D_INDIRDEP:
8910 			if (handle_written_indirdep(WK_INDIRDEP(wk), bp, &sbp))
8911 				WORKLIST_INSERT(&reattach, wk);
8912 			continue;
8913 
8914 		case D_FREEBLKS:
8915 			wk->wk_state |= COMPLETE;
8916 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE)
8917 				add_to_worklist(wk, 1);
8918 			continue;
8919 
8920 		case D_FREEWORK:
8921 			handle_written_freework(WK_FREEWORK(wk));
8922 			break;
8923 
8924 		case D_FREEDEP:
8925 			free_freedep(WK_FREEDEP(wk));
8926 			continue;
8927 
8928 		case D_JSEGDEP:
8929 			free_jsegdep(WK_JSEGDEP(wk));
8930 			continue;
8931 
8932 		case D_JSEG:
8933 			handle_written_jseg(WK_JSEG(wk), bp);
8934 			continue;
8935 
8936 		case D_SBDEP:
8937 			if (handle_written_sbdep(WK_SBDEP(wk), bp))
8938 				WORKLIST_INSERT(&reattach, wk);
8939 			continue;
8940 
8941 		default:
8942 			panic("handle_disk_write_complete: Unknown type %s",
8943 			    TYPENAME(wk->wk_type));
8944 			/* NOTREACHED */
8945 		}
8946 	}
8947 	/*
8948 	 * Reattach any requests that must be redone.
8949 	 */
8950 	while ((wk = LIST_FIRST(&reattach)) != NULL) {
8951 		WORKLIST_REMOVE(wk);
8952 		WORKLIST_INSERT(&bp->b_dep, wk);
8953 	}
8954 	FREE_LOCK(&lk);
8955 	if (sbp)
8956 		brelse(sbp);
8957 }
8958 
8959 /*
8960  * Called from within softdep_disk_write_complete above. Note that
8961  * this routine is always called from interrupt level with further
8962  * splbio interrupts blocked.
8963  */
8964 static void
8965 handle_allocdirect_partdone(adp, wkhd)
8966 	struct allocdirect *adp;	/* the completed allocdirect */
8967 	struct workhead *wkhd;		/* Work to do when inode is writtne. */
8968 {
8969 	struct allocdirectlst *listhead;
8970 	struct allocdirect *listadp;
8971 	struct inodedep *inodedep;
8972 	long bsize;
8973 
8974 	if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
8975 		return;
8976 	/*
8977 	 * The on-disk inode cannot claim to be any larger than the last
8978 	 * fragment that has been written. Otherwise, the on-disk inode
8979 	 * might have fragments that were not the last block in the file
8980 	 * which would corrupt the filesystem. Thus, we cannot free any
8981 	 * allocdirects after one whose ad_oldblkno claims a fragment as
8982 	 * these blocks must be rolled back to zero before writing the inode.
8983 	 * We check the currently active set of allocdirects in id_inoupdt
8984 	 * or id_extupdt as appropriate.
8985 	 */
8986 	inodedep = adp->ad_inodedep;
8987 	bsize = inodedep->id_fs->fs_bsize;
8988 	if (adp->ad_state & EXTDATA)
8989 		listhead = &inodedep->id_extupdt;
8990 	else
8991 		listhead = &inodedep->id_inoupdt;
8992 	TAILQ_FOREACH(listadp, listhead, ad_next) {
8993 		/* found our block */
8994 		if (listadp == adp)
8995 			break;
8996 		/* continue if ad_oldlbn is not a fragment */
8997 		if (listadp->ad_oldsize == 0 ||
8998 		    listadp->ad_oldsize == bsize)
8999 			continue;
9000 		/* hit a fragment */
9001 		return;
9002 	}
9003 	/*
9004 	 * If we have reached the end of the current list without
9005 	 * finding the just finished dependency, then it must be
9006 	 * on the future dependency list. Future dependencies cannot
9007 	 * be freed until they are moved to the current list.
9008 	 */
9009 	if (listadp == NULL) {
9010 #ifdef DEBUG
9011 		if (adp->ad_state & EXTDATA)
9012 			listhead = &inodedep->id_newextupdt;
9013 		else
9014 			listhead = &inodedep->id_newinoupdt;
9015 		TAILQ_FOREACH(listadp, listhead, ad_next)
9016 			/* found our block */
9017 			if (listadp == adp)
9018 				break;
9019 		if (listadp == NULL)
9020 			panic("handle_allocdirect_partdone: lost dep");
9021 #endif /* DEBUG */
9022 		return;
9023 	}
9024 	/*
9025 	 * If we have found the just finished dependency, then queue
9026 	 * it along with anything that follows it that is complete.
9027 	 * Since the pointer has not yet been written in the inode
9028 	 * as the dependency prevents it, place the allocdirect on the
9029 	 * bufwait list where it will be freed once the pointer is
9030 	 * valid.
9031 	 */
9032 	if (wkhd == NULL)
9033 		wkhd = &inodedep->id_bufwait;
9034 	for (; adp; adp = listadp) {
9035 		listadp = TAILQ_NEXT(adp, ad_next);
9036 		if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
9037 			return;
9038 		TAILQ_REMOVE(listhead, adp, ad_next);
9039 		WORKLIST_INSERT(wkhd, &adp->ad_block.nb_list);
9040 	}
9041 }
9042 
9043 /*
9044  * Called from within softdep_disk_write_complete above.  This routine
9045  * completes successfully written allocindirs.
9046  */
9047 static void
9048 handle_allocindir_partdone(aip)
9049 	struct allocindir *aip;		/* the completed allocindir */
9050 {
9051 	struct indirdep *indirdep;
9052 
9053 	if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
9054 		return;
9055 	indirdep = aip->ai_indirdep;
9056 	LIST_REMOVE(aip, ai_next);
9057 	if (indirdep->ir_state & UNDONE) {
9058 		LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
9059 		return;
9060 	}
9061 	if (indirdep->ir_state & UFS1FMT)
9062 		((ufs1_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
9063 		    aip->ai_newblkno;
9064 	else
9065 		((ufs2_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
9066 		    aip->ai_newblkno;
9067 	/*
9068 	 * Await the pointer write before freeing the allocindir.
9069 	 */
9070 	LIST_INSERT_HEAD(&indirdep->ir_writehd, aip, ai_next);
9071 }
9072 
9073 /*
9074  * Release segments held on a jwork list.
9075  */
9076 static void
9077 handle_jwork(wkhd)
9078 	struct workhead *wkhd;
9079 {
9080 	struct worklist *wk;
9081 
9082 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
9083 		WORKLIST_REMOVE(wk);
9084 		switch (wk->wk_type) {
9085 		case D_JSEGDEP:
9086 			free_jsegdep(WK_JSEGDEP(wk));
9087 			continue;
9088 		default:
9089 			panic("handle_jwork: Unknown type %s\n",
9090 			    TYPENAME(wk->wk_type));
9091 		}
9092 	}
9093 }
9094 
9095 /*
9096  * Handle the bufwait list on an inode when it is safe to release items
9097  * held there.  This normally happens after an inode block is written but
9098  * may be delayed and handled later if there are pending journal items that
9099  * are not yet safe to be released.
9100  */
9101 static struct freefile *
9102 handle_bufwait(inodedep, refhd)
9103 	struct inodedep *inodedep;
9104 	struct workhead *refhd;
9105 {
9106 	struct jaddref *jaddref;
9107 	struct freefile *freefile;
9108 	struct worklist *wk;
9109 
9110 	freefile = NULL;
9111 	while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
9112 		WORKLIST_REMOVE(wk);
9113 		switch (wk->wk_type) {
9114 		case D_FREEFILE:
9115 			/*
9116 			 * We defer adding freefile to the worklist
9117 			 * until all other additions have been made to
9118 			 * ensure that it will be done after all the
9119 			 * old blocks have been freed.
9120 			 */
9121 			if (freefile != NULL)
9122 				panic("handle_bufwait: freefile");
9123 			freefile = WK_FREEFILE(wk);
9124 			continue;
9125 
9126 		case D_MKDIR:
9127 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
9128 			continue;
9129 
9130 		case D_DIRADD:
9131 			diradd_inode_written(WK_DIRADD(wk), inodedep);
9132 			continue;
9133 
9134 		case D_FREEFRAG:
9135 			wk->wk_state |= COMPLETE;
9136 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE)
9137 				add_to_worklist(wk, 0);
9138 			continue;
9139 
9140 		case D_DIRREM:
9141 			wk->wk_state |= COMPLETE;
9142 			add_to_worklist(wk, 0);
9143 			continue;
9144 
9145 		case D_ALLOCDIRECT:
9146 		case D_ALLOCINDIR:
9147 			free_newblk(WK_NEWBLK(wk));
9148 			continue;
9149 
9150 		case D_JNEWBLK:
9151 			wk->wk_state |= COMPLETE;
9152 			free_jnewblk(WK_JNEWBLK(wk));
9153 			continue;
9154 
9155 		/*
9156 		 * Save freed journal segments and add references on
9157 		 * the supplied list which will delay their release
9158 		 * until the cg bitmap is cleared on disk.
9159 		 */
9160 		case D_JSEGDEP:
9161 			if (refhd == NULL)
9162 				free_jsegdep(WK_JSEGDEP(wk));
9163 			else
9164 				WORKLIST_INSERT(refhd, wk);
9165 			continue;
9166 
9167 		case D_JADDREF:
9168 			jaddref = WK_JADDREF(wk);
9169 			TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
9170 			    if_deps);
9171 			/*
9172 			 * Transfer any jaddrefs to the list to be freed with
9173 			 * the bitmap if we're handling a removed file.
9174 			 */
9175 			if (refhd == NULL) {
9176 				wk->wk_state |= COMPLETE;
9177 				free_jaddref(jaddref);
9178 			} else
9179 				WORKLIST_INSERT(refhd, wk);
9180 			continue;
9181 
9182 		default:
9183 			panic("handle_bufwait: Unknown type %p(%s)",
9184 			    wk, TYPENAME(wk->wk_type));
9185 			/* NOTREACHED */
9186 		}
9187 	}
9188 	return (freefile);
9189 }
9190 /*
9191  * Called from within softdep_disk_write_complete above to restore
9192  * in-memory inode block contents to their most up-to-date state. Note
9193  * that this routine is always called from interrupt level with further
9194  * splbio interrupts blocked.
9195  */
9196 static int
9197 handle_written_inodeblock(inodedep, bp)
9198 	struct inodedep *inodedep;
9199 	struct buf *bp;		/* buffer containing the inode block */
9200 {
9201 	struct freefile *freefile;
9202 	struct allocdirect *adp, *nextadp;
9203 	struct ufs1_dinode *dp1 = NULL;
9204 	struct ufs2_dinode *dp2 = NULL;
9205 	struct workhead wkhd;
9206 	int hadchanges, fstype;
9207 	ino_t freelink;
9208 
9209 	LIST_INIT(&wkhd);
9210 	hadchanges = 0;
9211 	freefile = NULL;
9212 	if ((inodedep->id_state & IOSTARTED) == 0)
9213 		panic("handle_written_inodeblock: not started");
9214 	inodedep->id_state &= ~IOSTARTED;
9215 	if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC) {
9216 		fstype = UFS1;
9217 		dp1 = (struct ufs1_dinode *)bp->b_data +
9218 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
9219 		freelink = dp1->di_freelink;
9220 	} else {
9221 		fstype = UFS2;
9222 		dp2 = (struct ufs2_dinode *)bp->b_data +
9223 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
9224 		freelink = dp2->di_freelink;
9225 	}
9226 	/*
9227 	 * If we wrote a valid freelink pointer during the last write
9228 	 * record it here.
9229 	 */
9230 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
9231 		struct inodedep *inon;
9232 
9233 		inon = TAILQ_NEXT(inodedep, id_unlinked);
9234 		if ((inon == NULL && freelink == 0) ||
9235 		    (inon && inon->id_ino == freelink)) {
9236 			if (inon)
9237 				inon->id_state |= UNLINKPREV;
9238 			inodedep->id_state |= UNLINKNEXT;
9239 		} else
9240 			hadchanges = 1;
9241 	}
9242 	/* Leave this inodeblock dirty until it's in the list. */
9243 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) == UNLINKED)
9244 		hadchanges = 1;
9245 	/*
9246 	 * If we had to rollback the inode allocation because of
9247 	 * bitmaps being incomplete, then simply restore it.
9248 	 * Keep the block dirty so that it will not be reclaimed until
9249 	 * all associated dependencies have been cleared and the
9250 	 * corresponding updates written to disk.
9251 	 */
9252 	if (inodedep->id_savedino1 != NULL) {
9253 		hadchanges = 1;
9254 		if (fstype == UFS1)
9255 			*dp1 = *inodedep->id_savedino1;
9256 		else
9257 			*dp2 = *inodedep->id_savedino2;
9258 		free(inodedep->id_savedino1, M_SAVEDINO);
9259 		inodedep->id_savedino1 = NULL;
9260 		if ((bp->b_flags & B_DELWRI) == 0)
9261 			stat_inode_bitmap++;
9262 		bdirty(bp);
9263 		/*
9264 		 * If the inode is clear here and GOINGAWAY it will never
9265 		 * be written.  Process the bufwait and clear any pending
9266 		 * work which may include the freefile.
9267 		 */
9268 		if (inodedep->id_state & GOINGAWAY)
9269 			goto bufwait;
9270 		return (1);
9271 	}
9272 	inodedep->id_state |= COMPLETE;
9273 	/*
9274 	 * Roll forward anything that had to be rolled back before
9275 	 * the inode could be updated.
9276 	 */
9277 	for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
9278 		nextadp = TAILQ_NEXT(adp, ad_next);
9279 		if (adp->ad_state & ATTACHED)
9280 			panic("handle_written_inodeblock: new entry");
9281 		if (fstype == UFS1) {
9282 			if (adp->ad_offset < NDADDR) {
9283 				if (dp1->di_db[adp->ad_offset]!=adp->ad_oldblkno)
9284 					panic("%s %s #%jd mismatch %d != %jd",
9285 					    "handle_written_inodeblock:",
9286 					    "direct pointer",
9287 					    (intmax_t)adp->ad_offset,
9288 					    dp1->di_db[adp->ad_offset],
9289 					    (intmax_t)adp->ad_oldblkno);
9290 				dp1->di_db[adp->ad_offset] = adp->ad_newblkno;
9291 			} else {
9292 				if (dp1->di_ib[adp->ad_offset - NDADDR] != 0)
9293 					panic("%s: %s #%jd allocated as %d",
9294 					    "handle_written_inodeblock",
9295 					    "indirect pointer",
9296 					    (intmax_t)adp->ad_offset - NDADDR,
9297 					    dp1->di_ib[adp->ad_offset - NDADDR]);
9298 				dp1->di_ib[adp->ad_offset - NDADDR] =
9299 				    adp->ad_newblkno;
9300 			}
9301 		} else {
9302 			if (adp->ad_offset < NDADDR) {
9303 				if (dp2->di_db[adp->ad_offset]!=adp->ad_oldblkno)
9304 					panic("%s: %s #%jd %s %jd != %jd",
9305 					    "handle_written_inodeblock",
9306 					    "direct pointer",
9307 					    (intmax_t)adp->ad_offset, "mismatch",
9308 					    (intmax_t)dp2->di_db[adp->ad_offset],
9309 					    (intmax_t)adp->ad_oldblkno);
9310 				dp2->di_db[adp->ad_offset] = adp->ad_newblkno;
9311 			} else {
9312 				if (dp2->di_ib[adp->ad_offset - NDADDR] != 0)
9313 					panic("%s: %s #%jd allocated as %jd",
9314 					    "handle_written_inodeblock",
9315 					    "indirect pointer",
9316 					    (intmax_t)adp->ad_offset - NDADDR,
9317 					    (intmax_t)
9318 					    dp2->di_ib[adp->ad_offset - NDADDR]);
9319 				dp2->di_ib[adp->ad_offset - NDADDR] =
9320 				    adp->ad_newblkno;
9321 			}
9322 		}
9323 		adp->ad_state &= ~UNDONE;
9324 		adp->ad_state |= ATTACHED;
9325 		hadchanges = 1;
9326 	}
9327 	for (adp = TAILQ_FIRST(&inodedep->id_extupdt); adp; adp = nextadp) {
9328 		nextadp = TAILQ_NEXT(adp, ad_next);
9329 		if (adp->ad_state & ATTACHED)
9330 			panic("handle_written_inodeblock: new entry");
9331 		if (dp2->di_extb[adp->ad_offset] != adp->ad_oldblkno)
9332 			panic("%s: direct pointers #%jd %s %jd != %jd",
9333 			    "handle_written_inodeblock",
9334 			    (intmax_t)adp->ad_offset, "mismatch",
9335 			    (intmax_t)dp2->di_extb[adp->ad_offset],
9336 			    (intmax_t)adp->ad_oldblkno);
9337 		dp2->di_extb[adp->ad_offset] = adp->ad_newblkno;
9338 		adp->ad_state &= ~UNDONE;
9339 		adp->ad_state |= ATTACHED;
9340 		hadchanges = 1;
9341 	}
9342 	if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
9343 		stat_direct_blk_ptrs++;
9344 	/*
9345 	 * Reset the file size to its most up-to-date value.
9346 	 */
9347 	if (inodedep->id_savedsize == -1 || inodedep->id_savedextsize == -1)
9348 		panic("handle_written_inodeblock: bad size");
9349 	if (inodedep->id_savednlink > LINK_MAX)
9350 		panic("handle_written_inodeblock: Invalid link count "
9351 		    "%d for inodedep %p", inodedep->id_savednlink, inodedep);
9352 	if (fstype == UFS1) {
9353 		if (dp1->di_nlink != inodedep->id_savednlink) {
9354 			dp1->di_nlink = inodedep->id_savednlink;
9355 			hadchanges = 1;
9356 		}
9357 		if (dp1->di_size != inodedep->id_savedsize) {
9358 			dp1->di_size = inodedep->id_savedsize;
9359 			hadchanges = 1;
9360 		}
9361 	} else {
9362 		if (dp2->di_nlink != inodedep->id_savednlink) {
9363 			dp2->di_nlink = inodedep->id_savednlink;
9364 			hadchanges = 1;
9365 		}
9366 		if (dp2->di_size != inodedep->id_savedsize) {
9367 			dp2->di_size = inodedep->id_savedsize;
9368 			hadchanges = 1;
9369 		}
9370 		if (dp2->di_extsize != inodedep->id_savedextsize) {
9371 			dp2->di_extsize = inodedep->id_savedextsize;
9372 			hadchanges = 1;
9373 		}
9374 	}
9375 	inodedep->id_savedsize = -1;
9376 	inodedep->id_savedextsize = -1;
9377 	inodedep->id_savednlink = -1;
9378 	/*
9379 	 * If there were any rollbacks in the inode block, then it must be
9380 	 * marked dirty so that its will eventually get written back in
9381 	 * its correct form.
9382 	 */
9383 	if (hadchanges)
9384 		bdirty(bp);
9385 bufwait:
9386 	/*
9387 	 * Process any allocdirects that completed during the update.
9388 	 */
9389 	if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
9390 		handle_allocdirect_partdone(adp, &wkhd);
9391 	if ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
9392 		handle_allocdirect_partdone(adp, &wkhd);
9393 	/*
9394 	 * Process deallocations that were held pending until the
9395 	 * inode had been written to disk. Freeing of the inode
9396 	 * is delayed until after all blocks have been freed to
9397 	 * avoid creation of new <vfsid, inum, lbn> triples
9398 	 * before the old ones have been deleted.  Completely
9399 	 * unlinked inodes are not processed until the unlinked
9400 	 * inode list is written or the last reference is removed.
9401 	 */
9402 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) != UNLINKED) {
9403 		freefile = handle_bufwait(inodedep, NULL);
9404 		if (freefile && !LIST_EMPTY(&wkhd)) {
9405 			WORKLIST_INSERT(&wkhd, &freefile->fx_list);
9406 			freefile = NULL;
9407 		}
9408 	}
9409 	/*
9410 	 * Move rolled forward dependency completions to the bufwait list
9411 	 * now that those that were already written have been processed.
9412 	 */
9413 	if (!LIST_EMPTY(&wkhd) && hadchanges == 0)
9414 		panic("handle_written_inodeblock: bufwait but no changes");
9415 	jwork_move(&inodedep->id_bufwait, &wkhd);
9416 
9417 	if (freefile != NULL) {
9418 		/*
9419 		 * If the inode is goingaway it was never written.  Fake up
9420 		 * the state here so free_inodedep() can succeed.
9421 		 */
9422 		if (inodedep->id_state & GOINGAWAY)
9423 			inodedep->id_state |= COMPLETE | DEPCOMPLETE;
9424 		if (free_inodedep(inodedep) == 0)
9425 			panic("handle_written_inodeblock: live inodedep %p",
9426 			    inodedep);
9427 		add_to_worklist(&freefile->fx_list, 0);
9428 		return (0);
9429 	}
9430 
9431 	/*
9432 	 * If no outstanding dependencies, free it.
9433 	 */
9434 	if (free_inodedep(inodedep) ||
9435 	    (TAILQ_FIRST(&inodedep->id_inoreflst) == 0 &&
9436 	     TAILQ_FIRST(&inodedep->id_inoupdt) == 0 &&
9437 	     TAILQ_FIRST(&inodedep->id_extupdt) == 0 &&
9438 	     LIST_FIRST(&inodedep->id_bufwait) == 0))
9439 		return (0);
9440 	return (hadchanges);
9441 }
9442 
9443 static int
9444 handle_written_indirdep(indirdep, bp, bpp)
9445 	struct indirdep *indirdep;
9446 	struct buf *bp;
9447 	struct buf **bpp;
9448 {
9449 	struct allocindir *aip;
9450 	int chgs;
9451 
9452 	if (indirdep->ir_state & GOINGAWAY)
9453 		panic("disk_write_complete: indirdep gone");
9454 	chgs = 0;
9455 	/*
9456 	 * If there were rollbacks revert them here.
9457 	 */
9458 	if (indirdep->ir_saveddata) {
9459 		bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
9460 		free(indirdep->ir_saveddata, M_INDIRDEP);
9461 		indirdep->ir_saveddata = 0;
9462 		chgs = 1;
9463 	}
9464 	indirdep->ir_state &= ~UNDONE;
9465 	indirdep->ir_state |= ATTACHED;
9466 	/*
9467 	 * Move allocindirs with written pointers to the completehd if
9468 	 * the indirdep's pointer is not yet written.  Otherwise
9469 	 * free them here.
9470 	 */
9471 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != 0) {
9472 		LIST_REMOVE(aip, ai_next);
9473 		if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
9474 			LIST_INSERT_HEAD(&indirdep->ir_completehd, aip,
9475 			    ai_next);
9476 			continue;
9477 		}
9478 		free_newblk(&aip->ai_block);
9479 	}
9480 	/*
9481 	 * Move allocindirs that have finished dependency processing from
9482 	 * the done list to the write list after updating the pointers.
9483 	 */
9484 	while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != 0) {
9485 		handle_allocindir_partdone(aip);
9486 		if (aip == LIST_FIRST(&indirdep->ir_donehd))
9487 			panic("disk_write_complete: not gone");
9488 		chgs = 1;
9489 	}
9490 	/*
9491 	 * If this indirdep has been detached from its newblk during
9492 	 * I/O we need to keep this dep attached to the buffer so
9493 	 * deallocate_dependencies can find it and properly resolve
9494 	 * any outstanding dependencies.
9495 	 */
9496 	if ((indirdep->ir_state & (ONDEPLIST | DEPCOMPLETE)) == 0)
9497 		chgs = 1;
9498 	if ((bp->b_flags & B_DELWRI) == 0)
9499 		stat_indir_blk_ptrs++;
9500 	/*
9501 	 * If there were no changes we can discard the savedbp and detach
9502 	 * ourselves from the buf.  We are only carrying completed pointers
9503 	 * in this case.
9504 	 */
9505 	if (chgs == 0) {
9506 		struct buf *sbp;
9507 
9508 		sbp = indirdep->ir_savebp;
9509 		sbp->b_flags |= B_INVAL | B_NOCACHE;
9510 		indirdep->ir_savebp = NULL;
9511 		if (*bpp != NULL)
9512 			panic("handle_written_indirdep: bp already exists.");
9513 		*bpp = sbp;
9514 	} else
9515 		bdirty(bp);
9516 	/*
9517 	 * If there are no fresh dependencies and none waiting on writes
9518 	 * we can free the indirdep.
9519 	 */
9520 	if ((indirdep->ir_state & DEPCOMPLETE) && chgs == 0) {
9521 		if (indirdep->ir_state & ONDEPLIST)
9522 			LIST_REMOVE(indirdep, ir_next);
9523 		free_indirdep(indirdep);
9524 		return (0);
9525 	}
9526 
9527 	return (chgs);
9528 }
9529 
9530 /*
9531  * Process a diradd entry after its dependent inode has been written.
9532  * This routine must be called with splbio interrupts blocked.
9533  */
9534 static void
9535 diradd_inode_written(dap, inodedep)
9536 	struct diradd *dap;
9537 	struct inodedep *inodedep;
9538 {
9539 
9540 	dap->da_state |= COMPLETE;
9541 	complete_diradd(dap);
9542 	WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
9543 }
9544 
9545 /*
9546  * Returns true if the bmsafemap will have rollbacks when written.  Must
9547  * only be called with lk and the buf lock on the cg held.
9548  */
9549 static int
9550 bmsafemap_rollbacks(bmsafemap)
9551 	struct bmsafemap *bmsafemap;
9552 {
9553 
9554 	return (!LIST_EMPTY(&bmsafemap->sm_jaddrefhd) |
9555 	    !LIST_EMPTY(&bmsafemap->sm_jnewblkhd));
9556 }
9557 
9558 /*
9559  * Complete a write to a bmsafemap structure.  Roll forward any bitmap
9560  * changes if it's not a background write.  Set all written dependencies
9561  * to DEPCOMPLETE and free the structure if possible.
9562  */
9563 static int
9564 handle_written_bmsafemap(bmsafemap, bp)
9565 	struct bmsafemap *bmsafemap;
9566 	struct buf *bp;
9567 {
9568 	struct newblk *newblk;
9569 	struct inodedep *inodedep;
9570 	struct jaddref *jaddref, *jatmp;
9571 	struct jnewblk *jnewblk, *jntmp;
9572 	uint8_t *inosused;
9573 	uint8_t *blksfree;
9574 	struct cg *cgp;
9575 	struct fs *fs;
9576 	ino_t ino;
9577 	long bno;
9578 	int chgs;
9579 	int i;
9580 
9581 	if ((bmsafemap->sm_state & IOSTARTED) == 0)
9582 		panic("initiate_write_bmsafemap: Not started\n");
9583 	chgs = 0;
9584 	bmsafemap->sm_state &= ~IOSTARTED;
9585 	/*
9586 	 * Restore unwritten inode allocation pending jaddref writes.
9587 	 */
9588 	if (!LIST_EMPTY(&bmsafemap->sm_jaddrefhd)) {
9589 		cgp = (struct cg *)bp->b_data;
9590 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
9591 		inosused = cg_inosused(cgp);
9592 		LIST_FOREACH_SAFE(jaddref, &bmsafemap->sm_jaddrefhd,
9593 		    ja_bmdeps, jatmp) {
9594 			if ((jaddref->ja_state & UNDONE) == 0)
9595 				continue;
9596 			ino = jaddref->ja_ino % fs->fs_ipg;
9597 			if (isset(inosused, ino))
9598 				panic("handle_written_bmsafemap: "
9599 				    "re-allocated inode");
9600 			if ((bp->b_xflags & BX_BKGRDMARKER) == 0) {
9601 				if ((jaddref->ja_mode & IFMT) == IFDIR)
9602 					cgp->cg_cs.cs_ndir++;
9603 				cgp->cg_cs.cs_nifree--;
9604 				setbit(inosused, ino);
9605 				chgs = 1;
9606 			}
9607 			jaddref->ja_state &= ~UNDONE;
9608 			jaddref->ja_state |= ATTACHED;
9609 			free_jaddref(jaddref);
9610 		}
9611 	}
9612 	/*
9613 	 * Restore any block allocations which are pending journal writes.
9614 	 */
9615 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
9616 		cgp = (struct cg *)bp->b_data;
9617 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
9618 		blksfree = cg_blksfree(cgp);
9619 		LIST_FOREACH_SAFE(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps,
9620 		    jntmp) {
9621 			if ((jnewblk->jn_state & UNDONE) == 0)
9622 				continue;
9623 			bno = dtogd(fs, jnewblk->jn_blkno);
9624 			for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags;
9625 			    i++) {
9626 				if (bp->b_xflags & BX_BKGRDMARKER)
9627 					break;
9628 				if ((jnewblk->jn_state & NEWBLOCK) == 0 &&
9629 				    isclr(blksfree, bno + i))
9630 					panic("handle_written_bmsafemap: "
9631 					    "re-allocated fragment");
9632 				clrbit(blksfree, bno + i);
9633 				chgs = 1;
9634 			}
9635 			jnewblk->jn_state &= ~(UNDONE | NEWBLOCK);
9636 			jnewblk->jn_state |= ATTACHED;
9637 			free_jnewblk(jnewblk);
9638 		}
9639 	}
9640 	while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkwr))) {
9641 		newblk->nb_state |= DEPCOMPLETE;
9642 		newblk->nb_state &= ~ONDEPLIST;
9643 		newblk->nb_bmsafemap = NULL;
9644 		LIST_REMOVE(newblk, nb_deps);
9645 		if (newblk->nb_list.wk_type == D_ALLOCDIRECT)
9646 			handle_allocdirect_partdone(
9647 			    WK_ALLOCDIRECT(&newblk->nb_list), NULL);
9648 		else if (newblk->nb_list.wk_type == D_ALLOCINDIR)
9649 			handle_allocindir_partdone(
9650 			    WK_ALLOCINDIR(&newblk->nb_list));
9651 		else if (newblk->nb_list.wk_type != D_NEWBLK)
9652 			panic("handle_written_bmsafemap: Unexpected type: %s",
9653 			    TYPENAME(newblk->nb_list.wk_type));
9654 	}
9655 	while ((inodedep = LIST_FIRST(&bmsafemap->sm_inodedepwr)) != NULL) {
9656 		inodedep->id_state |= DEPCOMPLETE;
9657 		inodedep->id_state &= ~ONDEPLIST;
9658 		LIST_REMOVE(inodedep, id_deps);
9659 		inodedep->id_bmsafemap = NULL;
9660 	}
9661 	if (LIST_EMPTY(&bmsafemap->sm_jaddrefhd) &&
9662 	    LIST_EMPTY(&bmsafemap->sm_jnewblkhd) &&
9663 	    LIST_EMPTY(&bmsafemap->sm_newblkhd) &&
9664 	    LIST_EMPTY(&bmsafemap->sm_inodedephd)) {
9665 		if (chgs)
9666 			bdirty(bp);
9667 		LIST_REMOVE(bmsafemap, sm_hash);
9668 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
9669 		return (0);
9670 	}
9671 	bdirty(bp);
9672 	return (1);
9673 }
9674 
9675 /*
9676  * Try to free a mkdir dependency.
9677  */
9678 static void
9679 complete_mkdir(mkdir)
9680 	struct mkdir *mkdir;
9681 {
9682 	struct diradd *dap;
9683 
9684 	if ((mkdir->md_state & ALLCOMPLETE) != ALLCOMPLETE)
9685 		return;
9686 	LIST_REMOVE(mkdir, md_mkdirs);
9687 	dap = mkdir->md_diradd;
9688 	dap->da_state &= ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
9689 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0) {
9690 		dap->da_state |= DEPCOMPLETE;
9691 		complete_diradd(dap);
9692 	}
9693 	WORKITEM_FREE(mkdir, D_MKDIR);
9694 }
9695 
9696 /*
9697  * Handle the completion of a mkdir dependency.
9698  */
9699 static void
9700 handle_written_mkdir(mkdir, type)
9701 	struct mkdir *mkdir;
9702 	int type;
9703 {
9704 
9705 	if ((mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY)) != type)
9706 		panic("handle_written_mkdir: bad type");
9707 	mkdir->md_state |= COMPLETE;
9708 	complete_mkdir(mkdir);
9709 }
9710 
9711 static void
9712 free_pagedep(pagedep)
9713 	struct pagedep *pagedep;
9714 {
9715 	int i;
9716 
9717 	if (pagedep->pd_state & (NEWBLOCK | ONWORKLIST))
9718 		return;
9719 	for (i = 0; i < DAHASHSZ; i++)
9720 		if (!LIST_EMPTY(&pagedep->pd_diraddhd[i]))
9721 			return;
9722 	if (!LIST_EMPTY(&pagedep->pd_jmvrefhd))
9723 		return;
9724 	if (!LIST_EMPTY(&pagedep->pd_dirremhd))
9725 		return;
9726 	if (!LIST_EMPTY(&pagedep->pd_pendinghd))
9727 		return;
9728 	LIST_REMOVE(pagedep, pd_hash);
9729 	WORKITEM_FREE(pagedep, D_PAGEDEP);
9730 }
9731 
9732 /*
9733  * Called from within softdep_disk_write_complete above.
9734  * A write operation was just completed. Removed inodes can
9735  * now be freed and associated block pointers may be committed.
9736  * Note that this routine is always called from interrupt level
9737  * with further splbio interrupts blocked.
9738  */
9739 static int
9740 handle_written_filepage(pagedep, bp)
9741 	struct pagedep *pagedep;
9742 	struct buf *bp;		/* buffer containing the written page */
9743 {
9744 	struct dirrem *dirrem;
9745 	struct diradd *dap, *nextdap;
9746 	struct direct *ep;
9747 	int i, chgs;
9748 
9749 	if ((pagedep->pd_state & IOSTARTED) == 0)
9750 		panic("handle_written_filepage: not started");
9751 	pagedep->pd_state &= ~IOSTARTED;
9752 	/*
9753 	 * Process any directory removals that have been committed.
9754 	 */
9755 	while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
9756 		LIST_REMOVE(dirrem, dm_next);
9757 		dirrem->dm_state |= COMPLETE;
9758 		dirrem->dm_dirinum = pagedep->pd_ino;
9759 		KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
9760 		    ("handle_written_filepage: Journal entries not written."));
9761 		add_to_worklist(&dirrem->dm_list, 0);
9762 	}
9763 	/*
9764 	 * Free any directory additions that have been committed.
9765 	 * If it is a newly allocated block, we have to wait until
9766 	 * the on-disk directory inode claims the new block.
9767 	 */
9768 	if ((pagedep->pd_state & NEWBLOCK) == 0)
9769 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
9770 			free_diradd(dap, NULL);
9771 	/*
9772 	 * Uncommitted directory entries must be restored.
9773 	 */
9774 	for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
9775 		for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
9776 		     dap = nextdap) {
9777 			nextdap = LIST_NEXT(dap, da_pdlist);
9778 			if (dap->da_state & ATTACHED)
9779 				panic("handle_written_filepage: attached");
9780 			ep = (struct direct *)
9781 			    ((char *)bp->b_data + dap->da_offset);
9782 			ep->d_ino = dap->da_newinum;
9783 			dap->da_state &= ~UNDONE;
9784 			dap->da_state |= ATTACHED;
9785 			chgs = 1;
9786 			/*
9787 			 * If the inode referenced by the directory has
9788 			 * been written out, then the dependency can be
9789 			 * moved to the pending list.
9790 			 */
9791 			if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
9792 				LIST_REMOVE(dap, da_pdlist);
9793 				LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
9794 				    da_pdlist);
9795 			}
9796 		}
9797 	}
9798 	/*
9799 	 * If there were any rollbacks in the directory, then it must be
9800 	 * marked dirty so that its will eventually get written back in
9801 	 * its correct form.
9802 	 */
9803 	if (chgs) {
9804 		if ((bp->b_flags & B_DELWRI) == 0)
9805 			stat_dir_entry++;
9806 		bdirty(bp);
9807 		return (1);
9808 	}
9809 	/*
9810 	 * If we are not waiting for a new directory block to be
9811 	 * claimed by its inode, then the pagedep will be freed.
9812 	 * Otherwise it will remain to track any new entries on
9813 	 * the page in case they are fsync'ed.
9814 	 */
9815 	if ((pagedep->pd_state & NEWBLOCK) == 0 &&
9816 	    LIST_EMPTY(&pagedep->pd_jmvrefhd)) {
9817 		LIST_REMOVE(pagedep, pd_hash);
9818 		WORKITEM_FREE(pagedep, D_PAGEDEP);
9819 	}
9820 	return (0);
9821 }
9822 
9823 /*
9824  * Writing back in-core inode structures.
9825  *
9826  * The filesystem only accesses an inode's contents when it occupies an
9827  * "in-core" inode structure.  These "in-core" structures are separate from
9828  * the page frames used to cache inode blocks.  Only the latter are
9829  * transferred to/from the disk.  So, when the updated contents of the
9830  * "in-core" inode structure are copied to the corresponding in-memory inode
9831  * block, the dependencies are also transferred.  The following procedure is
9832  * called when copying a dirty "in-core" inode to a cached inode block.
9833  */
9834 
9835 /*
9836  * Called when an inode is loaded from disk. If the effective link count
9837  * differed from the actual link count when it was last flushed, then we
9838  * need to ensure that the correct effective link count is put back.
9839  */
9840 void
9841 softdep_load_inodeblock(ip)
9842 	struct inode *ip;	/* the "in_core" copy of the inode */
9843 {
9844 	struct inodedep *inodedep;
9845 
9846 	/*
9847 	 * Check for alternate nlink count.
9848 	 */
9849 	ip->i_effnlink = ip->i_nlink;
9850 	ACQUIRE_LOCK(&lk);
9851 	if (inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, 0,
9852 	    &inodedep) == 0) {
9853 		FREE_LOCK(&lk);
9854 		return;
9855 	}
9856 	ip->i_effnlink -= inodedep->id_nlinkdelta;
9857 	FREE_LOCK(&lk);
9858 }
9859 
9860 /*
9861  * This routine is called just before the "in-core" inode
9862  * information is to be copied to the in-memory inode block.
9863  * Recall that an inode block contains several inodes. If
9864  * the force flag is set, then the dependencies will be
9865  * cleared so that the update can always be made. Note that
9866  * the buffer is locked when this routine is called, so we
9867  * will never be in the middle of writing the inode block
9868  * to disk.
9869  */
9870 void
9871 softdep_update_inodeblock(ip, bp, waitfor)
9872 	struct inode *ip;	/* the "in_core" copy of the inode */
9873 	struct buf *bp;		/* the buffer containing the inode block */
9874 	int waitfor;		/* nonzero => update must be allowed */
9875 {
9876 	struct inodedep *inodedep;
9877 	struct inoref *inoref;
9878 	struct worklist *wk;
9879 	struct mount *mp;
9880 	struct buf *ibp;
9881 	struct fs *fs;
9882 	int error;
9883 
9884 	mp = UFSTOVFS(ip->i_ump);
9885 	fs = ip->i_fs;
9886 	/*
9887 	 * Preserve the freelink that is on disk.  clear_unlinked_inodedep()
9888 	 * does not have access to the in-core ip so must write directly into
9889 	 * the inode block buffer when setting freelink.
9890 	 */
9891 	if (fs->fs_magic == FS_UFS1_MAGIC)
9892 		DIP_SET(ip, i_freelink, ((struct ufs1_dinode *)bp->b_data +
9893 		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
9894 	else
9895 		DIP_SET(ip, i_freelink, ((struct ufs2_dinode *)bp->b_data +
9896 		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
9897 	/*
9898 	 * If the effective link count is not equal to the actual link
9899 	 * count, then we must track the difference in an inodedep while
9900 	 * the inode is (potentially) tossed out of the cache. Otherwise,
9901 	 * if there is no existing inodedep, then there are no dependencies
9902 	 * to track.
9903 	 */
9904 	ACQUIRE_LOCK(&lk);
9905 again:
9906 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
9907 		FREE_LOCK(&lk);
9908 		if (ip->i_effnlink != ip->i_nlink)
9909 			panic("softdep_update_inodeblock: bad link count");
9910 		return;
9911 	}
9912 	if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink)
9913 		panic("softdep_update_inodeblock: bad delta");
9914 	/*
9915 	 * If we're flushing all dependencies we must also move any waiting
9916 	 * for journal writes onto the bufwait list prior to I/O.
9917 	 */
9918 	if (waitfor) {
9919 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
9920 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
9921 			    == DEPCOMPLETE) {
9922 				stat_jwait_inode++;
9923 				jwait(&inoref->if_list);
9924 				goto again;
9925 			}
9926 		}
9927 	}
9928 	/*
9929 	 * Changes have been initiated. Anything depending on these
9930 	 * changes cannot occur until this inode has been written.
9931 	 */
9932 	inodedep->id_state &= ~COMPLETE;
9933 	if ((inodedep->id_state & ONWORKLIST) == 0)
9934 		WORKLIST_INSERT(&bp->b_dep, &inodedep->id_list);
9935 	/*
9936 	 * Any new dependencies associated with the incore inode must
9937 	 * now be moved to the list associated with the buffer holding
9938 	 * the in-memory copy of the inode. Once merged process any
9939 	 * allocdirects that are completed by the merger.
9940 	 */
9941 	merge_inode_lists(&inodedep->id_newinoupdt, &inodedep->id_inoupdt);
9942 	if (!TAILQ_EMPTY(&inodedep->id_inoupdt))
9943 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt),
9944 		    NULL);
9945 	merge_inode_lists(&inodedep->id_newextupdt, &inodedep->id_extupdt);
9946 	if (!TAILQ_EMPTY(&inodedep->id_extupdt))
9947 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_extupdt),
9948 		    NULL);
9949 	/*
9950 	 * Now that the inode has been pushed into the buffer, the
9951 	 * operations dependent on the inode being written to disk
9952 	 * can be moved to the id_bufwait so that they will be
9953 	 * processed when the buffer I/O completes.
9954 	 */
9955 	while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
9956 		WORKLIST_REMOVE(wk);
9957 		WORKLIST_INSERT(&inodedep->id_bufwait, wk);
9958 	}
9959 	/*
9960 	 * Newly allocated inodes cannot be written until the bitmap
9961 	 * that allocates them have been written (indicated by
9962 	 * DEPCOMPLETE being set in id_state). If we are doing a
9963 	 * forced sync (e.g., an fsync on a file), we force the bitmap
9964 	 * to be written so that the update can be done.
9965 	 */
9966 	if (waitfor == 0) {
9967 		FREE_LOCK(&lk);
9968 		return;
9969 	}
9970 retry:
9971 	if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) != 0) {
9972 		FREE_LOCK(&lk);
9973 		return;
9974 	}
9975 	ibp = inodedep->id_bmsafemap->sm_buf;
9976 	ibp = getdirtybuf(ibp, &lk, MNT_WAIT);
9977 	if (ibp == NULL) {
9978 		/*
9979 		 * If ibp came back as NULL, the dependency could have been
9980 		 * freed while we slept.  Look it up again, and check to see
9981 		 * that it has completed.
9982 		 */
9983 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
9984 			goto retry;
9985 		FREE_LOCK(&lk);
9986 		return;
9987 	}
9988 	FREE_LOCK(&lk);
9989 	if ((error = bwrite(ibp)) != 0)
9990 		softdep_error("softdep_update_inodeblock: bwrite", error);
9991 }
9992 
9993 /*
9994  * Merge the a new inode dependency list (such as id_newinoupdt) into an
9995  * old inode dependency list (such as id_inoupdt). This routine must be
9996  * called with splbio interrupts blocked.
9997  */
9998 static void
9999 merge_inode_lists(newlisthead, oldlisthead)
10000 	struct allocdirectlst *newlisthead;
10001 	struct allocdirectlst *oldlisthead;
10002 {
10003 	struct allocdirect *listadp, *newadp;
10004 
10005 	newadp = TAILQ_FIRST(newlisthead);
10006 	for (listadp = TAILQ_FIRST(oldlisthead); listadp && newadp;) {
10007 		if (listadp->ad_offset < newadp->ad_offset) {
10008 			listadp = TAILQ_NEXT(listadp, ad_next);
10009 			continue;
10010 		}
10011 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
10012 		TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
10013 		if (listadp->ad_offset == newadp->ad_offset) {
10014 			allocdirect_merge(oldlisthead, newadp,
10015 			    listadp);
10016 			listadp = newadp;
10017 		}
10018 		newadp = TAILQ_FIRST(newlisthead);
10019 	}
10020 	while ((newadp = TAILQ_FIRST(newlisthead)) != NULL) {
10021 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
10022 		TAILQ_INSERT_TAIL(oldlisthead, newadp, ad_next);
10023 	}
10024 }
10025 
10026 /*
10027  * If we are doing an fsync, then we must ensure that any directory
10028  * entries for the inode have been written after the inode gets to disk.
10029  */
10030 int
10031 softdep_fsync(vp)
10032 	struct vnode *vp;	/* the "in_core" copy of the inode */
10033 {
10034 	struct inodedep *inodedep;
10035 	struct pagedep *pagedep;
10036 	struct inoref *inoref;
10037 	struct worklist *wk;
10038 	struct diradd *dap;
10039 	struct mount *mp;
10040 	struct vnode *pvp;
10041 	struct inode *ip;
10042 	struct buf *bp;
10043 	struct fs *fs;
10044 	struct thread *td = curthread;
10045 	int error, flushparent, pagedep_new_block;
10046 	ino_t parentino;
10047 	ufs_lbn_t lbn;
10048 
10049 	ip = VTOI(vp);
10050 	fs = ip->i_fs;
10051 	mp = vp->v_mount;
10052 	ACQUIRE_LOCK(&lk);
10053 restart:
10054 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
10055 		FREE_LOCK(&lk);
10056 		return (0);
10057 	}
10058 	TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
10059 		if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
10060 		    == DEPCOMPLETE) {
10061 			stat_jwait_inode++;
10062 			jwait(&inoref->if_list);
10063 			goto restart;
10064 		}
10065 	}
10066 	if (!LIST_EMPTY(&inodedep->id_inowait) ||
10067 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
10068 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
10069 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
10070 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt))
10071 		panic("softdep_fsync: pending ops %p", inodedep);
10072 	for (error = 0, flushparent = 0; ; ) {
10073 		if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
10074 			break;
10075 		if (wk->wk_type != D_DIRADD)
10076 			panic("softdep_fsync: Unexpected type %s",
10077 			    TYPENAME(wk->wk_type));
10078 		dap = WK_DIRADD(wk);
10079 		/*
10080 		 * Flush our parent if this directory entry has a MKDIR_PARENT
10081 		 * dependency or is contained in a newly allocated block.
10082 		 */
10083 		if (dap->da_state & DIRCHG)
10084 			pagedep = dap->da_previous->dm_pagedep;
10085 		else
10086 			pagedep = dap->da_pagedep;
10087 		parentino = pagedep->pd_ino;
10088 		lbn = pagedep->pd_lbn;
10089 		if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE)
10090 			panic("softdep_fsync: dirty");
10091 		if ((dap->da_state & MKDIR_PARENT) ||
10092 		    (pagedep->pd_state & NEWBLOCK))
10093 			flushparent = 1;
10094 		else
10095 			flushparent = 0;
10096 		/*
10097 		 * If we are being fsync'ed as part of vgone'ing this vnode,
10098 		 * then we will not be able to release and recover the
10099 		 * vnode below, so we just have to give up on writing its
10100 		 * directory entry out. It will eventually be written, just
10101 		 * not now, but then the user was not asking to have it
10102 		 * written, so we are not breaking any promises.
10103 		 */
10104 		if (vp->v_iflag & VI_DOOMED)
10105 			break;
10106 		/*
10107 		 * We prevent deadlock by always fetching inodes from the
10108 		 * root, moving down the directory tree. Thus, when fetching
10109 		 * our parent directory, we first try to get the lock. If
10110 		 * that fails, we must unlock ourselves before requesting
10111 		 * the lock on our parent. See the comment in ufs_lookup
10112 		 * for details on possible races.
10113 		 */
10114 		FREE_LOCK(&lk);
10115 		if (ffs_vgetf(mp, parentino, LK_NOWAIT | LK_EXCLUSIVE, &pvp,
10116 		    FFSV_FORCEINSMQ)) {
10117 			error = vfs_busy(mp, MBF_NOWAIT);
10118 			if (error != 0) {
10119 				vfs_ref(mp);
10120 				VOP_UNLOCK(vp, 0);
10121 				error = vfs_busy(mp, 0);
10122 				vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
10123 				vfs_rel(mp);
10124 				if (error != 0)
10125 					return (ENOENT);
10126 				if (vp->v_iflag & VI_DOOMED) {
10127 					vfs_unbusy(mp);
10128 					return (ENOENT);
10129 				}
10130 			}
10131 			VOP_UNLOCK(vp, 0);
10132 			error = ffs_vgetf(mp, parentino, LK_EXCLUSIVE,
10133 			    &pvp, FFSV_FORCEINSMQ);
10134 			vfs_unbusy(mp);
10135 			vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
10136 			if (vp->v_iflag & VI_DOOMED) {
10137 				if (error == 0)
10138 					vput(pvp);
10139 				error = ENOENT;
10140 			}
10141 			if (error != 0)
10142 				return (error);
10143 		}
10144 		/*
10145 		 * All MKDIR_PARENT dependencies and all the NEWBLOCK pagedeps
10146 		 * that are contained in direct blocks will be resolved by
10147 		 * doing a ffs_update. Pagedeps contained in indirect blocks
10148 		 * may require a complete sync'ing of the directory. So, we
10149 		 * try the cheap and fast ffs_update first, and if that fails,
10150 		 * then we do the slower ffs_syncvnode of the directory.
10151 		 */
10152 		if (flushparent) {
10153 			int locked;
10154 
10155 			if ((error = ffs_update(pvp, 1)) != 0) {
10156 				vput(pvp);
10157 				return (error);
10158 			}
10159 			ACQUIRE_LOCK(&lk);
10160 			locked = 1;
10161 			if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0) {
10162 				if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) != NULL) {
10163 					if (wk->wk_type != D_DIRADD)
10164 						panic("softdep_fsync: Unexpected type %s",
10165 						      TYPENAME(wk->wk_type));
10166 					dap = WK_DIRADD(wk);
10167 					if (dap->da_state & DIRCHG)
10168 						pagedep = dap->da_previous->dm_pagedep;
10169 					else
10170 						pagedep = dap->da_pagedep;
10171 					pagedep_new_block = pagedep->pd_state & NEWBLOCK;
10172 					FREE_LOCK(&lk);
10173 					locked = 0;
10174 					if (pagedep_new_block &&
10175 					    (error = ffs_syncvnode(pvp, MNT_WAIT))) {
10176 						vput(pvp);
10177 						return (error);
10178 					}
10179 				}
10180 			}
10181 			if (locked)
10182 				FREE_LOCK(&lk);
10183 		}
10184 		/*
10185 		 * Flush directory page containing the inode's name.
10186 		 */
10187 		error = bread(pvp, lbn, blksize(fs, VTOI(pvp), lbn), td->td_ucred,
10188 		    &bp);
10189 		if (error == 0)
10190 			error = bwrite(bp);
10191 		else
10192 			brelse(bp);
10193 		vput(pvp);
10194 		if (error != 0)
10195 			return (error);
10196 		ACQUIRE_LOCK(&lk);
10197 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
10198 			break;
10199 	}
10200 	FREE_LOCK(&lk);
10201 	return (0);
10202 }
10203 
10204 /*
10205  * Flush all the dirty bitmaps associated with the block device
10206  * before flushing the rest of the dirty blocks so as to reduce
10207  * the number of dependencies that will have to be rolled back.
10208  */
10209 void
10210 softdep_fsync_mountdev(vp)
10211 	struct vnode *vp;
10212 {
10213 	struct buf *bp, *nbp;
10214 	struct worklist *wk;
10215 	struct bufobj *bo;
10216 
10217 	if (!vn_isdisk(vp, NULL))
10218 		panic("softdep_fsync_mountdev: vnode not a disk");
10219 	bo = &vp->v_bufobj;
10220 restart:
10221 	BO_LOCK(bo);
10222 	ACQUIRE_LOCK(&lk);
10223 	TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
10224 		/*
10225 		 * If it is already scheduled, skip to the next buffer.
10226 		 */
10227 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL))
10228 			continue;
10229 
10230 		if ((bp->b_flags & B_DELWRI) == 0)
10231 			panic("softdep_fsync_mountdev: not dirty");
10232 		/*
10233 		 * We are only interested in bitmaps with outstanding
10234 		 * dependencies.
10235 		 */
10236 		if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
10237 		    wk->wk_type != D_BMSAFEMAP ||
10238 		    (bp->b_vflags & BV_BKGRDINPROG)) {
10239 			BUF_UNLOCK(bp);
10240 			continue;
10241 		}
10242 		FREE_LOCK(&lk);
10243 		BO_UNLOCK(bo);
10244 		bremfree(bp);
10245 		(void) bawrite(bp);
10246 		goto restart;
10247 	}
10248 	FREE_LOCK(&lk);
10249 	drain_output(vp);
10250 	BO_UNLOCK(bo);
10251 }
10252 
10253 /*
10254  * This routine is called when we are trying to synchronously flush a
10255  * file. This routine must eliminate any filesystem metadata dependencies
10256  * so that the syncing routine can succeed by pushing the dirty blocks
10257  * associated with the file. If any I/O errors occur, they are returned.
10258  */
10259 int
10260 softdep_sync_metadata(struct vnode *vp)
10261 {
10262 	struct pagedep *pagedep;
10263 	struct allocindir *aip;
10264 	struct newblk *newblk;
10265 	struct buf *bp, *nbp;
10266 	struct worklist *wk;
10267 	struct bufobj *bo;
10268 	int i, error, waitfor;
10269 
10270 	if (!DOINGSOFTDEP(vp))
10271 		return (0);
10272 	/*
10273 	 * Ensure that any direct block dependencies have been cleared.
10274 	 */
10275 	ACQUIRE_LOCK(&lk);
10276 	if ((error = flush_inodedep_deps(vp->v_mount, VTOI(vp)->i_number))) {
10277 		FREE_LOCK(&lk);
10278 		return (error);
10279 	}
10280 	FREE_LOCK(&lk);
10281 	/*
10282 	 * For most files, the only metadata dependencies are the
10283 	 * cylinder group maps that allocate their inode or blocks.
10284 	 * The block allocation dependencies can be found by traversing
10285 	 * the dependency lists for any buffers that remain on their
10286 	 * dirty buffer list. The inode allocation dependency will
10287 	 * be resolved when the inode is updated with MNT_WAIT.
10288 	 * This work is done in two passes. The first pass grabs most
10289 	 * of the buffers and begins asynchronously writing them. The
10290 	 * only way to wait for these asynchronous writes is to sleep
10291 	 * on the filesystem vnode which may stay busy for a long time
10292 	 * if the filesystem is active. So, instead, we make a second
10293 	 * pass over the dependencies blocking on each write. In the
10294 	 * usual case we will be blocking against a write that we
10295 	 * initiated, so when it is done the dependency will have been
10296 	 * resolved. Thus the second pass is expected to end quickly.
10297 	 */
10298 	waitfor = MNT_NOWAIT;
10299 	bo = &vp->v_bufobj;
10300 
10301 top:
10302 	/*
10303 	 * We must wait for any I/O in progress to finish so that
10304 	 * all potential buffers on the dirty list will be visible.
10305 	 */
10306 	BO_LOCK(bo);
10307 	drain_output(vp);
10308 	while ((bp = TAILQ_FIRST(&bo->bo_dirty.bv_hd)) != NULL) {
10309 		bp = getdirtybuf(bp, BO_MTX(bo), MNT_WAIT);
10310 		if (bp)
10311 			break;
10312 	}
10313 	BO_UNLOCK(bo);
10314 	if (bp == NULL)
10315 		return (0);
10316 loop:
10317 	/* While syncing snapshots, we must allow recursive lookups */
10318 	BUF_AREC(bp);
10319 	ACQUIRE_LOCK(&lk);
10320 	/*
10321 	 * As we hold the buffer locked, none of its dependencies
10322 	 * will disappear.
10323 	 */
10324 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
10325 		switch (wk->wk_type) {
10326 
10327 		case D_ALLOCDIRECT:
10328 		case D_ALLOCINDIR:
10329 			newblk = WK_NEWBLK(wk);
10330 			if (newblk->nb_jnewblk != NULL) {
10331 				stat_jwait_newblk++;
10332 				jwait(&newblk->nb_jnewblk->jn_list);
10333 				goto restart;
10334 			}
10335 			if (newblk->nb_state & DEPCOMPLETE)
10336 				continue;
10337 			nbp = newblk->nb_bmsafemap->sm_buf;
10338 			nbp = getdirtybuf(nbp, &lk, waitfor);
10339 			if (nbp == NULL)
10340 				continue;
10341 			FREE_LOCK(&lk);
10342 			if (waitfor == MNT_NOWAIT) {
10343 				bawrite(nbp);
10344 			} else if ((error = bwrite(nbp)) != 0) {
10345 				break;
10346 			}
10347 			ACQUIRE_LOCK(&lk);
10348 			continue;
10349 
10350 		case D_INDIRDEP:
10351 		restart:
10352 
10353 			LIST_FOREACH(aip,
10354 			    &WK_INDIRDEP(wk)->ir_deplisthd, ai_next) {
10355 				newblk = (struct newblk *)aip;
10356 				if (newblk->nb_jnewblk != NULL) {
10357 					stat_jwait_newblk++;
10358 					jwait(&newblk->nb_jnewblk->jn_list);
10359 					goto restart;
10360 				}
10361 				if (newblk->nb_state & DEPCOMPLETE)
10362 					continue;
10363 				nbp = newblk->nb_bmsafemap->sm_buf;
10364 				nbp = getdirtybuf(nbp, &lk, MNT_WAIT);
10365 				if (nbp == NULL)
10366 					goto restart;
10367 				FREE_LOCK(&lk);
10368 				if ((error = bwrite(nbp)) != 0) {
10369 					goto loop_end;
10370 				}
10371 				ACQUIRE_LOCK(&lk);
10372 				goto restart;
10373 			}
10374 			continue;
10375 
10376 		case D_PAGEDEP:
10377 			/*
10378 			 * We are trying to sync a directory that may
10379 			 * have dependencies on both its own metadata
10380 			 * and/or dependencies on the inodes of any
10381 			 * recently allocated files. We walk its diradd
10382 			 * lists pushing out the associated inode.
10383 			 */
10384 			pagedep = WK_PAGEDEP(wk);
10385 			for (i = 0; i < DAHASHSZ; i++) {
10386 				if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
10387 					continue;
10388 				if ((error =
10389 				    flush_pagedep_deps(vp, wk->wk_mp,
10390 						&pagedep->pd_diraddhd[i]))) {
10391 					FREE_LOCK(&lk);
10392 					goto loop_end;
10393 				}
10394 			}
10395 			continue;
10396 
10397 		default:
10398 			panic("softdep_sync_metadata: Unknown type %s",
10399 			    TYPENAME(wk->wk_type));
10400 			/* NOTREACHED */
10401 		}
10402 	loop_end:
10403 		/* We reach here only in error and unlocked */
10404 		if (error == 0)
10405 			panic("softdep_sync_metadata: zero error");
10406 		BUF_NOREC(bp);
10407 		bawrite(bp);
10408 		return (error);
10409 	}
10410 	FREE_LOCK(&lk);
10411 	BO_LOCK(bo);
10412 	while ((nbp = TAILQ_NEXT(bp, b_bobufs)) != NULL) {
10413 		nbp = getdirtybuf(nbp, BO_MTX(bo), MNT_WAIT);
10414 		if (nbp)
10415 			break;
10416 	}
10417 	BO_UNLOCK(bo);
10418 	BUF_NOREC(bp);
10419 	bawrite(bp);
10420 	if (nbp != NULL) {
10421 		bp = nbp;
10422 		goto loop;
10423 	}
10424 	/*
10425 	 * The brief unlock is to allow any pent up dependency
10426 	 * processing to be done. Then proceed with the second pass.
10427 	 */
10428 	if (waitfor == MNT_NOWAIT) {
10429 		waitfor = MNT_WAIT;
10430 		goto top;
10431 	}
10432 
10433 	/*
10434 	 * If we have managed to get rid of all the dirty buffers,
10435 	 * then we are done. For certain directories and block
10436 	 * devices, we may need to do further work.
10437 	 *
10438 	 * We must wait for any I/O in progress to finish so that
10439 	 * all potential buffers on the dirty list will be visible.
10440 	 */
10441 	BO_LOCK(bo);
10442 	drain_output(vp);
10443 	BO_UNLOCK(bo);
10444 	return ffs_update(vp, 1);
10445 	/* return (0); */
10446 }
10447 
10448 /*
10449  * Flush the dependencies associated with an inodedep.
10450  * Called with splbio blocked.
10451  */
10452 static int
10453 flush_inodedep_deps(mp, ino)
10454 	struct mount *mp;
10455 	ino_t ino;
10456 {
10457 	struct inodedep *inodedep;
10458 	struct inoref *inoref;
10459 	int error, waitfor;
10460 
10461 	/*
10462 	 * This work is done in two passes. The first pass grabs most
10463 	 * of the buffers and begins asynchronously writing them. The
10464 	 * only way to wait for these asynchronous writes is to sleep
10465 	 * on the filesystem vnode which may stay busy for a long time
10466 	 * if the filesystem is active. So, instead, we make a second
10467 	 * pass over the dependencies blocking on each write. In the
10468 	 * usual case we will be blocking against a write that we
10469 	 * initiated, so when it is done the dependency will have been
10470 	 * resolved. Thus the second pass is expected to end quickly.
10471 	 * We give a brief window at the top of the loop to allow
10472 	 * any pending I/O to complete.
10473 	 */
10474 	for (error = 0, waitfor = MNT_NOWAIT; ; ) {
10475 		if (error)
10476 			return (error);
10477 		FREE_LOCK(&lk);
10478 		ACQUIRE_LOCK(&lk);
10479 restart:
10480 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
10481 			return (0);
10482 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
10483 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
10484 			    == DEPCOMPLETE) {
10485 				stat_jwait_inode++;
10486 				jwait(&inoref->if_list);
10487 				goto restart;
10488 			}
10489 		}
10490 		if (flush_deplist(&inodedep->id_inoupdt, waitfor, &error) ||
10491 		    flush_deplist(&inodedep->id_newinoupdt, waitfor, &error) ||
10492 		    flush_deplist(&inodedep->id_extupdt, waitfor, &error) ||
10493 		    flush_deplist(&inodedep->id_newextupdt, waitfor, &error))
10494 			continue;
10495 		/*
10496 		 * If pass2, we are done, otherwise do pass 2.
10497 		 */
10498 		if (waitfor == MNT_WAIT)
10499 			break;
10500 		waitfor = MNT_WAIT;
10501 	}
10502 	/*
10503 	 * Try freeing inodedep in case all dependencies have been removed.
10504 	 */
10505 	if (inodedep_lookup(mp, ino, 0, &inodedep) != 0)
10506 		(void) free_inodedep(inodedep);
10507 	return (0);
10508 }
10509 
10510 /*
10511  * Flush an inode dependency list.
10512  * Called with splbio blocked.
10513  */
10514 static int
10515 flush_deplist(listhead, waitfor, errorp)
10516 	struct allocdirectlst *listhead;
10517 	int waitfor;
10518 	int *errorp;
10519 {
10520 	struct allocdirect *adp;
10521 	struct newblk *newblk;
10522 	struct buf *bp;
10523 
10524 	mtx_assert(&lk, MA_OWNED);
10525 	TAILQ_FOREACH(adp, listhead, ad_next) {
10526 		newblk = (struct newblk *)adp;
10527 		if (newblk->nb_jnewblk != NULL) {
10528 			stat_jwait_newblk++;
10529 			jwait(&newblk->nb_jnewblk->jn_list);
10530 			return (1);
10531 		}
10532 		if (newblk->nb_state & DEPCOMPLETE)
10533 			continue;
10534 		bp = newblk->nb_bmsafemap->sm_buf;
10535 		bp = getdirtybuf(bp, &lk, waitfor);
10536 		if (bp == NULL) {
10537 			if (waitfor == MNT_NOWAIT)
10538 				continue;
10539 			return (1);
10540 		}
10541 		FREE_LOCK(&lk);
10542 		if (waitfor == MNT_NOWAIT) {
10543 			bawrite(bp);
10544 		} else if ((*errorp = bwrite(bp)) != 0) {
10545 			ACQUIRE_LOCK(&lk);
10546 			return (1);
10547 		}
10548 		ACQUIRE_LOCK(&lk);
10549 		return (1);
10550 	}
10551 	return (0);
10552 }
10553 
10554 /*
10555  * Flush dependencies associated with an allocdirect block.
10556  */
10557 static int
10558 flush_newblk_dep(vp, mp, lbn)
10559 	struct vnode *vp;
10560 	struct mount *mp;
10561 	ufs_lbn_t lbn;
10562 {
10563 	struct newblk *newblk;
10564 	struct bufobj *bo;
10565 	struct inode *ip;
10566 	struct buf *bp;
10567 	ufs2_daddr_t blkno;
10568 	int error;
10569 
10570 	error = 0;
10571 	bo = &vp->v_bufobj;
10572 	ip = VTOI(vp);
10573 	blkno = DIP(ip, i_db[lbn]);
10574 	if (blkno == 0)
10575 		panic("flush_newblk_dep: Missing block");
10576 	ACQUIRE_LOCK(&lk);
10577 	/*
10578 	 * Loop until all dependencies related to this block are satisfied.
10579 	 * We must be careful to restart after each sleep in case a write
10580 	 * completes some part of this process for us.
10581 	 */
10582 	for (;;) {
10583 		if (newblk_lookup(mp, blkno, 0, &newblk) == 0) {
10584 			FREE_LOCK(&lk);
10585 			break;
10586 		}
10587 		if (newblk->nb_list.wk_type != D_ALLOCDIRECT)
10588 			panic("flush_newblk_deps: Bad newblk %p", newblk);
10589 		/*
10590 		 * Flush the journal.
10591 		 */
10592 		if (newblk->nb_jnewblk != NULL) {
10593 			stat_jwait_newblk++;
10594 			jwait(&newblk->nb_jnewblk->jn_list);
10595 			continue;
10596 		}
10597 		/*
10598 		 * Write the bitmap dependency.
10599 		 */
10600 		if ((newblk->nb_state & DEPCOMPLETE) == 0) {
10601 			bp = newblk->nb_bmsafemap->sm_buf;
10602 			bp = getdirtybuf(bp, &lk, MNT_WAIT);
10603 			if (bp == NULL)
10604 				continue;
10605 			FREE_LOCK(&lk);
10606 			error = bwrite(bp);
10607 			if (error)
10608 				break;
10609 			ACQUIRE_LOCK(&lk);
10610 			continue;
10611 		}
10612 		/*
10613 		 * Write the buffer.
10614 		 */
10615 		FREE_LOCK(&lk);
10616 		BO_LOCK(bo);
10617 		bp = gbincore(bo, lbn);
10618 		if (bp != NULL) {
10619 			error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
10620 			    LK_INTERLOCK, BO_MTX(bo));
10621 			if (error == ENOLCK) {
10622 				ACQUIRE_LOCK(&lk);
10623 				continue; /* Slept, retry */
10624 			}
10625 			if (error != 0)
10626 				break;	/* Failed */
10627 			if (bp->b_flags & B_DELWRI) {
10628 				bremfree(bp);
10629 				error = bwrite(bp);
10630 				if (error)
10631 					break;
10632 			} else
10633 				BUF_UNLOCK(bp);
10634 		} else
10635 			BO_UNLOCK(bo);
10636 		/*
10637 		 * We have to wait for the direct pointers to
10638 		 * point at the newdirblk before the dependency
10639 		 * will go away.
10640 		 */
10641 		error = ffs_update(vp, MNT_WAIT);
10642 		if (error)
10643 			break;
10644 		ACQUIRE_LOCK(&lk);
10645 	}
10646 	return (error);
10647 }
10648 
10649 /*
10650  * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
10651  * Called with splbio blocked.
10652  */
10653 static int
10654 flush_pagedep_deps(pvp, mp, diraddhdp)
10655 	struct vnode *pvp;
10656 	struct mount *mp;
10657 	struct diraddhd *diraddhdp;
10658 {
10659 	struct inodedep *inodedep;
10660 	struct inoref *inoref;
10661 	struct ufsmount *ump;
10662 	struct diradd *dap;
10663 	struct vnode *vp;
10664 	int error = 0;
10665 	struct buf *bp;
10666 	ino_t inum;
10667 
10668 	ump = VFSTOUFS(mp);
10669 restart:
10670 	while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
10671 		/*
10672 		 * Flush ourselves if this directory entry
10673 		 * has a MKDIR_PARENT dependency.
10674 		 */
10675 		if (dap->da_state & MKDIR_PARENT) {
10676 			FREE_LOCK(&lk);
10677 			if ((error = ffs_update(pvp, MNT_WAIT)) != 0)
10678 				break;
10679 			ACQUIRE_LOCK(&lk);
10680 			/*
10681 			 * If that cleared dependencies, go on to next.
10682 			 */
10683 			if (dap != LIST_FIRST(diraddhdp))
10684 				continue;
10685 			if (dap->da_state & MKDIR_PARENT)
10686 				panic("flush_pagedep_deps: MKDIR_PARENT");
10687 		}
10688 		/*
10689 		 * A newly allocated directory must have its "." and
10690 		 * ".." entries written out before its name can be
10691 		 * committed in its parent.
10692 		 */
10693 		inum = dap->da_newinum;
10694 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
10695 			panic("flush_pagedep_deps: lost inode1");
10696 		/*
10697 		 * Wait for any pending journal adds to complete so we don't
10698 		 * cause rollbacks while syncing.
10699 		 */
10700 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
10701 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
10702 			    == DEPCOMPLETE) {
10703 				stat_jwait_inode++;
10704 				jwait(&inoref->if_list);
10705 				goto restart;
10706 			}
10707 		}
10708 		if (dap->da_state & MKDIR_BODY) {
10709 			FREE_LOCK(&lk);
10710 			if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
10711 			    FFSV_FORCEINSMQ)))
10712 				break;
10713 			error = flush_newblk_dep(vp, mp, 0);
10714 			/*
10715 			 * If we still have the dependency we might need to
10716 			 * update the vnode to sync the new link count to
10717 			 * disk.
10718 			 */
10719 			if (error == 0 && dap == LIST_FIRST(diraddhdp))
10720 				error = ffs_update(vp, MNT_WAIT);
10721 			vput(vp);
10722 			if (error != 0)
10723 				break;
10724 			ACQUIRE_LOCK(&lk);
10725 			/*
10726 			 * If that cleared dependencies, go on to next.
10727 			 */
10728 			if (dap != LIST_FIRST(diraddhdp))
10729 				continue;
10730 			if (dap->da_state & MKDIR_BODY) {
10731 				inodedep_lookup(UFSTOVFS(ump), inum, 0,
10732 				    &inodedep);
10733 				panic("flush_pagedep_deps: MKDIR_BODY "
10734 				    "inodedep %p dap %p vp %p",
10735 				    inodedep, dap, vp);
10736 			}
10737 		}
10738 		/*
10739 		 * Flush the inode on which the directory entry depends.
10740 		 * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
10741 		 * the only remaining dependency is that the updated inode
10742 		 * count must get pushed to disk. The inode has already
10743 		 * been pushed into its inode buffer (via VOP_UPDATE) at
10744 		 * the time of the reference count change. So we need only
10745 		 * locate that buffer, ensure that there will be no rollback
10746 		 * caused by a bitmap dependency, then write the inode buffer.
10747 		 */
10748 retry:
10749 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
10750 			panic("flush_pagedep_deps: lost inode");
10751 		/*
10752 		 * If the inode still has bitmap dependencies,
10753 		 * push them to disk.
10754 		 */
10755 		if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) == 0) {
10756 			bp = inodedep->id_bmsafemap->sm_buf;
10757 			bp = getdirtybuf(bp, &lk, MNT_WAIT);
10758 			if (bp == NULL)
10759 				goto retry;
10760 			FREE_LOCK(&lk);
10761 			if ((error = bwrite(bp)) != 0)
10762 				break;
10763 			ACQUIRE_LOCK(&lk);
10764 			if (dap != LIST_FIRST(diraddhdp))
10765 				continue;
10766 		}
10767 		/*
10768 		 * If the inode is still sitting in a buffer waiting
10769 		 * to be written or waiting for the link count to be
10770 		 * adjusted update it here to flush it to disk.
10771 		 */
10772 		if (dap == LIST_FIRST(diraddhdp)) {
10773 			FREE_LOCK(&lk);
10774 			if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
10775 			    FFSV_FORCEINSMQ)))
10776 				break;
10777 			error = ffs_update(vp, MNT_WAIT);
10778 			vput(vp);
10779 			if (error)
10780 				break;
10781 			ACQUIRE_LOCK(&lk);
10782 		}
10783 		/*
10784 		 * If we have failed to get rid of all the dependencies
10785 		 * then something is seriously wrong.
10786 		 */
10787 		if (dap == LIST_FIRST(diraddhdp)) {
10788 			inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep);
10789 			panic("flush_pagedep_deps: failed to flush "
10790 			    "inodedep %p ino %d dap %p", inodedep, inum, dap);
10791 		}
10792 	}
10793 	if (error)
10794 		ACQUIRE_LOCK(&lk);
10795 	return (error);
10796 }
10797 
10798 /*
10799  * A large burst of file addition or deletion activity can drive the
10800  * memory load excessively high. First attempt to slow things down
10801  * using the techniques below. If that fails, this routine requests
10802  * the offending operations to fall back to running synchronously
10803  * until the memory load returns to a reasonable level.
10804  */
10805 int
10806 softdep_slowdown(vp)
10807 	struct vnode *vp;
10808 {
10809 	struct ufsmount *ump;
10810 	int jlow;
10811 	int max_softdeps_hard;
10812 
10813 	ACQUIRE_LOCK(&lk);
10814 	jlow = 0;
10815 	/*
10816 	 * Check for journal space if needed.
10817 	 */
10818 	if (DOINGSUJ(vp)) {
10819 		ump = VFSTOUFS(vp->v_mount);
10820 		if (journal_space(ump, 0) == 0)
10821 			jlow = 1;
10822 	}
10823 	max_softdeps_hard = max_softdeps * 11 / 10;
10824 	if (num_dirrem < max_softdeps_hard / 2 &&
10825 	    num_inodedep < max_softdeps_hard &&
10826 	    VFSTOUFS(vp->v_mount)->um_numindirdeps < maxindirdeps &&
10827 	    num_freeblkdep < max_softdeps_hard && jlow == 0) {
10828 		FREE_LOCK(&lk);
10829   		return (0);
10830 	}
10831 	if (VFSTOUFS(vp->v_mount)->um_numindirdeps >= maxindirdeps || jlow)
10832 		softdep_speedup();
10833 	stat_sync_limit_hit += 1;
10834 	FREE_LOCK(&lk);
10835 	return (1);
10836 }
10837 
10838 /*
10839  * Called by the allocation routines when they are about to fail
10840  * in the hope that we can free up some disk space.
10841  *
10842  * First check to see if the work list has anything on it. If it has,
10843  * clean up entries until we successfully free some space. Because this
10844  * process holds inodes locked, we cannot handle any remove requests
10845  * that might block on a locked inode as that could lead to deadlock.
10846  * If the worklist yields no free space, encourage the syncer daemon
10847  * to help us. In no event will we try for longer than tickdelay seconds.
10848  */
10849 int
10850 softdep_request_cleanup(fs, vp)
10851 	struct fs *fs;
10852 	struct vnode *vp;
10853 {
10854 	struct ufsmount *ump;
10855 	long starttime;
10856 	ufs2_daddr_t needed;
10857 	int error;
10858 
10859 	ump = VTOI(vp)->i_ump;
10860 	mtx_assert(UFS_MTX(ump), MA_OWNED);
10861 	needed = fs->fs_cstotal.cs_nbfree + fs->fs_contigsumsize;
10862 	starttime = time_second + tickdelay;
10863 	/*
10864 	 * If we are being called because of a process doing a
10865 	 * copy-on-write, then it is not safe to update the vnode
10866 	 * as we may recurse into the copy-on-write routine.
10867 	 */
10868 	if (!(curthread->td_pflags & TDP_COWINPROGRESS)) {
10869 		UFS_UNLOCK(ump);
10870 		error = ffs_update(vp, 1);
10871 		UFS_LOCK(ump);
10872 		if (error != 0)
10873 			return (0);
10874 	}
10875 	while (fs->fs_pendingblocks > 0 && fs->fs_cstotal.cs_nbfree <= needed) {
10876 		if (time_second > starttime)
10877 			return (0);
10878 		UFS_UNLOCK(ump);
10879 		ACQUIRE_LOCK(&lk);
10880 		process_removes(vp);
10881 		if (ump->softdep_on_worklist > 0 &&
10882 		    process_worklist_item(UFSTOVFS(ump), LK_NOWAIT) != -1) {
10883 			stat_worklist_push += 1;
10884 			FREE_LOCK(&lk);
10885 			UFS_LOCK(ump);
10886 			continue;
10887 		}
10888 		request_cleanup(UFSTOVFS(ump), FLUSH_REMOVE_WAIT);
10889 		FREE_LOCK(&lk);
10890 		UFS_LOCK(ump);
10891 	}
10892 	return (1);
10893 }
10894 
10895 /*
10896  * If memory utilization has gotten too high, deliberately slow things
10897  * down and speed up the I/O processing.
10898  */
10899 extern struct thread *syncertd;
10900 static int
10901 request_cleanup(mp, resource)
10902 	struct mount *mp;
10903 	int resource;
10904 {
10905 	struct thread *td = curthread;
10906 	struct ufsmount *ump;
10907 
10908 	mtx_assert(&lk, MA_OWNED);
10909 	/*
10910 	 * We never hold up the filesystem syncer or buf daemon.
10911 	 */
10912 	if (td->td_pflags & (TDP_SOFTDEP|TDP_NORUNNINGBUF))
10913 		return (0);
10914 	ump = VFSTOUFS(mp);
10915 	/*
10916 	 * First check to see if the work list has gotten backlogged.
10917 	 * If it has, co-opt this process to help clean up two entries.
10918 	 * Because this process may hold inodes locked, we cannot
10919 	 * handle any remove requests that might block on a locked
10920 	 * inode as that could lead to deadlock.  We set TDP_SOFTDEP
10921 	 * to avoid recursively processing the worklist.
10922 	 */
10923 	if (ump->softdep_on_worklist > max_softdeps / 10) {
10924 		td->td_pflags |= TDP_SOFTDEP;
10925 		process_worklist_item(mp, LK_NOWAIT);
10926 		process_worklist_item(mp, LK_NOWAIT);
10927 		td->td_pflags &= ~TDP_SOFTDEP;
10928 		stat_worklist_push += 2;
10929 		return(1);
10930 	}
10931 	/*
10932 	 * Next, we attempt to speed up the syncer process. If that
10933 	 * is successful, then we allow the process to continue.
10934 	 */
10935 	if (softdep_speedup() && resource != FLUSH_REMOVE_WAIT)
10936 		return(0);
10937 	/*
10938 	 * If we are resource constrained on inode dependencies, try
10939 	 * flushing some dirty inodes. Otherwise, we are constrained
10940 	 * by file deletions, so try accelerating flushes of directories
10941 	 * with removal dependencies. We would like to do the cleanup
10942 	 * here, but we probably hold an inode locked at this point and
10943 	 * that might deadlock against one that we try to clean. So,
10944 	 * the best that we can do is request the syncer daemon to do
10945 	 * the cleanup for us.
10946 	 */
10947 	switch (resource) {
10948 
10949 	case FLUSH_INODES:
10950 		stat_ino_limit_push += 1;
10951 		req_clear_inodedeps += 1;
10952 		stat_countp = &stat_ino_limit_hit;
10953 		break;
10954 
10955 	case FLUSH_REMOVE:
10956 	case FLUSH_REMOVE_WAIT:
10957 		stat_blk_limit_push += 1;
10958 		req_clear_remove += 1;
10959 		stat_countp = &stat_blk_limit_hit;
10960 		break;
10961 
10962 	default:
10963 		panic("request_cleanup: unknown type");
10964 	}
10965 	/*
10966 	 * Hopefully the syncer daemon will catch up and awaken us.
10967 	 * We wait at most tickdelay before proceeding in any case.
10968 	 */
10969 	proc_waiting += 1;
10970 	if (callout_pending(&softdep_callout) == FALSE)
10971 		callout_reset(&softdep_callout, tickdelay > 2 ? tickdelay : 2,
10972 		    pause_timer, 0);
10973 
10974 	msleep((caddr_t)&proc_waiting, &lk, PPAUSE, "softupdate", 0);
10975 	proc_waiting -= 1;
10976 	return (1);
10977 }
10978 
10979 /*
10980  * Awaken processes pausing in request_cleanup and clear proc_waiting
10981  * to indicate that there is no longer a timer running.
10982  */
10983 static void
10984 pause_timer(arg)
10985 	void *arg;
10986 {
10987 
10988 	/*
10989 	 * The callout_ API has acquired mtx and will hold it around this
10990 	 * function call.
10991 	 */
10992 	*stat_countp += 1;
10993 	wakeup_one(&proc_waiting);
10994 	if (proc_waiting > 0)
10995 		callout_reset(&softdep_callout, tickdelay > 2 ? tickdelay : 2,
10996 		    pause_timer, 0);
10997 }
10998 
10999 /*
11000  * Flush out a directory with at least one removal dependency in an effort to
11001  * reduce the number of dirrem, freefile, and freeblks dependency structures.
11002  */
11003 static void
11004 clear_remove(td)
11005 	struct thread *td;
11006 {
11007 	struct pagedep_hashhead *pagedephd;
11008 	struct pagedep *pagedep;
11009 	static int next = 0;
11010 	struct mount *mp;
11011 	struct vnode *vp;
11012 	struct bufobj *bo;
11013 	int error, cnt;
11014 	ino_t ino;
11015 
11016 	mtx_assert(&lk, MA_OWNED);
11017 
11018 	for (cnt = 0; cnt < pagedep_hash; cnt++) {
11019 		pagedephd = &pagedep_hashtbl[next++];
11020 		if (next >= pagedep_hash)
11021 			next = 0;
11022 		LIST_FOREACH(pagedep, pagedephd, pd_hash) {
11023 			if (LIST_EMPTY(&pagedep->pd_dirremhd))
11024 				continue;
11025 			mp = pagedep->pd_list.wk_mp;
11026 			ino = pagedep->pd_ino;
11027 			if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
11028 				continue;
11029 			FREE_LOCK(&lk);
11030 
11031 			/*
11032 			 * Let unmount clear deps
11033 			 */
11034 			error = vfs_busy(mp, MBF_NOWAIT);
11035 			if (error != 0)
11036 				goto finish_write;
11037 			error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
11038 			     FFSV_FORCEINSMQ);
11039 			vfs_unbusy(mp);
11040 			if (error != 0) {
11041 				softdep_error("clear_remove: vget", error);
11042 				goto finish_write;
11043 			}
11044 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT)))
11045 				softdep_error("clear_remove: fsync", error);
11046 			bo = &vp->v_bufobj;
11047 			BO_LOCK(bo);
11048 			drain_output(vp);
11049 			BO_UNLOCK(bo);
11050 			vput(vp);
11051 		finish_write:
11052 			vn_finished_write(mp);
11053 			ACQUIRE_LOCK(&lk);
11054 			return;
11055 		}
11056 	}
11057 }
11058 
11059 /*
11060  * Clear out a block of dirty inodes in an effort to reduce
11061  * the number of inodedep dependency structures.
11062  */
11063 static void
11064 clear_inodedeps(td)
11065 	struct thread *td;
11066 {
11067 	struct inodedep_hashhead *inodedephd;
11068 	struct inodedep *inodedep;
11069 	static int next = 0;
11070 	struct mount *mp;
11071 	struct vnode *vp;
11072 	struct fs *fs;
11073 	int error, cnt;
11074 	ino_t firstino, lastino, ino;
11075 
11076 	mtx_assert(&lk, MA_OWNED);
11077 	/*
11078 	 * Pick a random inode dependency to be cleared.
11079 	 * We will then gather up all the inodes in its block
11080 	 * that have dependencies and flush them out.
11081 	 */
11082 	for (cnt = 0; cnt < inodedep_hash; cnt++) {
11083 		inodedephd = &inodedep_hashtbl[next++];
11084 		if (next >= inodedep_hash)
11085 			next = 0;
11086 		if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
11087 			break;
11088 	}
11089 	if (inodedep == NULL)
11090 		return;
11091 	fs = inodedep->id_fs;
11092 	mp = inodedep->id_list.wk_mp;
11093 	/*
11094 	 * Find the last inode in the block with dependencies.
11095 	 */
11096 	firstino = inodedep->id_ino & ~(INOPB(fs) - 1);
11097 	for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
11098 		if (inodedep_lookup(mp, lastino, 0, &inodedep) != 0)
11099 			break;
11100 	/*
11101 	 * Asynchronously push all but the last inode with dependencies.
11102 	 * Synchronously push the last inode with dependencies to ensure
11103 	 * that the inode block gets written to free up the inodedeps.
11104 	 */
11105 	for (ino = firstino; ino <= lastino; ino++) {
11106 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
11107 			continue;
11108 		if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
11109 			continue;
11110 		FREE_LOCK(&lk);
11111 		error = vfs_busy(mp, MBF_NOWAIT); /* Let unmount clear deps */
11112 		if (error != 0) {
11113 			vn_finished_write(mp);
11114 			ACQUIRE_LOCK(&lk);
11115 			return;
11116 		}
11117 		if ((error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
11118 		    FFSV_FORCEINSMQ)) != 0) {
11119 			softdep_error("clear_inodedeps: vget", error);
11120 			vfs_unbusy(mp);
11121 			vn_finished_write(mp);
11122 			ACQUIRE_LOCK(&lk);
11123 			return;
11124 		}
11125 		vfs_unbusy(mp);
11126 		if (ino == lastino) {
11127 			if ((error = ffs_syncvnode(vp, MNT_WAIT)))
11128 				softdep_error("clear_inodedeps: fsync1", error);
11129 		} else {
11130 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT)))
11131 				softdep_error("clear_inodedeps: fsync2", error);
11132 			BO_LOCK(&vp->v_bufobj);
11133 			drain_output(vp);
11134 			BO_UNLOCK(&vp->v_bufobj);
11135 		}
11136 		vput(vp);
11137 		vn_finished_write(mp);
11138 		ACQUIRE_LOCK(&lk);
11139 	}
11140 }
11141 
11142 /*
11143  * Function to determine if the buffer has outstanding dependencies
11144  * that will cause a roll-back if the buffer is written. If wantcount
11145  * is set, return number of dependencies, otherwise just yes or no.
11146  */
11147 static int
11148 softdep_count_dependencies(bp, wantcount)
11149 	struct buf *bp;
11150 	int wantcount;
11151 {
11152 	struct worklist *wk;
11153 	struct bmsafemap *bmsafemap;
11154 	struct inodedep *inodedep;
11155 	struct indirdep *indirdep;
11156 	struct freeblks *freeblks;
11157 	struct allocindir *aip;
11158 	struct pagedep *pagedep;
11159 	struct dirrem *dirrem;
11160 	struct newblk *newblk;
11161 	struct mkdir *mkdir;
11162 	struct diradd *dap;
11163 	int i, retval;
11164 
11165 	retval = 0;
11166 	ACQUIRE_LOCK(&lk);
11167 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
11168 		switch (wk->wk_type) {
11169 
11170 		case D_INODEDEP:
11171 			inodedep = WK_INODEDEP(wk);
11172 			if ((inodedep->id_state & DEPCOMPLETE) == 0) {
11173 				/* bitmap allocation dependency */
11174 				retval += 1;
11175 				if (!wantcount)
11176 					goto out;
11177 			}
11178 			if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
11179 				/* direct block pointer dependency */
11180 				retval += 1;
11181 				if (!wantcount)
11182 					goto out;
11183 			}
11184 			if (TAILQ_FIRST(&inodedep->id_extupdt)) {
11185 				/* direct block pointer dependency */
11186 				retval += 1;
11187 				if (!wantcount)
11188 					goto out;
11189 			}
11190 			if (TAILQ_FIRST(&inodedep->id_inoreflst)) {
11191 				/* Add reference dependency. */
11192 				retval += 1;
11193 				if (!wantcount)
11194 					goto out;
11195 			}
11196 			continue;
11197 
11198 		case D_INDIRDEP:
11199 			indirdep = WK_INDIRDEP(wk);
11200 
11201 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
11202 				/* indirect block pointer dependency */
11203 				retval += 1;
11204 				if (!wantcount)
11205 					goto out;
11206 			}
11207 			continue;
11208 
11209 		case D_PAGEDEP:
11210 			pagedep = WK_PAGEDEP(wk);
11211 			LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
11212 				if (LIST_FIRST(&dirrem->dm_jremrefhd)) {
11213 					/* Journal remove ref dependency. */
11214 					retval += 1;
11215 					if (!wantcount)
11216 						goto out;
11217 				}
11218 			}
11219 			for (i = 0; i < DAHASHSZ; i++) {
11220 
11221 				LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
11222 					/* directory entry dependency */
11223 					retval += 1;
11224 					if (!wantcount)
11225 						goto out;
11226 				}
11227 			}
11228 			continue;
11229 
11230 		case D_BMSAFEMAP:
11231 			bmsafemap = WK_BMSAFEMAP(wk);
11232 			if (LIST_FIRST(&bmsafemap->sm_jaddrefhd)) {
11233 				/* Add reference dependency. */
11234 				retval += 1;
11235 				if (!wantcount)
11236 					goto out;
11237 			}
11238 			if (LIST_FIRST(&bmsafemap->sm_jnewblkhd)) {
11239 				/* Allocate block dependency. */
11240 				retval += 1;
11241 				if (!wantcount)
11242 					goto out;
11243 			}
11244 			continue;
11245 
11246 		case D_FREEBLKS:
11247 			freeblks = WK_FREEBLKS(wk);
11248 			if (LIST_FIRST(&freeblks->fb_jfreeblkhd)) {
11249 				/* Freeblk journal dependency. */
11250 				retval += 1;
11251 				if (!wantcount)
11252 					goto out;
11253 			}
11254 			continue;
11255 
11256 		case D_ALLOCDIRECT:
11257 		case D_ALLOCINDIR:
11258 			newblk = WK_NEWBLK(wk);
11259 			if (newblk->nb_jnewblk) {
11260 				/* Journal allocate dependency. */
11261 				retval += 1;
11262 				if (!wantcount)
11263 					goto out;
11264 			}
11265 			continue;
11266 
11267 		case D_MKDIR:
11268 			mkdir = WK_MKDIR(wk);
11269 			if (mkdir->md_jaddref) {
11270 				/* Journal reference dependency. */
11271 				retval += 1;
11272 				if (!wantcount)
11273 					goto out;
11274 			}
11275 			continue;
11276 
11277 		case D_FREEWORK:
11278 		case D_FREEDEP:
11279 		case D_JSEGDEP:
11280 		case D_JSEG:
11281 		case D_SBDEP:
11282 			/* never a dependency on these blocks */
11283 			continue;
11284 
11285 		default:
11286 			panic("softdep_count_dependencies: Unexpected type %s",
11287 			    TYPENAME(wk->wk_type));
11288 			/* NOTREACHED */
11289 		}
11290 	}
11291 out:
11292 	FREE_LOCK(&lk);
11293 	return retval;
11294 }
11295 
11296 /*
11297  * Acquire exclusive access to a buffer.
11298  * Must be called with a locked mtx parameter.
11299  * Return acquired buffer or NULL on failure.
11300  */
11301 static struct buf *
11302 getdirtybuf(bp, mtx, waitfor)
11303 	struct buf *bp;
11304 	struct mtx *mtx;
11305 	int waitfor;
11306 {
11307 	int error;
11308 
11309 	mtx_assert(mtx, MA_OWNED);
11310 	if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0) {
11311 		if (waitfor != MNT_WAIT)
11312 			return (NULL);
11313 		error = BUF_LOCK(bp,
11314 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, mtx);
11315 		/*
11316 		 * Even if we sucessfully acquire bp here, we have dropped
11317 		 * mtx, which may violates our guarantee.
11318 		 */
11319 		if (error == 0)
11320 			BUF_UNLOCK(bp);
11321 		else if (error != ENOLCK)
11322 			panic("getdirtybuf: inconsistent lock: %d", error);
11323 		mtx_lock(mtx);
11324 		return (NULL);
11325 	}
11326 	if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
11327 		if (mtx == &lk && waitfor == MNT_WAIT) {
11328 			mtx_unlock(mtx);
11329 			BO_LOCK(bp->b_bufobj);
11330 			BUF_UNLOCK(bp);
11331 			if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
11332 				bp->b_vflags |= BV_BKGRDWAIT;
11333 				msleep(&bp->b_xflags, BO_MTX(bp->b_bufobj),
11334 				       PRIBIO | PDROP, "getbuf", 0);
11335 			} else
11336 				BO_UNLOCK(bp->b_bufobj);
11337 			mtx_lock(mtx);
11338 			return (NULL);
11339 		}
11340 		BUF_UNLOCK(bp);
11341 		if (waitfor != MNT_WAIT)
11342 			return (NULL);
11343 		/*
11344 		 * The mtx argument must be bp->b_vp's mutex in
11345 		 * this case.
11346 		 */
11347 #ifdef	DEBUG_VFS_LOCKS
11348 		if (bp->b_vp->v_type != VCHR)
11349 			ASSERT_BO_LOCKED(bp->b_bufobj);
11350 #endif
11351 		bp->b_vflags |= BV_BKGRDWAIT;
11352 		msleep(&bp->b_xflags, mtx, PRIBIO, "getbuf", 0);
11353 		return (NULL);
11354 	}
11355 	if ((bp->b_flags & B_DELWRI) == 0) {
11356 		BUF_UNLOCK(bp);
11357 		return (NULL);
11358 	}
11359 	bremfree(bp);
11360 	return (bp);
11361 }
11362 
11363 
11364 /*
11365  * Check if it is safe to suspend the file system now.  On entry,
11366  * the vnode interlock for devvp should be held.  Return 0 with
11367  * the mount interlock held if the file system can be suspended now,
11368  * otherwise return EAGAIN with the mount interlock held.
11369  */
11370 int
11371 softdep_check_suspend(struct mount *mp,
11372 		      struct vnode *devvp,
11373 		      int softdep_deps,
11374 		      int softdep_accdeps,
11375 		      int secondary_writes,
11376 		      int secondary_accwrites)
11377 {
11378 	struct bufobj *bo;
11379 	struct ufsmount *ump;
11380 	int error;
11381 
11382 	ump = VFSTOUFS(mp);
11383 	bo = &devvp->v_bufobj;
11384 	ASSERT_BO_LOCKED(bo);
11385 
11386 	for (;;) {
11387 		if (!TRY_ACQUIRE_LOCK(&lk)) {
11388 			BO_UNLOCK(bo);
11389 			ACQUIRE_LOCK(&lk);
11390 			FREE_LOCK(&lk);
11391 			BO_LOCK(bo);
11392 			continue;
11393 		}
11394 		MNT_ILOCK(mp);
11395 		if (mp->mnt_secondary_writes != 0) {
11396 			FREE_LOCK(&lk);
11397 			BO_UNLOCK(bo);
11398 			msleep(&mp->mnt_secondary_writes,
11399 			       MNT_MTX(mp),
11400 			       (PUSER - 1) | PDROP, "secwr", 0);
11401 			BO_LOCK(bo);
11402 			continue;
11403 		}
11404 		break;
11405 	}
11406 
11407 	/*
11408 	 * Reasons for needing more work before suspend:
11409 	 * - Dirty buffers on devvp.
11410 	 * - Softdep activity occurred after start of vnode sync loop
11411 	 * - Secondary writes occurred after start of vnode sync loop
11412 	 */
11413 	error = 0;
11414 	if (bo->bo_numoutput > 0 ||
11415 	    bo->bo_dirty.bv_cnt > 0 ||
11416 	    softdep_deps != 0 ||
11417 	    ump->softdep_deps != 0 ||
11418 	    softdep_accdeps != ump->softdep_accdeps ||
11419 	    secondary_writes != 0 ||
11420 	    mp->mnt_secondary_writes != 0 ||
11421 	    secondary_accwrites != mp->mnt_secondary_accwrites)
11422 		error = EAGAIN;
11423 	FREE_LOCK(&lk);
11424 	BO_UNLOCK(bo);
11425 	return (error);
11426 }
11427 
11428 
11429 /*
11430  * Get the number of dependency structures for the file system, both
11431  * the current number and the total number allocated.  These will
11432  * later be used to detect that softdep processing has occurred.
11433  */
11434 void
11435 softdep_get_depcounts(struct mount *mp,
11436 		      int *softdep_depsp,
11437 		      int *softdep_accdepsp)
11438 {
11439 	struct ufsmount *ump;
11440 
11441 	ump = VFSTOUFS(mp);
11442 	ACQUIRE_LOCK(&lk);
11443 	*softdep_depsp = ump->softdep_deps;
11444 	*softdep_accdepsp = ump->softdep_accdeps;
11445 	FREE_LOCK(&lk);
11446 }
11447 
11448 /*
11449  * Wait for pending output on a vnode to complete.
11450  * Must be called with vnode lock and interlock locked.
11451  *
11452  * XXX: Should just be a call to bufobj_wwait().
11453  */
11454 static void
11455 drain_output(vp)
11456 	struct vnode *vp;
11457 {
11458 	struct bufobj *bo;
11459 
11460 	bo = &vp->v_bufobj;
11461 	ASSERT_VOP_LOCKED(vp, "drain_output");
11462 	ASSERT_BO_LOCKED(bo);
11463 
11464 	while (bo->bo_numoutput) {
11465 		bo->bo_flag |= BO_WWAIT;
11466 		msleep((caddr_t)&bo->bo_numoutput,
11467 		    BO_MTX(bo), PRIBIO + 1, "drainvp", 0);
11468 	}
11469 }
11470 
11471 /*
11472  * Called whenever a buffer that is being invalidated or reallocated
11473  * contains dependencies. This should only happen if an I/O error has
11474  * occurred. The routine is called with the buffer locked.
11475  */
11476 static void
11477 softdep_deallocate_dependencies(bp)
11478 	struct buf *bp;
11479 {
11480 
11481 	if ((bp->b_ioflags & BIO_ERROR) == 0)
11482 		panic("softdep_deallocate_dependencies: dangling deps");
11483 	softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntonname, bp->b_error);
11484 	panic("softdep_deallocate_dependencies: unrecovered I/O error");
11485 }
11486 
11487 /*
11488  * Function to handle asynchronous write errors in the filesystem.
11489  */
11490 static void
11491 softdep_error(func, error)
11492 	char *func;
11493 	int error;
11494 {
11495 
11496 	/* XXX should do something better! */
11497 	printf("%s: got error %d while accessing filesystem\n", func, error);
11498 }
11499 
11500 #ifdef DDB
11501 
11502 static void
11503 inodedep_print(struct inodedep *inodedep, int verbose)
11504 {
11505 	db_printf("%p fs %p st %x ino %jd inoblk %jd delta %d nlink %d"
11506 	    " saveino %p\n",
11507 	    inodedep, inodedep->id_fs, inodedep->id_state,
11508 	    (intmax_t)inodedep->id_ino,
11509 	    (intmax_t)fsbtodb(inodedep->id_fs,
11510 	    ino_to_fsba(inodedep->id_fs, inodedep->id_ino)),
11511 	    inodedep->id_nlinkdelta, inodedep->id_savednlink,
11512 	    inodedep->id_savedino1);
11513 
11514 	if (verbose == 0)
11515 		return;
11516 
11517 	db_printf("\tpendinghd %p, bufwait %p, inowait %p, inoreflst %p, "
11518 	    "mkdiradd %p\n",
11519 	    LIST_FIRST(&inodedep->id_pendinghd),
11520 	    LIST_FIRST(&inodedep->id_bufwait),
11521 	    LIST_FIRST(&inodedep->id_inowait),
11522 	    TAILQ_FIRST(&inodedep->id_inoreflst),
11523 	    inodedep->id_mkdiradd);
11524 	db_printf("\tinoupdt %p, newinoupdt %p, extupdt %p, newextupdt %p\n",
11525 	    TAILQ_FIRST(&inodedep->id_inoupdt),
11526 	    TAILQ_FIRST(&inodedep->id_newinoupdt),
11527 	    TAILQ_FIRST(&inodedep->id_extupdt),
11528 	    TAILQ_FIRST(&inodedep->id_newextupdt));
11529 }
11530 
11531 DB_SHOW_COMMAND(inodedep, db_show_inodedep)
11532 {
11533 
11534 	if (have_addr == 0) {
11535 		db_printf("Address required\n");
11536 		return;
11537 	}
11538 	inodedep_print((struct inodedep*)addr, 1);
11539 }
11540 
11541 DB_SHOW_COMMAND(inodedeps, db_show_inodedeps)
11542 {
11543 	struct inodedep_hashhead *inodedephd;
11544 	struct inodedep *inodedep;
11545 	struct fs *fs;
11546 	int cnt;
11547 
11548 	fs = have_addr ? (struct fs *)addr : NULL;
11549 	for (cnt = 0; cnt < inodedep_hash; cnt++) {
11550 		inodedephd = &inodedep_hashtbl[cnt];
11551 		LIST_FOREACH(inodedep, inodedephd, id_hash) {
11552 			if (fs != NULL && fs != inodedep->id_fs)
11553 				continue;
11554 			inodedep_print(inodedep, 0);
11555 		}
11556 	}
11557 }
11558 
11559 DB_SHOW_COMMAND(worklist, db_show_worklist)
11560 {
11561 	struct worklist *wk;
11562 
11563 	if (have_addr == 0) {
11564 		db_printf("Address required\n");
11565 		return;
11566 	}
11567 	wk = (struct worklist *)addr;
11568 	printf("worklist: %p type %s state 0x%X\n",
11569 	    wk, TYPENAME(wk->wk_type), wk->wk_state);
11570 }
11571 
11572 DB_SHOW_COMMAND(workhead, db_show_workhead)
11573 {
11574 	struct workhead *wkhd;
11575 	struct worklist *wk;
11576 	int i;
11577 
11578 	if (have_addr == 0) {
11579 		db_printf("Address required\n");
11580 		return;
11581 	}
11582 	wkhd = (struct workhead *)addr;
11583 	wk = LIST_FIRST(wkhd);
11584 	for (i = 0; i < 100 && wk != NULL; i++, wk = LIST_NEXT(wk, wk_list))
11585 		db_printf("worklist: %p type %s state 0x%X",
11586 		    wk, TYPENAME(wk->wk_type), wk->wk_state);
11587 	if (i == 100)
11588 		db_printf("workhead overflow");
11589 	printf("\n");
11590 }
11591 
11592 
11593 DB_SHOW_COMMAND(mkdirs, db_show_mkdirs)
11594 {
11595 	struct jaddref *jaddref;
11596 	struct diradd *diradd;
11597 	struct mkdir *mkdir;
11598 
11599 	LIST_FOREACH(mkdir, &mkdirlisthd, md_mkdirs) {
11600 		diradd = mkdir->md_diradd;
11601 		db_printf("mkdir: %p state 0x%X dap %p state 0x%X",
11602 		    mkdir, mkdir->md_state, diradd, diradd->da_state);
11603 		if ((jaddref = mkdir->md_jaddref) != NULL)
11604 			db_printf(" jaddref %p jaddref state 0x%X",
11605 			    jaddref, jaddref->ja_state);
11606 		db_printf("\n");
11607 	}
11608 }
11609 
11610 #endif /* DDB */
11611 
11612 #endif /* SOFTUPDATES */
11613