ffs_softdep.c revision 268077
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: stable/10/sys/ufs/ffs/ffs_softdep.c 268077 2014-07-01 06:59:23Z scottl $");
44
45#include "opt_ffs.h"
46#include "opt_quota.h"
47#include "opt_ddb.h"
48
49/*
50 * For now we want the safety net that the DEBUG flag provides.
51 */
52#ifndef DEBUG
53#define DEBUG
54#endif
55
56#include <sys/param.h>
57#include <sys/kernel.h>
58#include <sys/systm.h>
59#include <sys/bio.h>
60#include <sys/buf.h>
61#include <sys/kdb.h>
62#include <sys/kthread.h>
63#include <sys/ktr.h>
64#include <sys/limits.h>
65#include <sys/lock.h>
66#include <sys/malloc.h>
67#include <sys/mount.h>
68#include <sys/mutex.h>
69#include <sys/namei.h>
70#include <sys/priv.h>
71#include <sys/proc.h>
72#include <sys/rwlock.h>
73#include <sys/stat.h>
74#include <sys/sysctl.h>
75#include <sys/syslog.h>
76#include <sys/vnode.h>
77#include <sys/conf.h>
78
79#include <ufs/ufs/dir.h>
80#include <ufs/ufs/extattr.h>
81#include <ufs/ufs/quota.h>
82#include <ufs/ufs/inode.h>
83#include <ufs/ufs/ufsmount.h>
84#include <ufs/ffs/fs.h>
85#include <ufs/ffs/softdep.h>
86#include <ufs/ffs/ffs_extern.h>
87#include <ufs/ufs/ufs_extern.h>
88
89#include <vm/vm.h>
90#include <vm/vm_extern.h>
91#include <vm/vm_object.h>
92
93#include <geom/geom.h>
94
95#include <ddb/ddb.h>
96
97#define	KTR_SUJ	0	/* Define to KTR_SPARE. */
98
99#ifndef SOFTUPDATES
100
101int
102softdep_flushfiles(oldmnt, flags, td)
103	struct mount *oldmnt;
104	int flags;
105	struct thread *td;
106{
107
108	panic("softdep_flushfiles called");
109}
110
111int
112softdep_mount(devvp, mp, fs, cred)
113	struct vnode *devvp;
114	struct mount *mp;
115	struct fs *fs;
116	struct ucred *cred;
117{
118
119	return (0);
120}
121
122void
123softdep_initialize()
124{
125
126	return;
127}
128
129void
130softdep_uninitialize()
131{
132
133	return;
134}
135
136void
137softdep_unmount(mp)
138	struct mount *mp;
139{
140
141	panic("softdep_unmount called");
142}
143
144void
145softdep_setup_sbupdate(ump, fs, bp)
146	struct ufsmount *ump;
147	struct fs *fs;
148	struct buf *bp;
149{
150
151	panic("softdep_setup_sbupdate called");
152}
153
154void
155softdep_setup_inomapdep(bp, ip, newinum, mode)
156	struct buf *bp;
157	struct inode *ip;
158	ino_t newinum;
159	int mode;
160{
161
162	panic("softdep_setup_inomapdep called");
163}
164
165void
166softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
167	struct buf *bp;
168	struct mount *mp;
169	ufs2_daddr_t newblkno;
170	int frags;
171	int oldfrags;
172{
173
174	panic("softdep_setup_blkmapdep called");
175}
176
177void
178softdep_setup_allocdirect(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
179	struct inode *ip;
180	ufs_lbn_t lbn;
181	ufs2_daddr_t newblkno;
182	ufs2_daddr_t oldblkno;
183	long newsize;
184	long oldsize;
185	struct buf *bp;
186{
187
188	panic("softdep_setup_allocdirect called");
189}
190
191void
192softdep_setup_allocext(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
193	struct inode *ip;
194	ufs_lbn_t lbn;
195	ufs2_daddr_t newblkno;
196	ufs2_daddr_t oldblkno;
197	long newsize;
198	long oldsize;
199	struct buf *bp;
200{
201
202	panic("softdep_setup_allocext called");
203}
204
205void
206softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
207	struct inode *ip;
208	ufs_lbn_t lbn;
209	struct buf *bp;
210	int ptrno;
211	ufs2_daddr_t newblkno;
212	ufs2_daddr_t oldblkno;
213	struct buf *nbp;
214{
215
216	panic("softdep_setup_allocindir_page called");
217}
218
219void
220softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
221	struct buf *nbp;
222	struct inode *ip;
223	struct buf *bp;
224	int ptrno;
225	ufs2_daddr_t newblkno;
226{
227
228	panic("softdep_setup_allocindir_meta called");
229}
230
231void
232softdep_journal_freeblocks(ip, cred, length, flags)
233	struct inode *ip;
234	struct ucred *cred;
235	off_t length;
236	int flags;
237{
238
239	panic("softdep_journal_freeblocks called");
240}
241
242void
243softdep_journal_fsync(ip)
244	struct inode *ip;
245{
246
247	panic("softdep_journal_fsync called");
248}
249
250void
251softdep_setup_freeblocks(ip, length, flags)
252	struct inode *ip;
253	off_t length;
254	int flags;
255{
256
257	panic("softdep_setup_freeblocks called");
258}
259
260void
261softdep_freefile(pvp, ino, mode)
262		struct vnode *pvp;
263		ino_t ino;
264		int mode;
265{
266
267	panic("softdep_freefile called");
268}
269
270int
271softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
272	struct buf *bp;
273	struct inode *dp;
274	off_t diroffset;
275	ino_t newinum;
276	struct buf *newdirbp;
277	int isnewblk;
278{
279
280	panic("softdep_setup_directory_add called");
281}
282
283void
284softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
285	struct buf *bp;
286	struct inode *dp;
287	caddr_t base;
288	caddr_t oldloc;
289	caddr_t newloc;
290	int entrysize;
291{
292
293	panic("softdep_change_directoryentry_offset called");
294}
295
296void
297softdep_setup_remove(bp, dp, ip, isrmdir)
298	struct buf *bp;
299	struct inode *dp;
300	struct inode *ip;
301	int isrmdir;
302{
303
304	panic("softdep_setup_remove called");
305}
306
307void
308softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
309	struct buf *bp;
310	struct inode *dp;
311	struct inode *ip;
312	ino_t newinum;
313	int isrmdir;
314{
315
316	panic("softdep_setup_directory_change called");
317}
318
319void
320softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
321	struct mount *mp;
322	struct buf *bp;
323	ufs2_daddr_t blkno;
324	int frags;
325	struct workhead *wkhd;
326{
327
328	panic("%s called", __FUNCTION__);
329}
330
331void
332softdep_setup_inofree(mp, bp, ino, wkhd)
333	struct mount *mp;
334	struct buf *bp;
335	ino_t ino;
336	struct workhead *wkhd;
337{
338
339	panic("%s called", __FUNCTION__);
340}
341
342void
343softdep_setup_unlink(dp, ip)
344	struct inode *dp;
345	struct inode *ip;
346{
347
348	panic("%s called", __FUNCTION__);
349}
350
351void
352softdep_setup_link(dp, ip)
353	struct inode *dp;
354	struct inode *ip;
355{
356
357	panic("%s called", __FUNCTION__);
358}
359
360void
361softdep_revert_link(dp, ip)
362	struct inode *dp;
363	struct inode *ip;
364{
365
366	panic("%s called", __FUNCTION__);
367}
368
369void
370softdep_setup_rmdir(dp, ip)
371	struct inode *dp;
372	struct inode *ip;
373{
374
375	panic("%s called", __FUNCTION__);
376}
377
378void
379softdep_revert_rmdir(dp, ip)
380	struct inode *dp;
381	struct inode *ip;
382{
383
384	panic("%s called", __FUNCTION__);
385}
386
387void
388softdep_setup_create(dp, ip)
389	struct inode *dp;
390	struct inode *ip;
391{
392
393	panic("%s called", __FUNCTION__);
394}
395
396void
397softdep_revert_create(dp, ip)
398	struct inode *dp;
399	struct inode *ip;
400{
401
402	panic("%s called", __FUNCTION__);
403}
404
405void
406softdep_setup_mkdir(dp, ip)
407	struct inode *dp;
408	struct inode *ip;
409{
410
411	panic("%s called", __FUNCTION__);
412}
413
414void
415softdep_revert_mkdir(dp, ip)
416	struct inode *dp;
417	struct inode *ip;
418{
419
420	panic("%s called", __FUNCTION__);
421}
422
423void
424softdep_setup_dotdot_link(dp, ip)
425	struct inode *dp;
426	struct inode *ip;
427{
428
429	panic("%s called", __FUNCTION__);
430}
431
432int
433softdep_prealloc(vp, waitok)
434	struct vnode *vp;
435	int waitok;
436{
437
438	panic("%s called", __FUNCTION__);
439}
440
441int
442softdep_journal_lookup(mp, vpp)
443	struct mount *mp;
444	struct vnode **vpp;
445{
446
447	return (ENOENT);
448}
449
450void
451softdep_change_linkcnt(ip)
452	struct inode *ip;
453{
454
455	panic("softdep_change_linkcnt called");
456}
457
458void
459softdep_load_inodeblock(ip)
460	struct inode *ip;
461{
462
463	panic("softdep_load_inodeblock called");
464}
465
466void
467softdep_update_inodeblock(ip, bp, waitfor)
468	struct inode *ip;
469	struct buf *bp;
470	int waitfor;
471{
472
473	panic("softdep_update_inodeblock called");
474}
475
476int
477softdep_fsync(vp)
478	struct vnode *vp;	/* the "in_core" copy of the inode */
479{
480
481	return (0);
482}
483
484void
485softdep_fsync_mountdev(vp)
486	struct vnode *vp;
487{
488
489	return;
490}
491
492int
493softdep_flushworklist(oldmnt, countp, td)
494	struct mount *oldmnt;
495	int *countp;
496	struct thread *td;
497{
498
499	*countp = 0;
500	return (0);
501}
502
503int
504softdep_sync_metadata(struct vnode *vp)
505{
506
507	panic("softdep_sync_metadata called");
508}
509
510int
511softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
512{
513
514	panic("softdep_sync_buf called");
515}
516
517int
518softdep_slowdown(vp)
519	struct vnode *vp;
520{
521
522	panic("softdep_slowdown called");
523}
524
525int
526softdep_request_cleanup(fs, vp, cred, resource)
527	struct fs *fs;
528	struct vnode *vp;
529	struct ucred *cred;
530	int resource;
531{
532
533	return (0);
534}
535
536int
537softdep_check_suspend(struct mount *mp,
538		      struct vnode *devvp,
539		      int softdep_depcnt,
540		      int softdep_accdepcnt,
541		      int secondary_writes,
542		      int secondary_accwrites)
543{
544	struct bufobj *bo;
545	int error;
546
547	(void) softdep_depcnt,
548	(void) softdep_accdepcnt;
549
550	bo = &devvp->v_bufobj;
551	ASSERT_BO_WLOCKED(bo);
552
553	MNT_ILOCK(mp);
554	while (mp->mnt_secondary_writes != 0) {
555		BO_UNLOCK(bo);
556		msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
557		    (PUSER - 1) | PDROP, "secwr", 0);
558		BO_LOCK(bo);
559		MNT_ILOCK(mp);
560	}
561
562	/*
563	 * Reasons for needing more work before suspend:
564	 * - Dirty buffers on devvp.
565	 * - Secondary writes occurred after start of vnode sync loop
566	 */
567	error = 0;
568	if (bo->bo_numoutput > 0 ||
569	    bo->bo_dirty.bv_cnt > 0 ||
570	    secondary_writes != 0 ||
571	    mp->mnt_secondary_writes != 0 ||
572	    secondary_accwrites != mp->mnt_secondary_accwrites)
573		error = EAGAIN;
574	BO_UNLOCK(bo);
575	return (error);
576}
577
578void
579softdep_get_depcounts(struct mount *mp,
580		      int *softdepactivep,
581		      int *softdepactiveaccp)
582{
583	(void) mp;
584	*softdepactivep = 0;
585	*softdepactiveaccp = 0;
586}
587
588void
589softdep_buf_append(bp, wkhd)
590	struct buf *bp;
591	struct workhead *wkhd;
592{
593
594	panic("softdep_buf_appendwork called");
595}
596
597void
598softdep_inode_append(ip, cred, wkhd)
599	struct inode *ip;
600	struct ucred *cred;
601	struct workhead *wkhd;
602{
603
604	panic("softdep_inode_appendwork called");
605}
606
607void
608softdep_freework(wkhd)
609	struct workhead *wkhd;
610{
611
612	panic("softdep_freework called");
613}
614
615#else
616
617FEATURE(softupdates, "FFS soft-updates support");
618
619static SYSCTL_NODE(_debug, OID_AUTO, softdep, CTLFLAG_RW, 0,
620    "soft updates stats");
621static SYSCTL_NODE(_debug_softdep, OID_AUTO, total, CTLFLAG_RW, 0,
622    "total dependencies allocated");
623static SYSCTL_NODE(_debug_softdep, OID_AUTO, highuse, CTLFLAG_RW, 0,
624    "high use dependencies allocated");
625static SYSCTL_NODE(_debug_softdep, OID_AUTO, current, CTLFLAG_RW, 0,
626    "current dependencies allocated");
627static SYSCTL_NODE(_debug_softdep, OID_AUTO, write, CTLFLAG_RW, 0,
628    "current dependencies written");
629
630unsigned long dep_current[D_LAST + 1];
631unsigned long dep_highuse[D_LAST + 1];
632unsigned long dep_total[D_LAST + 1];
633unsigned long dep_write[D_LAST + 1];
634
635#define	SOFTDEP_TYPE(type, str, long)					\
636    static MALLOC_DEFINE(M_ ## type, #str, long);			\
637    SYSCTL_ULONG(_debug_softdep_total, OID_AUTO, str, CTLFLAG_RD,	\
638	&dep_total[D_ ## type], 0, "");					\
639    SYSCTL_ULONG(_debug_softdep_current, OID_AUTO, str, CTLFLAG_RD, 	\
640	&dep_current[D_ ## type], 0, "");				\
641    SYSCTL_ULONG(_debug_softdep_highuse, OID_AUTO, str, CTLFLAG_RD, 	\
642	&dep_highuse[D_ ## type], 0, "");				\
643    SYSCTL_ULONG(_debug_softdep_write, OID_AUTO, str, CTLFLAG_RD, 	\
644	&dep_write[D_ ## type], 0, "");
645
646SOFTDEP_TYPE(PAGEDEP, pagedep, "File page dependencies");
647SOFTDEP_TYPE(INODEDEP, inodedep, "Inode dependencies");
648SOFTDEP_TYPE(BMSAFEMAP, bmsafemap,
649    "Block or frag allocated from cyl group map");
650SOFTDEP_TYPE(NEWBLK, newblk, "New block or frag allocation dependency");
651SOFTDEP_TYPE(ALLOCDIRECT, allocdirect, "Block or frag dependency for an inode");
652SOFTDEP_TYPE(INDIRDEP, indirdep, "Indirect block dependencies");
653SOFTDEP_TYPE(ALLOCINDIR, allocindir, "Block dependency for an indirect block");
654SOFTDEP_TYPE(FREEFRAG, freefrag, "Previously used frag for an inode");
655SOFTDEP_TYPE(FREEBLKS, freeblks, "Blocks freed from an inode");
656SOFTDEP_TYPE(FREEFILE, freefile, "Inode deallocated");
657SOFTDEP_TYPE(DIRADD, diradd, "New directory entry");
658SOFTDEP_TYPE(MKDIR, mkdir, "New directory");
659SOFTDEP_TYPE(DIRREM, dirrem, "Directory entry deleted");
660SOFTDEP_TYPE(NEWDIRBLK, newdirblk, "Unclaimed new directory block");
661SOFTDEP_TYPE(FREEWORK, freework, "free an inode block");
662SOFTDEP_TYPE(FREEDEP, freedep, "track a block free");
663SOFTDEP_TYPE(JADDREF, jaddref, "Journal inode ref add");
664SOFTDEP_TYPE(JREMREF, jremref, "Journal inode ref remove");
665SOFTDEP_TYPE(JMVREF, jmvref, "Journal inode ref move");
666SOFTDEP_TYPE(JNEWBLK, jnewblk, "Journal new block");
667SOFTDEP_TYPE(JFREEBLK, jfreeblk, "Journal free block");
668SOFTDEP_TYPE(JFREEFRAG, jfreefrag, "Journal free frag");
669SOFTDEP_TYPE(JSEG, jseg, "Journal segment");
670SOFTDEP_TYPE(JSEGDEP, jsegdep, "Journal segment complete");
671SOFTDEP_TYPE(SBDEP, sbdep, "Superblock write dependency");
672SOFTDEP_TYPE(JTRUNC, jtrunc, "Journal inode truncation");
673SOFTDEP_TYPE(JFSYNC, jfsync, "Journal fsync complete");
674
675static MALLOC_DEFINE(M_SENTINEL, "sentinel", "Worklist sentinel");
676
677static MALLOC_DEFINE(M_SAVEDINO, "savedino", "Saved inodes");
678static MALLOC_DEFINE(M_JBLOCKS, "jblocks", "Journal block locations");
679static MALLOC_DEFINE(M_MOUNTDATA, "softdep", "Softdep per-mount data");
680
681#define M_SOFTDEP_FLAGS	(M_WAITOK)
682
683/*
684 * translate from workitem type to memory type
685 * MUST match the defines above, such that memtype[D_XXX] == M_XXX
686 */
687static struct malloc_type *memtype[] = {
688	M_PAGEDEP,
689	M_INODEDEP,
690	M_BMSAFEMAP,
691	M_NEWBLK,
692	M_ALLOCDIRECT,
693	M_INDIRDEP,
694	M_ALLOCINDIR,
695	M_FREEFRAG,
696	M_FREEBLKS,
697	M_FREEFILE,
698	M_DIRADD,
699	M_MKDIR,
700	M_DIRREM,
701	M_NEWDIRBLK,
702	M_FREEWORK,
703	M_FREEDEP,
704	M_JADDREF,
705	M_JREMREF,
706	M_JMVREF,
707	M_JNEWBLK,
708	M_JFREEBLK,
709	M_JFREEFRAG,
710	M_JSEG,
711	M_JSEGDEP,
712	M_SBDEP,
713	M_JTRUNC,
714	M_JFSYNC,
715	M_SENTINEL
716};
717
718#define DtoM(type) (memtype[type])
719
720/*
721 * Names of malloc types.
722 */
723#define TYPENAME(type)  \
724	((unsigned)(type) <= D_LAST ? memtype[type]->ks_shortdesc : "???")
725/*
726 * End system adaptation definitions.
727 */
728
729#define	DOTDOT_OFFSET	offsetof(struct dirtemplate, dotdot_ino)
730#define	DOT_OFFSET	offsetof(struct dirtemplate, dot_ino)
731
732/*
733 * Internal function prototypes.
734 */
735static	void check_clear_deps(struct mount *);
736static	void softdep_error(char *, int);
737static	int softdep_process_worklist(struct mount *, int);
738static	int softdep_waitidle(struct mount *);
739static	void drain_output(struct vnode *);
740static	struct buf *getdirtybuf(struct buf *, struct rwlock *, int);
741static	void clear_remove(struct mount *);
742static	void clear_inodedeps(struct mount *);
743static	void unlinked_inodedep(struct mount *, struct inodedep *);
744static	void clear_unlinked_inodedep(struct inodedep *);
745static	struct inodedep *first_unlinked_inodedep(struct ufsmount *);
746static	int flush_pagedep_deps(struct vnode *, struct mount *,
747	    struct diraddhd *);
748static	int free_pagedep(struct pagedep *);
749static	int flush_newblk_dep(struct vnode *, struct mount *, ufs_lbn_t);
750static	int flush_inodedep_deps(struct vnode *, struct mount *, ino_t);
751static	int flush_deplist(struct allocdirectlst *, int, int *);
752static	int sync_cgs(struct mount *, int);
753static	int handle_written_filepage(struct pagedep *, struct buf *);
754static	int handle_written_sbdep(struct sbdep *, struct buf *);
755static	void initiate_write_sbdep(struct sbdep *);
756static	void diradd_inode_written(struct diradd *, struct inodedep *);
757static	int handle_written_indirdep(struct indirdep *, struct buf *,
758	    struct buf**);
759static	int handle_written_inodeblock(struct inodedep *, struct buf *);
760static	int jnewblk_rollforward(struct jnewblk *, struct fs *, struct cg *,
761	    uint8_t *);
762static	int handle_written_bmsafemap(struct bmsafemap *, struct buf *);
763static	void handle_written_jaddref(struct jaddref *);
764static	void handle_written_jremref(struct jremref *);
765static	void handle_written_jseg(struct jseg *, struct buf *);
766static	void handle_written_jnewblk(struct jnewblk *);
767static	void handle_written_jblkdep(struct jblkdep *);
768static	void handle_written_jfreefrag(struct jfreefrag *);
769static	void complete_jseg(struct jseg *);
770static	void complete_jsegs(struct jseg *);
771static	void jseg_write(struct ufsmount *ump, struct jseg *, uint8_t *);
772static	void jaddref_write(struct jaddref *, struct jseg *, uint8_t *);
773static	void jremref_write(struct jremref *, struct jseg *, uint8_t *);
774static	void jmvref_write(struct jmvref *, struct jseg *, uint8_t *);
775static	void jtrunc_write(struct jtrunc *, struct jseg *, uint8_t *);
776static	void jfsync_write(struct jfsync *, struct jseg *, uint8_t *data);
777static	void jnewblk_write(struct jnewblk *, struct jseg *, uint8_t *);
778static	void jfreeblk_write(struct jfreeblk *, struct jseg *, uint8_t *);
779static	void jfreefrag_write(struct jfreefrag *, struct jseg *, uint8_t *);
780static	inline void inoref_write(struct inoref *, struct jseg *,
781	    struct jrefrec *);
782static	void handle_allocdirect_partdone(struct allocdirect *,
783	    struct workhead *);
784static	struct jnewblk *cancel_newblk(struct newblk *, struct worklist *,
785	    struct workhead *);
786static	void indirdep_complete(struct indirdep *);
787static	int indirblk_lookup(struct mount *, ufs2_daddr_t);
788static	void indirblk_insert(struct freework *);
789static	void indirblk_remove(struct freework *);
790static	void handle_allocindir_partdone(struct allocindir *);
791static	void initiate_write_filepage(struct pagedep *, struct buf *);
792static	void initiate_write_indirdep(struct indirdep*, struct buf *);
793static	void handle_written_mkdir(struct mkdir *, int);
794static	int jnewblk_rollback(struct jnewblk *, struct fs *, struct cg *,
795	    uint8_t *);
796static	void initiate_write_bmsafemap(struct bmsafemap *, struct buf *);
797static	void initiate_write_inodeblock_ufs1(struct inodedep *, struct buf *);
798static	void initiate_write_inodeblock_ufs2(struct inodedep *, struct buf *);
799static	void handle_workitem_freefile(struct freefile *);
800static	int handle_workitem_remove(struct dirrem *, int);
801static	struct dirrem *newdirrem(struct buf *, struct inode *,
802	    struct inode *, int, struct dirrem **);
803static	struct indirdep *indirdep_lookup(struct mount *, struct inode *,
804	    struct buf *);
805static	void cancel_indirdep(struct indirdep *, struct buf *,
806	    struct freeblks *);
807static	void free_indirdep(struct indirdep *);
808static	void free_diradd(struct diradd *, struct workhead *);
809static	void merge_diradd(struct inodedep *, struct diradd *);
810static	void complete_diradd(struct diradd *);
811static	struct diradd *diradd_lookup(struct pagedep *, int);
812static	struct jremref *cancel_diradd_dotdot(struct inode *, struct dirrem *,
813	    struct jremref *);
814static	struct jremref *cancel_mkdir_dotdot(struct inode *, struct dirrem *,
815	    struct jremref *);
816static	void cancel_diradd(struct diradd *, struct dirrem *, struct jremref *,
817	    struct jremref *, struct jremref *);
818static	void dirrem_journal(struct dirrem *, struct jremref *, struct jremref *,
819	    struct jremref *);
820static	void cancel_allocindir(struct allocindir *, struct buf *bp,
821	    struct freeblks *, int);
822static	int setup_trunc_indir(struct freeblks *, struct inode *,
823	    ufs_lbn_t, ufs_lbn_t, ufs2_daddr_t);
824static	void complete_trunc_indir(struct freework *);
825static	void trunc_indirdep(struct indirdep *, struct freeblks *, struct buf *,
826	    int);
827static	void complete_mkdir(struct mkdir *);
828static	void free_newdirblk(struct newdirblk *);
829static	void free_jremref(struct jremref *);
830static	void free_jaddref(struct jaddref *);
831static	void free_jsegdep(struct jsegdep *);
832static	void free_jsegs(struct jblocks *);
833static	void rele_jseg(struct jseg *);
834static	void free_jseg(struct jseg *, struct jblocks *);
835static	void free_jnewblk(struct jnewblk *);
836static	void free_jblkdep(struct jblkdep *);
837static	void free_jfreefrag(struct jfreefrag *);
838static	void free_freedep(struct freedep *);
839static	void journal_jremref(struct dirrem *, struct jremref *,
840	    struct inodedep *);
841static	void cancel_jnewblk(struct jnewblk *, struct workhead *);
842static	int cancel_jaddref(struct jaddref *, struct inodedep *,
843	    struct workhead *);
844static	void cancel_jfreefrag(struct jfreefrag *);
845static	inline void setup_freedirect(struct freeblks *, struct inode *,
846	    int, int);
847static	inline void setup_freeext(struct freeblks *, struct inode *, int, int);
848static	inline void setup_freeindir(struct freeblks *, struct inode *, int,
849	    ufs_lbn_t, int);
850static	inline struct freeblks *newfreeblks(struct mount *, struct inode *);
851static	void freeblks_free(struct ufsmount *, struct freeblks *, int);
852static	void indir_trunc(struct freework *, ufs2_daddr_t, ufs_lbn_t);
853static	ufs2_daddr_t blkcount(struct fs *, ufs2_daddr_t, off_t);
854static	int trunc_check_buf(struct buf *, int *, ufs_lbn_t, int, int);
855static	void trunc_dependencies(struct inode *, struct freeblks *, ufs_lbn_t,
856	    int, int);
857static	void trunc_pages(struct inode *, off_t, ufs2_daddr_t, int);
858static 	int cancel_pagedep(struct pagedep *, struct freeblks *, int);
859static	int deallocate_dependencies(struct buf *, struct freeblks *, int);
860static	void newblk_freefrag(struct newblk*);
861static	void free_newblk(struct newblk *);
862static	void cancel_allocdirect(struct allocdirectlst *,
863	    struct allocdirect *, struct freeblks *);
864static	int check_inode_unwritten(struct inodedep *);
865static	int free_inodedep(struct inodedep *);
866static	void freework_freeblock(struct freework *);
867static	void freework_enqueue(struct freework *);
868static	int handle_workitem_freeblocks(struct freeblks *, int);
869static	int handle_complete_freeblocks(struct freeblks *, int);
870static	void handle_workitem_indirblk(struct freework *);
871static	void handle_written_freework(struct freework *);
872static	void merge_inode_lists(struct allocdirectlst *,struct allocdirectlst *);
873static	struct worklist *jnewblk_merge(struct worklist *, struct worklist *,
874	    struct workhead *);
875static	struct freefrag *setup_allocindir_phase2(struct buf *, struct inode *,
876	    struct inodedep *, struct allocindir *, ufs_lbn_t);
877static	struct allocindir *newallocindir(struct inode *, int, ufs2_daddr_t,
878	    ufs2_daddr_t, ufs_lbn_t);
879static	void handle_workitem_freefrag(struct freefrag *);
880static	struct freefrag *newfreefrag(struct inode *, ufs2_daddr_t, long,
881	    ufs_lbn_t);
882static	void allocdirect_merge(struct allocdirectlst *,
883	    struct allocdirect *, struct allocdirect *);
884static	struct freefrag *allocindir_merge(struct allocindir *,
885	    struct allocindir *);
886static	int bmsafemap_find(struct bmsafemap_hashhead *, int,
887	    struct bmsafemap **);
888static	struct bmsafemap *bmsafemap_lookup(struct mount *, struct buf *,
889	    int cg, struct bmsafemap *);
890static	int newblk_find(struct newblk_hashhead *, ufs2_daddr_t, int,
891	    struct newblk **);
892static	int newblk_lookup(struct mount *, ufs2_daddr_t, int, struct newblk **);
893static	int inodedep_find(struct inodedep_hashhead *, ino_t,
894	    struct inodedep **);
895static	int inodedep_lookup(struct mount *, ino_t, int, struct inodedep **);
896static	int pagedep_lookup(struct mount *, struct buf *bp, ino_t, ufs_lbn_t,
897	    int, struct pagedep **);
898static	int pagedep_find(struct pagedep_hashhead *, ino_t, ufs_lbn_t,
899	    struct pagedep **);
900static	void pause_timer(void *);
901static	int request_cleanup(struct mount *, int);
902static	int process_worklist_item(struct mount *, int, int);
903static	void process_removes(struct vnode *);
904static	void process_truncates(struct vnode *);
905static	void jwork_move(struct workhead *, struct workhead *);
906static	void jwork_insert(struct workhead *, struct jsegdep *);
907static	void add_to_worklist(struct worklist *, int);
908static	void wake_worklist(struct worklist *);
909static	void wait_worklist(struct worklist *, char *);
910static	void remove_from_worklist(struct worklist *);
911static	void softdep_flush(void);
912static	void softdep_flushjournal(struct mount *);
913static	int softdep_speedup(void);
914static	void worklist_speedup(struct mount *);
915static	int journal_mount(struct mount *, struct fs *, struct ucred *);
916static	void journal_unmount(struct ufsmount *);
917static	int journal_space(struct ufsmount *, int);
918static	void journal_suspend(struct ufsmount *);
919static	int journal_unsuspend(struct ufsmount *ump);
920static	void softdep_prelink(struct vnode *, struct vnode *);
921static	void add_to_journal(struct worklist *);
922static	void remove_from_journal(struct worklist *);
923static	void softdep_process_journal(struct mount *, struct worklist *, int);
924static	struct jremref *newjremref(struct dirrem *, struct inode *,
925	    struct inode *ip, off_t, nlink_t);
926static	struct jaddref *newjaddref(struct inode *, ino_t, off_t, int16_t,
927	    uint16_t);
928static	inline void newinoref(struct inoref *, ino_t, ino_t, off_t, nlink_t,
929	    uint16_t);
930static	inline struct jsegdep *inoref_jseg(struct inoref *);
931static	struct jmvref *newjmvref(struct inode *, ino_t, off_t, off_t);
932static	struct jfreeblk *newjfreeblk(struct freeblks *, ufs_lbn_t,
933	    ufs2_daddr_t, int);
934static	struct jtrunc *newjtrunc(struct freeblks *, off_t, int);
935static	void move_newblock_dep(struct jaddref *, struct inodedep *);
936static	void cancel_jfreeblk(struct freeblks *, ufs2_daddr_t);
937static	struct jfreefrag *newjfreefrag(struct freefrag *, struct inode *,
938	    ufs2_daddr_t, long, ufs_lbn_t);
939static	struct freework *newfreework(struct ufsmount *, struct freeblks *,
940	    struct freework *, ufs_lbn_t, ufs2_daddr_t, int, int, int);
941static	int jwait(struct worklist *, int);
942static	struct inodedep *inodedep_lookup_ip(struct inode *);
943static	int bmsafemap_backgroundwrite(struct bmsafemap *, struct buf *);
944static	struct freefile *handle_bufwait(struct inodedep *, struct workhead *);
945static	void handle_jwork(struct workhead *);
946static	struct mkdir *setup_newdir(struct diradd *, ino_t, ino_t, struct buf *,
947	    struct mkdir **);
948static	struct jblocks *jblocks_create(void);
949static	ufs2_daddr_t jblocks_alloc(struct jblocks *, int, int *);
950static	void jblocks_free(struct jblocks *, struct mount *, int);
951static	void jblocks_destroy(struct jblocks *);
952static	void jblocks_add(struct jblocks *, ufs2_daddr_t, int);
953
954/*
955 * Exported softdep operations.
956 */
957static	void softdep_disk_io_initiation(struct buf *);
958static	void softdep_disk_write_complete(struct buf *);
959static	void softdep_deallocate_dependencies(struct buf *);
960static	int softdep_count_dependencies(struct buf *bp, int);
961
962/*
963 * Global lock over all of soft updates.
964 */
965static struct rwlock lk;
966RW_SYSINIT(softdep_lock, &lk, "Softdep Lock");
967
968/*
969 * Allow per-filesystem soft-updates locking.
970 * For now all use the same global lock defined above.
971 */
972#define LOCK_PTR(ump)		((ump)->um_softdep->sd_fslock)
973#define TRY_ACQUIRE_LOCK(ump)	rw_try_wlock((ump)->um_softdep->sd_fslock)
974#define ACQUIRE_LOCK(ump)	rw_wlock((ump)->um_softdep->sd_fslock)
975#define FREE_LOCK(ump)		rw_wunlock((ump)->um_softdep->sd_fslock)
976#define LOCK_OWNED(ump)		rw_assert((ump)->um_softdep->sd_fslock, \
977				    RA_WLOCKED)
978
979#define	BUF_AREC(bp)		lockallowrecurse(&(bp)->b_lock)
980#define	BUF_NOREC(bp)		lockdisablerecurse(&(bp)->b_lock)
981
982/*
983 * Worklist queue management.
984 * These routines require that the lock be held.
985 */
986#ifndef /* NOT */ DEBUG
987#define WORKLIST_INSERT(head, item) do {	\
988	(item)->wk_state |= ONWORKLIST;		\
989	LIST_INSERT_HEAD(head, item, wk_list);	\
990} while (0)
991#define WORKLIST_REMOVE(item) do {		\
992	(item)->wk_state &= ~ONWORKLIST;	\
993	LIST_REMOVE(item, wk_list);		\
994} while (0)
995#define WORKLIST_INSERT_UNLOCKED	WORKLIST_INSERT
996#define WORKLIST_REMOVE_UNLOCKED	WORKLIST_REMOVE
997
998#else /* DEBUG */
999static	void worklist_insert(struct workhead *, struct worklist *, int);
1000static	void worklist_remove(struct worklist *, int);
1001
1002#define WORKLIST_INSERT(head, item) worklist_insert(head, item, 1)
1003#define WORKLIST_INSERT_UNLOCKED(head, item) worklist_insert(head, item, 0)
1004#define WORKLIST_REMOVE(item) worklist_remove(item, 1)
1005#define WORKLIST_REMOVE_UNLOCKED(item) worklist_remove(item, 0)
1006
1007static void
1008worklist_insert(head, item, locked)
1009	struct workhead *head;
1010	struct worklist *item;
1011	int locked;
1012{
1013
1014	if (locked)
1015		LOCK_OWNED(VFSTOUFS(item->wk_mp));
1016	if (item->wk_state & ONWORKLIST)
1017		panic("worklist_insert: %p %s(0x%X) already on list",
1018		    item, TYPENAME(item->wk_type), item->wk_state);
1019	item->wk_state |= ONWORKLIST;
1020	LIST_INSERT_HEAD(head, item, wk_list);
1021}
1022
1023static void
1024worklist_remove(item, locked)
1025	struct worklist *item;
1026	int locked;
1027{
1028
1029	if (locked)
1030		LOCK_OWNED(VFSTOUFS(item->wk_mp));
1031	if ((item->wk_state & ONWORKLIST) == 0)
1032		panic("worklist_remove: %p %s(0x%X) not on list",
1033		    item, TYPENAME(item->wk_type), item->wk_state);
1034	item->wk_state &= ~ONWORKLIST;
1035	LIST_REMOVE(item, wk_list);
1036}
1037#endif /* DEBUG */
1038
1039/*
1040 * Merge two jsegdeps keeping only the oldest one as newer references
1041 * can't be discarded until after older references.
1042 */
1043static inline struct jsegdep *
1044jsegdep_merge(struct jsegdep *one, struct jsegdep *two)
1045{
1046	struct jsegdep *swp;
1047
1048	if (two == NULL)
1049		return (one);
1050
1051	if (one->jd_seg->js_seq > two->jd_seg->js_seq) {
1052		swp = one;
1053		one = two;
1054		two = swp;
1055	}
1056	WORKLIST_REMOVE(&two->jd_list);
1057	free_jsegdep(two);
1058
1059	return (one);
1060}
1061
1062/*
1063 * If two freedeps are compatible free one to reduce list size.
1064 */
1065static inline struct freedep *
1066freedep_merge(struct freedep *one, struct freedep *two)
1067{
1068	if (two == NULL)
1069		return (one);
1070
1071	if (one->fd_freework == two->fd_freework) {
1072		WORKLIST_REMOVE(&two->fd_list);
1073		free_freedep(two);
1074	}
1075	return (one);
1076}
1077
1078/*
1079 * Move journal work from one list to another.  Duplicate freedeps and
1080 * jsegdeps are coalesced to keep the lists as small as possible.
1081 */
1082static void
1083jwork_move(dst, src)
1084	struct workhead *dst;
1085	struct workhead *src;
1086{
1087	struct freedep *freedep;
1088	struct jsegdep *jsegdep;
1089	struct worklist *wkn;
1090	struct worklist *wk;
1091
1092	KASSERT(dst != src,
1093	    ("jwork_move: dst == src"));
1094	freedep = NULL;
1095	jsegdep = NULL;
1096	LIST_FOREACH_SAFE(wk, dst, wk_list, wkn) {
1097		if (wk->wk_type == D_JSEGDEP)
1098			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1099		if (wk->wk_type == D_FREEDEP)
1100			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1101	}
1102
1103	while ((wk = LIST_FIRST(src)) != NULL) {
1104		WORKLIST_REMOVE(wk);
1105		WORKLIST_INSERT(dst, wk);
1106		if (wk->wk_type == D_JSEGDEP) {
1107			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1108			continue;
1109		}
1110		if (wk->wk_type == D_FREEDEP)
1111			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1112	}
1113}
1114
1115static void
1116jwork_insert(dst, jsegdep)
1117	struct workhead *dst;
1118	struct jsegdep *jsegdep;
1119{
1120	struct jsegdep *jsegdepn;
1121	struct worklist *wk;
1122
1123	LIST_FOREACH(wk, dst, wk_list)
1124		if (wk->wk_type == D_JSEGDEP)
1125			break;
1126	if (wk == NULL) {
1127		WORKLIST_INSERT(dst, &jsegdep->jd_list);
1128		return;
1129	}
1130	jsegdepn = WK_JSEGDEP(wk);
1131	if (jsegdep->jd_seg->js_seq < jsegdepn->jd_seg->js_seq) {
1132		WORKLIST_REMOVE(wk);
1133		free_jsegdep(jsegdepn);
1134		WORKLIST_INSERT(dst, &jsegdep->jd_list);
1135	} else
1136		free_jsegdep(jsegdep);
1137}
1138
1139/*
1140 * Routines for tracking and managing workitems.
1141 */
1142static	void workitem_free(struct worklist *, int);
1143static	void workitem_alloc(struct worklist *, int, struct mount *);
1144static	void workitem_reassign(struct worklist *, int);
1145
1146#define	WORKITEM_FREE(item, type) \
1147	workitem_free((struct worklist *)(item), (type))
1148#define	WORKITEM_REASSIGN(item, type) \
1149	workitem_reassign((struct worklist *)(item), (type))
1150
1151static void
1152workitem_free(item, type)
1153	struct worklist *item;
1154	int type;
1155{
1156	struct ufsmount *ump;
1157
1158#ifdef DEBUG
1159	if (item->wk_state & ONWORKLIST)
1160		panic("workitem_free: %s(0x%X) still on list",
1161		    TYPENAME(item->wk_type), item->wk_state);
1162	if (item->wk_type != type && type != D_NEWBLK)
1163		panic("workitem_free: type mismatch %s != %s",
1164		    TYPENAME(item->wk_type), TYPENAME(type));
1165#endif
1166	if (item->wk_state & IOWAITING)
1167		wakeup(item);
1168	ump = VFSTOUFS(item->wk_mp);
1169	LOCK_OWNED(ump);
1170	KASSERT(ump->softdep_deps > 0,
1171	    ("workitem_free: %s: softdep_deps going negative",
1172	    ump->um_fs->fs_fsmnt));
1173	if (--ump->softdep_deps == 0 && ump->softdep_req)
1174		wakeup(&ump->softdep_deps);
1175	KASSERT(dep_current[item->wk_type] > 0,
1176	    ("workitem_free: %s: dep_current[%s] going negative",
1177	    ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1178	KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1179	    ("workitem_free: %s: softdep_curdeps[%s] going negative",
1180	    ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1181	dep_current[item->wk_type]--;
1182	ump->softdep_curdeps[item->wk_type] -= 1;
1183	free(item, DtoM(type));
1184}
1185
1186static void
1187workitem_alloc(item, type, mp)
1188	struct worklist *item;
1189	int type;
1190	struct mount *mp;
1191{
1192	struct ufsmount *ump;
1193
1194	item->wk_type = type;
1195	item->wk_mp = mp;
1196	item->wk_state = 0;
1197
1198	ump = VFSTOUFS(mp);
1199	ACQUIRE_LOCK(ump);
1200	dep_current[type]++;
1201	if (dep_current[type] > dep_highuse[type])
1202		dep_highuse[type] = dep_current[type];
1203	dep_total[type]++;
1204	ump->softdep_curdeps[type] += 1;
1205	ump->softdep_deps++;
1206	ump->softdep_accdeps++;
1207	FREE_LOCK(ump);
1208}
1209
1210static void
1211workitem_reassign(item, newtype)
1212	struct worklist *item;
1213	int newtype;
1214{
1215	struct ufsmount *ump;
1216
1217	ump = VFSTOUFS(item->wk_mp);
1218	LOCK_OWNED(ump);
1219	KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1220	    ("workitem_reassign: %s: softdep_curdeps[%s] going negative",
1221	    VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1222	ump->softdep_curdeps[item->wk_type] -= 1;
1223	ump->softdep_curdeps[newtype] += 1;
1224	KASSERT(dep_current[item->wk_type] > 0,
1225	    ("workitem_reassign: %s: dep_current[%s] going negative",
1226	    VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1227	dep_current[item->wk_type]--;
1228	dep_current[newtype]++;
1229	if (dep_current[newtype] > dep_highuse[newtype])
1230		dep_highuse[newtype] = dep_current[newtype];
1231	dep_total[newtype]++;
1232	item->wk_type = newtype;
1233}
1234
1235/*
1236 * Workitem queue management
1237 */
1238static int max_softdeps;	/* maximum number of structs before slowdown */
1239static int maxindirdeps = 50;	/* max number of indirdeps before slowdown */
1240static int tickdelay = 2;	/* number of ticks to pause during slowdown */
1241static int proc_waiting;	/* tracks whether we have a timeout posted */
1242static int *stat_countp;	/* statistic to count in proc_waiting timeout */
1243static struct callout softdep_callout;
1244static struct mount *req_pending;
1245#define ALLCLEAN ((struct mount *)-1)
1246static int req_clear_inodedeps;	/* syncer process flush some inodedeps */
1247static int req_clear_remove;	/* syncer process flush some freeblks */
1248static int softdep_flushcache = 0; /* Should we do BIO_FLUSH? */
1249
1250/*
1251 * runtime statistics
1252 */
1253static int stat_softdep_mounts;	/* number of softdep mounted filesystems */
1254static int stat_worklist_push;	/* number of worklist cleanups */
1255static int stat_blk_limit_push;	/* number of times block limit neared */
1256static int stat_ino_limit_push;	/* number of times inode limit neared */
1257static int stat_blk_limit_hit;	/* number of times block slowdown imposed */
1258static int stat_ino_limit_hit;	/* number of times inode slowdown imposed */
1259static int stat_sync_limit_hit;	/* number of synchronous slowdowns imposed */
1260static int stat_indir_blk_ptrs;	/* bufs redirtied as indir ptrs not written */
1261static int stat_inode_bitmap;	/* bufs redirtied as inode bitmap not written */
1262static int stat_direct_blk_ptrs;/* bufs redirtied as direct ptrs not written */
1263static int stat_dir_entry;	/* bufs redirtied as dir entry cannot write */
1264static int stat_jaddref;	/* bufs redirtied as ino bitmap can not write */
1265static int stat_jnewblk;	/* bufs redirtied as blk bitmap can not write */
1266static int stat_journal_min;	/* Times hit journal min threshold */
1267static int stat_journal_low;	/* Times hit journal low threshold */
1268static int stat_journal_wait;	/* Times blocked in jwait(). */
1269static int stat_jwait_filepage;	/* Times blocked in jwait() for filepage. */
1270static int stat_jwait_freeblks;	/* Times blocked in jwait() for freeblks. */
1271static int stat_jwait_inode;	/* Times blocked in jwait() for inodes. */
1272static int stat_jwait_newblk;	/* Times blocked in jwait() for newblks. */
1273static int stat_cleanup_high_delay; /* Maximum cleanup delay (in ticks) */
1274static int stat_cleanup_blkrequests; /* Number of block cleanup requests */
1275static int stat_cleanup_inorequests; /* Number of inode cleanup requests */
1276static int stat_cleanup_retries; /* Number of cleanups that needed to flush */
1277static int stat_cleanup_failures; /* Number of cleanup requests that failed */
1278static int stat_emptyjblocks; /* Number of potentially empty journal blocks */
1279
1280SYSCTL_INT(_debug_softdep, OID_AUTO, max_softdeps, CTLFLAG_RW,
1281    &max_softdeps, 0, "");
1282SYSCTL_INT(_debug_softdep, OID_AUTO, tickdelay, CTLFLAG_RW,
1283    &tickdelay, 0, "");
1284SYSCTL_INT(_debug_softdep, OID_AUTO, maxindirdeps, CTLFLAG_RW,
1285    &maxindirdeps, 0, "");
1286SYSCTL_INT(_debug_softdep, OID_AUTO, softdep_mounts, CTLFLAG_RD,
1287    &stat_softdep_mounts, 0, "");
1288SYSCTL_INT(_debug_softdep, OID_AUTO, worklist_push, CTLFLAG_RW,
1289    &stat_worklist_push, 0,"");
1290SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_push, CTLFLAG_RW,
1291    &stat_blk_limit_push, 0,"");
1292SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_push, CTLFLAG_RW,
1293    &stat_ino_limit_push, 0,"");
1294SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_hit, CTLFLAG_RW,
1295    &stat_blk_limit_hit, 0, "");
1296SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_hit, CTLFLAG_RW,
1297    &stat_ino_limit_hit, 0, "");
1298SYSCTL_INT(_debug_softdep, OID_AUTO, sync_limit_hit, CTLFLAG_RW,
1299    &stat_sync_limit_hit, 0, "");
1300SYSCTL_INT(_debug_softdep, OID_AUTO, indir_blk_ptrs, CTLFLAG_RW,
1301    &stat_indir_blk_ptrs, 0, "");
1302SYSCTL_INT(_debug_softdep, OID_AUTO, inode_bitmap, CTLFLAG_RW,
1303    &stat_inode_bitmap, 0, "");
1304SYSCTL_INT(_debug_softdep, OID_AUTO, direct_blk_ptrs, CTLFLAG_RW,
1305    &stat_direct_blk_ptrs, 0, "");
1306SYSCTL_INT(_debug_softdep, OID_AUTO, dir_entry, CTLFLAG_RW,
1307    &stat_dir_entry, 0, "");
1308SYSCTL_INT(_debug_softdep, OID_AUTO, jaddref_rollback, CTLFLAG_RW,
1309    &stat_jaddref, 0, "");
1310SYSCTL_INT(_debug_softdep, OID_AUTO, jnewblk_rollback, CTLFLAG_RW,
1311    &stat_jnewblk, 0, "");
1312SYSCTL_INT(_debug_softdep, OID_AUTO, journal_low, CTLFLAG_RW,
1313    &stat_journal_low, 0, "");
1314SYSCTL_INT(_debug_softdep, OID_AUTO, journal_min, CTLFLAG_RW,
1315    &stat_journal_min, 0, "");
1316SYSCTL_INT(_debug_softdep, OID_AUTO, journal_wait, CTLFLAG_RW,
1317    &stat_journal_wait, 0, "");
1318SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_filepage, CTLFLAG_RW,
1319    &stat_jwait_filepage, 0, "");
1320SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_freeblks, CTLFLAG_RW,
1321    &stat_jwait_freeblks, 0, "");
1322SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_inode, CTLFLAG_RW,
1323    &stat_jwait_inode, 0, "");
1324SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_newblk, CTLFLAG_RW,
1325    &stat_jwait_newblk, 0, "");
1326SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_blkrequests, CTLFLAG_RW,
1327    &stat_cleanup_blkrequests, 0, "");
1328SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_inorequests, CTLFLAG_RW,
1329    &stat_cleanup_inorequests, 0, "");
1330SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_high_delay, CTLFLAG_RW,
1331    &stat_cleanup_high_delay, 0, "");
1332SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_retries, CTLFLAG_RW,
1333    &stat_cleanup_retries, 0, "");
1334SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_failures, CTLFLAG_RW,
1335    &stat_cleanup_failures, 0, "");
1336SYSCTL_INT(_debug_softdep, OID_AUTO, flushcache, CTLFLAG_RW,
1337    &softdep_flushcache, 0, "");
1338SYSCTL_INT(_debug_softdep, OID_AUTO, emptyjblocks, CTLFLAG_RD,
1339    &stat_emptyjblocks, 0, "");
1340
1341SYSCTL_DECL(_vfs_ffs);
1342
1343/* Whether to recompute the summary at mount time */
1344static int compute_summary_at_mount = 0;
1345SYSCTL_INT(_vfs_ffs, OID_AUTO, compute_summary_at_mount, CTLFLAG_RW,
1346	   &compute_summary_at_mount, 0, "Recompute summary at mount");
1347static struct proc *softdepproc;
1348static struct kproc_desc softdep_kp = {
1349	"softdepflush",
1350	softdep_flush,
1351	&softdepproc
1352};
1353SYSINIT(sdproc, SI_SUB_KTHREAD_UPDATE, SI_ORDER_ANY, kproc_start,
1354    &softdep_kp);
1355
1356static void
1357softdep_flush(void)
1358{
1359	struct mount *nmp;
1360	struct mount *mp;
1361	struct ufsmount *ump;
1362	struct thread *td;
1363	int remaining;
1364	int progress;
1365
1366	td = curthread;
1367	td->td_pflags |= TDP_NORUNNINGBUF;
1368
1369	for (;;) {
1370		kproc_suspend_check(softdepproc);
1371		remaining = progress = 0;
1372		mtx_lock(&mountlist_mtx);
1373		for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp)  {
1374			nmp = TAILQ_NEXT(mp, mnt_list);
1375			if (MOUNTEDSOFTDEP(mp) == 0)
1376				continue;
1377			if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK))
1378				continue;
1379			ump = VFSTOUFS(mp);
1380			progress += softdep_process_worklist(mp, 0);
1381			remaining += ump->softdep_on_worklist;
1382			mtx_lock(&mountlist_mtx);
1383			nmp = TAILQ_NEXT(mp, mnt_list);
1384			vfs_unbusy(mp);
1385		}
1386		mtx_unlock(&mountlist_mtx);
1387		if (remaining && progress)
1388			continue;
1389		rw_wlock(&lk);
1390		if (req_pending == NULL)
1391			msleep(&req_pending, &lk, PVM, "sdflush", hz);
1392		req_pending = NULL;
1393		rw_wunlock(&lk);
1394	}
1395}
1396
1397static void
1398worklist_speedup(mp)
1399	struct mount *mp;
1400{
1401	rw_assert(&lk, RA_WLOCKED);
1402	if (req_pending == 0) {
1403		req_pending = mp;
1404		wakeup(&req_pending);
1405	}
1406}
1407
1408static int
1409softdep_speedup(void)
1410{
1411
1412	worklist_speedup(ALLCLEAN);
1413	bd_speedup();
1414	return (speedup_syncer());
1415}
1416
1417/*
1418 * Add an item to the end of the work queue.
1419 * This routine requires that the lock be held.
1420 * This is the only routine that adds items to the list.
1421 * The following routine is the only one that removes items
1422 * and does so in order from first to last.
1423 */
1424
1425#define	WK_HEAD		0x0001	/* Add to HEAD. */
1426#define	WK_NODELAY	0x0002	/* Process immediately. */
1427
1428static void
1429add_to_worklist(wk, flags)
1430	struct worklist *wk;
1431	int flags;
1432{
1433	struct ufsmount *ump;
1434
1435	ump = VFSTOUFS(wk->wk_mp);
1436	LOCK_OWNED(ump);
1437	if (wk->wk_state & ONWORKLIST)
1438		panic("add_to_worklist: %s(0x%X) already on list",
1439		    TYPENAME(wk->wk_type), wk->wk_state);
1440	wk->wk_state |= ONWORKLIST;
1441	if (ump->softdep_on_worklist == 0) {
1442		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1443		ump->softdep_worklist_tail = wk;
1444	} else if (flags & WK_HEAD) {
1445		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1446	} else {
1447		LIST_INSERT_AFTER(ump->softdep_worklist_tail, wk, wk_list);
1448		ump->softdep_worklist_tail = wk;
1449	}
1450	ump->softdep_on_worklist += 1;
1451	if (flags & WK_NODELAY)
1452		worklist_speedup(wk->wk_mp);
1453}
1454
1455/*
1456 * Remove the item to be processed. If we are removing the last
1457 * item on the list, we need to recalculate the tail pointer.
1458 */
1459static void
1460remove_from_worklist(wk)
1461	struct worklist *wk;
1462{
1463	struct ufsmount *ump;
1464
1465	ump = VFSTOUFS(wk->wk_mp);
1466	WORKLIST_REMOVE(wk);
1467	if (ump->softdep_worklist_tail == wk)
1468		ump->softdep_worklist_tail =
1469		    (struct worklist *)wk->wk_list.le_prev;
1470	ump->softdep_on_worklist -= 1;
1471}
1472
1473static void
1474wake_worklist(wk)
1475	struct worklist *wk;
1476{
1477	if (wk->wk_state & IOWAITING) {
1478		wk->wk_state &= ~IOWAITING;
1479		wakeup(wk);
1480	}
1481}
1482
1483static void
1484wait_worklist(wk, wmesg)
1485	struct worklist *wk;
1486	char *wmesg;
1487{
1488	struct ufsmount *ump;
1489
1490	ump = VFSTOUFS(wk->wk_mp);
1491	wk->wk_state |= IOWAITING;
1492	msleep(wk, LOCK_PTR(ump), PVM, wmesg, 0);
1493}
1494
1495/*
1496 * Process that runs once per second to handle items in the background queue.
1497 *
1498 * Note that we ensure that everything is done in the order in which they
1499 * appear in the queue. The code below depends on this property to ensure
1500 * that blocks of a file are freed before the inode itself is freed. This
1501 * ordering ensures that no new <vfsid, inum, lbn> triples will be generated
1502 * until all the old ones have been purged from the dependency lists.
1503 */
1504static int
1505softdep_process_worklist(mp, full)
1506	struct mount *mp;
1507	int full;
1508{
1509	int cnt, matchcnt;
1510	struct ufsmount *ump;
1511	long starttime;
1512
1513	KASSERT(mp != NULL, ("softdep_process_worklist: NULL mp"));
1514	if (MOUNTEDSOFTDEP(mp) == 0)
1515		return (0);
1516	matchcnt = 0;
1517	ump = VFSTOUFS(mp);
1518	ACQUIRE_LOCK(ump);
1519	starttime = time_second;
1520	softdep_process_journal(mp, NULL, full ? MNT_WAIT : 0);
1521	check_clear_deps(mp);
1522	while (ump->softdep_on_worklist > 0) {
1523		if ((cnt = process_worklist_item(mp, 10, LK_NOWAIT)) == 0)
1524			break;
1525		else
1526			matchcnt += cnt;
1527		check_clear_deps(mp);
1528		/*
1529		 * We do not generally want to stop for buffer space, but if
1530		 * we are really being a buffer hog, we will stop and wait.
1531		 */
1532		if (should_yield()) {
1533			FREE_LOCK(ump);
1534			kern_yield(PRI_USER);
1535			bwillwrite();
1536			ACQUIRE_LOCK(ump);
1537		}
1538		/*
1539		 * Never allow processing to run for more than one
1540		 * second. This gives the syncer thread the opportunity
1541		 * to pause if appropriate.
1542		 */
1543		if (!full && starttime != time_second)
1544			break;
1545	}
1546	if (full == 0)
1547		journal_unsuspend(ump);
1548	FREE_LOCK(ump);
1549	return (matchcnt);
1550}
1551
1552/*
1553 * Process all removes associated with a vnode if we are running out of
1554 * journal space.  Any other process which attempts to flush these will
1555 * be unable as we have the vnodes locked.
1556 */
1557static void
1558process_removes(vp)
1559	struct vnode *vp;
1560{
1561	struct inodedep *inodedep;
1562	struct dirrem *dirrem;
1563	struct ufsmount *ump;
1564	struct mount *mp;
1565	ino_t inum;
1566
1567	mp = vp->v_mount;
1568	ump = VFSTOUFS(mp);
1569	LOCK_OWNED(ump);
1570	inum = VTOI(vp)->i_number;
1571	for (;;) {
1572top:
1573		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1574			return;
1575		LIST_FOREACH(dirrem, &inodedep->id_dirremhd, dm_inonext) {
1576			/*
1577			 * If another thread is trying to lock this vnode
1578			 * it will fail but we must wait for it to do so
1579			 * before we can proceed.
1580			 */
1581			if (dirrem->dm_state & INPROGRESS) {
1582				wait_worklist(&dirrem->dm_list, "pwrwait");
1583				goto top;
1584			}
1585			if ((dirrem->dm_state & (COMPLETE | ONWORKLIST)) ==
1586			    (COMPLETE | ONWORKLIST))
1587				break;
1588		}
1589		if (dirrem == NULL)
1590			return;
1591		remove_from_worklist(&dirrem->dm_list);
1592		FREE_LOCK(ump);
1593		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1594			panic("process_removes: suspended filesystem");
1595		handle_workitem_remove(dirrem, 0);
1596		vn_finished_secondary_write(mp);
1597		ACQUIRE_LOCK(ump);
1598	}
1599}
1600
1601/*
1602 * Process all truncations associated with a vnode if we are running out
1603 * of journal space.  This is called when the vnode lock is already held
1604 * and no other process can clear the truncation.  This function returns
1605 * a value greater than zero if it did any work.
1606 */
1607static void
1608process_truncates(vp)
1609	struct vnode *vp;
1610{
1611	struct inodedep *inodedep;
1612	struct freeblks *freeblks;
1613	struct ufsmount *ump;
1614	struct mount *mp;
1615	ino_t inum;
1616	int cgwait;
1617
1618	mp = vp->v_mount;
1619	ump = VFSTOUFS(mp);
1620	LOCK_OWNED(ump);
1621	inum = VTOI(vp)->i_number;
1622	for (;;) {
1623		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1624			return;
1625		cgwait = 0;
1626		TAILQ_FOREACH(freeblks, &inodedep->id_freeblklst, fb_next) {
1627			/* Journal entries not yet written.  */
1628			if (!LIST_EMPTY(&freeblks->fb_jblkdephd)) {
1629				jwait(&LIST_FIRST(
1630				    &freeblks->fb_jblkdephd)->jb_list,
1631				    MNT_WAIT);
1632				break;
1633			}
1634			/* Another thread is executing this item. */
1635			if (freeblks->fb_state & INPROGRESS) {
1636				wait_worklist(&freeblks->fb_list, "ptrwait");
1637				break;
1638			}
1639			/* Freeblks is waiting on a inode write. */
1640			if ((freeblks->fb_state & COMPLETE) == 0) {
1641				FREE_LOCK(ump);
1642				ffs_update(vp, 1);
1643				ACQUIRE_LOCK(ump);
1644				break;
1645			}
1646			if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST)) ==
1647			    (ALLCOMPLETE | ONWORKLIST)) {
1648				remove_from_worklist(&freeblks->fb_list);
1649				freeblks->fb_state |= INPROGRESS;
1650				FREE_LOCK(ump);
1651				if (vn_start_secondary_write(NULL, &mp,
1652				    V_NOWAIT))
1653					panic("process_truncates: "
1654					    "suspended filesystem");
1655				handle_workitem_freeblocks(freeblks, 0);
1656				vn_finished_secondary_write(mp);
1657				ACQUIRE_LOCK(ump);
1658				break;
1659			}
1660			if (freeblks->fb_cgwait)
1661				cgwait++;
1662		}
1663		if (cgwait) {
1664			FREE_LOCK(ump);
1665			sync_cgs(mp, MNT_WAIT);
1666			ffs_sync_snap(mp, MNT_WAIT);
1667			ACQUIRE_LOCK(ump);
1668			continue;
1669		}
1670		if (freeblks == NULL)
1671			break;
1672	}
1673	return;
1674}
1675
1676/*
1677 * Process one item on the worklist.
1678 */
1679static int
1680process_worklist_item(mp, target, flags)
1681	struct mount *mp;
1682	int target;
1683	int flags;
1684{
1685	struct worklist sentinel;
1686	struct worklist *wk;
1687	struct ufsmount *ump;
1688	int matchcnt;
1689	int error;
1690
1691	KASSERT(mp != NULL, ("process_worklist_item: NULL mp"));
1692	/*
1693	 * If we are being called because of a process doing a
1694	 * copy-on-write, then it is not safe to write as we may
1695	 * recurse into the copy-on-write routine.
1696	 */
1697	if (curthread->td_pflags & TDP_COWINPROGRESS)
1698		return (-1);
1699	PHOLD(curproc);	/* Don't let the stack go away. */
1700	ump = VFSTOUFS(mp);
1701	LOCK_OWNED(ump);
1702	matchcnt = 0;
1703	sentinel.wk_mp = NULL;
1704	sentinel.wk_type = D_SENTINEL;
1705	LIST_INSERT_HEAD(&ump->softdep_workitem_pending, &sentinel, wk_list);
1706	for (wk = LIST_NEXT(&sentinel, wk_list); wk != NULL;
1707	    wk = LIST_NEXT(&sentinel, wk_list)) {
1708		if (wk->wk_type == D_SENTINEL) {
1709			LIST_REMOVE(&sentinel, wk_list);
1710			LIST_INSERT_AFTER(wk, &sentinel, wk_list);
1711			continue;
1712		}
1713		if (wk->wk_state & INPROGRESS)
1714			panic("process_worklist_item: %p already in progress.",
1715			    wk);
1716		wk->wk_state |= INPROGRESS;
1717		remove_from_worklist(wk);
1718		FREE_LOCK(ump);
1719		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1720			panic("process_worklist_item: suspended filesystem");
1721		switch (wk->wk_type) {
1722		case D_DIRREM:
1723			/* removal of a directory entry */
1724			error = handle_workitem_remove(WK_DIRREM(wk), flags);
1725			break;
1726
1727		case D_FREEBLKS:
1728			/* releasing blocks and/or fragments from a file */
1729			error = handle_workitem_freeblocks(WK_FREEBLKS(wk),
1730			    flags);
1731			break;
1732
1733		case D_FREEFRAG:
1734			/* releasing a fragment when replaced as a file grows */
1735			handle_workitem_freefrag(WK_FREEFRAG(wk));
1736			error = 0;
1737			break;
1738
1739		case D_FREEFILE:
1740			/* releasing an inode when its link count drops to 0 */
1741			handle_workitem_freefile(WK_FREEFILE(wk));
1742			error = 0;
1743			break;
1744
1745		default:
1746			panic("%s_process_worklist: Unknown type %s",
1747			    "softdep", TYPENAME(wk->wk_type));
1748			/* NOTREACHED */
1749		}
1750		vn_finished_secondary_write(mp);
1751		ACQUIRE_LOCK(ump);
1752		if (error == 0) {
1753			if (++matchcnt == target)
1754				break;
1755			continue;
1756		}
1757		/*
1758		 * We have to retry the worklist item later.  Wake up any
1759		 * waiters who may be able to complete it immediately and
1760		 * add the item back to the head so we don't try to execute
1761		 * it again.
1762		 */
1763		wk->wk_state &= ~INPROGRESS;
1764		wake_worklist(wk);
1765		add_to_worklist(wk, WK_HEAD);
1766	}
1767	LIST_REMOVE(&sentinel, wk_list);
1768	/* Sentinal could've become the tail from remove_from_worklist. */
1769	if (ump->softdep_worklist_tail == &sentinel)
1770		ump->softdep_worklist_tail =
1771		    (struct worklist *)sentinel.wk_list.le_prev;
1772	PRELE(curproc);
1773	return (matchcnt);
1774}
1775
1776/*
1777 * Move dependencies from one buffer to another.
1778 */
1779int
1780softdep_move_dependencies(oldbp, newbp)
1781	struct buf *oldbp;
1782	struct buf *newbp;
1783{
1784	struct worklist *wk, *wktail;
1785	struct ufsmount *ump;
1786	int dirty;
1787
1788	if ((wk = LIST_FIRST(&oldbp->b_dep)) == NULL)
1789		return (0);
1790	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
1791	    ("softdep_move_dependencies called on non-softdep filesystem"));
1792	dirty = 0;
1793	wktail = NULL;
1794	ump = VFSTOUFS(wk->wk_mp);
1795	ACQUIRE_LOCK(ump);
1796	while ((wk = LIST_FIRST(&oldbp->b_dep)) != NULL) {
1797		LIST_REMOVE(wk, wk_list);
1798		if (wk->wk_type == D_BMSAFEMAP &&
1799		    bmsafemap_backgroundwrite(WK_BMSAFEMAP(wk), newbp))
1800			dirty = 1;
1801		if (wktail == 0)
1802			LIST_INSERT_HEAD(&newbp->b_dep, wk, wk_list);
1803		else
1804			LIST_INSERT_AFTER(wktail, wk, wk_list);
1805		wktail = wk;
1806	}
1807	FREE_LOCK(ump);
1808
1809	return (dirty);
1810}
1811
1812/*
1813 * Purge the work list of all items associated with a particular mount point.
1814 */
1815int
1816softdep_flushworklist(oldmnt, countp, td)
1817	struct mount *oldmnt;
1818	int *countp;
1819	struct thread *td;
1820{
1821	struct vnode *devvp;
1822	int count, error = 0;
1823	struct ufsmount *ump;
1824
1825	/*
1826	 * Alternately flush the block device associated with the mount
1827	 * point and process any dependencies that the flushing
1828	 * creates. We continue until no more worklist dependencies
1829	 * are found.
1830	 */
1831	*countp = 0;
1832	ump = VFSTOUFS(oldmnt);
1833	devvp = ump->um_devvp;
1834	while ((count = softdep_process_worklist(oldmnt, 1)) > 0) {
1835		*countp += count;
1836		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1837		error = VOP_FSYNC(devvp, MNT_WAIT, td);
1838		VOP_UNLOCK(devvp, 0);
1839		if (error)
1840			break;
1841	}
1842	return (error);
1843}
1844
1845static int
1846softdep_waitidle(struct mount *mp)
1847{
1848	struct ufsmount *ump;
1849	int error;
1850	int i;
1851
1852	ump = VFSTOUFS(mp);
1853	ACQUIRE_LOCK(ump);
1854	for (i = 0; i < 10 && ump->softdep_deps; i++) {
1855		ump->softdep_req = 1;
1856		if (ump->softdep_on_worklist)
1857			panic("softdep_waitidle: work added after flush.");
1858		msleep(&ump->softdep_deps, LOCK_PTR(ump), PVM, "softdeps", 1);
1859	}
1860	ump->softdep_req = 0;
1861	FREE_LOCK(ump);
1862	error = 0;
1863	if (i == 10) {
1864		error = EBUSY;
1865		printf("softdep_waitidle: Failed to flush worklist for %p\n",
1866		    mp);
1867	}
1868
1869	return (error);
1870}
1871
1872/*
1873 * Flush all vnodes and worklist items associated with a specified mount point.
1874 */
1875int
1876softdep_flushfiles(oldmnt, flags, td)
1877	struct mount *oldmnt;
1878	int flags;
1879	struct thread *td;
1880{
1881#ifdef QUOTA
1882	struct ufsmount *ump;
1883	int i;
1884#endif
1885	int error, early, depcount, loopcnt, retry_flush_count, retry;
1886	int morework;
1887
1888	KASSERT(MOUNTEDSOFTDEP(oldmnt) != 0,
1889	    ("softdep_flushfiles called on non-softdep filesystem"));
1890	loopcnt = 10;
1891	retry_flush_count = 3;
1892retry_flush:
1893	error = 0;
1894
1895	/*
1896	 * Alternately flush the vnodes associated with the mount
1897	 * point and process any dependencies that the flushing
1898	 * creates. In theory, this loop can happen at most twice,
1899	 * but we give it a few extra just to be sure.
1900	 */
1901	for (; loopcnt > 0; loopcnt--) {
1902		/*
1903		 * Do another flush in case any vnodes were brought in
1904		 * as part of the cleanup operations.
1905		 */
1906		early = retry_flush_count == 1 || (oldmnt->mnt_kern_flag &
1907		    MNTK_UNMOUNT) == 0 ? 0 : EARLYFLUSH;
1908		if ((error = ffs_flushfiles(oldmnt, flags | early, td)) != 0)
1909			break;
1910		if ((error = softdep_flushworklist(oldmnt, &depcount, td)) != 0 ||
1911		    depcount == 0)
1912			break;
1913	}
1914	/*
1915	 * If we are unmounting then it is an error to fail. If we
1916	 * are simply trying to downgrade to read-only, then filesystem
1917	 * activity can keep us busy forever, so we just fail with EBUSY.
1918	 */
1919	if (loopcnt == 0) {
1920		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT)
1921			panic("softdep_flushfiles: looping");
1922		error = EBUSY;
1923	}
1924	if (!error)
1925		error = softdep_waitidle(oldmnt);
1926	if (!error) {
1927		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT) {
1928			retry = 0;
1929			MNT_ILOCK(oldmnt);
1930			KASSERT((oldmnt->mnt_kern_flag & MNTK_NOINSMNTQ) != 0,
1931			    ("softdep_flushfiles: !MNTK_NOINSMNTQ"));
1932			morework = oldmnt->mnt_nvnodelistsize > 0;
1933#ifdef QUOTA
1934			ump = VFSTOUFS(oldmnt);
1935			UFS_LOCK(ump);
1936			for (i = 0; i < MAXQUOTAS; i++) {
1937				if (ump->um_quotas[i] != NULLVP)
1938					morework = 1;
1939			}
1940			UFS_UNLOCK(ump);
1941#endif
1942			if (morework) {
1943				if (--retry_flush_count > 0) {
1944					retry = 1;
1945					loopcnt = 3;
1946				} else
1947					error = EBUSY;
1948			}
1949			MNT_IUNLOCK(oldmnt);
1950			if (retry)
1951				goto retry_flush;
1952		}
1953	}
1954	return (error);
1955}
1956
1957/*
1958 * Structure hashing.
1959 *
1960 * There are four types of structures that can be looked up:
1961 *	1) pagedep structures identified by mount point, inode number,
1962 *	   and logical block.
1963 *	2) inodedep structures identified by mount point and inode number.
1964 *	3) newblk structures identified by mount point and
1965 *	   physical block number.
1966 *	4) bmsafemap structures identified by mount point and
1967 *	   cylinder group number.
1968 *
1969 * The "pagedep" and "inodedep" dependency structures are hashed
1970 * separately from the file blocks and inodes to which they correspond.
1971 * This separation helps when the in-memory copy of an inode or
1972 * file block must be replaced. It also obviates the need to access
1973 * an inode or file page when simply updating (or de-allocating)
1974 * dependency structures. Lookup of newblk structures is needed to
1975 * find newly allocated blocks when trying to associate them with
1976 * their allocdirect or allocindir structure.
1977 *
1978 * The lookup routines optionally create and hash a new instance when
1979 * an existing entry is not found. The bmsafemap lookup routine always
1980 * allocates a new structure if an existing one is not found.
1981 */
1982#define DEPALLOC	0x0001	/* allocate structure if lookup fails */
1983#define NODELAY		0x0002	/* cannot do background work */
1984
1985/*
1986 * Structures and routines associated with pagedep caching.
1987 */
1988#define	PAGEDEP_HASH(ump, inum, lbn) \
1989	(&(ump)->pagedep_hashtbl[((inum) + (lbn)) & (ump)->pagedep_hash_size])
1990
1991static int
1992pagedep_find(pagedephd, ino, lbn, pagedeppp)
1993	struct pagedep_hashhead *pagedephd;
1994	ino_t ino;
1995	ufs_lbn_t lbn;
1996	struct pagedep **pagedeppp;
1997{
1998	struct pagedep *pagedep;
1999
2000	LIST_FOREACH(pagedep, pagedephd, pd_hash) {
2001		if (ino == pagedep->pd_ino && lbn == pagedep->pd_lbn) {
2002			*pagedeppp = pagedep;
2003			return (1);
2004		}
2005	}
2006	*pagedeppp = NULL;
2007	return (0);
2008}
2009/*
2010 * Look up a pagedep. Return 1 if found, 0 otherwise.
2011 * If not found, allocate if DEPALLOC flag is passed.
2012 * Found or allocated entry is returned in pagedeppp.
2013 * This routine must be called with splbio interrupts blocked.
2014 */
2015static int
2016pagedep_lookup(mp, bp, ino, lbn, flags, pagedeppp)
2017	struct mount *mp;
2018	struct buf *bp;
2019	ino_t ino;
2020	ufs_lbn_t lbn;
2021	int flags;
2022	struct pagedep **pagedeppp;
2023{
2024	struct pagedep *pagedep;
2025	struct pagedep_hashhead *pagedephd;
2026	struct worklist *wk;
2027	struct ufsmount *ump;
2028	int ret;
2029	int i;
2030
2031	ump = VFSTOUFS(mp);
2032	LOCK_OWNED(ump);
2033	if (bp) {
2034		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
2035			if (wk->wk_type == D_PAGEDEP) {
2036				*pagedeppp = WK_PAGEDEP(wk);
2037				return (1);
2038			}
2039		}
2040	}
2041	pagedephd = PAGEDEP_HASH(ump, ino, lbn);
2042	ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2043	if (ret) {
2044		if (((*pagedeppp)->pd_state & ONWORKLIST) == 0 && bp)
2045			WORKLIST_INSERT(&bp->b_dep, &(*pagedeppp)->pd_list);
2046		return (1);
2047	}
2048	if ((flags & DEPALLOC) == 0)
2049		return (0);
2050	FREE_LOCK(ump);
2051	pagedep = malloc(sizeof(struct pagedep),
2052	    M_PAGEDEP, M_SOFTDEP_FLAGS|M_ZERO);
2053	workitem_alloc(&pagedep->pd_list, D_PAGEDEP, mp);
2054	ACQUIRE_LOCK(ump);
2055	ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2056	if (*pagedeppp) {
2057		/*
2058		 * This should never happen since we only create pagedeps
2059		 * with the vnode lock held.  Could be an assert.
2060		 */
2061		WORKITEM_FREE(pagedep, D_PAGEDEP);
2062		return (ret);
2063	}
2064	pagedep->pd_ino = ino;
2065	pagedep->pd_lbn = lbn;
2066	LIST_INIT(&pagedep->pd_dirremhd);
2067	LIST_INIT(&pagedep->pd_pendinghd);
2068	for (i = 0; i < DAHASHSZ; i++)
2069		LIST_INIT(&pagedep->pd_diraddhd[i]);
2070	LIST_INSERT_HEAD(pagedephd, pagedep, pd_hash);
2071	WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
2072	*pagedeppp = pagedep;
2073	return (0);
2074}
2075
2076/*
2077 * Structures and routines associated with inodedep caching.
2078 */
2079#define	INODEDEP_HASH(ump, inum) \
2080      (&(ump)->inodedep_hashtbl[(inum) & (ump)->inodedep_hash_size])
2081
2082static int
2083inodedep_find(inodedephd, inum, inodedeppp)
2084	struct inodedep_hashhead *inodedephd;
2085	ino_t inum;
2086	struct inodedep **inodedeppp;
2087{
2088	struct inodedep *inodedep;
2089
2090	LIST_FOREACH(inodedep, inodedephd, id_hash)
2091		if (inum == inodedep->id_ino)
2092			break;
2093	if (inodedep) {
2094		*inodedeppp = inodedep;
2095		return (1);
2096	}
2097	*inodedeppp = NULL;
2098
2099	return (0);
2100}
2101/*
2102 * Look up an inodedep. Return 1 if found, 0 if not found.
2103 * If not found, allocate if DEPALLOC flag is passed.
2104 * Found or allocated entry is returned in inodedeppp.
2105 * This routine must be called with splbio interrupts blocked.
2106 */
2107static int
2108inodedep_lookup(mp, inum, flags, inodedeppp)
2109	struct mount *mp;
2110	ino_t inum;
2111	int flags;
2112	struct inodedep **inodedeppp;
2113{
2114	struct inodedep *inodedep;
2115	struct inodedep_hashhead *inodedephd;
2116	struct ufsmount *ump;
2117	struct fs *fs;
2118
2119	ump = VFSTOUFS(mp);
2120	LOCK_OWNED(ump);
2121	fs = ump->um_fs;
2122	inodedephd = INODEDEP_HASH(ump, inum);
2123
2124	if (inodedep_find(inodedephd, inum, inodedeppp))
2125		return (1);
2126	if ((flags & DEPALLOC) == 0)
2127		return (0);
2128	/*
2129	 * If we are over our limit, try to improve the situation.
2130	 */
2131	if (dep_current[D_INODEDEP] > max_softdeps && (flags & NODELAY) == 0)
2132		request_cleanup(mp, FLUSH_INODES);
2133	FREE_LOCK(ump);
2134	inodedep = malloc(sizeof(struct inodedep),
2135		M_INODEDEP, M_SOFTDEP_FLAGS);
2136	workitem_alloc(&inodedep->id_list, D_INODEDEP, mp);
2137	ACQUIRE_LOCK(ump);
2138	if (inodedep_find(inodedephd, inum, inodedeppp)) {
2139		WORKITEM_FREE(inodedep, D_INODEDEP);
2140		return (1);
2141	}
2142	inodedep->id_fs = fs;
2143	inodedep->id_ino = inum;
2144	inodedep->id_state = ALLCOMPLETE;
2145	inodedep->id_nlinkdelta = 0;
2146	inodedep->id_savedino1 = NULL;
2147	inodedep->id_savedsize = -1;
2148	inodedep->id_savedextsize = -1;
2149	inodedep->id_savednlink = -1;
2150	inodedep->id_bmsafemap = NULL;
2151	inodedep->id_mkdiradd = NULL;
2152	LIST_INIT(&inodedep->id_dirremhd);
2153	LIST_INIT(&inodedep->id_pendinghd);
2154	LIST_INIT(&inodedep->id_inowait);
2155	LIST_INIT(&inodedep->id_bufwait);
2156	TAILQ_INIT(&inodedep->id_inoreflst);
2157	TAILQ_INIT(&inodedep->id_inoupdt);
2158	TAILQ_INIT(&inodedep->id_newinoupdt);
2159	TAILQ_INIT(&inodedep->id_extupdt);
2160	TAILQ_INIT(&inodedep->id_newextupdt);
2161	TAILQ_INIT(&inodedep->id_freeblklst);
2162	LIST_INSERT_HEAD(inodedephd, inodedep, id_hash);
2163	*inodedeppp = inodedep;
2164	return (0);
2165}
2166
2167/*
2168 * Structures and routines associated with newblk caching.
2169 */
2170#define	NEWBLK_HASH(ump, inum) \
2171	(&(ump)->newblk_hashtbl[(inum) & (ump)->newblk_hash_size])
2172
2173static int
2174newblk_find(newblkhd, newblkno, flags, newblkpp)
2175	struct newblk_hashhead *newblkhd;
2176	ufs2_daddr_t newblkno;
2177	int flags;
2178	struct newblk **newblkpp;
2179{
2180	struct newblk *newblk;
2181
2182	LIST_FOREACH(newblk, newblkhd, nb_hash) {
2183		if (newblkno != newblk->nb_newblkno)
2184			continue;
2185		/*
2186		 * If we're creating a new dependency don't match those that
2187		 * have already been converted to allocdirects.  This is for
2188		 * a frag extend.
2189		 */
2190		if ((flags & DEPALLOC) && newblk->nb_list.wk_type != D_NEWBLK)
2191			continue;
2192		break;
2193	}
2194	if (newblk) {
2195		*newblkpp = newblk;
2196		return (1);
2197	}
2198	*newblkpp = NULL;
2199	return (0);
2200}
2201
2202/*
2203 * Look up a newblk. Return 1 if found, 0 if not found.
2204 * If not found, allocate if DEPALLOC flag is passed.
2205 * Found or allocated entry is returned in newblkpp.
2206 */
2207static int
2208newblk_lookup(mp, newblkno, flags, newblkpp)
2209	struct mount *mp;
2210	ufs2_daddr_t newblkno;
2211	int flags;
2212	struct newblk **newblkpp;
2213{
2214	struct newblk *newblk;
2215	struct newblk_hashhead *newblkhd;
2216	struct ufsmount *ump;
2217
2218	ump = VFSTOUFS(mp);
2219	LOCK_OWNED(ump);
2220	newblkhd = NEWBLK_HASH(ump, newblkno);
2221	if (newblk_find(newblkhd, newblkno, flags, newblkpp))
2222		return (1);
2223	if ((flags & DEPALLOC) == 0)
2224		return (0);
2225	FREE_LOCK(ump);
2226	newblk = malloc(sizeof(union allblk), M_NEWBLK,
2227	    M_SOFTDEP_FLAGS | M_ZERO);
2228	workitem_alloc(&newblk->nb_list, D_NEWBLK, mp);
2229	ACQUIRE_LOCK(ump);
2230	if (newblk_find(newblkhd, newblkno, flags, newblkpp)) {
2231		WORKITEM_FREE(newblk, D_NEWBLK);
2232		return (1);
2233	}
2234	newblk->nb_freefrag = NULL;
2235	LIST_INIT(&newblk->nb_indirdeps);
2236	LIST_INIT(&newblk->nb_newdirblk);
2237	LIST_INIT(&newblk->nb_jwork);
2238	newblk->nb_state = ATTACHED;
2239	newblk->nb_newblkno = newblkno;
2240	LIST_INSERT_HEAD(newblkhd, newblk, nb_hash);
2241	*newblkpp = newblk;
2242	return (0);
2243}
2244
2245/*
2246 * Structures and routines associated with freed indirect block caching.
2247 */
2248#define	INDIR_HASH(ump, blkno) \
2249	(&(ump)->indir_hashtbl[(blkno) & (ump)->indir_hash_size])
2250
2251/*
2252 * Lookup an indirect block in the indir hash table.  The freework is
2253 * removed and potentially freed.  The caller must do a blocking journal
2254 * write before writing to the blkno.
2255 */
2256static int
2257indirblk_lookup(mp, blkno)
2258	struct mount *mp;
2259	ufs2_daddr_t blkno;
2260{
2261	struct freework *freework;
2262	struct indir_hashhead *wkhd;
2263	struct ufsmount *ump;
2264
2265	ump = VFSTOUFS(mp);
2266	wkhd = INDIR_HASH(ump, blkno);
2267	TAILQ_FOREACH(freework, wkhd, fw_next) {
2268		if (freework->fw_blkno != blkno)
2269			continue;
2270		indirblk_remove(freework);
2271		return (1);
2272	}
2273	return (0);
2274}
2275
2276/*
2277 * Insert an indirect block represented by freework into the indirblk
2278 * hash table so that it may prevent the block from being re-used prior
2279 * to the journal being written.
2280 */
2281static void
2282indirblk_insert(freework)
2283	struct freework *freework;
2284{
2285	struct jblocks *jblocks;
2286	struct jseg *jseg;
2287	struct ufsmount *ump;
2288
2289	ump = VFSTOUFS(freework->fw_list.wk_mp);
2290	jblocks = ump->softdep_jblocks;
2291	jseg = TAILQ_LAST(&jblocks->jb_segs, jseglst);
2292	if (jseg == NULL)
2293		return;
2294
2295	LIST_INSERT_HEAD(&jseg->js_indirs, freework, fw_segs);
2296	TAILQ_INSERT_HEAD(INDIR_HASH(ump, freework->fw_blkno), freework,
2297	    fw_next);
2298	freework->fw_state &= ~DEPCOMPLETE;
2299}
2300
2301static void
2302indirblk_remove(freework)
2303	struct freework *freework;
2304{
2305	struct ufsmount *ump;
2306
2307	ump = VFSTOUFS(freework->fw_list.wk_mp);
2308	LIST_REMOVE(freework, fw_segs);
2309	TAILQ_REMOVE(INDIR_HASH(ump, freework->fw_blkno), freework, fw_next);
2310	freework->fw_state |= DEPCOMPLETE;
2311	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
2312		WORKITEM_FREE(freework, D_FREEWORK);
2313}
2314
2315/*
2316 * Executed during filesystem system initialization before
2317 * mounting any filesystems.
2318 */
2319void
2320softdep_initialize()
2321{
2322
2323	max_softdeps = desiredvnodes * 4;
2324
2325	/* initialise bioops hack */
2326	bioops.io_start = softdep_disk_io_initiation;
2327	bioops.io_complete = softdep_disk_write_complete;
2328	bioops.io_deallocate = softdep_deallocate_dependencies;
2329	bioops.io_countdeps = softdep_count_dependencies;
2330
2331	/* Initialize the callout with an mtx. */
2332	callout_init_mtx(&softdep_callout, &lk, 0);
2333}
2334
2335/*
2336 * Executed after all filesystems have been unmounted during
2337 * filesystem module unload.
2338 */
2339void
2340softdep_uninitialize()
2341{
2342
2343	/* clear bioops hack */
2344	bioops.io_start = NULL;
2345	bioops.io_complete = NULL;
2346	bioops.io_deallocate = NULL;
2347	bioops.io_countdeps = NULL;
2348
2349	callout_drain(&softdep_callout);
2350}
2351
2352/*
2353 * Called at mount time to notify the dependency code that a
2354 * filesystem wishes to use it.
2355 */
2356int
2357softdep_mount(devvp, mp, fs, cred)
2358	struct vnode *devvp;
2359	struct mount *mp;
2360	struct fs *fs;
2361	struct ucred *cred;
2362{
2363	struct csum_total cstotal;
2364	struct mount_softdeps *sdp;
2365	struct ufsmount *ump;
2366	struct cg *cgp;
2367	struct buf *bp;
2368	int i, error, cyl;
2369
2370	sdp = malloc(sizeof(struct mount_softdeps), M_MOUNTDATA,
2371	    M_WAITOK | M_ZERO);
2372	MNT_ILOCK(mp);
2373	mp->mnt_flag = (mp->mnt_flag & ~MNT_ASYNC) | MNT_SOFTDEP;
2374	if ((mp->mnt_kern_flag & MNTK_SOFTDEP) == 0) {
2375		mp->mnt_kern_flag = (mp->mnt_kern_flag & ~MNTK_ASYNC) |
2376			MNTK_SOFTDEP | MNTK_NOASYNC;
2377	}
2378	ump = VFSTOUFS(mp);
2379	ump->um_softdep = sdp;
2380	MNT_IUNLOCK(mp);
2381	LOCK_PTR(ump) = &lk;
2382	LIST_INIT(&ump->softdep_workitem_pending);
2383	LIST_INIT(&ump->softdep_journal_pending);
2384	TAILQ_INIT(&ump->softdep_unlinked);
2385	LIST_INIT(&ump->softdep_dirtycg);
2386	ump->softdep_worklist_tail = NULL;
2387	ump->softdep_on_worklist = 0;
2388	ump->softdep_deps = 0;
2389	LIST_INIT(&ump->softdep_mkdirlisthd);
2390	ump->pagedep_hashtbl = hashinit(desiredvnodes / 5, M_PAGEDEP,
2391	    &ump->pagedep_hash_size);
2392	ump->pagedep_nextclean = 0;
2393	ump->inodedep_hashtbl = hashinit(desiredvnodes, M_INODEDEP,
2394	    &ump->inodedep_hash_size);
2395	ump->inodedep_nextclean = 0;
2396	ump->newblk_hashtbl = hashinit(max_softdeps / 2,  M_NEWBLK,
2397	    &ump->newblk_hash_size);
2398	ump->bmsafemap_hashtbl = hashinit(1024, M_BMSAFEMAP,
2399	    &ump->bmsafemap_hash_size);
2400	i = 1 << (ffs(desiredvnodes / 10) - 1);
2401	ump->indir_hashtbl = malloc(i * sizeof(struct indir_hashhead),
2402	    M_FREEWORK, M_WAITOK);
2403	ump->indir_hash_size = i - 1;
2404	for (i = 0; i <= ump->indir_hash_size; i++)
2405		TAILQ_INIT(&ump->indir_hashtbl[i]);
2406	if ((fs->fs_flags & FS_SUJ) &&
2407	    (error = journal_mount(mp, fs, cred)) != 0) {
2408		printf("Failed to start journal: %d\n", error);
2409		softdep_unmount(mp);
2410		return (error);
2411	}
2412	atomic_add_int(&stat_softdep_mounts, 1);
2413	/*
2414	 * When doing soft updates, the counters in the
2415	 * superblock may have gotten out of sync. Recomputation
2416	 * can take a long time and can be deferred for background
2417	 * fsck.  However, the old behavior of scanning the cylinder
2418	 * groups and recalculating them at mount time is available
2419	 * by setting vfs.ffs.compute_summary_at_mount to one.
2420	 */
2421	if (compute_summary_at_mount == 0 || fs->fs_clean != 0)
2422		return (0);
2423	bzero(&cstotal, sizeof cstotal);
2424	for (cyl = 0; cyl < fs->fs_ncg; cyl++) {
2425		if ((error = bread(devvp, fsbtodb(fs, cgtod(fs, cyl)),
2426		    fs->fs_cgsize, cred, &bp)) != 0) {
2427			brelse(bp);
2428			softdep_unmount(mp);
2429			return (error);
2430		}
2431		cgp = (struct cg *)bp->b_data;
2432		cstotal.cs_nffree += cgp->cg_cs.cs_nffree;
2433		cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree;
2434		cstotal.cs_nifree += cgp->cg_cs.cs_nifree;
2435		cstotal.cs_ndir += cgp->cg_cs.cs_ndir;
2436		fs->fs_cs(fs, cyl) = cgp->cg_cs;
2437		brelse(bp);
2438	}
2439#ifdef DEBUG
2440	if (bcmp(&cstotal, &fs->fs_cstotal, sizeof cstotal))
2441		printf("%s: superblock summary recomputed\n", fs->fs_fsmnt);
2442#endif
2443	bcopy(&cstotal, &fs->fs_cstotal, sizeof cstotal);
2444	return (0);
2445}
2446
2447void
2448softdep_unmount(mp)
2449	struct mount *mp;
2450{
2451	struct ufsmount *ump;
2452#ifdef INVARIANTS
2453	int i;
2454#endif
2455
2456	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
2457	    ("softdep_unmount called on non-softdep filesystem"));
2458	ump = VFSTOUFS(mp);
2459	MNT_ILOCK(mp);
2460	mp->mnt_flag &= ~MNT_SOFTDEP;
2461	if (MOUNTEDSUJ(mp) == 0) {
2462		MNT_IUNLOCK(mp);
2463	} else {
2464		mp->mnt_flag &= ~MNT_SUJ;
2465		MNT_IUNLOCK(mp);
2466		journal_unmount(ump);
2467	}
2468	atomic_subtract_int(&stat_softdep_mounts, 1);
2469	hashdestroy(ump->pagedep_hashtbl, M_PAGEDEP, ump->pagedep_hash_size);
2470	hashdestroy(ump->inodedep_hashtbl, M_INODEDEP, ump->inodedep_hash_size);
2471	hashdestroy(ump->newblk_hashtbl, M_NEWBLK, ump->newblk_hash_size);
2472	hashdestroy(ump->bmsafemap_hashtbl, M_BMSAFEMAP,
2473	    ump->bmsafemap_hash_size);
2474	free(ump->indir_hashtbl, M_FREEWORK);
2475#ifdef INVARIANTS
2476	for (i = 0; i <= D_LAST; i++)
2477		KASSERT(ump->softdep_curdeps[i] == 0,
2478		    ("Unmount %s: Dep type %s != 0 (%ld)", ump->um_fs->fs_fsmnt,
2479		    TYPENAME(i), ump->softdep_curdeps[i]));
2480#endif
2481	free(ump->um_softdep, M_MOUNTDATA);
2482}
2483
2484static struct jblocks *
2485jblocks_create(void)
2486{
2487	struct jblocks *jblocks;
2488
2489	jblocks = malloc(sizeof(*jblocks), M_JBLOCKS, M_WAITOK | M_ZERO);
2490	TAILQ_INIT(&jblocks->jb_segs);
2491	jblocks->jb_avail = 10;
2492	jblocks->jb_extent = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2493	    M_JBLOCKS, M_WAITOK | M_ZERO);
2494
2495	return (jblocks);
2496}
2497
2498static ufs2_daddr_t
2499jblocks_alloc(jblocks, bytes, actual)
2500	struct jblocks *jblocks;
2501	int bytes;
2502	int *actual;
2503{
2504	ufs2_daddr_t daddr;
2505	struct jextent *jext;
2506	int freecnt;
2507	int blocks;
2508
2509	blocks = bytes / DEV_BSIZE;
2510	jext = &jblocks->jb_extent[jblocks->jb_head];
2511	freecnt = jext->je_blocks - jblocks->jb_off;
2512	if (freecnt == 0) {
2513		jblocks->jb_off = 0;
2514		if (++jblocks->jb_head > jblocks->jb_used)
2515			jblocks->jb_head = 0;
2516		jext = &jblocks->jb_extent[jblocks->jb_head];
2517		freecnt = jext->je_blocks;
2518	}
2519	if (freecnt > blocks)
2520		freecnt = blocks;
2521	*actual = freecnt * DEV_BSIZE;
2522	daddr = jext->je_daddr + jblocks->jb_off;
2523	jblocks->jb_off += freecnt;
2524	jblocks->jb_free -= freecnt;
2525
2526	return (daddr);
2527}
2528
2529static void
2530jblocks_free(jblocks, mp, bytes)
2531	struct jblocks *jblocks;
2532	struct mount *mp;
2533	int bytes;
2534{
2535
2536	LOCK_OWNED(VFSTOUFS(mp));
2537	jblocks->jb_free += bytes / DEV_BSIZE;
2538	if (jblocks->jb_suspended)
2539		worklist_speedup(mp);
2540	wakeup(jblocks);
2541}
2542
2543static void
2544jblocks_destroy(jblocks)
2545	struct jblocks *jblocks;
2546{
2547
2548	if (jblocks->jb_extent)
2549		free(jblocks->jb_extent, M_JBLOCKS);
2550	free(jblocks, M_JBLOCKS);
2551}
2552
2553static void
2554jblocks_add(jblocks, daddr, blocks)
2555	struct jblocks *jblocks;
2556	ufs2_daddr_t daddr;
2557	int blocks;
2558{
2559	struct jextent *jext;
2560
2561	jblocks->jb_blocks += blocks;
2562	jblocks->jb_free += blocks;
2563	jext = &jblocks->jb_extent[jblocks->jb_used];
2564	/* Adding the first block. */
2565	if (jext->je_daddr == 0) {
2566		jext->je_daddr = daddr;
2567		jext->je_blocks = blocks;
2568		return;
2569	}
2570	/* Extending the last extent. */
2571	if (jext->je_daddr + jext->je_blocks == daddr) {
2572		jext->je_blocks += blocks;
2573		return;
2574	}
2575	/* Adding a new extent. */
2576	if (++jblocks->jb_used == jblocks->jb_avail) {
2577		jblocks->jb_avail *= 2;
2578		jext = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2579		    M_JBLOCKS, M_WAITOK | M_ZERO);
2580		memcpy(jext, jblocks->jb_extent,
2581		    sizeof(struct jextent) * jblocks->jb_used);
2582		free(jblocks->jb_extent, M_JBLOCKS);
2583		jblocks->jb_extent = jext;
2584	}
2585	jext = &jblocks->jb_extent[jblocks->jb_used];
2586	jext->je_daddr = daddr;
2587	jext->je_blocks = blocks;
2588	return;
2589}
2590
2591int
2592softdep_journal_lookup(mp, vpp)
2593	struct mount *mp;
2594	struct vnode **vpp;
2595{
2596	struct componentname cnp;
2597	struct vnode *dvp;
2598	ino_t sujournal;
2599	int error;
2600
2601	error = VFS_VGET(mp, ROOTINO, LK_EXCLUSIVE, &dvp);
2602	if (error)
2603		return (error);
2604	bzero(&cnp, sizeof(cnp));
2605	cnp.cn_nameiop = LOOKUP;
2606	cnp.cn_flags = ISLASTCN;
2607	cnp.cn_thread = curthread;
2608	cnp.cn_cred = curthread->td_ucred;
2609	cnp.cn_pnbuf = SUJ_FILE;
2610	cnp.cn_nameptr = SUJ_FILE;
2611	cnp.cn_namelen = strlen(SUJ_FILE);
2612	error = ufs_lookup_ino(dvp, NULL, &cnp, &sujournal);
2613	vput(dvp);
2614	if (error != 0)
2615		return (error);
2616	error = VFS_VGET(mp, sujournal, LK_EXCLUSIVE, vpp);
2617	return (error);
2618}
2619
2620/*
2621 * Open and verify the journal file.
2622 */
2623static int
2624journal_mount(mp, fs, cred)
2625	struct mount *mp;
2626	struct fs *fs;
2627	struct ucred *cred;
2628{
2629	struct jblocks *jblocks;
2630	struct ufsmount *ump;
2631	struct vnode *vp;
2632	struct inode *ip;
2633	ufs2_daddr_t blkno;
2634	int bcount;
2635	int error;
2636	int i;
2637
2638	ump = VFSTOUFS(mp);
2639	ump->softdep_journal_tail = NULL;
2640	ump->softdep_on_journal = 0;
2641	ump->softdep_accdeps = 0;
2642	ump->softdep_req = 0;
2643	ump->softdep_jblocks = NULL;
2644	error = softdep_journal_lookup(mp, &vp);
2645	if (error != 0) {
2646		printf("Failed to find journal.  Use tunefs to create one\n");
2647		return (error);
2648	}
2649	ip = VTOI(vp);
2650	if (ip->i_size < SUJ_MIN) {
2651		error = ENOSPC;
2652		goto out;
2653	}
2654	bcount = lblkno(fs, ip->i_size);	/* Only use whole blocks. */
2655	jblocks = jblocks_create();
2656	for (i = 0; i < bcount; i++) {
2657		error = ufs_bmaparray(vp, i, &blkno, NULL, NULL, NULL);
2658		if (error)
2659			break;
2660		jblocks_add(jblocks, blkno, fsbtodb(fs, fs->fs_frag));
2661	}
2662	if (error) {
2663		jblocks_destroy(jblocks);
2664		goto out;
2665	}
2666	jblocks->jb_low = jblocks->jb_free / 3;	/* Reserve 33%. */
2667	jblocks->jb_min = jblocks->jb_free / 10; /* Suspend at 10%. */
2668	ump->softdep_jblocks = jblocks;
2669out:
2670	if (error == 0) {
2671		MNT_ILOCK(mp);
2672		mp->mnt_flag |= MNT_SUJ;
2673		mp->mnt_flag &= ~MNT_SOFTDEP;
2674		MNT_IUNLOCK(mp);
2675		/*
2676		 * Only validate the journal contents if the
2677		 * filesystem is clean, otherwise we write the logs
2678		 * but they'll never be used.  If the filesystem was
2679		 * still dirty when we mounted it the journal is
2680		 * invalid and a new journal can only be valid if it
2681		 * starts from a clean mount.
2682		 */
2683		if (fs->fs_clean) {
2684			DIP_SET(ip, i_modrev, fs->fs_mtime);
2685			ip->i_flags |= IN_MODIFIED;
2686			ffs_update(vp, 1);
2687		}
2688	}
2689	vput(vp);
2690	return (error);
2691}
2692
2693static void
2694journal_unmount(ump)
2695	struct ufsmount *ump;
2696{
2697
2698	if (ump->softdep_jblocks)
2699		jblocks_destroy(ump->softdep_jblocks);
2700	ump->softdep_jblocks = NULL;
2701}
2702
2703/*
2704 * Called when a journal record is ready to be written.  Space is allocated
2705 * and the journal entry is created when the journal is flushed to stable
2706 * store.
2707 */
2708static void
2709add_to_journal(wk)
2710	struct worklist *wk;
2711{
2712	struct ufsmount *ump;
2713
2714	ump = VFSTOUFS(wk->wk_mp);
2715	LOCK_OWNED(ump);
2716	if (wk->wk_state & ONWORKLIST)
2717		panic("add_to_journal: %s(0x%X) already on list",
2718		    TYPENAME(wk->wk_type), wk->wk_state);
2719	wk->wk_state |= ONWORKLIST | DEPCOMPLETE;
2720	if (LIST_EMPTY(&ump->softdep_journal_pending)) {
2721		ump->softdep_jblocks->jb_age = ticks;
2722		LIST_INSERT_HEAD(&ump->softdep_journal_pending, wk, wk_list);
2723	} else
2724		LIST_INSERT_AFTER(ump->softdep_journal_tail, wk, wk_list);
2725	ump->softdep_journal_tail = wk;
2726	ump->softdep_on_journal += 1;
2727}
2728
2729/*
2730 * Remove an arbitrary item for the journal worklist maintain the tail
2731 * pointer.  This happens when a new operation obviates the need to
2732 * journal an old operation.
2733 */
2734static void
2735remove_from_journal(wk)
2736	struct worklist *wk;
2737{
2738	struct ufsmount *ump;
2739
2740	ump = VFSTOUFS(wk->wk_mp);
2741	LOCK_OWNED(ump);
2742#ifdef SUJ_DEBUG
2743	{
2744		struct worklist *wkn;
2745
2746		LIST_FOREACH(wkn, &ump->softdep_journal_pending, wk_list)
2747			if (wkn == wk)
2748				break;
2749		if (wkn == NULL)
2750			panic("remove_from_journal: %p is not in journal", wk);
2751	}
2752#endif
2753	/*
2754	 * We emulate a TAILQ to save space in most structures which do not
2755	 * require TAILQ semantics.  Here we must update the tail position
2756	 * when removing the tail which is not the final entry. This works
2757	 * only if the worklist linkage are at the beginning of the structure.
2758	 */
2759	if (ump->softdep_journal_tail == wk)
2760		ump->softdep_journal_tail =
2761		    (struct worklist *)wk->wk_list.le_prev;
2762
2763	WORKLIST_REMOVE(wk);
2764	ump->softdep_on_journal -= 1;
2765}
2766
2767/*
2768 * Check for journal space as well as dependency limits so the prelink
2769 * code can throttle both journaled and non-journaled filesystems.
2770 * Threshold is 0 for low and 1 for min.
2771 */
2772static int
2773journal_space(ump, thresh)
2774	struct ufsmount *ump;
2775	int thresh;
2776{
2777	struct jblocks *jblocks;
2778	int limit, avail;
2779
2780	jblocks = ump->softdep_jblocks;
2781	if (jblocks == NULL)
2782		return (1);
2783	/*
2784	 * We use a tighter restriction here to prevent request_cleanup()
2785	 * running in threads from running into locks we currently hold.
2786	 * We have to be over the limit and our filesystem has to be
2787	 * responsible for more than our share of that usage.
2788	 */
2789	limit = (max_softdeps / 10) * 9;
2790	if (dep_current[D_INODEDEP] > limit &&
2791	    ump->softdep_curdeps[D_INODEDEP] > limit / stat_softdep_mounts)
2792		return (0);
2793	if (thresh)
2794		thresh = jblocks->jb_min;
2795	else
2796		thresh = jblocks->jb_low;
2797	avail = (ump->softdep_on_journal * JREC_SIZE) / DEV_BSIZE;
2798	avail = jblocks->jb_free - avail;
2799
2800	return (avail > thresh);
2801}
2802
2803static void
2804journal_suspend(ump)
2805	struct ufsmount *ump;
2806{
2807	struct jblocks *jblocks;
2808	struct mount *mp;
2809
2810	mp = UFSTOVFS(ump);
2811	jblocks = ump->softdep_jblocks;
2812	MNT_ILOCK(mp);
2813	if ((mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
2814		stat_journal_min++;
2815		mp->mnt_kern_flag |= MNTK_SUSPEND;
2816		mp->mnt_susp_owner = FIRST_THREAD_IN_PROC(softdepproc);
2817	}
2818	jblocks->jb_suspended = 1;
2819	MNT_IUNLOCK(mp);
2820}
2821
2822static int
2823journal_unsuspend(struct ufsmount *ump)
2824{
2825	struct jblocks *jblocks;
2826	struct mount *mp;
2827
2828	mp = UFSTOVFS(ump);
2829	jblocks = ump->softdep_jblocks;
2830
2831	if (jblocks != NULL && jblocks->jb_suspended &&
2832	    journal_space(ump, jblocks->jb_min)) {
2833		jblocks->jb_suspended = 0;
2834		FREE_LOCK(ump);
2835		mp->mnt_susp_owner = curthread;
2836		vfs_write_resume(mp, 0);
2837		ACQUIRE_LOCK(ump);
2838		return (1);
2839	}
2840	return (0);
2841}
2842
2843/*
2844 * Called before any allocation function to be certain that there is
2845 * sufficient space in the journal prior to creating any new records.
2846 * Since in the case of block allocation we may have multiple locked
2847 * buffers at the time of the actual allocation we can not block
2848 * when the journal records are created.  Doing so would create a deadlock
2849 * if any of these buffers needed to be flushed to reclaim space.  Instead
2850 * we require a sufficiently large amount of available space such that
2851 * each thread in the system could have passed this allocation check and
2852 * still have sufficient free space.  With 20% of a minimum journal size
2853 * of 1MB we have 6553 records available.
2854 */
2855int
2856softdep_prealloc(vp, waitok)
2857	struct vnode *vp;
2858	int waitok;
2859{
2860	struct ufsmount *ump;
2861
2862	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
2863	    ("softdep_prealloc called on non-softdep filesystem"));
2864	/*
2865	 * Nothing to do if we are not running journaled soft updates.
2866	 * If we currently hold the snapshot lock, we must avoid handling
2867	 * other resources that could cause deadlock.
2868	 */
2869	if (DOINGSUJ(vp) == 0 || IS_SNAPSHOT(VTOI(vp)))
2870		return (0);
2871	ump = VFSTOUFS(vp->v_mount);
2872	ACQUIRE_LOCK(ump);
2873	if (journal_space(ump, 0)) {
2874		FREE_LOCK(ump);
2875		return (0);
2876	}
2877	stat_journal_low++;
2878	FREE_LOCK(ump);
2879	if (waitok == MNT_NOWAIT)
2880		return (ENOSPC);
2881	/*
2882	 * Attempt to sync this vnode once to flush any journal
2883	 * work attached to it.
2884	 */
2885	if ((curthread->td_pflags & TDP_COWINPROGRESS) == 0)
2886		ffs_syncvnode(vp, waitok, 0);
2887	ACQUIRE_LOCK(ump);
2888	process_removes(vp);
2889	process_truncates(vp);
2890	if (journal_space(ump, 0) == 0) {
2891		softdep_speedup();
2892		if (journal_space(ump, 1) == 0)
2893			journal_suspend(ump);
2894	}
2895	FREE_LOCK(ump);
2896
2897	return (0);
2898}
2899
2900/*
2901 * Before adjusting a link count on a vnode verify that we have sufficient
2902 * journal space.  If not, process operations that depend on the currently
2903 * locked pair of vnodes to try to flush space as the syncer, buf daemon,
2904 * and softdep flush threads can not acquire these locks to reclaim space.
2905 */
2906static void
2907softdep_prelink(dvp, vp)
2908	struct vnode *dvp;
2909	struct vnode *vp;
2910{
2911	struct ufsmount *ump;
2912
2913	ump = VFSTOUFS(dvp->v_mount);
2914	LOCK_OWNED(ump);
2915	/*
2916	 * Nothing to do if we have sufficient journal space.
2917	 * If we currently hold the snapshot lock, we must avoid
2918	 * handling other resources that could cause deadlock.
2919	 */
2920	if (journal_space(ump, 0) || (vp && IS_SNAPSHOT(VTOI(vp))))
2921		return;
2922	stat_journal_low++;
2923	FREE_LOCK(ump);
2924	if (vp)
2925		ffs_syncvnode(vp, MNT_NOWAIT, 0);
2926	ffs_syncvnode(dvp, MNT_WAIT, 0);
2927	ACQUIRE_LOCK(ump);
2928	/* Process vp before dvp as it may create .. removes. */
2929	if (vp) {
2930		process_removes(vp);
2931		process_truncates(vp);
2932	}
2933	process_removes(dvp);
2934	process_truncates(dvp);
2935	softdep_speedup();
2936	process_worklist_item(UFSTOVFS(ump), 2, LK_NOWAIT);
2937	if (journal_space(ump, 0) == 0) {
2938		softdep_speedup();
2939		if (journal_space(ump, 1) == 0)
2940			journal_suspend(ump);
2941	}
2942}
2943
2944static void
2945jseg_write(ump, jseg, data)
2946	struct ufsmount *ump;
2947	struct jseg *jseg;
2948	uint8_t *data;
2949{
2950	struct jsegrec *rec;
2951
2952	rec = (struct jsegrec *)data;
2953	rec->jsr_seq = jseg->js_seq;
2954	rec->jsr_oldest = jseg->js_oldseq;
2955	rec->jsr_cnt = jseg->js_cnt;
2956	rec->jsr_blocks = jseg->js_size / ump->um_devvp->v_bufobj.bo_bsize;
2957	rec->jsr_crc = 0;
2958	rec->jsr_time = ump->um_fs->fs_mtime;
2959}
2960
2961static inline void
2962inoref_write(inoref, jseg, rec)
2963	struct inoref *inoref;
2964	struct jseg *jseg;
2965	struct jrefrec *rec;
2966{
2967
2968	inoref->if_jsegdep->jd_seg = jseg;
2969	rec->jr_ino = inoref->if_ino;
2970	rec->jr_parent = inoref->if_parent;
2971	rec->jr_nlink = inoref->if_nlink;
2972	rec->jr_mode = inoref->if_mode;
2973	rec->jr_diroff = inoref->if_diroff;
2974}
2975
2976static void
2977jaddref_write(jaddref, jseg, data)
2978	struct jaddref *jaddref;
2979	struct jseg *jseg;
2980	uint8_t *data;
2981{
2982	struct jrefrec *rec;
2983
2984	rec = (struct jrefrec *)data;
2985	rec->jr_op = JOP_ADDREF;
2986	inoref_write(&jaddref->ja_ref, jseg, rec);
2987}
2988
2989static void
2990jremref_write(jremref, jseg, data)
2991	struct jremref *jremref;
2992	struct jseg *jseg;
2993	uint8_t *data;
2994{
2995	struct jrefrec *rec;
2996
2997	rec = (struct jrefrec *)data;
2998	rec->jr_op = JOP_REMREF;
2999	inoref_write(&jremref->jr_ref, jseg, rec);
3000}
3001
3002static void
3003jmvref_write(jmvref, jseg, data)
3004	struct jmvref *jmvref;
3005	struct jseg *jseg;
3006	uint8_t *data;
3007{
3008	struct jmvrec *rec;
3009
3010	rec = (struct jmvrec *)data;
3011	rec->jm_op = JOP_MVREF;
3012	rec->jm_ino = jmvref->jm_ino;
3013	rec->jm_parent = jmvref->jm_parent;
3014	rec->jm_oldoff = jmvref->jm_oldoff;
3015	rec->jm_newoff = jmvref->jm_newoff;
3016}
3017
3018static void
3019jnewblk_write(jnewblk, jseg, data)
3020	struct jnewblk *jnewblk;
3021	struct jseg *jseg;
3022	uint8_t *data;
3023{
3024	struct jblkrec *rec;
3025
3026	jnewblk->jn_jsegdep->jd_seg = jseg;
3027	rec = (struct jblkrec *)data;
3028	rec->jb_op = JOP_NEWBLK;
3029	rec->jb_ino = jnewblk->jn_ino;
3030	rec->jb_blkno = jnewblk->jn_blkno;
3031	rec->jb_lbn = jnewblk->jn_lbn;
3032	rec->jb_frags = jnewblk->jn_frags;
3033	rec->jb_oldfrags = jnewblk->jn_oldfrags;
3034}
3035
3036static void
3037jfreeblk_write(jfreeblk, jseg, data)
3038	struct jfreeblk *jfreeblk;
3039	struct jseg *jseg;
3040	uint8_t *data;
3041{
3042	struct jblkrec *rec;
3043
3044	jfreeblk->jf_dep.jb_jsegdep->jd_seg = jseg;
3045	rec = (struct jblkrec *)data;
3046	rec->jb_op = JOP_FREEBLK;
3047	rec->jb_ino = jfreeblk->jf_ino;
3048	rec->jb_blkno = jfreeblk->jf_blkno;
3049	rec->jb_lbn = jfreeblk->jf_lbn;
3050	rec->jb_frags = jfreeblk->jf_frags;
3051	rec->jb_oldfrags = 0;
3052}
3053
3054static void
3055jfreefrag_write(jfreefrag, jseg, data)
3056	struct jfreefrag *jfreefrag;
3057	struct jseg *jseg;
3058	uint8_t *data;
3059{
3060	struct jblkrec *rec;
3061
3062	jfreefrag->fr_jsegdep->jd_seg = jseg;
3063	rec = (struct jblkrec *)data;
3064	rec->jb_op = JOP_FREEBLK;
3065	rec->jb_ino = jfreefrag->fr_ino;
3066	rec->jb_blkno = jfreefrag->fr_blkno;
3067	rec->jb_lbn = jfreefrag->fr_lbn;
3068	rec->jb_frags = jfreefrag->fr_frags;
3069	rec->jb_oldfrags = 0;
3070}
3071
3072static void
3073jtrunc_write(jtrunc, jseg, data)
3074	struct jtrunc *jtrunc;
3075	struct jseg *jseg;
3076	uint8_t *data;
3077{
3078	struct jtrncrec *rec;
3079
3080	jtrunc->jt_dep.jb_jsegdep->jd_seg = jseg;
3081	rec = (struct jtrncrec *)data;
3082	rec->jt_op = JOP_TRUNC;
3083	rec->jt_ino = jtrunc->jt_ino;
3084	rec->jt_size = jtrunc->jt_size;
3085	rec->jt_extsize = jtrunc->jt_extsize;
3086}
3087
3088static void
3089jfsync_write(jfsync, jseg, data)
3090	struct jfsync *jfsync;
3091	struct jseg *jseg;
3092	uint8_t *data;
3093{
3094	struct jtrncrec *rec;
3095
3096	rec = (struct jtrncrec *)data;
3097	rec->jt_op = JOP_SYNC;
3098	rec->jt_ino = jfsync->jfs_ino;
3099	rec->jt_size = jfsync->jfs_size;
3100	rec->jt_extsize = jfsync->jfs_extsize;
3101}
3102
3103static void
3104softdep_flushjournal(mp)
3105	struct mount *mp;
3106{
3107	struct jblocks *jblocks;
3108	struct ufsmount *ump;
3109
3110	if (MOUNTEDSUJ(mp) == 0)
3111		return;
3112	ump = VFSTOUFS(mp);
3113	jblocks = ump->softdep_jblocks;
3114	ACQUIRE_LOCK(ump);
3115	while (ump->softdep_on_journal) {
3116		jblocks->jb_needseg = 1;
3117		softdep_process_journal(mp, NULL, MNT_WAIT);
3118	}
3119	FREE_LOCK(ump);
3120}
3121
3122static void softdep_synchronize_completed(struct bio *);
3123static void softdep_synchronize(struct bio *, struct ufsmount *, void *);
3124
3125static void
3126softdep_synchronize_completed(bp)
3127        struct bio *bp;
3128{
3129	struct jseg *oldest;
3130	struct jseg *jseg;
3131	struct ufsmount *ump;
3132
3133	/*
3134	 * caller1 marks the last segment written before we issued the
3135	 * synchronize cache.
3136	 */
3137	jseg = bp->bio_caller1;
3138	if (jseg == NULL) {
3139		g_destroy_bio(bp);
3140		return;
3141	}
3142	ump = VFSTOUFS(jseg->js_list.wk_mp);
3143	ACQUIRE_LOCK(ump);
3144	oldest = NULL;
3145	/*
3146	 * Mark all the journal entries waiting on the synchronize cache
3147	 * as completed so they may continue on.
3148	 */
3149	while (jseg != NULL && (jseg->js_state & COMPLETE) == 0) {
3150		jseg->js_state |= COMPLETE;
3151		oldest = jseg;
3152		jseg = TAILQ_PREV(jseg, jseglst, js_next);
3153	}
3154	/*
3155	 * Restart deferred journal entry processing from the oldest
3156	 * completed jseg.
3157	 */
3158	if (oldest)
3159		complete_jsegs(oldest);
3160
3161	FREE_LOCK(ump);
3162	g_destroy_bio(bp);
3163}
3164
3165/*
3166 * Send BIO_FLUSH/SYNCHRONIZE CACHE to the device to enforce write ordering
3167 * barriers.  The journal must be written prior to any blocks that depend
3168 * on it and the journal can not be released until the blocks have be
3169 * written.  This code handles both barriers simultaneously.
3170 */
3171static void
3172softdep_synchronize(bp, ump, caller1)
3173	struct bio *bp;
3174	struct ufsmount *ump;
3175	void *caller1;
3176{
3177
3178	bp->bio_cmd = BIO_FLUSH;
3179	bp->bio_flags |= BIO_ORDERED;
3180	bp->bio_data = NULL;
3181	bp->bio_offset = ump->um_cp->provider->mediasize;
3182	bp->bio_length = 0;
3183	bp->bio_done = softdep_synchronize_completed;
3184	bp->bio_caller1 = caller1;
3185	g_io_request(bp,
3186	    (struct g_consumer *)ump->um_devvp->v_bufobj.bo_private);
3187}
3188
3189/*
3190 * Flush some journal records to disk.
3191 */
3192static void
3193softdep_process_journal(mp, needwk, flags)
3194	struct mount *mp;
3195	struct worklist *needwk;
3196	int flags;
3197{
3198	struct jblocks *jblocks;
3199	struct ufsmount *ump;
3200	struct worklist *wk;
3201	struct jseg *jseg;
3202	struct buf *bp;
3203	struct bio *bio;
3204	uint8_t *data;
3205	struct fs *fs;
3206	int shouldflush;
3207	int segwritten;
3208	int jrecmin;	/* Minimum records per block. */
3209	int jrecmax;	/* Maximum records per block. */
3210	int size;
3211	int cnt;
3212	int off;
3213	int devbsize;
3214
3215	if (MOUNTEDSUJ(mp) == 0)
3216		return;
3217	shouldflush = softdep_flushcache;
3218	bio = NULL;
3219	jseg = NULL;
3220	ump = VFSTOUFS(mp);
3221	LOCK_OWNED(ump);
3222	fs = ump->um_fs;
3223	jblocks = ump->softdep_jblocks;
3224	devbsize = ump->um_devvp->v_bufobj.bo_bsize;
3225	/*
3226	 * We write anywhere between a disk block and fs block.  The upper
3227	 * bound is picked to prevent buffer cache fragmentation and limit
3228	 * processing time per I/O.
3229	 */
3230	jrecmin = (devbsize / JREC_SIZE) - 1; /* -1 for seg header */
3231	jrecmax = (fs->fs_bsize / devbsize) * jrecmin;
3232	segwritten = 0;
3233	for (;;) {
3234		cnt = ump->softdep_on_journal;
3235		/*
3236		 * Criteria for writing a segment:
3237		 * 1) We have a full block.
3238		 * 2) We're called from jwait() and haven't found the
3239		 *    journal item yet.
3240		 * 3) Always write if needseg is set.
3241		 * 4) If we are called from process_worklist and have
3242		 *    not yet written anything we write a partial block
3243		 *    to enforce a 1 second maximum latency on journal
3244		 *    entries.
3245		 */
3246		if (cnt < (jrecmax - 1) && needwk == NULL &&
3247		    jblocks->jb_needseg == 0 && (segwritten || cnt == 0))
3248			break;
3249		cnt++;
3250		/*
3251		 * Verify some free journal space.  softdep_prealloc() should
3252		 * guarantee that we don't run out so this is indicative of
3253		 * a problem with the flow control.  Try to recover
3254		 * gracefully in any event.
3255		 */
3256		while (jblocks->jb_free == 0) {
3257			if (flags != MNT_WAIT)
3258				break;
3259			printf("softdep: Out of journal space!\n");
3260			softdep_speedup();
3261			msleep(jblocks, LOCK_PTR(ump), PRIBIO, "jblocks", hz);
3262		}
3263		FREE_LOCK(ump);
3264		jseg = malloc(sizeof(*jseg), M_JSEG, M_SOFTDEP_FLAGS);
3265		workitem_alloc(&jseg->js_list, D_JSEG, mp);
3266		LIST_INIT(&jseg->js_entries);
3267		LIST_INIT(&jseg->js_indirs);
3268		jseg->js_state = ATTACHED;
3269		if (shouldflush == 0)
3270			jseg->js_state |= COMPLETE;
3271		else if (bio == NULL)
3272			bio = g_alloc_bio();
3273		jseg->js_jblocks = jblocks;
3274		bp = geteblk(fs->fs_bsize, 0);
3275		ACQUIRE_LOCK(ump);
3276		/*
3277		 * If there was a race while we were allocating the block
3278		 * and jseg the entry we care about was likely written.
3279		 * We bail out in both the WAIT and NOWAIT case and assume
3280		 * the caller will loop if the entry it cares about is
3281		 * not written.
3282		 */
3283		cnt = ump->softdep_on_journal;
3284		if (cnt + jblocks->jb_needseg == 0 || jblocks->jb_free == 0) {
3285			bp->b_flags |= B_INVAL | B_NOCACHE;
3286			WORKITEM_FREE(jseg, D_JSEG);
3287			FREE_LOCK(ump);
3288			brelse(bp);
3289			ACQUIRE_LOCK(ump);
3290			break;
3291		}
3292		/*
3293		 * Calculate the disk block size required for the available
3294		 * records rounded to the min size.
3295		 */
3296		if (cnt == 0)
3297			size = devbsize;
3298		else if (cnt < jrecmax)
3299			size = howmany(cnt, jrecmin) * devbsize;
3300		else
3301			size = fs->fs_bsize;
3302		/*
3303		 * Allocate a disk block for this journal data and account
3304		 * for truncation of the requested size if enough contiguous
3305		 * space was not available.
3306		 */
3307		bp->b_blkno = jblocks_alloc(jblocks, size, &size);
3308		bp->b_lblkno = bp->b_blkno;
3309		bp->b_offset = bp->b_blkno * DEV_BSIZE;
3310		bp->b_bcount = size;
3311		bp->b_flags &= ~B_INVAL;
3312		bp->b_flags |= B_VALIDSUSPWRT | B_NOCOPY;
3313		/*
3314		 * Initialize our jseg with cnt records.  Assign the next
3315		 * sequence number to it and link it in-order.
3316		 */
3317		cnt = MIN(cnt, (size / devbsize) * jrecmin);
3318		jseg->js_buf = bp;
3319		jseg->js_cnt = cnt;
3320		jseg->js_refs = cnt + 1;	/* Self ref. */
3321		jseg->js_size = size;
3322		jseg->js_seq = jblocks->jb_nextseq++;
3323		if (jblocks->jb_oldestseg == NULL)
3324			jblocks->jb_oldestseg = jseg;
3325		jseg->js_oldseq = jblocks->jb_oldestseg->js_seq;
3326		TAILQ_INSERT_TAIL(&jblocks->jb_segs, jseg, js_next);
3327		if (jblocks->jb_writeseg == NULL)
3328			jblocks->jb_writeseg = jseg;
3329		/*
3330		 * Start filling in records from the pending list.
3331		 */
3332		data = bp->b_data;
3333		off = 0;
3334
3335		/*
3336		 * Always put a header on the first block.
3337		 * XXX As with below, there might not be a chance to get
3338		 * into the loop.  Ensure that something valid is written.
3339		 */
3340		jseg_write(ump, jseg, data);
3341		off += JREC_SIZE;
3342		data = bp->b_data + off;
3343
3344		/*
3345		 * XXX Something is wrong here.  There's no work to do,
3346		 * but we need to perform and I/O and allow it to complete
3347		 * anyways.
3348		 */
3349		if (LIST_EMPTY(&ump->softdep_journal_pending))
3350			stat_emptyjblocks++;
3351
3352		while ((wk = LIST_FIRST(&ump->softdep_journal_pending))
3353		    != NULL) {
3354			if (cnt == 0)
3355				break;
3356			/* Place a segment header on every device block. */
3357			if ((off % devbsize) == 0) {
3358				jseg_write(ump, jseg, data);
3359				off += JREC_SIZE;
3360				data = bp->b_data + off;
3361			}
3362			if (wk == needwk)
3363				needwk = NULL;
3364			remove_from_journal(wk);
3365			wk->wk_state |= INPROGRESS;
3366			WORKLIST_INSERT(&jseg->js_entries, wk);
3367			switch (wk->wk_type) {
3368			case D_JADDREF:
3369				jaddref_write(WK_JADDREF(wk), jseg, data);
3370				break;
3371			case D_JREMREF:
3372				jremref_write(WK_JREMREF(wk), jseg, data);
3373				break;
3374			case D_JMVREF:
3375				jmvref_write(WK_JMVREF(wk), jseg, data);
3376				break;
3377			case D_JNEWBLK:
3378				jnewblk_write(WK_JNEWBLK(wk), jseg, data);
3379				break;
3380			case D_JFREEBLK:
3381				jfreeblk_write(WK_JFREEBLK(wk), jseg, data);
3382				break;
3383			case D_JFREEFRAG:
3384				jfreefrag_write(WK_JFREEFRAG(wk), jseg, data);
3385				break;
3386			case D_JTRUNC:
3387				jtrunc_write(WK_JTRUNC(wk), jseg, data);
3388				break;
3389			case D_JFSYNC:
3390				jfsync_write(WK_JFSYNC(wk), jseg, data);
3391				break;
3392			default:
3393				panic("process_journal: Unknown type %s",
3394				    TYPENAME(wk->wk_type));
3395				/* NOTREACHED */
3396			}
3397			off += JREC_SIZE;
3398			data = bp->b_data + off;
3399			cnt--;
3400		}
3401
3402		/* Clear any remaining space so we don't leak kernel data */
3403		if (size > off)
3404			bzero(data, size - off);
3405
3406		/*
3407		 * Write this one buffer and continue.
3408		 */
3409		segwritten = 1;
3410		jblocks->jb_needseg = 0;
3411		WORKLIST_INSERT(&bp->b_dep, &jseg->js_list);
3412		FREE_LOCK(ump);
3413		pbgetvp(ump->um_devvp, bp);
3414		/*
3415		 * We only do the blocking wait once we find the journal
3416		 * entry we're looking for.
3417		 */
3418		if (needwk == NULL && flags == MNT_WAIT)
3419			bwrite(bp);
3420		else
3421			bawrite(bp);
3422		ACQUIRE_LOCK(ump);
3423	}
3424	/*
3425	 * If we wrote a segment issue a synchronize cache so the journal
3426	 * is reflected on disk before the data is written.  Since reclaiming
3427	 * journal space also requires writing a journal record this
3428	 * process also enforces a barrier before reclamation.
3429	 */
3430	if (segwritten && shouldflush) {
3431		softdep_synchronize(bio, ump,
3432		    TAILQ_LAST(&jblocks->jb_segs, jseglst));
3433	} else if (bio)
3434		g_destroy_bio(bio);
3435	/*
3436	 * If we've suspended the filesystem because we ran out of journal
3437	 * space either try to sync it here to make some progress or
3438	 * unsuspend it if we already have.
3439	 */
3440	if (flags == 0 && jblocks->jb_suspended) {
3441		if (journal_unsuspend(ump))
3442			return;
3443		FREE_LOCK(ump);
3444		VFS_SYNC(mp, MNT_NOWAIT);
3445		ffs_sbupdate(ump, MNT_WAIT, 0);
3446		ACQUIRE_LOCK(ump);
3447	}
3448}
3449
3450/*
3451 * Complete a jseg, allowing all dependencies awaiting journal writes
3452 * to proceed.  Each journal dependency also attaches a jsegdep to dependent
3453 * structures so that the journal segment can be freed to reclaim space.
3454 */
3455static void
3456complete_jseg(jseg)
3457	struct jseg *jseg;
3458{
3459	struct worklist *wk;
3460	struct jmvref *jmvref;
3461	int waiting;
3462#ifdef INVARIANTS
3463	int i = 0;
3464#endif
3465
3466	while ((wk = LIST_FIRST(&jseg->js_entries)) != NULL) {
3467		WORKLIST_REMOVE(wk);
3468		waiting = wk->wk_state & IOWAITING;
3469		wk->wk_state &= ~(INPROGRESS | IOWAITING);
3470		wk->wk_state |= COMPLETE;
3471		KASSERT(i++ < jseg->js_cnt,
3472		    ("handle_written_jseg: overflow %d >= %d",
3473		    i - 1, jseg->js_cnt));
3474		switch (wk->wk_type) {
3475		case D_JADDREF:
3476			handle_written_jaddref(WK_JADDREF(wk));
3477			break;
3478		case D_JREMREF:
3479			handle_written_jremref(WK_JREMREF(wk));
3480			break;
3481		case D_JMVREF:
3482			rele_jseg(jseg);	/* No jsegdep. */
3483			jmvref = WK_JMVREF(wk);
3484			LIST_REMOVE(jmvref, jm_deps);
3485			if ((jmvref->jm_pagedep->pd_state & ONWORKLIST) == 0)
3486				free_pagedep(jmvref->jm_pagedep);
3487			WORKITEM_FREE(jmvref, D_JMVREF);
3488			break;
3489		case D_JNEWBLK:
3490			handle_written_jnewblk(WK_JNEWBLK(wk));
3491			break;
3492		case D_JFREEBLK:
3493			handle_written_jblkdep(&WK_JFREEBLK(wk)->jf_dep);
3494			break;
3495		case D_JTRUNC:
3496			handle_written_jblkdep(&WK_JTRUNC(wk)->jt_dep);
3497			break;
3498		case D_JFSYNC:
3499			rele_jseg(jseg);	/* No jsegdep. */
3500			WORKITEM_FREE(wk, D_JFSYNC);
3501			break;
3502		case D_JFREEFRAG:
3503			handle_written_jfreefrag(WK_JFREEFRAG(wk));
3504			break;
3505		default:
3506			panic("handle_written_jseg: Unknown type %s",
3507			    TYPENAME(wk->wk_type));
3508			/* NOTREACHED */
3509		}
3510		if (waiting)
3511			wakeup(wk);
3512	}
3513	/* Release the self reference so the structure may be freed. */
3514	rele_jseg(jseg);
3515}
3516
3517/*
3518 * Determine which jsegs are ready for completion processing.  Waits for
3519 * synchronize cache to complete as well as forcing in-order completion
3520 * of journal entries.
3521 */
3522static void
3523complete_jsegs(jseg)
3524	struct jseg *jseg;
3525{
3526	struct jblocks *jblocks;
3527	struct jseg *jsegn;
3528
3529	jblocks = jseg->js_jblocks;
3530	/*
3531	 * Don't allow out of order completions.  If this isn't the first
3532	 * block wait for it to write before we're done.
3533	 */
3534	if (jseg != jblocks->jb_writeseg)
3535		return;
3536	/* Iterate through available jsegs processing their entries. */
3537	while (jseg && (jseg->js_state & ALLCOMPLETE) == ALLCOMPLETE) {
3538		jblocks->jb_oldestwrseq = jseg->js_oldseq;
3539		jsegn = TAILQ_NEXT(jseg, js_next);
3540		complete_jseg(jseg);
3541		jseg = jsegn;
3542	}
3543	jblocks->jb_writeseg = jseg;
3544	/*
3545	 * Attempt to free jsegs now that oldestwrseq may have advanced.
3546	 */
3547	free_jsegs(jblocks);
3548}
3549
3550/*
3551 * Mark a jseg as DEPCOMPLETE and throw away the buffer.  Attempt to handle
3552 * the final completions.
3553 */
3554static void
3555handle_written_jseg(jseg, bp)
3556	struct jseg *jseg;
3557	struct buf *bp;
3558{
3559
3560	if (jseg->js_refs == 0)
3561		panic("handle_written_jseg: No self-reference on %p", jseg);
3562	jseg->js_state |= DEPCOMPLETE;
3563	/*
3564	 * We'll never need this buffer again, set flags so it will be
3565	 * discarded.
3566	 */
3567	bp->b_flags |= B_INVAL | B_NOCACHE;
3568	pbrelvp(bp);
3569	complete_jsegs(jseg);
3570}
3571
3572static inline struct jsegdep *
3573inoref_jseg(inoref)
3574	struct inoref *inoref;
3575{
3576	struct jsegdep *jsegdep;
3577
3578	jsegdep = inoref->if_jsegdep;
3579	inoref->if_jsegdep = NULL;
3580
3581	return (jsegdep);
3582}
3583
3584/*
3585 * Called once a jremref has made it to stable store.  The jremref is marked
3586 * complete and we attempt to free it.  Any pagedeps writes sleeping waiting
3587 * for the jremref to complete will be awoken by free_jremref.
3588 */
3589static void
3590handle_written_jremref(jremref)
3591	struct jremref *jremref;
3592{
3593	struct inodedep *inodedep;
3594	struct jsegdep *jsegdep;
3595	struct dirrem *dirrem;
3596
3597	/* Grab the jsegdep. */
3598	jsegdep = inoref_jseg(&jremref->jr_ref);
3599	/*
3600	 * Remove us from the inoref list.
3601	 */
3602	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino,
3603	    0, &inodedep) == 0)
3604		panic("handle_written_jremref: Lost inodedep");
3605	TAILQ_REMOVE(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
3606	/*
3607	 * Complete the dirrem.
3608	 */
3609	dirrem = jremref->jr_dirrem;
3610	jremref->jr_dirrem = NULL;
3611	LIST_REMOVE(jremref, jr_deps);
3612	jsegdep->jd_state |= jremref->jr_state & MKDIR_PARENT;
3613	jwork_insert(&dirrem->dm_jwork, jsegdep);
3614	if (LIST_EMPTY(&dirrem->dm_jremrefhd) &&
3615	    (dirrem->dm_state & COMPLETE) != 0)
3616		add_to_worklist(&dirrem->dm_list, 0);
3617	free_jremref(jremref);
3618}
3619
3620/*
3621 * Called once a jaddref has made it to stable store.  The dependency is
3622 * marked complete and any dependent structures are added to the inode
3623 * bufwait list to be completed as soon as it is written.  If a bitmap write
3624 * depends on this entry we move the inode into the inodedephd of the
3625 * bmsafemap dependency and attempt to remove the jaddref from the bmsafemap.
3626 */
3627static void
3628handle_written_jaddref(jaddref)
3629	struct jaddref *jaddref;
3630{
3631	struct jsegdep *jsegdep;
3632	struct inodedep *inodedep;
3633	struct diradd *diradd;
3634	struct mkdir *mkdir;
3635
3636	/* Grab the jsegdep. */
3637	jsegdep = inoref_jseg(&jaddref->ja_ref);
3638	mkdir = NULL;
3639	diradd = NULL;
3640	if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
3641	    0, &inodedep) == 0)
3642		panic("handle_written_jaddref: Lost inodedep.");
3643	if (jaddref->ja_diradd == NULL)
3644		panic("handle_written_jaddref: No dependency");
3645	if (jaddref->ja_diradd->da_list.wk_type == D_DIRADD) {
3646		diradd = jaddref->ja_diradd;
3647		WORKLIST_INSERT(&inodedep->id_bufwait, &diradd->da_list);
3648	} else if (jaddref->ja_state & MKDIR_PARENT) {
3649		mkdir = jaddref->ja_mkdir;
3650		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir->md_list);
3651	} else if (jaddref->ja_state & MKDIR_BODY)
3652		mkdir = jaddref->ja_mkdir;
3653	else
3654		panic("handle_written_jaddref: Unknown dependency %p",
3655		    jaddref->ja_diradd);
3656	jaddref->ja_diradd = NULL;	/* also clears ja_mkdir */
3657	/*
3658	 * Remove us from the inode list.
3659	 */
3660	TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref, if_deps);
3661	/*
3662	 * The mkdir may be waiting on the jaddref to clear before freeing.
3663	 */
3664	if (mkdir) {
3665		KASSERT(mkdir->md_list.wk_type == D_MKDIR,
3666		    ("handle_written_jaddref: Incorrect type for mkdir %s",
3667		    TYPENAME(mkdir->md_list.wk_type)));
3668		mkdir->md_jaddref = NULL;
3669		diradd = mkdir->md_diradd;
3670		mkdir->md_state |= DEPCOMPLETE;
3671		complete_mkdir(mkdir);
3672	}
3673	jwork_insert(&diradd->da_jwork, jsegdep);
3674	if (jaddref->ja_state & NEWBLOCK) {
3675		inodedep->id_state |= ONDEPLIST;
3676		LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_inodedephd,
3677		    inodedep, id_deps);
3678	}
3679	free_jaddref(jaddref);
3680}
3681
3682/*
3683 * Called once a jnewblk journal is written.  The allocdirect or allocindir
3684 * is placed in the bmsafemap to await notification of a written bitmap.  If
3685 * the operation was canceled we add the segdep to the appropriate
3686 * dependency to free the journal space once the canceling operation
3687 * completes.
3688 */
3689static void
3690handle_written_jnewblk(jnewblk)
3691	struct jnewblk *jnewblk;
3692{
3693	struct bmsafemap *bmsafemap;
3694	struct freefrag *freefrag;
3695	struct freework *freework;
3696	struct jsegdep *jsegdep;
3697	struct newblk *newblk;
3698
3699	/* Grab the jsegdep. */
3700	jsegdep = jnewblk->jn_jsegdep;
3701	jnewblk->jn_jsegdep = NULL;
3702	if (jnewblk->jn_dep == NULL)
3703		panic("handle_written_jnewblk: No dependency for the segdep.");
3704	switch (jnewblk->jn_dep->wk_type) {
3705	case D_NEWBLK:
3706	case D_ALLOCDIRECT:
3707	case D_ALLOCINDIR:
3708		/*
3709		 * Add the written block to the bmsafemap so it can
3710		 * be notified when the bitmap is on disk.
3711		 */
3712		newblk = WK_NEWBLK(jnewblk->jn_dep);
3713		newblk->nb_jnewblk = NULL;
3714		if ((newblk->nb_state & GOINGAWAY) == 0) {
3715			bmsafemap = newblk->nb_bmsafemap;
3716			newblk->nb_state |= ONDEPLIST;
3717			LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk,
3718			    nb_deps);
3719		}
3720		jwork_insert(&newblk->nb_jwork, jsegdep);
3721		break;
3722	case D_FREEFRAG:
3723		/*
3724		 * A newblock being removed by a freefrag when replaced by
3725		 * frag extension.
3726		 */
3727		freefrag = WK_FREEFRAG(jnewblk->jn_dep);
3728		freefrag->ff_jdep = NULL;
3729		jwork_insert(&freefrag->ff_jwork, jsegdep);
3730		break;
3731	case D_FREEWORK:
3732		/*
3733		 * A direct block was removed by truncate.
3734		 */
3735		freework = WK_FREEWORK(jnewblk->jn_dep);
3736		freework->fw_jnewblk = NULL;
3737		jwork_insert(&freework->fw_freeblks->fb_jwork, jsegdep);
3738		break;
3739	default:
3740		panic("handle_written_jnewblk: Unknown type %d.",
3741		    jnewblk->jn_dep->wk_type);
3742	}
3743	jnewblk->jn_dep = NULL;
3744	free_jnewblk(jnewblk);
3745}
3746
3747/*
3748 * Cancel a jfreefrag that won't be needed, probably due to colliding with
3749 * an in-flight allocation that has not yet been committed.  Divorce us
3750 * from the freefrag and mark it DEPCOMPLETE so that it may be added
3751 * to the worklist.
3752 */
3753static void
3754cancel_jfreefrag(jfreefrag)
3755	struct jfreefrag *jfreefrag;
3756{
3757	struct freefrag *freefrag;
3758
3759	if (jfreefrag->fr_jsegdep) {
3760		free_jsegdep(jfreefrag->fr_jsegdep);
3761		jfreefrag->fr_jsegdep = NULL;
3762	}
3763	freefrag = jfreefrag->fr_freefrag;
3764	jfreefrag->fr_freefrag = NULL;
3765	free_jfreefrag(jfreefrag);
3766	freefrag->ff_state |= DEPCOMPLETE;
3767	CTR1(KTR_SUJ, "cancel_jfreefrag: blkno %jd", freefrag->ff_blkno);
3768}
3769
3770/*
3771 * Free a jfreefrag when the parent freefrag is rendered obsolete.
3772 */
3773static void
3774free_jfreefrag(jfreefrag)
3775	struct jfreefrag *jfreefrag;
3776{
3777
3778	if (jfreefrag->fr_state & INPROGRESS)
3779		WORKLIST_REMOVE(&jfreefrag->fr_list);
3780	else if (jfreefrag->fr_state & ONWORKLIST)
3781		remove_from_journal(&jfreefrag->fr_list);
3782	if (jfreefrag->fr_freefrag != NULL)
3783		panic("free_jfreefrag:  Still attached to a freefrag.");
3784	WORKITEM_FREE(jfreefrag, D_JFREEFRAG);
3785}
3786
3787/*
3788 * Called when the journal write for a jfreefrag completes.  The parent
3789 * freefrag is added to the worklist if this completes its dependencies.
3790 */
3791static void
3792handle_written_jfreefrag(jfreefrag)
3793	struct jfreefrag *jfreefrag;
3794{
3795	struct jsegdep *jsegdep;
3796	struct freefrag *freefrag;
3797
3798	/* Grab the jsegdep. */
3799	jsegdep = jfreefrag->fr_jsegdep;
3800	jfreefrag->fr_jsegdep = NULL;
3801	freefrag = jfreefrag->fr_freefrag;
3802	if (freefrag == NULL)
3803		panic("handle_written_jfreefrag: No freefrag.");
3804	freefrag->ff_state |= DEPCOMPLETE;
3805	freefrag->ff_jdep = NULL;
3806	jwork_insert(&freefrag->ff_jwork, jsegdep);
3807	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
3808		add_to_worklist(&freefrag->ff_list, 0);
3809	jfreefrag->fr_freefrag = NULL;
3810	free_jfreefrag(jfreefrag);
3811}
3812
3813/*
3814 * Called when the journal write for a jfreeblk completes.  The jfreeblk
3815 * is removed from the freeblks list of pending journal writes and the
3816 * jsegdep is moved to the freeblks jwork to be completed when all blocks
3817 * have been reclaimed.
3818 */
3819static void
3820handle_written_jblkdep(jblkdep)
3821	struct jblkdep *jblkdep;
3822{
3823	struct freeblks *freeblks;
3824	struct jsegdep *jsegdep;
3825
3826	/* Grab the jsegdep. */
3827	jsegdep = jblkdep->jb_jsegdep;
3828	jblkdep->jb_jsegdep = NULL;
3829	freeblks = jblkdep->jb_freeblks;
3830	LIST_REMOVE(jblkdep, jb_deps);
3831	jwork_insert(&freeblks->fb_jwork, jsegdep);
3832	/*
3833	 * If the freeblks is all journaled, we can add it to the worklist.
3834	 */
3835	if (LIST_EMPTY(&freeblks->fb_jblkdephd) &&
3836	    (freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
3837		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
3838
3839	free_jblkdep(jblkdep);
3840}
3841
3842static struct jsegdep *
3843newjsegdep(struct worklist *wk)
3844{
3845	struct jsegdep *jsegdep;
3846
3847	jsegdep = malloc(sizeof(*jsegdep), M_JSEGDEP, M_SOFTDEP_FLAGS);
3848	workitem_alloc(&jsegdep->jd_list, D_JSEGDEP, wk->wk_mp);
3849	jsegdep->jd_seg = NULL;
3850
3851	return (jsegdep);
3852}
3853
3854static struct jmvref *
3855newjmvref(dp, ino, oldoff, newoff)
3856	struct inode *dp;
3857	ino_t ino;
3858	off_t oldoff;
3859	off_t newoff;
3860{
3861	struct jmvref *jmvref;
3862
3863	jmvref = malloc(sizeof(*jmvref), M_JMVREF, M_SOFTDEP_FLAGS);
3864	workitem_alloc(&jmvref->jm_list, D_JMVREF, UFSTOVFS(dp->i_ump));
3865	jmvref->jm_list.wk_state = ATTACHED | DEPCOMPLETE;
3866	jmvref->jm_parent = dp->i_number;
3867	jmvref->jm_ino = ino;
3868	jmvref->jm_oldoff = oldoff;
3869	jmvref->jm_newoff = newoff;
3870
3871	return (jmvref);
3872}
3873
3874/*
3875 * Allocate a new jremref that tracks the removal of ip from dp with the
3876 * directory entry offset of diroff.  Mark the entry as ATTACHED and
3877 * DEPCOMPLETE as we have all the information required for the journal write
3878 * and the directory has already been removed from the buffer.  The caller
3879 * is responsible for linking the jremref into the pagedep and adding it
3880 * to the journal to write.  The MKDIR_PARENT flag is set if we're doing
3881 * a DOTDOT addition so handle_workitem_remove() can properly assign
3882 * the jsegdep when we're done.
3883 */
3884static struct jremref *
3885newjremref(struct dirrem *dirrem, struct inode *dp, struct inode *ip,
3886    off_t diroff, nlink_t nlink)
3887{
3888	struct jremref *jremref;
3889
3890	jremref = malloc(sizeof(*jremref), M_JREMREF, M_SOFTDEP_FLAGS);
3891	workitem_alloc(&jremref->jr_list, D_JREMREF, UFSTOVFS(dp->i_ump));
3892	jremref->jr_state = ATTACHED;
3893	newinoref(&jremref->jr_ref, ip->i_number, dp->i_number, diroff,
3894	   nlink, ip->i_mode);
3895	jremref->jr_dirrem = dirrem;
3896
3897	return (jremref);
3898}
3899
3900static inline void
3901newinoref(struct inoref *inoref, ino_t ino, ino_t parent, off_t diroff,
3902    nlink_t nlink, uint16_t mode)
3903{
3904
3905	inoref->if_jsegdep = newjsegdep(&inoref->if_list);
3906	inoref->if_diroff = diroff;
3907	inoref->if_ino = ino;
3908	inoref->if_parent = parent;
3909	inoref->if_nlink = nlink;
3910	inoref->if_mode = mode;
3911}
3912
3913/*
3914 * Allocate a new jaddref to track the addition of ino to dp at diroff.  The
3915 * directory offset may not be known until later.  The caller is responsible
3916 * adding the entry to the journal when this information is available.  nlink
3917 * should be the link count prior to the addition and mode is only required
3918 * to have the correct FMT.
3919 */
3920static struct jaddref *
3921newjaddref(struct inode *dp, ino_t ino, off_t diroff, int16_t nlink,
3922    uint16_t mode)
3923{
3924	struct jaddref *jaddref;
3925
3926	jaddref = malloc(sizeof(*jaddref), M_JADDREF, M_SOFTDEP_FLAGS);
3927	workitem_alloc(&jaddref->ja_list, D_JADDREF, UFSTOVFS(dp->i_ump));
3928	jaddref->ja_state = ATTACHED;
3929	jaddref->ja_mkdir = NULL;
3930	newinoref(&jaddref->ja_ref, ino, dp->i_number, diroff, nlink, mode);
3931
3932	return (jaddref);
3933}
3934
3935/*
3936 * Create a new free dependency for a freework.  The caller is responsible
3937 * for adjusting the reference count when it has the lock held.  The freedep
3938 * will track an outstanding bitmap write that will ultimately clear the
3939 * freework to continue.
3940 */
3941static struct freedep *
3942newfreedep(struct freework *freework)
3943{
3944	struct freedep *freedep;
3945
3946	freedep = malloc(sizeof(*freedep), M_FREEDEP, M_SOFTDEP_FLAGS);
3947	workitem_alloc(&freedep->fd_list, D_FREEDEP, freework->fw_list.wk_mp);
3948	freedep->fd_freework = freework;
3949
3950	return (freedep);
3951}
3952
3953/*
3954 * Free a freedep structure once the buffer it is linked to is written.  If
3955 * this is the last reference to the freework schedule it for completion.
3956 */
3957static void
3958free_freedep(freedep)
3959	struct freedep *freedep;
3960{
3961	struct freework *freework;
3962
3963	freework = freedep->fd_freework;
3964	freework->fw_freeblks->fb_cgwait--;
3965	if (--freework->fw_ref == 0)
3966		freework_enqueue(freework);
3967	WORKITEM_FREE(freedep, D_FREEDEP);
3968}
3969
3970/*
3971 * Allocate a new freework structure that may be a level in an indirect
3972 * when parent is not NULL or a top level block when it is.  The top level
3973 * freework structures are allocated without the soft updates lock held
3974 * and before the freeblks is visible outside of softdep_setup_freeblocks().
3975 */
3976static struct freework *
3977newfreework(ump, freeblks, parent, lbn, nb, frags, off, journal)
3978	struct ufsmount *ump;
3979	struct freeblks *freeblks;
3980	struct freework *parent;
3981	ufs_lbn_t lbn;
3982	ufs2_daddr_t nb;
3983	int frags;
3984	int off;
3985	int journal;
3986{
3987	struct freework *freework;
3988
3989	freework = malloc(sizeof(*freework), M_FREEWORK, M_SOFTDEP_FLAGS);
3990	workitem_alloc(&freework->fw_list, D_FREEWORK, freeblks->fb_list.wk_mp);
3991	freework->fw_state = ATTACHED;
3992	freework->fw_jnewblk = NULL;
3993	freework->fw_freeblks = freeblks;
3994	freework->fw_parent = parent;
3995	freework->fw_lbn = lbn;
3996	freework->fw_blkno = nb;
3997	freework->fw_frags = frags;
3998	freework->fw_indir = NULL;
3999	freework->fw_ref = (MOUNTEDSUJ(UFSTOVFS(ump)) == 0 || lbn >= -NXADDR)
4000		? 0 : NINDIR(ump->um_fs) + 1;
4001	freework->fw_start = freework->fw_off = off;
4002	if (journal)
4003		newjfreeblk(freeblks, lbn, nb, frags);
4004	if (parent == NULL) {
4005		ACQUIRE_LOCK(ump);
4006		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
4007		freeblks->fb_ref++;
4008		FREE_LOCK(ump);
4009	}
4010
4011	return (freework);
4012}
4013
4014/*
4015 * Eliminate a jfreeblk for a block that does not need journaling.
4016 */
4017static void
4018cancel_jfreeblk(freeblks, blkno)
4019	struct freeblks *freeblks;
4020	ufs2_daddr_t blkno;
4021{
4022	struct jfreeblk *jfreeblk;
4023	struct jblkdep *jblkdep;
4024
4025	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps) {
4026		if (jblkdep->jb_list.wk_type != D_JFREEBLK)
4027			continue;
4028		jfreeblk = WK_JFREEBLK(&jblkdep->jb_list);
4029		if (jfreeblk->jf_blkno == blkno)
4030			break;
4031	}
4032	if (jblkdep == NULL)
4033		return;
4034	CTR1(KTR_SUJ, "cancel_jfreeblk: blkno %jd", blkno);
4035	free_jsegdep(jblkdep->jb_jsegdep);
4036	LIST_REMOVE(jblkdep, jb_deps);
4037	WORKITEM_FREE(jfreeblk, D_JFREEBLK);
4038}
4039
4040/*
4041 * Allocate a new jfreeblk to journal top level block pointer when truncating
4042 * a file.  The caller must add this to the worklist when the soft updates
4043 * lock is held.
4044 */
4045static struct jfreeblk *
4046newjfreeblk(freeblks, lbn, blkno, frags)
4047	struct freeblks *freeblks;
4048	ufs_lbn_t lbn;
4049	ufs2_daddr_t blkno;
4050	int frags;
4051{
4052	struct jfreeblk *jfreeblk;
4053
4054	jfreeblk = malloc(sizeof(*jfreeblk), M_JFREEBLK, M_SOFTDEP_FLAGS);
4055	workitem_alloc(&jfreeblk->jf_dep.jb_list, D_JFREEBLK,
4056	    freeblks->fb_list.wk_mp);
4057	jfreeblk->jf_dep.jb_jsegdep = newjsegdep(&jfreeblk->jf_dep.jb_list);
4058	jfreeblk->jf_dep.jb_freeblks = freeblks;
4059	jfreeblk->jf_ino = freeblks->fb_inum;
4060	jfreeblk->jf_lbn = lbn;
4061	jfreeblk->jf_blkno = blkno;
4062	jfreeblk->jf_frags = frags;
4063	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jfreeblk->jf_dep, jb_deps);
4064
4065	return (jfreeblk);
4066}
4067
4068/*
4069 * Allocate a new jtrunc to track a partial truncation.
4070 */
4071static struct jtrunc *
4072newjtrunc(freeblks, size, extsize)
4073	struct freeblks *freeblks;
4074	off_t size;
4075	int extsize;
4076{
4077	struct jtrunc *jtrunc;
4078
4079	jtrunc = malloc(sizeof(*jtrunc), M_JTRUNC, M_SOFTDEP_FLAGS);
4080	workitem_alloc(&jtrunc->jt_dep.jb_list, D_JTRUNC,
4081	    freeblks->fb_list.wk_mp);
4082	jtrunc->jt_dep.jb_jsegdep = newjsegdep(&jtrunc->jt_dep.jb_list);
4083	jtrunc->jt_dep.jb_freeblks = freeblks;
4084	jtrunc->jt_ino = freeblks->fb_inum;
4085	jtrunc->jt_size = size;
4086	jtrunc->jt_extsize = extsize;
4087	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jtrunc->jt_dep, jb_deps);
4088
4089	return (jtrunc);
4090}
4091
4092/*
4093 * If we're canceling a new bitmap we have to search for another ref
4094 * to move into the bmsafemap dep.  This might be better expressed
4095 * with another structure.
4096 */
4097static void
4098move_newblock_dep(jaddref, inodedep)
4099	struct jaddref *jaddref;
4100	struct inodedep *inodedep;
4101{
4102	struct inoref *inoref;
4103	struct jaddref *jaddrefn;
4104
4105	jaddrefn = NULL;
4106	for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4107	    inoref = TAILQ_NEXT(inoref, if_deps)) {
4108		if ((jaddref->ja_state & NEWBLOCK) &&
4109		    inoref->if_list.wk_type == D_JADDREF) {
4110			jaddrefn = (struct jaddref *)inoref;
4111			break;
4112		}
4113	}
4114	if (jaddrefn == NULL)
4115		return;
4116	jaddrefn->ja_state &= ~(ATTACHED | UNDONE);
4117	jaddrefn->ja_state |= jaddref->ja_state &
4118	    (ATTACHED | UNDONE | NEWBLOCK);
4119	jaddref->ja_state &= ~(ATTACHED | UNDONE | NEWBLOCK);
4120	jaddref->ja_state |= ATTACHED;
4121	LIST_REMOVE(jaddref, ja_bmdeps);
4122	LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_jaddrefhd, jaddrefn,
4123	    ja_bmdeps);
4124}
4125
4126/*
4127 * Cancel a jaddref either before it has been written or while it is being
4128 * written.  This happens when a link is removed before the add reaches
4129 * the disk.  The jaddref dependency is kept linked into the bmsafemap
4130 * and inode to prevent the link count or bitmap from reaching the disk
4131 * until handle_workitem_remove() re-adjusts the counts and bitmaps as
4132 * required.
4133 *
4134 * Returns 1 if the canceled addref requires journaling of the remove and
4135 * 0 otherwise.
4136 */
4137static int
4138cancel_jaddref(jaddref, inodedep, wkhd)
4139	struct jaddref *jaddref;
4140	struct inodedep *inodedep;
4141	struct workhead *wkhd;
4142{
4143	struct inoref *inoref;
4144	struct jsegdep *jsegdep;
4145	int needsj;
4146
4147	KASSERT((jaddref->ja_state & COMPLETE) == 0,
4148	    ("cancel_jaddref: Canceling complete jaddref"));
4149	if (jaddref->ja_state & (INPROGRESS | COMPLETE))
4150		needsj = 1;
4151	else
4152		needsj = 0;
4153	if (inodedep == NULL)
4154		if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
4155		    0, &inodedep) == 0)
4156			panic("cancel_jaddref: Lost inodedep");
4157	/*
4158	 * We must adjust the nlink of any reference operation that follows
4159	 * us so that it is consistent with the in-memory reference.  This
4160	 * ensures that inode nlink rollbacks always have the correct link.
4161	 */
4162	if (needsj == 0) {
4163		for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4164		    inoref = TAILQ_NEXT(inoref, if_deps)) {
4165			if (inoref->if_state & GOINGAWAY)
4166				break;
4167			inoref->if_nlink--;
4168		}
4169	}
4170	jsegdep = inoref_jseg(&jaddref->ja_ref);
4171	if (jaddref->ja_state & NEWBLOCK)
4172		move_newblock_dep(jaddref, inodedep);
4173	wake_worklist(&jaddref->ja_list);
4174	jaddref->ja_mkdir = NULL;
4175	if (jaddref->ja_state & INPROGRESS) {
4176		jaddref->ja_state &= ~INPROGRESS;
4177		WORKLIST_REMOVE(&jaddref->ja_list);
4178		jwork_insert(wkhd, jsegdep);
4179	} else {
4180		free_jsegdep(jsegdep);
4181		if (jaddref->ja_state & DEPCOMPLETE)
4182			remove_from_journal(&jaddref->ja_list);
4183	}
4184	jaddref->ja_state |= (GOINGAWAY | DEPCOMPLETE);
4185	/*
4186	 * Leave NEWBLOCK jaddrefs on the inodedep so handle_workitem_remove
4187	 * can arrange for them to be freed with the bitmap.  Otherwise we
4188	 * no longer need this addref attached to the inoreflst and it
4189	 * will incorrectly adjust nlink if we leave it.
4190	 */
4191	if ((jaddref->ja_state & NEWBLOCK) == 0) {
4192		TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
4193		    if_deps);
4194		jaddref->ja_state |= COMPLETE;
4195		free_jaddref(jaddref);
4196		return (needsj);
4197	}
4198	/*
4199	 * Leave the head of the list for jsegdeps for fast merging.
4200	 */
4201	if (LIST_FIRST(wkhd) != NULL) {
4202		jaddref->ja_state |= ONWORKLIST;
4203		LIST_INSERT_AFTER(LIST_FIRST(wkhd), &jaddref->ja_list, wk_list);
4204	} else
4205		WORKLIST_INSERT(wkhd, &jaddref->ja_list);
4206
4207	return (needsj);
4208}
4209
4210/*
4211 * Attempt to free a jaddref structure when some work completes.  This
4212 * should only succeed once the entry is written and all dependencies have
4213 * been notified.
4214 */
4215static void
4216free_jaddref(jaddref)
4217	struct jaddref *jaddref;
4218{
4219
4220	if ((jaddref->ja_state & ALLCOMPLETE) != ALLCOMPLETE)
4221		return;
4222	if (jaddref->ja_ref.if_jsegdep)
4223		panic("free_jaddref: segdep attached to jaddref %p(0x%X)\n",
4224		    jaddref, jaddref->ja_state);
4225	if (jaddref->ja_state & NEWBLOCK)
4226		LIST_REMOVE(jaddref, ja_bmdeps);
4227	if (jaddref->ja_state & (INPROGRESS | ONWORKLIST))
4228		panic("free_jaddref: Bad state %p(0x%X)",
4229		    jaddref, jaddref->ja_state);
4230	if (jaddref->ja_mkdir != NULL)
4231		panic("free_jaddref: Work pending, 0x%X\n", jaddref->ja_state);
4232	WORKITEM_FREE(jaddref, D_JADDREF);
4233}
4234
4235/*
4236 * Free a jremref structure once it has been written or discarded.
4237 */
4238static void
4239free_jremref(jremref)
4240	struct jremref *jremref;
4241{
4242
4243	if (jremref->jr_ref.if_jsegdep)
4244		free_jsegdep(jremref->jr_ref.if_jsegdep);
4245	if (jremref->jr_state & INPROGRESS)
4246		panic("free_jremref: IO still pending");
4247	WORKITEM_FREE(jremref, D_JREMREF);
4248}
4249
4250/*
4251 * Free a jnewblk structure.
4252 */
4253static void
4254free_jnewblk(jnewblk)
4255	struct jnewblk *jnewblk;
4256{
4257
4258	if ((jnewblk->jn_state & ALLCOMPLETE) != ALLCOMPLETE)
4259		return;
4260	LIST_REMOVE(jnewblk, jn_deps);
4261	if (jnewblk->jn_dep != NULL)
4262		panic("free_jnewblk: Dependency still attached.");
4263	WORKITEM_FREE(jnewblk, D_JNEWBLK);
4264}
4265
4266/*
4267 * Cancel a jnewblk which has been been made redundant by frag extension.
4268 */
4269static void
4270cancel_jnewblk(jnewblk, wkhd)
4271	struct jnewblk *jnewblk;
4272	struct workhead *wkhd;
4273{
4274	struct jsegdep *jsegdep;
4275
4276	CTR1(KTR_SUJ, "cancel_jnewblk: blkno %jd", jnewblk->jn_blkno);
4277	jsegdep = jnewblk->jn_jsegdep;
4278	if (jnewblk->jn_jsegdep == NULL || jnewblk->jn_dep == NULL)
4279		panic("cancel_jnewblk: Invalid state");
4280	jnewblk->jn_jsegdep  = NULL;
4281	jnewblk->jn_dep = NULL;
4282	jnewblk->jn_state |= GOINGAWAY;
4283	if (jnewblk->jn_state & INPROGRESS) {
4284		jnewblk->jn_state &= ~INPROGRESS;
4285		WORKLIST_REMOVE(&jnewblk->jn_list);
4286		jwork_insert(wkhd, jsegdep);
4287	} else {
4288		free_jsegdep(jsegdep);
4289		remove_from_journal(&jnewblk->jn_list);
4290	}
4291	wake_worklist(&jnewblk->jn_list);
4292	WORKLIST_INSERT(wkhd, &jnewblk->jn_list);
4293}
4294
4295static void
4296free_jblkdep(jblkdep)
4297	struct jblkdep *jblkdep;
4298{
4299
4300	if (jblkdep->jb_list.wk_type == D_JFREEBLK)
4301		WORKITEM_FREE(jblkdep, D_JFREEBLK);
4302	else if (jblkdep->jb_list.wk_type == D_JTRUNC)
4303		WORKITEM_FREE(jblkdep, D_JTRUNC);
4304	else
4305		panic("free_jblkdep: Unexpected type %s",
4306		    TYPENAME(jblkdep->jb_list.wk_type));
4307}
4308
4309/*
4310 * Free a single jseg once it is no longer referenced in memory or on
4311 * disk.  Reclaim journal blocks and dependencies waiting for the segment
4312 * to disappear.
4313 */
4314static void
4315free_jseg(jseg, jblocks)
4316	struct jseg *jseg;
4317	struct jblocks *jblocks;
4318{
4319	struct freework *freework;
4320
4321	/*
4322	 * Free freework structures that were lingering to indicate freed
4323	 * indirect blocks that forced journal write ordering on reallocate.
4324	 */
4325	while ((freework = LIST_FIRST(&jseg->js_indirs)) != NULL)
4326		indirblk_remove(freework);
4327	if (jblocks->jb_oldestseg == jseg)
4328		jblocks->jb_oldestseg = TAILQ_NEXT(jseg, js_next);
4329	TAILQ_REMOVE(&jblocks->jb_segs, jseg, js_next);
4330	jblocks_free(jblocks, jseg->js_list.wk_mp, jseg->js_size);
4331	KASSERT(LIST_EMPTY(&jseg->js_entries),
4332	    ("free_jseg: Freed jseg has valid entries."));
4333	WORKITEM_FREE(jseg, D_JSEG);
4334}
4335
4336/*
4337 * Free all jsegs that meet the criteria for being reclaimed and update
4338 * oldestseg.
4339 */
4340static void
4341free_jsegs(jblocks)
4342	struct jblocks *jblocks;
4343{
4344	struct jseg *jseg;
4345
4346	/*
4347	 * Free only those jsegs which have none allocated before them to
4348	 * preserve the journal space ordering.
4349	 */
4350	while ((jseg = TAILQ_FIRST(&jblocks->jb_segs)) != NULL) {
4351		/*
4352		 * Only reclaim space when nothing depends on this journal
4353		 * set and another set has written that it is no longer
4354		 * valid.
4355		 */
4356		if (jseg->js_refs != 0) {
4357			jblocks->jb_oldestseg = jseg;
4358			return;
4359		}
4360		if ((jseg->js_state & ALLCOMPLETE) != ALLCOMPLETE)
4361			break;
4362		if (jseg->js_seq > jblocks->jb_oldestwrseq)
4363			break;
4364		/*
4365		 * We can free jsegs that didn't write entries when
4366		 * oldestwrseq == js_seq.
4367		 */
4368		if (jseg->js_seq == jblocks->jb_oldestwrseq &&
4369		    jseg->js_cnt != 0)
4370			break;
4371		free_jseg(jseg, jblocks);
4372	}
4373	/*
4374	 * If we exited the loop above we still must discover the
4375	 * oldest valid segment.
4376	 */
4377	if (jseg)
4378		for (jseg = jblocks->jb_oldestseg; jseg != NULL;
4379		     jseg = TAILQ_NEXT(jseg, js_next))
4380			if (jseg->js_refs != 0)
4381				break;
4382	jblocks->jb_oldestseg = jseg;
4383	/*
4384	 * The journal has no valid records but some jsegs may still be
4385	 * waiting on oldestwrseq to advance.  We force a small record
4386	 * out to permit these lingering records to be reclaimed.
4387	 */
4388	if (jblocks->jb_oldestseg == NULL && !TAILQ_EMPTY(&jblocks->jb_segs))
4389		jblocks->jb_needseg = 1;
4390}
4391
4392/*
4393 * Release one reference to a jseg and free it if the count reaches 0.  This
4394 * should eventually reclaim journal space as well.
4395 */
4396static void
4397rele_jseg(jseg)
4398	struct jseg *jseg;
4399{
4400
4401	KASSERT(jseg->js_refs > 0,
4402	    ("free_jseg: Invalid refcnt %d", jseg->js_refs));
4403	if (--jseg->js_refs != 0)
4404		return;
4405	free_jsegs(jseg->js_jblocks);
4406}
4407
4408/*
4409 * Release a jsegdep and decrement the jseg count.
4410 */
4411static void
4412free_jsegdep(jsegdep)
4413	struct jsegdep *jsegdep;
4414{
4415
4416	if (jsegdep->jd_seg)
4417		rele_jseg(jsegdep->jd_seg);
4418	WORKITEM_FREE(jsegdep, D_JSEGDEP);
4419}
4420
4421/*
4422 * Wait for a journal item to make it to disk.  Initiate journal processing
4423 * if required.
4424 */
4425static int
4426jwait(wk, waitfor)
4427	struct worklist *wk;
4428	int waitfor;
4429{
4430
4431	LOCK_OWNED(VFSTOUFS(wk->wk_mp));
4432	/*
4433	 * Blocking journal waits cause slow synchronous behavior.  Record
4434	 * stats on the frequency of these blocking operations.
4435	 */
4436	if (waitfor == MNT_WAIT) {
4437		stat_journal_wait++;
4438		switch (wk->wk_type) {
4439		case D_JREMREF:
4440		case D_JMVREF:
4441			stat_jwait_filepage++;
4442			break;
4443		case D_JTRUNC:
4444		case D_JFREEBLK:
4445			stat_jwait_freeblks++;
4446			break;
4447		case D_JNEWBLK:
4448			stat_jwait_newblk++;
4449			break;
4450		case D_JADDREF:
4451			stat_jwait_inode++;
4452			break;
4453		default:
4454			break;
4455		}
4456	}
4457	/*
4458	 * If IO has not started we process the journal.  We can't mark the
4459	 * worklist item as IOWAITING because we drop the lock while
4460	 * processing the journal and the worklist entry may be freed after
4461	 * this point.  The caller may call back in and re-issue the request.
4462	 */
4463	if ((wk->wk_state & INPROGRESS) == 0) {
4464		softdep_process_journal(wk->wk_mp, wk, waitfor);
4465		if (waitfor != MNT_WAIT)
4466			return (EBUSY);
4467		return (0);
4468	}
4469	if (waitfor != MNT_WAIT)
4470		return (EBUSY);
4471	wait_worklist(wk, "jwait");
4472	return (0);
4473}
4474
4475/*
4476 * Lookup an inodedep based on an inode pointer and set the nlinkdelta as
4477 * appropriate.  This is a convenience function to reduce duplicate code
4478 * for the setup and revert functions below.
4479 */
4480static struct inodedep *
4481inodedep_lookup_ip(ip)
4482	struct inode *ip;
4483{
4484	struct inodedep *inodedep;
4485	int dflags;
4486
4487	KASSERT(ip->i_nlink >= ip->i_effnlink,
4488	    ("inodedep_lookup_ip: bad delta"));
4489	dflags = DEPALLOC;
4490	if (IS_SNAPSHOT(ip))
4491		dflags |= NODELAY;
4492	(void) inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, dflags,
4493	    &inodedep);
4494	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
4495	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
4496
4497	return (inodedep);
4498}
4499
4500/*
4501 * Called prior to creating a new inode and linking it to a directory.  The
4502 * jaddref structure must already be allocated by softdep_setup_inomapdep
4503 * and it is discovered here so we can initialize the mode and update
4504 * nlinkdelta.
4505 */
4506void
4507softdep_setup_create(dp, ip)
4508	struct inode *dp;
4509	struct inode *ip;
4510{
4511	struct inodedep *inodedep;
4512	struct jaddref *jaddref;
4513	struct vnode *dvp;
4514
4515	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(dp->i_ump)) != 0,
4516	    ("softdep_setup_create called on non-softdep filesystem"));
4517	KASSERT(ip->i_nlink == 1,
4518	    ("softdep_setup_create: Invalid link count."));
4519	dvp = ITOV(dp);
4520	ACQUIRE_LOCK(dp->i_ump);
4521	inodedep = inodedep_lookup_ip(ip);
4522	if (DOINGSUJ(dvp)) {
4523		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4524		    inoreflst);
4525		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
4526		    ("softdep_setup_create: No addref structure present."));
4527	}
4528	softdep_prelink(dvp, NULL);
4529	FREE_LOCK(dp->i_ump);
4530}
4531
4532/*
4533 * Create a jaddref structure to track the addition of a DOTDOT link when
4534 * we are reparenting an inode as part of a rename.  This jaddref will be
4535 * found by softdep_setup_directory_change.  Adjusts nlinkdelta for
4536 * non-journaling softdep.
4537 */
4538void
4539softdep_setup_dotdot_link(dp, ip)
4540	struct inode *dp;
4541	struct inode *ip;
4542{
4543	struct inodedep *inodedep;
4544	struct jaddref *jaddref;
4545	struct vnode *dvp;
4546	struct vnode *vp;
4547
4548	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(dp->i_ump)) != 0,
4549	    ("softdep_setup_dotdot_link called on non-softdep filesystem"));
4550	dvp = ITOV(dp);
4551	vp = ITOV(ip);
4552	jaddref = NULL;
4553	/*
4554	 * We don't set MKDIR_PARENT as this is not tied to a mkdir and
4555	 * is used as a normal link would be.
4556	 */
4557	if (DOINGSUJ(dvp))
4558		jaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4559		    dp->i_effnlink - 1, dp->i_mode);
4560	ACQUIRE_LOCK(dp->i_ump);
4561	inodedep = inodedep_lookup_ip(dp);
4562	if (jaddref)
4563		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4564		    if_deps);
4565	softdep_prelink(dvp, ITOV(ip));
4566	FREE_LOCK(dp->i_ump);
4567}
4568
4569/*
4570 * Create a jaddref structure to track a new link to an inode.  The directory
4571 * offset is not known until softdep_setup_directory_add or
4572 * softdep_setup_directory_change.  Adjusts nlinkdelta for non-journaling
4573 * softdep.
4574 */
4575void
4576softdep_setup_link(dp, ip)
4577	struct inode *dp;
4578	struct inode *ip;
4579{
4580	struct inodedep *inodedep;
4581	struct jaddref *jaddref;
4582	struct vnode *dvp;
4583
4584	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(dp->i_ump)) != 0,
4585	    ("softdep_setup_link called on non-softdep filesystem"));
4586	dvp = ITOV(dp);
4587	jaddref = NULL;
4588	if (DOINGSUJ(dvp))
4589		jaddref = newjaddref(dp, ip->i_number, 0, ip->i_effnlink - 1,
4590		    ip->i_mode);
4591	ACQUIRE_LOCK(dp->i_ump);
4592	inodedep = inodedep_lookup_ip(ip);
4593	if (jaddref)
4594		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4595		    if_deps);
4596	softdep_prelink(dvp, ITOV(ip));
4597	FREE_LOCK(dp->i_ump);
4598}
4599
4600/*
4601 * Called to create the jaddref structures to track . and .. references as
4602 * well as lookup and further initialize the incomplete jaddref created
4603 * by softdep_setup_inomapdep when the inode was allocated.  Adjusts
4604 * nlinkdelta for non-journaling softdep.
4605 */
4606void
4607softdep_setup_mkdir(dp, ip)
4608	struct inode *dp;
4609	struct inode *ip;
4610{
4611	struct inodedep *inodedep;
4612	struct jaddref *dotdotaddref;
4613	struct jaddref *dotaddref;
4614	struct jaddref *jaddref;
4615	struct vnode *dvp;
4616
4617	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(dp->i_ump)) != 0,
4618	    ("softdep_setup_mkdir called on non-softdep filesystem"));
4619	dvp = ITOV(dp);
4620	dotaddref = dotdotaddref = NULL;
4621	if (DOINGSUJ(dvp)) {
4622		dotaddref = newjaddref(ip, ip->i_number, DOT_OFFSET, 1,
4623		    ip->i_mode);
4624		dotaddref->ja_state |= MKDIR_BODY;
4625		dotdotaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4626		    dp->i_effnlink - 1, dp->i_mode);
4627		dotdotaddref->ja_state |= MKDIR_PARENT;
4628	}
4629	ACQUIRE_LOCK(dp->i_ump);
4630	inodedep = inodedep_lookup_ip(ip);
4631	if (DOINGSUJ(dvp)) {
4632		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4633		    inoreflst);
4634		KASSERT(jaddref != NULL,
4635		    ("softdep_setup_mkdir: No addref structure present."));
4636		KASSERT(jaddref->ja_parent == dp->i_number,
4637		    ("softdep_setup_mkdir: bad parent %ju",
4638		    (uintmax_t)jaddref->ja_parent));
4639		TAILQ_INSERT_BEFORE(&jaddref->ja_ref, &dotaddref->ja_ref,
4640		    if_deps);
4641	}
4642	inodedep = inodedep_lookup_ip(dp);
4643	if (DOINGSUJ(dvp))
4644		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst,
4645		    &dotdotaddref->ja_ref, if_deps);
4646	softdep_prelink(ITOV(dp), NULL);
4647	FREE_LOCK(dp->i_ump);
4648}
4649
4650/*
4651 * Called to track nlinkdelta of the inode and parent directories prior to
4652 * unlinking a directory.
4653 */
4654void
4655softdep_setup_rmdir(dp, ip)
4656	struct inode *dp;
4657	struct inode *ip;
4658{
4659	struct vnode *dvp;
4660
4661	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(dp->i_ump)) != 0,
4662	    ("softdep_setup_rmdir called on non-softdep filesystem"));
4663	dvp = ITOV(dp);
4664	ACQUIRE_LOCK(dp->i_ump);
4665	(void) inodedep_lookup_ip(ip);
4666	(void) inodedep_lookup_ip(dp);
4667	softdep_prelink(dvp, ITOV(ip));
4668	FREE_LOCK(dp->i_ump);
4669}
4670
4671/*
4672 * Called to track nlinkdelta of the inode and parent directories prior to
4673 * unlink.
4674 */
4675void
4676softdep_setup_unlink(dp, ip)
4677	struct inode *dp;
4678	struct inode *ip;
4679{
4680	struct vnode *dvp;
4681
4682	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(dp->i_ump)) != 0,
4683	    ("softdep_setup_unlink called on non-softdep filesystem"));
4684	dvp = ITOV(dp);
4685	ACQUIRE_LOCK(dp->i_ump);
4686	(void) inodedep_lookup_ip(ip);
4687	(void) inodedep_lookup_ip(dp);
4688	softdep_prelink(dvp, ITOV(ip));
4689	FREE_LOCK(dp->i_ump);
4690}
4691
4692/*
4693 * Called to release the journal structures created by a failed non-directory
4694 * creation.  Adjusts nlinkdelta for non-journaling softdep.
4695 */
4696void
4697softdep_revert_create(dp, ip)
4698	struct inode *dp;
4699	struct inode *ip;
4700{
4701	struct inodedep *inodedep;
4702	struct jaddref *jaddref;
4703	struct vnode *dvp;
4704
4705	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(dp->i_ump)) != 0,
4706	    ("softdep_revert_create called on non-softdep filesystem"));
4707	dvp = ITOV(dp);
4708	ACQUIRE_LOCK(dp->i_ump);
4709	inodedep = inodedep_lookup_ip(ip);
4710	if (DOINGSUJ(dvp)) {
4711		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4712		    inoreflst);
4713		KASSERT(jaddref->ja_parent == dp->i_number,
4714		    ("softdep_revert_create: addref parent mismatch"));
4715		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4716	}
4717	FREE_LOCK(dp->i_ump);
4718}
4719
4720/*
4721 * Called to release the journal structures created by a failed link
4722 * addition.  Adjusts nlinkdelta for non-journaling softdep.
4723 */
4724void
4725softdep_revert_link(dp, ip)
4726	struct inode *dp;
4727	struct inode *ip;
4728{
4729	struct inodedep *inodedep;
4730	struct jaddref *jaddref;
4731	struct vnode *dvp;
4732
4733	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(dp->i_ump)) != 0,
4734	    ("softdep_revert_link called on non-softdep filesystem"));
4735	dvp = ITOV(dp);
4736	ACQUIRE_LOCK(dp->i_ump);
4737	inodedep = inodedep_lookup_ip(ip);
4738	if (DOINGSUJ(dvp)) {
4739		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4740		    inoreflst);
4741		KASSERT(jaddref->ja_parent == dp->i_number,
4742		    ("softdep_revert_link: addref parent mismatch"));
4743		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4744	}
4745	FREE_LOCK(dp->i_ump);
4746}
4747
4748/*
4749 * Called to release the journal structures created by a failed mkdir
4750 * attempt.  Adjusts nlinkdelta for non-journaling softdep.
4751 */
4752void
4753softdep_revert_mkdir(dp, ip)
4754	struct inode *dp;
4755	struct inode *ip;
4756{
4757	struct inodedep *inodedep;
4758	struct jaddref *jaddref;
4759	struct jaddref *dotaddref;
4760	struct vnode *dvp;
4761
4762	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(dp->i_ump)) != 0,
4763	    ("softdep_revert_mkdir called on non-softdep filesystem"));
4764	dvp = ITOV(dp);
4765
4766	ACQUIRE_LOCK(dp->i_ump);
4767	inodedep = inodedep_lookup_ip(dp);
4768	if (DOINGSUJ(dvp)) {
4769		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4770		    inoreflst);
4771		KASSERT(jaddref->ja_parent == ip->i_number,
4772		    ("softdep_revert_mkdir: dotdot addref parent mismatch"));
4773		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4774	}
4775	inodedep = inodedep_lookup_ip(ip);
4776	if (DOINGSUJ(dvp)) {
4777		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4778		    inoreflst);
4779		KASSERT(jaddref->ja_parent == dp->i_number,
4780		    ("softdep_revert_mkdir: addref parent mismatch"));
4781		dotaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
4782		    inoreflst, if_deps);
4783		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4784		KASSERT(dotaddref->ja_parent == ip->i_number,
4785		    ("softdep_revert_mkdir: dot addref parent mismatch"));
4786		cancel_jaddref(dotaddref, inodedep, &inodedep->id_inowait);
4787	}
4788	FREE_LOCK(dp->i_ump);
4789}
4790
4791/*
4792 * Called to correct nlinkdelta after a failed rmdir.
4793 */
4794void
4795softdep_revert_rmdir(dp, ip)
4796	struct inode *dp;
4797	struct inode *ip;
4798{
4799
4800	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(dp->i_ump)) != 0,
4801	    ("softdep_revert_rmdir called on non-softdep filesystem"));
4802	ACQUIRE_LOCK(dp->i_ump);
4803	(void) inodedep_lookup_ip(ip);
4804	(void) inodedep_lookup_ip(dp);
4805	FREE_LOCK(dp->i_ump);
4806}
4807
4808/*
4809 * Protecting the freemaps (or bitmaps).
4810 *
4811 * To eliminate the need to execute fsck before mounting a filesystem
4812 * after a power failure, one must (conservatively) guarantee that the
4813 * on-disk copy of the bitmaps never indicate that a live inode or block is
4814 * free.  So, when a block or inode is allocated, the bitmap should be
4815 * updated (on disk) before any new pointers.  When a block or inode is
4816 * freed, the bitmap should not be updated until all pointers have been
4817 * reset.  The latter dependency is handled by the delayed de-allocation
4818 * approach described below for block and inode de-allocation.  The former
4819 * dependency is handled by calling the following procedure when a block or
4820 * inode is allocated. When an inode is allocated an "inodedep" is created
4821 * with its DEPCOMPLETE flag cleared until its bitmap is written to disk.
4822 * Each "inodedep" is also inserted into the hash indexing structure so
4823 * that any additional link additions can be made dependent on the inode
4824 * allocation.
4825 *
4826 * The ufs filesystem maintains a number of free block counts (e.g., per
4827 * cylinder group, per cylinder and per <cylinder, rotational position> pair)
4828 * in addition to the bitmaps.  These counts are used to improve efficiency
4829 * during allocation and therefore must be consistent with the bitmaps.
4830 * There is no convenient way to guarantee post-crash consistency of these
4831 * counts with simple update ordering, for two main reasons: (1) The counts
4832 * and bitmaps for a single cylinder group block are not in the same disk
4833 * sector.  If a disk write is interrupted (e.g., by power failure), one may
4834 * be written and the other not.  (2) Some of the counts are located in the
4835 * superblock rather than the cylinder group block. So, we focus our soft
4836 * updates implementation on protecting the bitmaps. When mounting a
4837 * filesystem, we recompute the auxiliary counts from the bitmaps.
4838 */
4839
4840/*
4841 * Called just after updating the cylinder group block to allocate an inode.
4842 */
4843void
4844softdep_setup_inomapdep(bp, ip, newinum, mode)
4845	struct buf *bp;		/* buffer for cylgroup block with inode map */
4846	struct inode *ip;	/* inode related to allocation */
4847	ino_t newinum;		/* new inode number being allocated */
4848	int mode;
4849{
4850	struct inodedep *inodedep;
4851	struct bmsafemap *bmsafemap;
4852	struct jaddref *jaddref;
4853	struct mount *mp;
4854	struct fs *fs;
4855
4856	mp = UFSTOVFS(ip->i_ump);
4857	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
4858	    ("softdep_setup_inomapdep called on non-softdep filesystem"));
4859	fs = ip->i_ump->um_fs;
4860	jaddref = NULL;
4861
4862	/*
4863	 * Allocate the journal reference add structure so that the bitmap
4864	 * can be dependent on it.
4865	 */
4866	if (MOUNTEDSUJ(mp)) {
4867		jaddref = newjaddref(ip, newinum, 0, 0, mode);
4868		jaddref->ja_state |= NEWBLOCK;
4869	}
4870
4871	/*
4872	 * Create a dependency for the newly allocated inode.
4873	 * Panic if it already exists as something is seriously wrong.
4874	 * Otherwise add it to the dependency list for the buffer holding
4875	 * the cylinder group map from which it was allocated.
4876	 *
4877	 * We have to preallocate a bmsafemap entry in case it is needed
4878	 * in bmsafemap_lookup since once we allocate the inodedep, we
4879	 * have to finish initializing it before we can FREE_LOCK().
4880	 * By preallocating, we avoid FREE_LOCK() while doing a malloc
4881	 * in bmsafemap_lookup. We cannot call bmsafemap_lookup before
4882	 * creating the inodedep as it can be freed during the time
4883	 * that we FREE_LOCK() while allocating the inodedep. We must
4884	 * call workitem_alloc() before entering the locked section as
4885	 * it also acquires the lock and we must avoid trying doing so
4886	 * recursively.
4887	 */
4888	bmsafemap = malloc(sizeof(struct bmsafemap),
4889	    M_BMSAFEMAP, M_SOFTDEP_FLAGS);
4890	workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
4891	ACQUIRE_LOCK(ip->i_ump);
4892	if ((inodedep_lookup(mp, newinum, DEPALLOC | NODELAY, &inodedep)))
4893		panic("softdep_setup_inomapdep: dependency %p for new"
4894		    "inode already exists", inodedep);
4895	bmsafemap = bmsafemap_lookup(mp, bp, ino_to_cg(fs, newinum), bmsafemap);
4896	if (jaddref) {
4897		LIST_INSERT_HEAD(&bmsafemap->sm_jaddrefhd, jaddref, ja_bmdeps);
4898		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4899		    if_deps);
4900	} else {
4901		inodedep->id_state |= ONDEPLIST;
4902		LIST_INSERT_HEAD(&bmsafemap->sm_inodedephd, inodedep, id_deps);
4903	}
4904	inodedep->id_bmsafemap = bmsafemap;
4905	inodedep->id_state &= ~DEPCOMPLETE;
4906	FREE_LOCK(ip->i_ump);
4907}
4908
4909/*
4910 * Called just after updating the cylinder group block to
4911 * allocate block or fragment.
4912 */
4913void
4914softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
4915	struct buf *bp;		/* buffer for cylgroup block with block map */
4916	struct mount *mp;	/* filesystem doing allocation */
4917	ufs2_daddr_t newblkno;	/* number of newly allocated block */
4918	int frags;		/* Number of fragments. */
4919	int oldfrags;		/* Previous number of fragments for extend. */
4920{
4921	struct newblk *newblk;
4922	struct bmsafemap *bmsafemap;
4923	struct jnewblk *jnewblk;
4924	struct ufsmount *ump;
4925	struct fs *fs;
4926
4927	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
4928	    ("softdep_setup_blkmapdep called on non-softdep filesystem"));
4929	ump = VFSTOUFS(mp);
4930	fs = ump->um_fs;
4931	jnewblk = NULL;
4932	/*
4933	 * Create a dependency for the newly allocated block.
4934	 * Add it to the dependency list for the buffer holding
4935	 * the cylinder group map from which it was allocated.
4936	 */
4937	if (MOUNTEDSUJ(mp)) {
4938		jnewblk = malloc(sizeof(*jnewblk), M_JNEWBLK, M_SOFTDEP_FLAGS);
4939		workitem_alloc(&jnewblk->jn_list, D_JNEWBLK, mp);
4940		jnewblk->jn_jsegdep = newjsegdep(&jnewblk->jn_list);
4941		jnewblk->jn_state = ATTACHED;
4942		jnewblk->jn_blkno = newblkno;
4943		jnewblk->jn_frags = frags;
4944		jnewblk->jn_oldfrags = oldfrags;
4945#ifdef SUJ_DEBUG
4946		{
4947			struct cg *cgp;
4948			uint8_t *blksfree;
4949			long bno;
4950			int i;
4951
4952			cgp = (struct cg *)bp->b_data;
4953			blksfree = cg_blksfree(cgp);
4954			bno = dtogd(fs, jnewblk->jn_blkno);
4955			for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags;
4956			    i++) {
4957				if (isset(blksfree, bno + i))
4958					panic("softdep_setup_blkmapdep: "
4959					    "free fragment %d from %d-%d "
4960					    "state 0x%X dep %p", i,
4961					    jnewblk->jn_oldfrags,
4962					    jnewblk->jn_frags,
4963					    jnewblk->jn_state,
4964					    jnewblk->jn_dep);
4965			}
4966		}
4967#endif
4968	}
4969
4970	CTR3(KTR_SUJ,
4971	    "softdep_setup_blkmapdep: blkno %jd frags %d oldfrags %d",
4972	    newblkno, frags, oldfrags);
4973	ACQUIRE_LOCK(ump);
4974	if (newblk_lookup(mp, newblkno, DEPALLOC, &newblk) != 0)
4975		panic("softdep_setup_blkmapdep: found block");
4976	newblk->nb_bmsafemap = bmsafemap = bmsafemap_lookup(mp, bp,
4977	    dtog(fs, newblkno), NULL);
4978	if (jnewblk) {
4979		jnewblk->jn_dep = (struct worklist *)newblk;
4980		LIST_INSERT_HEAD(&bmsafemap->sm_jnewblkhd, jnewblk, jn_deps);
4981	} else {
4982		newblk->nb_state |= ONDEPLIST;
4983		LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
4984	}
4985	newblk->nb_bmsafemap = bmsafemap;
4986	newblk->nb_jnewblk = jnewblk;
4987	FREE_LOCK(ump);
4988}
4989
4990#define	BMSAFEMAP_HASH(ump, cg) \
4991      (&(ump)->bmsafemap_hashtbl[(cg) & (ump)->bmsafemap_hash_size])
4992
4993static int
4994bmsafemap_find(bmsafemaphd, cg, bmsafemapp)
4995	struct bmsafemap_hashhead *bmsafemaphd;
4996	int cg;
4997	struct bmsafemap **bmsafemapp;
4998{
4999	struct bmsafemap *bmsafemap;
5000
5001	LIST_FOREACH(bmsafemap, bmsafemaphd, sm_hash)
5002		if (bmsafemap->sm_cg == cg)
5003			break;
5004	if (bmsafemap) {
5005		*bmsafemapp = bmsafemap;
5006		return (1);
5007	}
5008	*bmsafemapp = NULL;
5009
5010	return (0);
5011}
5012
5013/*
5014 * Find the bmsafemap associated with a cylinder group buffer.
5015 * If none exists, create one. The buffer must be locked when
5016 * this routine is called and this routine must be called with
5017 * the softdep lock held. To avoid giving up the lock while
5018 * allocating a new bmsafemap, a preallocated bmsafemap may be
5019 * provided. If it is provided but not needed, it is freed.
5020 */
5021static struct bmsafemap *
5022bmsafemap_lookup(mp, bp, cg, newbmsafemap)
5023	struct mount *mp;
5024	struct buf *bp;
5025	int cg;
5026	struct bmsafemap *newbmsafemap;
5027{
5028	struct bmsafemap_hashhead *bmsafemaphd;
5029	struct bmsafemap *bmsafemap, *collision;
5030	struct worklist *wk;
5031	struct ufsmount *ump;
5032
5033	ump = VFSTOUFS(mp);
5034	LOCK_OWNED(ump);
5035	KASSERT(bp != NULL, ("bmsafemap_lookup: missing buffer"));
5036	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5037		if (wk->wk_type == D_BMSAFEMAP) {
5038			if (newbmsafemap)
5039				WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5040			return (WK_BMSAFEMAP(wk));
5041		}
5042	}
5043	bmsafemaphd = BMSAFEMAP_HASH(ump, cg);
5044	if (bmsafemap_find(bmsafemaphd, cg, &bmsafemap) == 1) {
5045		if (newbmsafemap)
5046			WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5047		return (bmsafemap);
5048	}
5049	if (newbmsafemap) {
5050		bmsafemap = newbmsafemap;
5051	} else {
5052		FREE_LOCK(ump);
5053		bmsafemap = malloc(sizeof(struct bmsafemap),
5054			M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5055		workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5056		ACQUIRE_LOCK(ump);
5057	}
5058	bmsafemap->sm_buf = bp;
5059	LIST_INIT(&bmsafemap->sm_inodedephd);
5060	LIST_INIT(&bmsafemap->sm_inodedepwr);
5061	LIST_INIT(&bmsafemap->sm_newblkhd);
5062	LIST_INIT(&bmsafemap->sm_newblkwr);
5063	LIST_INIT(&bmsafemap->sm_jaddrefhd);
5064	LIST_INIT(&bmsafemap->sm_jnewblkhd);
5065	LIST_INIT(&bmsafemap->sm_freehd);
5066	LIST_INIT(&bmsafemap->sm_freewr);
5067	if (bmsafemap_find(bmsafemaphd, cg, &collision) == 1) {
5068		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
5069		return (collision);
5070	}
5071	bmsafemap->sm_cg = cg;
5072	LIST_INSERT_HEAD(bmsafemaphd, bmsafemap, sm_hash);
5073	LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
5074	WORKLIST_INSERT(&bp->b_dep, &bmsafemap->sm_list);
5075	return (bmsafemap);
5076}
5077
5078/*
5079 * Direct block allocation dependencies.
5080 *
5081 * When a new block is allocated, the corresponding disk locations must be
5082 * initialized (with zeros or new data) before the on-disk inode points to
5083 * them.  Also, the freemap from which the block was allocated must be
5084 * updated (on disk) before the inode's pointer. These two dependencies are
5085 * independent of each other and are needed for all file blocks and indirect
5086 * blocks that are pointed to directly by the inode.  Just before the
5087 * "in-core" version of the inode is updated with a newly allocated block
5088 * number, a procedure (below) is called to setup allocation dependency
5089 * structures.  These structures are removed when the corresponding
5090 * dependencies are satisfied or when the block allocation becomes obsolete
5091 * (i.e., the file is deleted, the block is de-allocated, or the block is a
5092 * fragment that gets upgraded).  All of these cases are handled in
5093 * procedures described later.
5094 *
5095 * When a file extension causes a fragment to be upgraded, either to a larger
5096 * fragment or to a full block, the on-disk location may change (if the
5097 * previous fragment could not simply be extended). In this case, the old
5098 * fragment must be de-allocated, but not until after the inode's pointer has
5099 * been updated. In most cases, this is handled by later procedures, which
5100 * will construct a "freefrag" structure to be added to the workitem queue
5101 * when the inode update is complete (or obsolete).  The main exception to
5102 * this is when an allocation occurs while a pending allocation dependency
5103 * (for the same block pointer) remains.  This case is handled in the main
5104 * allocation dependency setup procedure by immediately freeing the
5105 * unreferenced fragments.
5106 */
5107void
5108softdep_setup_allocdirect(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5109	struct inode *ip;	/* inode to which block is being added */
5110	ufs_lbn_t off;		/* block pointer within inode */
5111	ufs2_daddr_t newblkno;	/* disk block number being added */
5112	ufs2_daddr_t oldblkno;	/* previous block number, 0 unless frag */
5113	long newsize;		/* size of new block */
5114	long oldsize;		/* size of new block */
5115	struct buf *bp;		/* bp for allocated block */
5116{
5117	struct allocdirect *adp, *oldadp;
5118	struct allocdirectlst *adphead;
5119	struct freefrag *freefrag;
5120	struct inodedep *inodedep;
5121	struct pagedep *pagedep;
5122	struct jnewblk *jnewblk;
5123	struct newblk *newblk;
5124	struct mount *mp;
5125	ufs_lbn_t lbn;
5126
5127	lbn = bp->b_lblkno;
5128	mp = UFSTOVFS(ip->i_ump);
5129	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5130	    ("softdep_setup_allocdirect called on non-softdep filesystem"));
5131	if (oldblkno && oldblkno != newblkno)
5132		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn);
5133	else
5134		freefrag = NULL;
5135
5136	CTR6(KTR_SUJ,
5137	    "softdep_setup_allocdirect: ino %d blkno %jd oldblkno %jd "
5138	    "off %jd newsize %ld oldsize %d",
5139	    ip->i_number, newblkno, oldblkno, off, newsize, oldsize);
5140	ACQUIRE_LOCK(ip->i_ump);
5141	if (off >= NDADDR) {
5142		if (lbn > 0)
5143			panic("softdep_setup_allocdirect: bad lbn %jd, off %jd",
5144			    lbn, off);
5145		/* allocating an indirect block */
5146		if (oldblkno != 0)
5147			panic("softdep_setup_allocdirect: non-zero indir");
5148	} else {
5149		if (off != lbn)
5150			panic("softdep_setup_allocdirect: lbn %jd != off %jd",
5151			    lbn, off);
5152		/*
5153		 * Allocating a direct block.
5154		 *
5155		 * If we are allocating a directory block, then we must
5156		 * allocate an associated pagedep to track additions and
5157		 * deletions.
5158		 */
5159		if ((ip->i_mode & IFMT) == IFDIR)
5160			pagedep_lookup(mp, bp, ip->i_number, off, DEPALLOC,
5161			    &pagedep);
5162	}
5163	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5164		panic("softdep_setup_allocdirect: lost block");
5165	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5166	    ("softdep_setup_allocdirect: newblk already initialized"));
5167	/*
5168	 * Convert the newblk to an allocdirect.
5169	 */
5170	WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5171	adp = (struct allocdirect *)newblk;
5172	newblk->nb_freefrag = freefrag;
5173	adp->ad_offset = off;
5174	adp->ad_oldblkno = oldblkno;
5175	adp->ad_newsize = newsize;
5176	adp->ad_oldsize = oldsize;
5177
5178	/*
5179	 * Finish initializing the journal.
5180	 */
5181	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5182		jnewblk->jn_ino = ip->i_number;
5183		jnewblk->jn_lbn = lbn;
5184		add_to_journal(&jnewblk->jn_list);
5185	}
5186	if (freefrag && freefrag->ff_jdep != NULL &&
5187	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5188		add_to_journal(freefrag->ff_jdep);
5189	inodedep_lookup(mp, ip->i_number, DEPALLOC | NODELAY, &inodedep);
5190	adp->ad_inodedep = inodedep;
5191
5192	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5193	/*
5194	 * The list of allocdirects must be kept in sorted and ascending
5195	 * order so that the rollback routines can quickly determine the
5196	 * first uncommitted block (the size of the file stored on disk
5197	 * ends at the end of the lowest committed fragment, or if there
5198	 * are no fragments, at the end of the highest committed block).
5199	 * Since files generally grow, the typical case is that the new
5200	 * block is to be added at the end of the list. We speed this
5201	 * special case by checking against the last allocdirect in the
5202	 * list before laboriously traversing the list looking for the
5203	 * insertion point.
5204	 */
5205	adphead = &inodedep->id_newinoupdt;
5206	oldadp = TAILQ_LAST(adphead, allocdirectlst);
5207	if (oldadp == NULL || oldadp->ad_offset <= off) {
5208		/* insert at end of list */
5209		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5210		if (oldadp != NULL && oldadp->ad_offset == off)
5211			allocdirect_merge(adphead, adp, oldadp);
5212		FREE_LOCK(ip->i_ump);
5213		return;
5214	}
5215	TAILQ_FOREACH(oldadp, adphead, ad_next) {
5216		if (oldadp->ad_offset >= off)
5217			break;
5218	}
5219	if (oldadp == NULL)
5220		panic("softdep_setup_allocdirect: lost entry");
5221	/* insert in middle of list */
5222	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5223	if (oldadp->ad_offset == off)
5224		allocdirect_merge(adphead, adp, oldadp);
5225
5226	FREE_LOCK(ip->i_ump);
5227}
5228
5229/*
5230 * Merge a newer and older journal record to be stored either in a
5231 * newblock or freefrag.  This handles aggregating journal records for
5232 * fragment allocation into a second record as well as replacing a
5233 * journal free with an aborted journal allocation.  A segment for the
5234 * oldest record will be placed on wkhd if it has been written.  If not
5235 * the segment for the newer record will suffice.
5236 */
5237static struct worklist *
5238jnewblk_merge(new, old, wkhd)
5239	struct worklist *new;
5240	struct worklist *old;
5241	struct workhead *wkhd;
5242{
5243	struct jnewblk *njnewblk;
5244	struct jnewblk *jnewblk;
5245
5246	/* Handle NULLs to simplify callers. */
5247	if (new == NULL)
5248		return (old);
5249	if (old == NULL)
5250		return (new);
5251	/* Replace a jfreefrag with a jnewblk. */
5252	if (new->wk_type == D_JFREEFRAG) {
5253		if (WK_JNEWBLK(old)->jn_blkno != WK_JFREEFRAG(new)->fr_blkno)
5254			panic("jnewblk_merge: blkno mismatch: %p, %p",
5255			    old, new);
5256		cancel_jfreefrag(WK_JFREEFRAG(new));
5257		return (old);
5258	}
5259	if (old->wk_type != D_JNEWBLK || new->wk_type != D_JNEWBLK)
5260		panic("jnewblk_merge: Bad type: old %d new %d\n",
5261		    old->wk_type, new->wk_type);
5262	/*
5263	 * Handle merging of two jnewblk records that describe
5264	 * different sets of fragments in the same block.
5265	 */
5266	jnewblk = WK_JNEWBLK(old);
5267	njnewblk = WK_JNEWBLK(new);
5268	if (jnewblk->jn_blkno != njnewblk->jn_blkno)
5269		panic("jnewblk_merge: Merging disparate blocks.");
5270	/*
5271	 * The record may be rolled back in the cg.
5272	 */
5273	if (jnewblk->jn_state & UNDONE) {
5274		jnewblk->jn_state &= ~UNDONE;
5275		njnewblk->jn_state |= UNDONE;
5276		njnewblk->jn_state &= ~ATTACHED;
5277	}
5278	/*
5279	 * We modify the newer addref and free the older so that if neither
5280	 * has been written the most up-to-date copy will be on disk.  If
5281	 * both have been written but rolled back we only temporarily need
5282	 * one of them to fix the bits when the cg write completes.
5283	 */
5284	jnewblk->jn_state |= ATTACHED | COMPLETE;
5285	njnewblk->jn_oldfrags = jnewblk->jn_oldfrags;
5286	cancel_jnewblk(jnewblk, wkhd);
5287	WORKLIST_REMOVE(&jnewblk->jn_list);
5288	free_jnewblk(jnewblk);
5289	return (new);
5290}
5291
5292/*
5293 * Replace an old allocdirect dependency with a newer one.
5294 * This routine must be called with splbio interrupts blocked.
5295 */
5296static void
5297allocdirect_merge(adphead, newadp, oldadp)
5298	struct allocdirectlst *adphead;	/* head of list holding allocdirects */
5299	struct allocdirect *newadp;	/* allocdirect being added */
5300	struct allocdirect *oldadp;	/* existing allocdirect being checked */
5301{
5302	struct worklist *wk;
5303	struct freefrag *freefrag;
5304
5305	freefrag = NULL;
5306	LOCK_OWNED(VFSTOUFS(newadp->ad_list.wk_mp));
5307	if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
5308	    newadp->ad_oldsize != oldadp->ad_newsize ||
5309	    newadp->ad_offset >= NDADDR)
5310		panic("%s %jd != new %jd || old size %ld != new %ld",
5311		    "allocdirect_merge: old blkno",
5312		    (intmax_t)newadp->ad_oldblkno,
5313		    (intmax_t)oldadp->ad_newblkno,
5314		    newadp->ad_oldsize, oldadp->ad_newsize);
5315	newadp->ad_oldblkno = oldadp->ad_oldblkno;
5316	newadp->ad_oldsize = oldadp->ad_oldsize;
5317	/*
5318	 * If the old dependency had a fragment to free or had never
5319	 * previously had a block allocated, then the new dependency
5320	 * can immediately post its freefrag and adopt the old freefrag.
5321	 * This action is done by swapping the freefrag dependencies.
5322	 * The new dependency gains the old one's freefrag, and the
5323	 * old one gets the new one and then immediately puts it on
5324	 * the worklist when it is freed by free_newblk. It is
5325	 * not possible to do this swap when the old dependency had a
5326	 * non-zero size but no previous fragment to free. This condition
5327	 * arises when the new block is an extension of the old block.
5328	 * Here, the first part of the fragment allocated to the new
5329	 * dependency is part of the block currently claimed on disk by
5330	 * the old dependency, so cannot legitimately be freed until the
5331	 * conditions for the new dependency are fulfilled.
5332	 */
5333	freefrag = newadp->ad_freefrag;
5334	if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
5335		newadp->ad_freefrag = oldadp->ad_freefrag;
5336		oldadp->ad_freefrag = freefrag;
5337	}
5338	/*
5339	 * If we are tracking a new directory-block allocation,
5340	 * move it from the old allocdirect to the new allocdirect.
5341	 */
5342	if ((wk = LIST_FIRST(&oldadp->ad_newdirblk)) != NULL) {
5343		WORKLIST_REMOVE(wk);
5344		if (!LIST_EMPTY(&oldadp->ad_newdirblk))
5345			panic("allocdirect_merge: extra newdirblk");
5346		WORKLIST_INSERT(&newadp->ad_newdirblk, wk);
5347	}
5348	TAILQ_REMOVE(adphead, oldadp, ad_next);
5349	/*
5350	 * We need to move any journal dependencies over to the freefrag
5351	 * that releases this block if it exists.  Otherwise we are
5352	 * extending an existing block and we'll wait until that is
5353	 * complete to release the journal space and extend the
5354	 * new journal to cover this old space as well.
5355	 */
5356	if (freefrag == NULL) {
5357		if (oldadp->ad_newblkno != newadp->ad_newblkno)
5358			panic("allocdirect_merge: %jd != %jd",
5359			    oldadp->ad_newblkno, newadp->ad_newblkno);
5360		newadp->ad_block.nb_jnewblk = (struct jnewblk *)
5361		    jnewblk_merge(&newadp->ad_block.nb_jnewblk->jn_list,
5362		    &oldadp->ad_block.nb_jnewblk->jn_list,
5363		    &newadp->ad_block.nb_jwork);
5364		oldadp->ad_block.nb_jnewblk = NULL;
5365		cancel_newblk(&oldadp->ad_block, NULL,
5366		    &newadp->ad_block.nb_jwork);
5367	} else {
5368		wk = (struct worklist *) cancel_newblk(&oldadp->ad_block,
5369		    &freefrag->ff_list, &freefrag->ff_jwork);
5370		freefrag->ff_jdep = jnewblk_merge(freefrag->ff_jdep, wk,
5371		    &freefrag->ff_jwork);
5372	}
5373	free_newblk(&oldadp->ad_block);
5374}
5375
5376/*
5377 * Allocate a jfreefrag structure to journal a single block free.
5378 */
5379static struct jfreefrag *
5380newjfreefrag(freefrag, ip, blkno, size, lbn)
5381	struct freefrag *freefrag;
5382	struct inode *ip;
5383	ufs2_daddr_t blkno;
5384	long size;
5385	ufs_lbn_t lbn;
5386{
5387	struct jfreefrag *jfreefrag;
5388	struct fs *fs;
5389
5390	fs = ip->i_fs;
5391	jfreefrag = malloc(sizeof(struct jfreefrag), M_JFREEFRAG,
5392	    M_SOFTDEP_FLAGS);
5393	workitem_alloc(&jfreefrag->fr_list, D_JFREEFRAG, UFSTOVFS(ip->i_ump));
5394	jfreefrag->fr_jsegdep = newjsegdep(&jfreefrag->fr_list);
5395	jfreefrag->fr_state = ATTACHED | DEPCOMPLETE;
5396	jfreefrag->fr_ino = ip->i_number;
5397	jfreefrag->fr_lbn = lbn;
5398	jfreefrag->fr_blkno = blkno;
5399	jfreefrag->fr_frags = numfrags(fs, size);
5400	jfreefrag->fr_freefrag = freefrag;
5401
5402	return (jfreefrag);
5403}
5404
5405/*
5406 * Allocate a new freefrag structure.
5407 */
5408static struct freefrag *
5409newfreefrag(ip, blkno, size, lbn)
5410	struct inode *ip;
5411	ufs2_daddr_t blkno;
5412	long size;
5413	ufs_lbn_t lbn;
5414{
5415	struct freefrag *freefrag;
5416	struct fs *fs;
5417
5418	CTR4(KTR_SUJ, "newfreefrag: ino %d blkno %jd size %ld lbn %jd",
5419	    ip->i_number, blkno, size, lbn);
5420	fs = ip->i_fs;
5421	if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
5422		panic("newfreefrag: frag size");
5423	freefrag = malloc(sizeof(struct freefrag),
5424	    M_FREEFRAG, M_SOFTDEP_FLAGS);
5425	workitem_alloc(&freefrag->ff_list, D_FREEFRAG, UFSTOVFS(ip->i_ump));
5426	freefrag->ff_state = ATTACHED;
5427	LIST_INIT(&freefrag->ff_jwork);
5428	freefrag->ff_inum = ip->i_number;
5429	freefrag->ff_vtype = ITOV(ip)->v_type;
5430	freefrag->ff_blkno = blkno;
5431	freefrag->ff_fragsize = size;
5432
5433	if (MOUNTEDSUJ(UFSTOVFS(ip->i_ump))) {
5434		freefrag->ff_jdep = (struct worklist *)
5435		    newjfreefrag(freefrag, ip, blkno, size, lbn);
5436	} else {
5437		freefrag->ff_state |= DEPCOMPLETE;
5438		freefrag->ff_jdep = NULL;
5439	}
5440
5441	return (freefrag);
5442}
5443
5444/*
5445 * This workitem de-allocates fragments that were replaced during
5446 * file block allocation.
5447 */
5448static void
5449handle_workitem_freefrag(freefrag)
5450	struct freefrag *freefrag;
5451{
5452	struct ufsmount *ump = VFSTOUFS(freefrag->ff_list.wk_mp);
5453	struct workhead wkhd;
5454
5455	CTR3(KTR_SUJ,
5456	    "handle_workitem_freefrag: ino %d blkno %jd size %ld",
5457	    freefrag->ff_inum, freefrag->ff_blkno, freefrag->ff_fragsize);
5458	/*
5459	 * It would be illegal to add new completion items to the
5460	 * freefrag after it was schedule to be done so it must be
5461	 * safe to modify the list head here.
5462	 */
5463	LIST_INIT(&wkhd);
5464	ACQUIRE_LOCK(ump);
5465	LIST_SWAP(&freefrag->ff_jwork, &wkhd, worklist, wk_list);
5466	/*
5467	 * If the journal has not been written we must cancel it here.
5468	 */
5469	if (freefrag->ff_jdep) {
5470		if (freefrag->ff_jdep->wk_type != D_JNEWBLK)
5471			panic("handle_workitem_freefrag: Unexpected type %d\n",
5472			    freefrag->ff_jdep->wk_type);
5473		cancel_jnewblk(WK_JNEWBLK(freefrag->ff_jdep), &wkhd);
5474	}
5475	FREE_LOCK(ump);
5476	ffs_blkfree(ump, ump->um_fs, ump->um_devvp, freefrag->ff_blkno,
5477	   freefrag->ff_fragsize, freefrag->ff_inum, freefrag->ff_vtype, &wkhd);
5478	ACQUIRE_LOCK(ump);
5479	WORKITEM_FREE(freefrag, D_FREEFRAG);
5480	FREE_LOCK(ump);
5481}
5482
5483/*
5484 * Set up a dependency structure for an external attributes data block.
5485 * This routine follows much of the structure of softdep_setup_allocdirect.
5486 * See the description of softdep_setup_allocdirect above for details.
5487 */
5488void
5489softdep_setup_allocext(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5490	struct inode *ip;
5491	ufs_lbn_t off;
5492	ufs2_daddr_t newblkno;
5493	ufs2_daddr_t oldblkno;
5494	long newsize;
5495	long oldsize;
5496	struct buf *bp;
5497{
5498	struct allocdirect *adp, *oldadp;
5499	struct allocdirectlst *adphead;
5500	struct freefrag *freefrag;
5501	struct inodedep *inodedep;
5502	struct jnewblk *jnewblk;
5503	struct newblk *newblk;
5504	struct mount *mp;
5505	ufs_lbn_t lbn;
5506
5507	mp = UFSTOVFS(ip->i_ump);
5508	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5509	    ("softdep_setup_allocext called on non-softdep filesystem"));
5510	KASSERT(off < NXADDR, ("softdep_setup_allocext: lbn %lld > NXADDR",
5511		    (long long)off));
5512
5513	lbn = bp->b_lblkno;
5514	if (oldblkno && oldblkno != newblkno)
5515		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn);
5516	else
5517		freefrag = NULL;
5518
5519	ACQUIRE_LOCK(ip->i_ump);
5520	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5521		panic("softdep_setup_allocext: lost block");
5522	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5523	    ("softdep_setup_allocext: newblk already initialized"));
5524	/*
5525	 * Convert the newblk to an allocdirect.
5526	 */
5527	WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5528	adp = (struct allocdirect *)newblk;
5529	newblk->nb_freefrag = freefrag;
5530	adp->ad_offset = off;
5531	adp->ad_oldblkno = oldblkno;
5532	adp->ad_newsize = newsize;
5533	adp->ad_oldsize = oldsize;
5534	adp->ad_state |=  EXTDATA;
5535
5536	/*
5537	 * Finish initializing the journal.
5538	 */
5539	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5540		jnewblk->jn_ino = ip->i_number;
5541		jnewblk->jn_lbn = lbn;
5542		add_to_journal(&jnewblk->jn_list);
5543	}
5544	if (freefrag && freefrag->ff_jdep != NULL &&
5545	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5546		add_to_journal(freefrag->ff_jdep);
5547	inodedep_lookup(mp, ip->i_number, DEPALLOC | NODELAY, &inodedep);
5548	adp->ad_inodedep = inodedep;
5549
5550	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5551	/*
5552	 * The list of allocdirects must be kept in sorted and ascending
5553	 * order so that the rollback routines can quickly determine the
5554	 * first uncommitted block (the size of the file stored on disk
5555	 * ends at the end of the lowest committed fragment, or if there
5556	 * are no fragments, at the end of the highest committed block).
5557	 * Since files generally grow, the typical case is that the new
5558	 * block is to be added at the end of the list. We speed this
5559	 * special case by checking against the last allocdirect in the
5560	 * list before laboriously traversing the list looking for the
5561	 * insertion point.
5562	 */
5563	adphead = &inodedep->id_newextupdt;
5564	oldadp = TAILQ_LAST(adphead, allocdirectlst);
5565	if (oldadp == NULL || oldadp->ad_offset <= off) {
5566		/* insert at end of list */
5567		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5568		if (oldadp != NULL && oldadp->ad_offset == off)
5569			allocdirect_merge(adphead, adp, oldadp);
5570		FREE_LOCK(ip->i_ump);
5571		return;
5572	}
5573	TAILQ_FOREACH(oldadp, adphead, ad_next) {
5574		if (oldadp->ad_offset >= off)
5575			break;
5576	}
5577	if (oldadp == NULL)
5578		panic("softdep_setup_allocext: lost entry");
5579	/* insert in middle of list */
5580	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5581	if (oldadp->ad_offset == off)
5582		allocdirect_merge(adphead, adp, oldadp);
5583	FREE_LOCK(ip->i_ump);
5584}
5585
5586/*
5587 * Indirect block allocation dependencies.
5588 *
5589 * The same dependencies that exist for a direct block also exist when
5590 * a new block is allocated and pointed to by an entry in a block of
5591 * indirect pointers. The undo/redo states described above are also
5592 * used here. Because an indirect block contains many pointers that
5593 * may have dependencies, a second copy of the entire in-memory indirect
5594 * block is kept. The buffer cache copy is always completely up-to-date.
5595 * The second copy, which is used only as a source for disk writes,
5596 * contains only the safe pointers (i.e., those that have no remaining
5597 * update dependencies). The second copy is freed when all pointers
5598 * are safe. The cache is not allowed to replace indirect blocks with
5599 * pending update dependencies. If a buffer containing an indirect
5600 * block with dependencies is written, these routines will mark it
5601 * dirty again. It can only be successfully written once all the
5602 * dependencies are removed. The ffs_fsync routine in conjunction with
5603 * softdep_sync_metadata work together to get all the dependencies
5604 * removed so that a file can be successfully written to disk. Three
5605 * procedures are used when setting up indirect block pointer
5606 * dependencies. The division is necessary because of the organization
5607 * of the "balloc" routine and because of the distinction between file
5608 * pages and file metadata blocks.
5609 */
5610
5611/*
5612 * Allocate a new allocindir structure.
5613 */
5614static struct allocindir *
5615newallocindir(ip, ptrno, newblkno, oldblkno, lbn)
5616	struct inode *ip;	/* inode for file being extended */
5617	int ptrno;		/* offset of pointer in indirect block */
5618	ufs2_daddr_t newblkno;	/* disk block number being added */
5619	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
5620	ufs_lbn_t lbn;
5621{
5622	struct newblk *newblk;
5623	struct allocindir *aip;
5624	struct freefrag *freefrag;
5625	struct jnewblk *jnewblk;
5626
5627	if (oldblkno)
5628		freefrag = newfreefrag(ip, oldblkno, ip->i_fs->fs_bsize, lbn);
5629	else
5630		freefrag = NULL;
5631	ACQUIRE_LOCK(ip->i_ump);
5632	if (newblk_lookup(UFSTOVFS(ip->i_ump), newblkno, 0, &newblk) == 0)
5633		panic("new_allocindir: lost block");
5634	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5635	    ("newallocindir: newblk already initialized"));
5636	WORKITEM_REASSIGN(newblk, D_ALLOCINDIR);
5637	newblk->nb_freefrag = freefrag;
5638	aip = (struct allocindir *)newblk;
5639	aip->ai_offset = ptrno;
5640	aip->ai_oldblkno = oldblkno;
5641	aip->ai_lbn = lbn;
5642	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5643		jnewblk->jn_ino = ip->i_number;
5644		jnewblk->jn_lbn = lbn;
5645		add_to_journal(&jnewblk->jn_list);
5646	}
5647	if (freefrag && freefrag->ff_jdep != NULL &&
5648	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5649		add_to_journal(freefrag->ff_jdep);
5650	return (aip);
5651}
5652
5653/*
5654 * Called just before setting an indirect block pointer
5655 * to a newly allocated file page.
5656 */
5657void
5658softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
5659	struct inode *ip;	/* inode for file being extended */
5660	ufs_lbn_t lbn;		/* allocated block number within file */
5661	struct buf *bp;		/* buffer with indirect blk referencing page */
5662	int ptrno;		/* offset of pointer in indirect block */
5663	ufs2_daddr_t newblkno;	/* disk block number being added */
5664	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
5665	struct buf *nbp;	/* buffer holding allocated page */
5666{
5667	struct inodedep *inodedep;
5668	struct freefrag *freefrag;
5669	struct allocindir *aip;
5670	struct pagedep *pagedep;
5671	struct mount *mp;
5672	int dflags;
5673
5674	mp = UFSTOVFS(ip->i_ump);
5675	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5676	    ("softdep_setup_allocindir_page called on non-softdep filesystem"));
5677	KASSERT(lbn == nbp->b_lblkno,
5678	    ("softdep_setup_allocindir_page: lbn %jd != lblkno %jd",
5679	    lbn, bp->b_lblkno));
5680	CTR4(KTR_SUJ,
5681	    "softdep_setup_allocindir_page: ino %d blkno %jd oldblkno %jd "
5682	    "lbn %jd", ip->i_number, newblkno, oldblkno, lbn);
5683	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_page");
5684	aip = newallocindir(ip, ptrno, newblkno, oldblkno, lbn);
5685	dflags = DEPALLOC;
5686	if (IS_SNAPSHOT(ip))
5687		dflags |= NODELAY;
5688	(void) inodedep_lookup(mp, ip->i_number, dflags, &inodedep);
5689	/*
5690	 * If we are allocating a directory page, then we must
5691	 * allocate an associated pagedep to track additions and
5692	 * deletions.
5693	 */
5694	if ((ip->i_mode & IFMT) == IFDIR)
5695		pagedep_lookup(mp, nbp, ip->i_number, lbn, DEPALLOC, &pagedep);
5696	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5697	freefrag = setup_allocindir_phase2(bp, ip, inodedep, aip, lbn);
5698	FREE_LOCK(ip->i_ump);
5699	if (freefrag)
5700		handle_workitem_freefrag(freefrag);
5701}
5702
5703/*
5704 * Called just before setting an indirect block pointer to a
5705 * newly allocated indirect block.
5706 */
5707void
5708softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
5709	struct buf *nbp;	/* newly allocated indirect block */
5710	struct inode *ip;	/* inode for file being extended */
5711	struct buf *bp;		/* indirect block referencing allocated block */
5712	int ptrno;		/* offset of pointer in indirect block */
5713	ufs2_daddr_t newblkno;	/* disk block number being added */
5714{
5715	struct inodedep *inodedep;
5716	struct allocindir *aip;
5717	ufs_lbn_t lbn;
5718	int dflags;
5719
5720	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ip->i_ump)) != 0,
5721	    ("softdep_setup_allocindir_meta called on non-softdep filesystem"));
5722	CTR3(KTR_SUJ,
5723	    "softdep_setup_allocindir_meta: ino %d blkno %jd ptrno %d",
5724	    ip->i_number, newblkno, ptrno);
5725	lbn = nbp->b_lblkno;
5726	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_meta");
5727	aip = newallocindir(ip, ptrno, newblkno, 0, lbn);
5728	dflags = DEPALLOC;
5729	if (IS_SNAPSHOT(ip))
5730		dflags |= NODELAY;
5731	inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, dflags, &inodedep);
5732	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5733	if (setup_allocindir_phase2(bp, ip, inodedep, aip, lbn))
5734		panic("softdep_setup_allocindir_meta: Block already existed");
5735	FREE_LOCK(ip->i_ump);
5736}
5737
5738static void
5739indirdep_complete(indirdep)
5740	struct indirdep *indirdep;
5741{
5742	struct allocindir *aip;
5743
5744	LIST_REMOVE(indirdep, ir_next);
5745	indirdep->ir_state |= DEPCOMPLETE;
5746
5747	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL) {
5748		LIST_REMOVE(aip, ai_next);
5749		free_newblk(&aip->ai_block);
5750	}
5751	/*
5752	 * If this indirdep is not attached to a buf it was simply waiting
5753	 * on completion to clear completehd.  free_indirdep() asserts
5754	 * that nothing is dangling.
5755	 */
5756	if ((indirdep->ir_state & ONWORKLIST) == 0)
5757		free_indirdep(indirdep);
5758}
5759
5760static struct indirdep *
5761indirdep_lookup(mp, ip, bp)
5762	struct mount *mp;
5763	struct inode *ip;
5764	struct buf *bp;
5765{
5766	struct indirdep *indirdep, *newindirdep;
5767	struct newblk *newblk;
5768	struct ufsmount *ump;
5769	struct worklist *wk;
5770	struct fs *fs;
5771	ufs2_daddr_t blkno;
5772
5773	ump = VFSTOUFS(mp);
5774	LOCK_OWNED(ump);
5775	indirdep = NULL;
5776	newindirdep = NULL;
5777	fs = ip->i_fs;
5778	for (;;) {
5779		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5780			if (wk->wk_type != D_INDIRDEP)
5781				continue;
5782			indirdep = WK_INDIRDEP(wk);
5783			break;
5784		}
5785		/* Found on the buffer worklist, no new structure to free. */
5786		if (indirdep != NULL && newindirdep == NULL)
5787			return (indirdep);
5788		if (indirdep != NULL && newindirdep != NULL)
5789			panic("indirdep_lookup: simultaneous create");
5790		/* None found on the buffer and a new structure is ready. */
5791		if (indirdep == NULL && newindirdep != NULL)
5792			break;
5793		/* None found and no new structure available. */
5794		FREE_LOCK(ump);
5795		newindirdep = malloc(sizeof(struct indirdep),
5796		    M_INDIRDEP, M_SOFTDEP_FLAGS);
5797		workitem_alloc(&newindirdep->ir_list, D_INDIRDEP, mp);
5798		newindirdep->ir_state = ATTACHED;
5799		if (ip->i_ump->um_fstype == UFS1)
5800			newindirdep->ir_state |= UFS1FMT;
5801		TAILQ_INIT(&newindirdep->ir_trunc);
5802		newindirdep->ir_saveddata = NULL;
5803		LIST_INIT(&newindirdep->ir_deplisthd);
5804		LIST_INIT(&newindirdep->ir_donehd);
5805		LIST_INIT(&newindirdep->ir_writehd);
5806		LIST_INIT(&newindirdep->ir_completehd);
5807		if (bp->b_blkno == bp->b_lblkno) {
5808			ufs_bmaparray(bp->b_vp, bp->b_lblkno, &blkno, bp,
5809			    NULL, NULL);
5810			bp->b_blkno = blkno;
5811		}
5812		newindirdep->ir_freeblks = NULL;
5813		newindirdep->ir_savebp =
5814		    getblk(ip->i_devvp, bp->b_blkno, bp->b_bcount, 0, 0, 0);
5815		newindirdep->ir_bp = bp;
5816		BUF_KERNPROC(newindirdep->ir_savebp);
5817		bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
5818		ACQUIRE_LOCK(ump);
5819	}
5820	indirdep = newindirdep;
5821	WORKLIST_INSERT(&bp->b_dep, &indirdep->ir_list);
5822	/*
5823	 * If the block is not yet allocated we don't set DEPCOMPLETE so
5824	 * that we don't free dependencies until the pointers are valid.
5825	 * This could search b_dep for D_ALLOCDIRECT/D_ALLOCINDIR rather
5826	 * than using the hash.
5827	 */
5828	if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk))
5829		LIST_INSERT_HEAD(&newblk->nb_indirdeps, indirdep, ir_next);
5830	else
5831		indirdep->ir_state |= DEPCOMPLETE;
5832	return (indirdep);
5833}
5834
5835/*
5836 * Called to finish the allocation of the "aip" allocated
5837 * by one of the two routines above.
5838 */
5839static struct freefrag *
5840setup_allocindir_phase2(bp, ip, inodedep, aip, lbn)
5841	struct buf *bp;		/* in-memory copy of the indirect block */
5842	struct inode *ip;	/* inode for file being extended */
5843	struct inodedep *inodedep; /* Inodedep for ip */
5844	struct allocindir *aip;	/* allocindir allocated by the above routines */
5845	ufs_lbn_t lbn;		/* Logical block number for this block. */
5846{
5847	struct fs *fs;
5848	struct indirdep *indirdep;
5849	struct allocindir *oldaip;
5850	struct freefrag *freefrag;
5851	struct mount *mp;
5852
5853	LOCK_OWNED(ip->i_ump);
5854	mp = UFSTOVFS(ip->i_ump);
5855	fs = ip->i_fs;
5856	if (bp->b_lblkno >= 0)
5857		panic("setup_allocindir_phase2: not indir blk");
5858	KASSERT(aip->ai_offset >= 0 && aip->ai_offset < NINDIR(fs),
5859	    ("setup_allocindir_phase2: Bad offset %d", aip->ai_offset));
5860	indirdep = indirdep_lookup(mp, ip, bp);
5861	KASSERT(indirdep->ir_savebp != NULL,
5862	    ("setup_allocindir_phase2 NULL ir_savebp"));
5863	aip->ai_indirdep = indirdep;
5864	/*
5865	 * Check for an unwritten dependency for this indirect offset.  If
5866	 * there is, merge the old dependency into the new one.  This happens
5867	 * as a result of reallocblk only.
5868	 */
5869	freefrag = NULL;
5870	if (aip->ai_oldblkno != 0) {
5871		LIST_FOREACH(oldaip, &indirdep->ir_deplisthd, ai_next) {
5872			if (oldaip->ai_offset == aip->ai_offset) {
5873				freefrag = allocindir_merge(aip, oldaip);
5874				goto done;
5875			}
5876		}
5877		LIST_FOREACH(oldaip, &indirdep->ir_donehd, ai_next) {
5878			if (oldaip->ai_offset == aip->ai_offset) {
5879				freefrag = allocindir_merge(aip, oldaip);
5880				goto done;
5881			}
5882		}
5883	}
5884done:
5885	LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
5886	return (freefrag);
5887}
5888
5889/*
5890 * Merge two allocindirs which refer to the same block.  Move newblock
5891 * dependencies and setup the freefrags appropriately.
5892 */
5893static struct freefrag *
5894allocindir_merge(aip, oldaip)
5895	struct allocindir *aip;
5896	struct allocindir *oldaip;
5897{
5898	struct freefrag *freefrag;
5899	struct worklist *wk;
5900
5901	if (oldaip->ai_newblkno != aip->ai_oldblkno)
5902		panic("allocindir_merge: blkno");
5903	aip->ai_oldblkno = oldaip->ai_oldblkno;
5904	freefrag = aip->ai_freefrag;
5905	aip->ai_freefrag = oldaip->ai_freefrag;
5906	oldaip->ai_freefrag = NULL;
5907	KASSERT(freefrag != NULL, ("setup_allocindir_phase2: No freefrag"));
5908	/*
5909	 * If we are tracking a new directory-block allocation,
5910	 * move it from the old allocindir to the new allocindir.
5911	 */
5912	if ((wk = LIST_FIRST(&oldaip->ai_newdirblk)) != NULL) {
5913		WORKLIST_REMOVE(wk);
5914		if (!LIST_EMPTY(&oldaip->ai_newdirblk))
5915			panic("allocindir_merge: extra newdirblk");
5916		WORKLIST_INSERT(&aip->ai_newdirblk, wk);
5917	}
5918	/*
5919	 * We can skip journaling for this freefrag and just complete
5920	 * any pending journal work for the allocindir that is being
5921	 * removed after the freefrag completes.
5922	 */
5923	if (freefrag->ff_jdep)
5924		cancel_jfreefrag(WK_JFREEFRAG(freefrag->ff_jdep));
5925	LIST_REMOVE(oldaip, ai_next);
5926	freefrag->ff_jdep = (struct worklist *)cancel_newblk(&oldaip->ai_block,
5927	    &freefrag->ff_list, &freefrag->ff_jwork);
5928	free_newblk(&oldaip->ai_block);
5929
5930	return (freefrag);
5931}
5932
5933static inline void
5934setup_freedirect(freeblks, ip, i, needj)
5935	struct freeblks *freeblks;
5936	struct inode *ip;
5937	int i;
5938	int needj;
5939{
5940	ufs2_daddr_t blkno;
5941	int frags;
5942
5943	blkno = DIP(ip, i_db[i]);
5944	if (blkno == 0)
5945		return;
5946	DIP_SET(ip, i_db[i], 0);
5947	frags = sblksize(ip->i_fs, ip->i_size, i);
5948	frags = numfrags(ip->i_fs, frags);
5949	newfreework(ip->i_ump, freeblks, NULL, i, blkno, frags, 0, needj);
5950}
5951
5952static inline void
5953setup_freeext(freeblks, ip, i, needj)
5954	struct freeblks *freeblks;
5955	struct inode *ip;
5956	int i;
5957	int needj;
5958{
5959	ufs2_daddr_t blkno;
5960	int frags;
5961
5962	blkno = ip->i_din2->di_extb[i];
5963	if (blkno == 0)
5964		return;
5965	ip->i_din2->di_extb[i] = 0;
5966	frags = sblksize(ip->i_fs, ip->i_din2->di_extsize, i);
5967	frags = numfrags(ip->i_fs, frags);
5968	newfreework(ip->i_ump, freeblks, NULL, -1 - i, blkno, frags, 0, needj);
5969}
5970
5971static inline void
5972setup_freeindir(freeblks, ip, i, lbn, needj)
5973	struct freeblks *freeblks;
5974	struct inode *ip;
5975	int i;
5976	ufs_lbn_t lbn;
5977	int needj;
5978{
5979	ufs2_daddr_t blkno;
5980
5981	blkno = DIP(ip, i_ib[i]);
5982	if (blkno == 0)
5983		return;
5984	DIP_SET(ip, i_ib[i], 0);
5985	newfreework(ip->i_ump, freeblks, NULL, lbn, blkno, ip->i_fs->fs_frag,
5986	    0, needj);
5987}
5988
5989static inline struct freeblks *
5990newfreeblks(mp, ip)
5991	struct mount *mp;
5992	struct inode *ip;
5993{
5994	struct freeblks *freeblks;
5995
5996	freeblks = malloc(sizeof(struct freeblks),
5997		M_FREEBLKS, M_SOFTDEP_FLAGS|M_ZERO);
5998	workitem_alloc(&freeblks->fb_list, D_FREEBLKS, mp);
5999	LIST_INIT(&freeblks->fb_jblkdephd);
6000	LIST_INIT(&freeblks->fb_jwork);
6001	freeblks->fb_ref = 0;
6002	freeblks->fb_cgwait = 0;
6003	freeblks->fb_state = ATTACHED;
6004	freeblks->fb_uid = ip->i_uid;
6005	freeblks->fb_inum = ip->i_number;
6006	freeblks->fb_vtype = ITOV(ip)->v_type;
6007	freeblks->fb_modrev = DIP(ip, i_modrev);
6008	freeblks->fb_devvp = ip->i_devvp;
6009	freeblks->fb_chkcnt = 0;
6010	freeblks->fb_len = 0;
6011
6012	return (freeblks);
6013}
6014
6015static void
6016trunc_indirdep(indirdep, freeblks, bp, off)
6017	struct indirdep *indirdep;
6018	struct freeblks *freeblks;
6019	struct buf *bp;
6020	int off;
6021{
6022	struct allocindir *aip, *aipn;
6023
6024	/*
6025	 * The first set of allocindirs won't be in savedbp.
6026	 */
6027	LIST_FOREACH_SAFE(aip, &indirdep->ir_deplisthd, ai_next, aipn)
6028		if (aip->ai_offset > off)
6029			cancel_allocindir(aip, bp, freeblks, 1);
6030	LIST_FOREACH_SAFE(aip, &indirdep->ir_donehd, ai_next, aipn)
6031		if (aip->ai_offset > off)
6032			cancel_allocindir(aip, bp, freeblks, 1);
6033	/*
6034	 * These will exist in savedbp.
6035	 */
6036	LIST_FOREACH_SAFE(aip, &indirdep->ir_writehd, ai_next, aipn)
6037		if (aip->ai_offset > off)
6038			cancel_allocindir(aip, NULL, freeblks, 0);
6039	LIST_FOREACH_SAFE(aip, &indirdep->ir_completehd, ai_next, aipn)
6040		if (aip->ai_offset > off)
6041			cancel_allocindir(aip, NULL, freeblks, 0);
6042}
6043
6044/*
6045 * Follow the chain of indirects down to lastlbn creating a freework
6046 * structure for each.  This will be used to start indir_trunc() at
6047 * the right offset and create the journal records for the parrtial
6048 * truncation.  A second step will handle the truncated dependencies.
6049 */
6050static int
6051setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno)
6052	struct freeblks *freeblks;
6053	struct inode *ip;
6054	ufs_lbn_t lbn;
6055	ufs_lbn_t lastlbn;
6056	ufs2_daddr_t blkno;
6057{
6058	struct indirdep *indirdep;
6059	struct indirdep *indirn;
6060	struct freework *freework;
6061	struct newblk *newblk;
6062	struct mount *mp;
6063	struct buf *bp;
6064	uint8_t *start;
6065	uint8_t *end;
6066	ufs_lbn_t lbnadd;
6067	int level;
6068	int error;
6069	int off;
6070
6071
6072	freework = NULL;
6073	if (blkno == 0)
6074		return (0);
6075	mp = freeblks->fb_list.wk_mp;
6076	bp = getblk(ITOV(ip), lbn, mp->mnt_stat.f_iosize, 0, 0, 0);
6077	if ((bp->b_flags & B_CACHE) == 0) {
6078		bp->b_blkno = blkptrtodb(VFSTOUFS(mp), blkno);
6079		bp->b_iocmd = BIO_READ;
6080		bp->b_flags &= ~B_INVAL;
6081		bp->b_ioflags &= ~BIO_ERROR;
6082		vfs_busy_pages(bp, 0);
6083		bp->b_iooffset = dbtob(bp->b_blkno);
6084		bstrategy(bp);
6085		curthread->td_ru.ru_inblock++;
6086		error = bufwait(bp);
6087		if (error) {
6088			brelse(bp);
6089			return (error);
6090		}
6091	}
6092	level = lbn_level(lbn);
6093	lbnadd = lbn_offset(ip->i_fs, level);
6094	/*
6095	 * Compute the offset of the last block we want to keep.  Store
6096	 * in the freework the first block we want to completely free.
6097	 */
6098	off = (lastlbn - -(lbn + level)) / lbnadd;
6099	if (off + 1 == NINDIR(ip->i_fs))
6100		goto nowork;
6101	freework = newfreework(ip->i_ump, freeblks, NULL, lbn, blkno, 0, off+1,
6102	    0);
6103	/*
6104	 * Link the freework into the indirdep.  This will prevent any new
6105	 * allocations from proceeding until we are finished with the
6106	 * truncate and the block is written.
6107	 */
6108	ACQUIRE_LOCK(ip->i_ump);
6109	indirdep = indirdep_lookup(mp, ip, bp);
6110	if (indirdep->ir_freeblks)
6111		panic("setup_trunc_indir: indirdep already truncated.");
6112	TAILQ_INSERT_TAIL(&indirdep->ir_trunc, freework, fw_next);
6113	freework->fw_indir = indirdep;
6114	/*
6115	 * Cancel any allocindirs that will not make it to disk.
6116	 * We have to do this for all copies of the indirdep that
6117	 * live on this newblk.
6118	 */
6119	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
6120		newblk_lookup(mp, dbtofsb(ip->i_fs, bp->b_blkno), 0, &newblk);
6121		LIST_FOREACH(indirn, &newblk->nb_indirdeps, ir_next)
6122			trunc_indirdep(indirn, freeblks, bp, off);
6123	} else
6124		trunc_indirdep(indirdep, freeblks, bp, off);
6125	FREE_LOCK(ip->i_ump);
6126	/*
6127	 * Creation is protected by the buf lock. The saveddata is only
6128	 * needed if a full truncation follows a partial truncation but it
6129	 * is difficult to allocate in that case so we fetch it anyway.
6130	 */
6131	if (indirdep->ir_saveddata == NULL)
6132		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
6133		    M_SOFTDEP_FLAGS);
6134nowork:
6135	/* Fetch the blkno of the child and the zero start offset. */
6136	if (ip->i_ump->um_fstype == UFS1) {
6137		blkno = ((ufs1_daddr_t *)bp->b_data)[off];
6138		start = (uint8_t *)&((ufs1_daddr_t *)bp->b_data)[off+1];
6139	} else {
6140		blkno = ((ufs2_daddr_t *)bp->b_data)[off];
6141		start = (uint8_t *)&((ufs2_daddr_t *)bp->b_data)[off+1];
6142	}
6143	if (freework) {
6144		/* Zero the truncated pointers. */
6145		end = bp->b_data + bp->b_bcount;
6146		bzero(start, end - start);
6147		bdwrite(bp);
6148	} else
6149		bqrelse(bp);
6150	if (level == 0)
6151		return (0);
6152	lbn++; /* adjust level */
6153	lbn -= (off * lbnadd);
6154	return setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno);
6155}
6156
6157/*
6158 * Complete the partial truncation of an indirect block setup by
6159 * setup_trunc_indir().  This zeros the truncated pointers in the saved
6160 * copy and writes them to disk before the freeblks is allowed to complete.
6161 */
6162static void
6163complete_trunc_indir(freework)
6164	struct freework *freework;
6165{
6166	struct freework *fwn;
6167	struct indirdep *indirdep;
6168	struct ufsmount *ump;
6169	struct buf *bp;
6170	uintptr_t start;
6171	int count;
6172
6173	ump = VFSTOUFS(freework->fw_list.wk_mp);
6174	LOCK_OWNED(ump);
6175	indirdep = freework->fw_indir;
6176	for (;;) {
6177		bp = indirdep->ir_bp;
6178		/* See if the block was discarded. */
6179		if (bp == NULL)
6180			break;
6181		/* Inline part of getdirtybuf().  We dont want bremfree. */
6182		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) == 0)
6183			break;
6184		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
6185		    LOCK_PTR(ump)) == 0)
6186			BUF_UNLOCK(bp);
6187		ACQUIRE_LOCK(ump);
6188	}
6189	freework->fw_state |= DEPCOMPLETE;
6190	TAILQ_REMOVE(&indirdep->ir_trunc, freework, fw_next);
6191	/*
6192	 * Zero the pointers in the saved copy.
6193	 */
6194	if (indirdep->ir_state & UFS1FMT)
6195		start = sizeof(ufs1_daddr_t);
6196	else
6197		start = sizeof(ufs2_daddr_t);
6198	start *= freework->fw_start;
6199	count = indirdep->ir_savebp->b_bcount - start;
6200	start += (uintptr_t)indirdep->ir_savebp->b_data;
6201	bzero((char *)start, count);
6202	/*
6203	 * We need to start the next truncation in the list if it has not
6204	 * been started yet.
6205	 */
6206	fwn = TAILQ_FIRST(&indirdep->ir_trunc);
6207	if (fwn != NULL) {
6208		if (fwn->fw_freeblks == indirdep->ir_freeblks)
6209			TAILQ_REMOVE(&indirdep->ir_trunc, fwn, fw_next);
6210		if ((fwn->fw_state & ONWORKLIST) == 0)
6211			freework_enqueue(fwn);
6212	}
6213	/*
6214	 * If bp is NULL the block was fully truncated, restore
6215	 * the saved block list otherwise free it if it is no
6216	 * longer needed.
6217	 */
6218	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
6219		if (bp == NULL)
6220			bcopy(indirdep->ir_saveddata,
6221			    indirdep->ir_savebp->b_data,
6222			    indirdep->ir_savebp->b_bcount);
6223		free(indirdep->ir_saveddata, M_INDIRDEP);
6224		indirdep->ir_saveddata = NULL;
6225	}
6226	/*
6227	 * When bp is NULL there is a full truncation pending.  We
6228	 * must wait for this full truncation to be journaled before
6229	 * we can release this freework because the disk pointers will
6230	 * never be written as zero.
6231	 */
6232	if (bp == NULL)  {
6233		if (LIST_EMPTY(&indirdep->ir_freeblks->fb_jblkdephd))
6234			handle_written_freework(freework);
6235		else
6236			WORKLIST_INSERT(&indirdep->ir_freeblks->fb_freeworkhd,
6237			   &freework->fw_list);
6238	} else {
6239		/* Complete when the real copy is written. */
6240		WORKLIST_INSERT(&bp->b_dep, &freework->fw_list);
6241		BUF_UNLOCK(bp);
6242	}
6243}
6244
6245/*
6246 * Calculate the number of blocks we are going to release where datablocks
6247 * is the current total and length is the new file size.
6248 */
6249static ufs2_daddr_t
6250blkcount(fs, datablocks, length)
6251	struct fs *fs;
6252	ufs2_daddr_t datablocks;
6253	off_t length;
6254{
6255	off_t totblks, numblks;
6256
6257	totblks = 0;
6258	numblks = howmany(length, fs->fs_bsize);
6259	if (numblks <= NDADDR) {
6260		totblks = howmany(length, fs->fs_fsize);
6261		goto out;
6262	}
6263        totblks = blkstofrags(fs, numblks);
6264	numblks -= NDADDR;
6265	/*
6266	 * Count all single, then double, then triple indirects required.
6267	 * Subtracting one indirects worth of blocks for each pass
6268	 * acknowledges one of each pointed to by the inode.
6269	 */
6270	for (;;) {
6271		totblks += blkstofrags(fs, howmany(numblks, NINDIR(fs)));
6272		numblks -= NINDIR(fs);
6273		if (numblks <= 0)
6274			break;
6275		numblks = howmany(numblks, NINDIR(fs));
6276	}
6277out:
6278	totblks = fsbtodb(fs, totblks);
6279	/*
6280	 * Handle sparse files.  We can't reclaim more blocks than the inode
6281	 * references.  We will correct it later in handle_complete_freeblks()
6282	 * when we know the real count.
6283	 */
6284	if (totblks > datablocks)
6285		return (0);
6286	return (datablocks - totblks);
6287}
6288
6289/*
6290 * Handle freeblocks for journaled softupdate filesystems.
6291 *
6292 * Contrary to normal softupdates, we must preserve the block pointers in
6293 * indirects until their subordinates are free.  This is to avoid journaling
6294 * every block that is freed which may consume more space than the journal
6295 * itself.  The recovery program will see the free block journals at the
6296 * base of the truncated area and traverse them to reclaim space.  The
6297 * pointers in the inode may be cleared immediately after the journal
6298 * records are written because each direct and indirect pointer in the
6299 * inode is recorded in a journal.  This permits full truncation to proceed
6300 * asynchronously.  The write order is journal -> inode -> cgs -> indirects.
6301 *
6302 * The algorithm is as follows:
6303 * 1) Traverse the in-memory state and create journal entries to release
6304 *    the relevant blocks and full indirect trees.
6305 * 2) Traverse the indirect block chain adding partial truncation freework
6306 *    records to indirects in the path to lastlbn.  The freework will
6307 *    prevent new allocation dependencies from being satisfied in this
6308 *    indirect until the truncation completes.
6309 * 3) Read and lock the inode block, performing an update with the new size
6310 *    and pointers.  This prevents truncated data from becoming valid on
6311 *    disk through step 4.
6312 * 4) Reap unsatisfied dependencies that are beyond the truncated area,
6313 *    eliminate journal work for those records that do not require it.
6314 * 5) Schedule the journal records to be written followed by the inode block.
6315 * 6) Allocate any necessary frags for the end of file.
6316 * 7) Zero any partially truncated blocks.
6317 *
6318 * From this truncation proceeds asynchronously using the freework and
6319 * indir_trunc machinery.  The file will not be extended again into a
6320 * partially truncated indirect block until all work is completed but
6321 * the normal dependency mechanism ensures that it is rolled back/forward
6322 * as appropriate.  Further truncation may occur without delay and is
6323 * serialized in indir_trunc().
6324 */
6325void
6326softdep_journal_freeblocks(ip, cred, length, flags)
6327	struct inode *ip;	/* The inode whose length is to be reduced */
6328	struct ucred *cred;
6329	off_t length;		/* The new length for the file */
6330	int flags;		/* IO_EXT and/or IO_NORMAL */
6331{
6332	struct freeblks *freeblks, *fbn;
6333	struct worklist *wk, *wkn;
6334	struct inodedep *inodedep;
6335	struct jblkdep *jblkdep;
6336	struct allocdirect *adp, *adpn;
6337	struct ufsmount *ump;
6338	struct fs *fs;
6339	struct buf *bp;
6340	struct vnode *vp;
6341	struct mount *mp;
6342	ufs2_daddr_t extblocks, datablocks;
6343	ufs_lbn_t tmpval, lbn, lastlbn;
6344	int frags, lastoff, iboff, allocblock, needj, dflags, error, i;
6345
6346	fs = ip->i_fs;
6347	ump = ip->i_ump;
6348	mp = UFSTOVFS(ump);
6349	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6350	    ("softdep_journal_freeblocks called on non-softdep filesystem"));
6351	vp = ITOV(ip);
6352	needj = 1;
6353	iboff = -1;
6354	allocblock = 0;
6355	extblocks = 0;
6356	datablocks = 0;
6357	frags = 0;
6358	freeblks = newfreeblks(mp, ip);
6359	ACQUIRE_LOCK(ump);
6360	/*
6361	 * If we're truncating a removed file that will never be written
6362	 * we don't need to journal the block frees.  The canceled journals
6363	 * for the allocations will suffice.
6364	 */
6365	dflags = DEPALLOC;
6366	if (IS_SNAPSHOT(ip))
6367		dflags |= NODELAY;
6368	inodedep_lookup(mp, ip->i_number, dflags, &inodedep);
6369	if ((inodedep->id_state & (UNLINKED | DEPCOMPLETE)) == UNLINKED &&
6370	    length == 0)
6371		needj = 0;
6372	CTR3(KTR_SUJ, "softdep_journal_freeblks: ip %d length %ld needj %d",
6373	    ip->i_number, length, needj);
6374	FREE_LOCK(ump);
6375	/*
6376	 * Calculate the lbn that we are truncating to.  This results in -1
6377	 * if we're truncating the 0 bytes.  So it is the last lbn we want
6378	 * to keep, not the first lbn we want to truncate.
6379	 */
6380	lastlbn = lblkno(fs, length + fs->fs_bsize - 1) - 1;
6381	lastoff = blkoff(fs, length);
6382	/*
6383	 * Compute frags we are keeping in lastlbn.  0 means all.
6384	 */
6385	if (lastlbn >= 0 && lastlbn < NDADDR) {
6386		frags = fragroundup(fs, lastoff);
6387		/* adp offset of last valid allocdirect. */
6388		iboff = lastlbn;
6389	} else if (lastlbn > 0)
6390		iboff = NDADDR;
6391	if (fs->fs_magic == FS_UFS2_MAGIC)
6392		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6393	/*
6394	 * Handle normal data blocks and indirects.  This section saves
6395	 * values used after the inode update to complete frag and indirect
6396	 * truncation.
6397	 */
6398	if ((flags & IO_NORMAL) != 0) {
6399		/*
6400		 * Handle truncation of whole direct and indirect blocks.
6401		 */
6402		for (i = iboff + 1; i < NDADDR; i++)
6403			setup_freedirect(freeblks, ip, i, needj);
6404		for (i = 0, tmpval = NINDIR(fs), lbn = NDADDR; i < NIADDR;
6405		    i++, lbn += tmpval, tmpval *= NINDIR(fs)) {
6406			/* Release a whole indirect tree. */
6407			if (lbn > lastlbn) {
6408				setup_freeindir(freeblks, ip, i, -lbn -i,
6409				    needj);
6410				continue;
6411			}
6412			iboff = i + NDADDR;
6413			/*
6414			 * Traverse partially truncated indirect tree.
6415			 */
6416			if (lbn <= lastlbn && lbn + tmpval - 1 > lastlbn)
6417				setup_trunc_indir(freeblks, ip, -lbn - i,
6418				    lastlbn, DIP(ip, i_ib[i]));
6419		}
6420		/*
6421		 * Handle partial truncation to a frag boundary.
6422		 */
6423		if (frags) {
6424			ufs2_daddr_t blkno;
6425			long oldfrags;
6426
6427			oldfrags = blksize(fs, ip, lastlbn);
6428			blkno = DIP(ip, i_db[lastlbn]);
6429			if (blkno && oldfrags != frags) {
6430				oldfrags -= frags;
6431				oldfrags = numfrags(ip->i_fs, oldfrags);
6432				blkno += numfrags(ip->i_fs, frags);
6433				newfreework(ump, freeblks, NULL, lastlbn,
6434				    blkno, oldfrags, 0, needj);
6435			} else if (blkno == 0)
6436				allocblock = 1;
6437		}
6438		/*
6439		 * Add a journal record for partial truncate if we are
6440		 * handling indirect blocks.  Non-indirects need no extra
6441		 * journaling.
6442		 */
6443		if (length != 0 && lastlbn >= NDADDR) {
6444			ip->i_flag |= IN_TRUNCATED;
6445			newjtrunc(freeblks, length, 0);
6446		}
6447		ip->i_size = length;
6448		DIP_SET(ip, i_size, ip->i_size);
6449		datablocks = DIP(ip, i_blocks) - extblocks;
6450		if (length != 0)
6451			datablocks = blkcount(ip->i_fs, datablocks, length);
6452		freeblks->fb_len = length;
6453	}
6454	if ((flags & IO_EXT) != 0) {
6455		for (i = 0; i < NXADDR; i++)
6456			setup_freeext(freeblks, ip, i, needj);
6457		ip->i_din2->di_extsize = 0;
6458		datablocks += extblocks;
6459	}
6460#ifdef QUOTA
6461	/* Reference the quotas in case the block count is wrong in the end. */
6462	quotaref(vp, freeblks->fb_quota);
6463	(void) chkdq(ip, -datablocks, NOCRED, 0);
6464#endif
6465	freeblks->fb_chkcnt = -datablocks;
6466	UFS_LOCK(ump);
6467	fs->fs_pendingblocks += datablocks;
6468	UFS_UNLOCK(ump);
6469	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6470	/*
6471	 * Handle truncation of incomplete alloc direct dependencies.  We
6472	 * hold the inode block locked to prevent incomplete dependencies
6473	 * from reaching the disk while we are eliminating those that
6474	 * have been truncated.  This is a partially inlined ffs_update().
6475	 */
6476	ufs_itimes(vp);
6477	ip->i_flag &= ~(IN_LAZYACCESS | IN_LAZYMOD | IN_MODIFIED);
6478	error = bread(ip->i_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6479	    (int)fs->fs_bsize, cred, &bp);
6480	if (error) {
6481		brelse(bp);
6482		softdep_error("softdep_journal_freeblocks", error);
6483		return;
6484	}
6485	if (bp->b_bufsize == fs->fs_bsize)
6486		bp->b_flags |= B_CLUSTEROK;
6487	softdep_update_inodeblock(ip, bp, 0);
6488	if (ump->um_fstype == UFS1)
6489		*((struct ufs1_dinode *)bp->b_data +
6490		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din1;
6491	else
6492		*((struct ufs2_dinode *)bp->b_data +
6493		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din2;
6494	ACQUIRE_LOCK(ump);
6495	(void) inodedep_lookup(mp, ip->i_number, dflags, &inodedep);
6496	if ((inodedep->id_state & IOSTARTED) != 0)
6497		panic("softdep_setup_freeblocks: inode busy");
6498	/*
6499	 * Add the freeblks structure to the list of operations that
6500	 * must await the zero'ed inode being written to disk. If we
6501	 * still have a bitmap dependency (needj), then the inode
6502	 * has never been written to disk, so we can process the
6503	 * freeblks below once we have deleted the dependencies.
6504	 */
6505	if (needj)
6506		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6507	else
6508		freeblks->fb_state |= COMPLETE;
6509	if ((flags & IO_NORMAL) != 0) {
6510		TAILQ_FOREACH_SAFE(adp, &inodedep->id_inoupdt, ad_next, adpn) {
6511			if (adp->ad_offset > iboff)
6512				cancel_allocdirect(&inodedep->id_inoupdt, adp,
6513				    freeblks);
6514			/*
6515			 * Truncate the allocdirect.  We could eliminate
6516			 * or modify journal records as well.
6517			 */
6518			else if (adp->ad_offset == iboff && frags)
6519				adp->ad_newsize = frags;
6520		}
6521	}
6522	if ((flags & IO_EXT) != 0)
6523		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != 0)
6524			cancel_allocdirect(&inodedep->id_extupdt, adp,
6525			    freeblks);
6526	/*
6527	 * Scan the bufwait list for newblock dependencies that will never
6528	 * make it to disk.
6529	 */
6530	LIST_FOREACH_SAFE(wk, &inodedep->id_bufwait, wk_list, wkn) {
6531		if (wk->wk_type != D_ALLOCDIRECT)
6532			continue;
6533		adp = WK_ALLOCDIRECT(wk);
6534		if (((flags & IO_NORMAL) != 0 && (adp->ad_offset > iboff)) ||
6535		    ((flags & IO_EXT) != 0 && (adp->ad_state & EXTDATA))) {
6536			cancel_jfreeblk(freeblks, adp->ad_newblkno);
6537			cancel_newblk(WK_NEWBLK(wk), NULL, &freeblks->fb_jwork);
6538			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
6539		}
6540	}
6541	/*
6542	 * Add journal work.
6543	 */
6544	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps)
6545		add_to_journal(&jblkdep->jb_list);
6546	FREE_LOCK(ump);
6547	bdwrite(bp);
6548	/*
6549	 * Truncate dependency structures beyond length.
6550	 */
6551	trunc_dependencies(ip, freeblks, lastlbn, frags, flags);
6552	/*
6553	 * This is only set when we need to allocate a fragment because
6554	 * none existed at the end of a frag-sized file.  It handles only
6555	 * allocating a new, zero filled block.
6556	 */
6557	if (allocblock) {
6558		ip->i_size = length - lastoff;
6559		DIP_SET(ip, i_size, ip->i_size);
6560		error = UFS_BALLOC(vp, length - 1, 1, cred, BA_CLRBUF, &bp);
6561		if (error != 0) {
6562			softdep_error("softdep_journal_freeblks", error);
6563			return;
6564		}
6565		ip->i_size = length;
6566		DIP_SET(ip, i_size, length);
6567		ip->i_flag |= IN_CHANGE | IN_UPDATE;
6568		allocbuf(bp, frags);
6569		ffs_update(vp, 0);
6570		bawrite(bp);
6571	} else if (lastoff != 0 && vp->v_type != VDIR) {
6572		int size;
6573
6574		/*
6575		 * Zero the end of a truncated frag or block.
6576		 */
6577		size = sblksize(fs, length, lastlbn);
6578		error = bread(vp, lastlbn, size, cred, &bp);
6579		if (error) {
6580			softdep_error("softdep_journal_freeblks", error);
6581			return;
6582		}
6583		bzero((char *)bp->b_data + lastoff, size - lastoff);
6584		bawrite(bp);
6585
6586	}
6587	ACQUIRE_LOCK(ump);
6588	inodedep_lookup(mp, ip->i_number, dflags, &inodedep);
6589	TAILQ_INSERT_TAIL(&inodedep->id_freeblklst, freeblks, fb_next);
6590	freeblks->fb_state |= DEPCOMPLETE | ONDEPLIST;
6591	/*
6592	 * We zero earlier truncations so they don't erroneously
6593	 * update i_blocks.
6594	 */
6595	if (freeblks->fb_len == 0 && (flags & IO_NORMAL) != 0)
6596		TAILQ_FOREACH(fbn, &inodedep->id_freeblklst, fb_next)
6597			fbn->fb_len = 0;
6598	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE &&
6599	    LIST_EMPTY(&freeblks->fb_jblkdephd))
6600		freeblks->fb_state |= INPROGRESS;
6601	else
6602		freeblks = NULL;
6603	FREE_LOCK(ump);
6604	if (freeblks)
6605		handle_workitem_freeblocks(freeblks, 0);
6606	trunc_pages(ip, length, extblocks, flags);
6607
6608}
6609
6610/*
6611 * Flush a JOP_SYNC to the journal.
6612 */
6613void
6614softdep_journal_fsync(ip)
6615	struct inode *ip;
6616{
6617	struct jfsync *jfsync;
6618
6619	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ip->i_ump)) != 0,
6620	    ("softdep_journal_fsync called on non-softdep filesystem"));
6621	if ((ip->i_flag & IN_TRUNCATED) == 0)
6622		return;
6623	ip->i_flag &= ~IN_TRUNCATED;
6624	jfsync = malloc(sizeof(*jfsync), M_JFSYNC, M_SOFTDEP_FLAGS | M_ZERO);
6625	workitem_alloc(&jfsync->jfs_list, D_JFSYNC, UFSTOVFS(ip->i_ump));
6626	jfsync->jfs_size = ip->i_size;
6627	jfsync->jfs_ino = ip->i_number;
6628	ACQUIRE_LOCK(ip->i_ump);
6629	add_to_journal(&jfsync->jfs_list);
6630	jwait(&jfsync->jfs_list, MNT_WAIT);
6631	FREE_LOCK(ip->i_ump);
6632}
6633
6634/*
6635 * Block de-allocation dependencies.
6636 *
6637 * When blocks are de-allocated, the on-disk pointers must be nullified before
6638 * the blocks are made available for use by other files.  (The true
6639 * requirement is that old pointers must be nullified before new on-disk
6640 * pointers are set.  We chose this slightly more stringent requirement to
6641 * reduce complexity.) Our implementation handles this dependency by updating
6642 * the inode (or indirect block) appropriately but delaying the actual block
6643 * de-allocation (i.e., freemap and free space count manipulation) until
6644 * after the updated versions reach stable storage.  After the disk is
6645 * updated, the blocks can be safely de-allocated whenever it is convenient.
6646 * This implementation handles only the common case of reducing a file's
6647 * length to zero. Other cases are handled by the conventional synchronous
6648 * write approach.
6649 *
6650 * The ffs implementation with which we worked double-checks
6651 * the state of the block pointers and file size as it reduces
6652 * a file's length.  Some of this code is replicated here in our
6653 * soft updates implementation.  The freeblks->fb_chkcnt field is
6654 * used to transfer a part of this information to the procedure
6655 * that eventually de-allocates the blocks.
6656 *
6657 * This routine should be called from the routine that shortens
6658 * a file's length, before the inode's size or block pointers
6659 * are modified. It will save the block pointer information for
6660 * later release and zero the inode so that the calling routine
6661 * can release it.
6662 */
6663void
6664softdep_setup_freeblocks(ip, length, flags)
6665	struct inode *ip;	/* The inode whose length is to be reduced */
6666	off_t length;		/* The new length for the file */
6667	int flags;		/* IO_EXT and/or IO_NORMAL */
6668{
6669	struct ufs1_dinode *dp1;
6670	struct ufs2_dinode *dp2;
6671	struct freeblks *freeblks;
6672	struct inodedep *inodedep;
6673	struct allocdirect *adp;
6674	struct ufsmount *ump;
6675	struct buf *bp;
6676	struct fs *fs;
6677	ufs2_daddr_t extblocks, datablocks;
6678	struct mount *mp;
6679	int i, delay, error, dflags;
6680	ufs_lbn_t tmpval;
6681	ufs_lbn_t lbn;
6682
6683	ump = ip->i_ump;
6684	mp = UFSTOVFS(ump);
6685	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6686	    ("softdep_setup_freeblocks called on non-softdep filesystem"));
6687	CTR2(KTR_SUJ, "softdep_setup_freeblks: ip %d length %ld",
6688	    ip->i_number, length);
6689	KASSERT(length == 0, ("softdep_setup_freeblocks: non-zero length"));
6690	fs = ip->i_fs;
6691	freeblks = newfreeblks(mp, ip);
6692	extblocks = 0;
6693	datablocks = 0;
6694	if (fs->fs_magic == FS_UFS2_MAGIC)
6695		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6696	if ((flags & IO_NORMAL) != 0) {
6697		for (i = 0; i < NDADDR; i++)
6698			setup_freedirect(freeblks, ip, i, 0);
6699		for (i = 0, tmpval = NINDIR(fs), lbn = NDADDR; i < NIADDR;
6700		    i++, lbn += tmpval, tmpval *= NINDIR(fs))
6701			setup_freeindir(freeblks, ip, i, -lbn -i, 0);
6702		ip->i_size = 0;
6703		DIP_SET(ip, i_size, 0);
6704		datablocks = DIP(ip, i_blocks) - extblocks;
6705	}
6706	if ((flags & IO_EXT) != 0) {
6707		for (i = 0; i < NXADDR; i++)
6708			setup_freeext(freeblks, ip, i, 0);
6709		ip->i_din2->di_extsize = 0;
6710		datablocks += extblocks;
6711	}
6712#ifdef QUOTA
6713	/* Reference the quotas in case the block count is wrong in the end. */
6714	quotaref(ITOV(ip), freeblks->fb_quota);
6715	(void) chkdq(ip, -datablocks, NOCRED, 0);
6716#endif
6717	freeblks->fb_chkcnt = -datablocks;
6718	UFS_LOCK(ump);
6719	fs->fs_pendingblocks += datablocks;
6720	UFS_UNLOCK(ump);
6721	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6722	/*
6723	 * Push the zero'ed inode to to its disk buffer so that we are free
6724	 * to delete its dependencies below. Once the dependencies are gone
6725	 * the buffer can be safely released.
6726	 */
6727	if ((error = bread(ip->i_devvp,
6728	    fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6729	    (int)fs->fs_bsize, NOCRED, &bp)) != 0) {
6730		brelse(bp);
6731		softdep_error("softdep_setup_freeblocks", error);
6732	}
6733	if (ump->um_fstype == UFS1) {
6734		dp1 = ((struct ufs1_dinode *)bp->b_data +
6735		    ino_to_fsbo(fs, ip->i_number));
6736		ip->i_din1->di_freelink = dp1->di_freelink;
6737		*dp1 = *ip->i_din1;
6738	} else {
6739		dp2 = ((struct ufs2_dinode *)bp->b_data +
6740		    ino_to_fsbo(fs, ip->i_number));
6741		ip->i_din2->di_freelink = dp2->di_freelink;
6742		*dp2 = *ip->i_din2;
6743	}
6744	/*
6745	 * Find and eliminate any inode dependencies.
6746	 */
6747	ACQUIRE_LOCK(ump);
6748	dflags = DEPALLOC;
6749	if (IS_SNAPSHOT(ip))
6750		dflags |= NODELAY;
6751	(void) inodedep_lookup(mp, ip->i_number, dflags, &inodedep);
6752	if ((inodedep->id_state & IOSTARTED) != 0)
6753		panic("softdep_setup_freeblocks: inode busy");
6754	/*
6755	 * Add the freeblks structure to the list of operations that
6756	 * must await the zero'ed inode being written to disk. If we
6757	 * still have a bitmap dependency (delay == 0), then the inode
6758	 * has never been written to disk, so we can process the
6759	 * freeblks below once we have deleted the dependencies.
6760	 */
6761	delay = (inodedep->id_state & DEPCOMPLETE);
6762	if (delay)
6763		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6764	else
6765		freeblks->fb_state |= COMPLETE;
6766	/*
6767	 * Because the file length has been truncated to zero, any
6768	 * pending block allocation dependency structures associated
6769	 * with this inode are obsolete and can simply be de-allocated.
6770	 * We must first merge the two dependency lists to get rid of
6771	 * any duplicate freefrag structures, then purge the merged list.
6772	 * If we still have a bitmap dependency, then the inode has never
6773	 * been written to disk, so we can free any fragments without delay.
6774	 */
6775	if (flags & IO_NORMAL) {
6776		merge_inode_lists(&inodedep->id_newinoupdt,
6777		    &inodedep->id_inoupdt);
6778		while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != 0)
6779			cancel_allocdirect(&inodedep->id_inoupdt, adp,
6780			    freeblks);
6781	}
6782	if (flags & IO_EXT) {
6783		merge_inode_lists(&inodedep->id_newextupdt,
6784		    &inodedep->id_extupdt);
6785		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != 0)
6786			cancel_allocdirect(&inodedep->id_extupdt, adp,
6787			    freeblks);
6788	}
6789	FREE_LOCK(ump);
6790	bdwrite(bp);
6791	trunc_dependencies(ip, freeblks, -1, 0, flags);
6792	ACQUIRE_LOCK(ump);
6793	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
6794		(void) free_inodedep(inodedep);
6795	freeblks->fb_state |= DEPCOMPLETE;
6796	/*
6797	 * If the inode with zeroed block pointers is now on disk
6798	 * we can start freeing blocks.
6799	 */
6800	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
6801		freeblks->fb_state |= INPROGRESS;
6802	else
6803		freeblks = NULL;
6804	FREE_LOCK(ump);
6805	if (freeblks)
6806		handle_workitem_freeblocks(freeblks, 0);
6807	trunc_pages(ip, length, extblocks, flags);
6808}
6809
6810/*
6811 * Eliminate pages from the page cache that back parts of this inode and
6812 * adjust the vnode pager's idea of our size.  This prevents stale data
6813 * from hanging around in the page cache.
6814 */
6815static void
6816trunc_pages(ip, length, extblocks, flags)
6817	struct inode *ip;
6818	off_t length;
6819	ufs2_daddr_t extblocks;
6820	int flags;
6821{
6822	struct vnode *vp;
6823	struct fs *fs;
6824	ufs_lbn_t lbn;
6825	off_t end, extend;
6826
6827	vp = ITOV(ip);
6828	fs = ip->i_fs;
6829	extend = OFF_TO_IDX(lblktosize(fs, -extblocks));
6830	if ((flags & IO_EXT) != 0)
6831		vn_pages_remove(vp, extend, 0);
6832	if ((flags & IO_NORMAL) == 0)
6833		return;
6834	BO_LOCK(&vp->v_bufobj);
6835	drain_output(vp);
6836	BO_UNLOCK(&vp->v_bufobj);
6837	/*
6838	 * The vnode pager eliminates file pages we eliminate indirects
6839	 * below.
6840	 */
6841	vnode_pager_setsize(vp, length);
6842	/*
6843	 * Calculate the end based on the last indirect we want to keep.  If
6844	 * the block extends into indirects we can just use the negative of
6845	 * its lbn.  Doubles and triples exist at lower numbers so we must
6846	 * be careful not to remove those, if they exist.  double and triple
6847	 * indirect lbns do not overlap with others so it is not important
6848	 * to verify how many levels are required.
6849	 */
6850	lbn = lblkno(fs, length);
6851	if (lbn >= NDADDR) {
6852		/* Calculate the virtual lbn of the triple indirect. */
6853		lbn = -lbn - (NIADDR - 1);
6854		end = OFF_TO_IDX(lblktosize(fs, lbn));
6855	} else
6856		end = extend;
6857	vn_pages_remove(vp, OFF_TO_IDX(OFF_MAX), end);
6858}
6859
6860/*
6861 * See if the buf bp is in the range eliminated by truncation.
6862 */
6863static int
6864trunc_check_buf(bp, blkoffp, lastlbn, lastoff, flags)
6865	struct buf *bp;
6866	int *blkoffp;
6867	ufs_lbn_t lastlbn;
6868	int lastoff;
6869	int flags;
6870{
6871	ufs_lbn_t lbn;
6872
6873	*blkoffp = 0;
6874	/* Only match ext/normal blocks as appropriate. */
6875	if (((flags & IO_EXT) == 0 && (bp->b_xflags & BX_ALTDATA)) ||
6876	    ((flags & IO_NORMAL) == 0 && (bp->b_xflags & BX_ALTDATA) == 0))
6877		return (0);
6878	/* ALTDATA is always a full truncation. */
6879	if ((bp->b_xflags & BX_ALTDATA) != 0)
6880		return (1);
6881	/* -1 is full truncation. */
6882	if (lastlbn == -1)
6883		return (1);
6884	/*
6885	 * If this is a partial truncate we only want those
6886	 * blocks and indirect blocks that cover the range
6887	 * we're after.
6888	 */
6889	lbn = bp->b_lblkno;
6890	if (lbn < 0)
6891		lbn = -(lbn + lbn_level(lbn));
6892	if (lbn < lastlbn)
6893		return (0);
6894	/* Here we only truncate lblkno if it's partial. */
6895	if (lbn == lastlbn) {
6896		if (lastoff == 0)
6897			return (0);
6898		*blkoffp = lastoff;
6899	}
6900	return (1);
6901}
6902
6903/*
6904 * Eliminate any dependencies that exist in memory beyond lblkno:off
6905 */
6906static void
6907trunc_dependencies(ip, freeblks, lastlbn, lastoff, flags)
6908	struct inode *ip;
6909	struct freeblks *freeblks;
6910	ufs_lbn_t lastlbn;
6911	int lastoff;
6912	int flags;
6913{
6914	struct bufobj *bo;
6915	struct vnode *vp;
6916	struct buf *bp;
6917	struct fs *fs;
6918	int blkoff;
6919
6920	/*
6921	 * We must wait for any I/O in progress to finish so that
6922	 * all potential buffers on the dirty list will be visible.
6923	 * Once they are all there, walk the list and get rid of
6924	 * any dependencies.
6925	 */
6926	fs = ip->i_fs;
6927	vp = ITOV(ip);
6928	bo = &vp->v_bufobj;
6929	BO_LOCK(bo);
6930	drain_output(vp);
6931	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs)
6932		bp->b_vflags &= ~BV_SCANNED;
6933restart:
6934	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) {
6935		if (bp->b_vflags & BV_SCANNED)
6936			continue;
6937		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
6938			bp->b_vflags |= BV_SCANNED;
6939			continue;
6940		}
6941		KASSERT(bp->b_bufobj == bo, ("Wrong object in buffer"));
6942		if ((bp = getdirtybuf(bp, BO_LOCKPTR(bo), MNT_WAIT)) == NULL)
6943			goto restart;
6944		BO_UNLOCK(bo);
6945		if (deallocate_dependencies(bp, freeblks, blkoff))
6946			bqrelse(bp);
6947		else
6948			brelse(bp);
6949		BO_LOCK(bo);
6950		goto restart;
6951	}
6952	/*
6953	 * Now do the work of vtruncbuf while also matching indirect blocks.
6954	 */
6955	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs)
6956		bp->b_vflags &= ~BV_SCANNED;
6957cleanrestart:
6958	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs) {
6959		if (bp->b_vflags & BV_SCANNED)
6960			continue;
6961		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
6962			bp->b_vflags |= BV_SCANNED;
6963			continue;
6964		}
6965		if (BUF_LOCK(bp,
6966		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
6967		    BO_LOCKPTR(bo)) == ENOLCK) {
6968			BO_LOCK(bo);
6969			goto cleanrestart;
6970		}
6971		bp->b_vflags |= BV_SCANNED;
6972		bremfree(bp);
6973		if (blkoff != 0) {
6974			allocbuf(bp, blkoff);
6975			bqrelse(bp);
6976		} else {
6977			bp->b_flags |= B_INVAL | B_NOCACHE | B_RELBUF;
6978			brelse(bp);
6979		}
6980		BO_LOCK(bo);
6981		goto cleanrestart;
6982	}
6983	drain_output(vp);
6984	BO_UNLOCK(bo);
6985}
6986
6987static int
6988cancel_pagedep(pagedep, freeblks, blkoff)
6989	struct pagedep *pagedep;
6990	struct freeblks *freeblks;
6991	int blkoff;
6992{
6993	struct jremref *jremref;
6994	struct jmvref *jmvref;
6995	struct dirrem *dirrem, *tmp;
6996	int i;
6997
6998	/*
6999	 * Copy any directory remove dependencies to the list
7000	 * to be processed after the freeblks proceeds.  If
7001	 * directory entry never made it to disk they
7002	 * can be dumped directly onto the work list.
7003	 */
7004	LIST_FOREACH_SAFE(dirrem, &pagedep->pd_dirremhd, dm_next, tmp) {
7005		/* Skip this directory removal if it is intended to remain. */
7006		if (dirrem->dm_offset < blkoff)
7007			continue;
7008		/*
7009		 * If there are any dirrems we wait for the journal write
7010		 * to complete and then restart the buf scan as the lock
7011		 * has been dropped.
7012		 */
7013		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL) {
7014			jwait(&jremref->jr_list, MNT_WAIT);
7015			return (ERESTART);
7016		}
7017		LIST_REMOVE(dirrem, dm_next);
7018		dirrem->dm_dirinum = pagedep->pd_ino;
7019		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &dirrem->dm_list);
7020	}
7021	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL) {
7022		jwait(&jmvref->jm_list, MNT_WAIT);
7023		return (ERESTART);
7024	}
7025	/*
7026	 * When we're partially truncating a pagedep we just want to flush
7027	 * journal entries and return.  There can not be any adds in the
7028	 * truncated portion of the directory and newblk must remain if
7029	 * part of the block remains.
7030	 */
7031	if (blkoff != 0) {
7032		struct diradd *dap;
7033
7034		LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
7035			if (dap->da_offset > blkoff)
7036				panic("cancel_pagedep: diradd %p off %d > %d",
7037				    dap, dap->da_offset, blkoff);
7038		for (i = 0; i < DAHASHSZ; i++)
7039			LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist)
7040				if (dap->da_offset > blkoff)
7041					panic("cancel_pagedep: diradd %p off %d > %d",
7042					    dap, dap->da_offset, blkoff);
7043		return (0);
7044	}
7045	/*
7046	 * There should be no directory add dependencies present
7047	 * as the directory could not be truncated until all
7048	 * children were removed.
7049	 */
7050	KASSERT(LIST_FIRST(&pagedep->pd_pendinghd) == NULL,
7051	    ("deallocate_dependencies: pendinghd != NULL"));
7052	for (i = 0; i < DAHASHSZ; i++)
7053		KASSERT(LIST_FIRST(&pagedep->pd_diraddhd[i]) == NULL,
7054		    ("deallocate_dependencies: diraddhd != NULL"));
7055	if ((pagedep->pd_state & NEWBLOCK) != 0)
7056		free_newdirblk(pagedep->pd_newdirblk);
7057	if (free_pagedep(pagedep) == 0)
7058		panic("Failed to free pagedep %p", pagedep);
7059	return (0);
7060}
7061
7062/*
7063 * Reclaim any dependency structures from a buffer that is about to
7064 * be reallocated to a new vnode. The buffer must be locked, thus,
7065 * no I/O completion operations can occur while we are manipulating
7066 * its associated dependencies. The mutex is held so that other I/O's
7067 * associated with related dependencies do not occur.
7068 */
7069static int
7070deallocate_dependencies(bp, freeblks, off)
7071	struct buf *bp;
7072	struct freeblks *freeblks;
7073	int off;
7074{
7075	struct indirdep *indirdep;
7076	struct pagedep *pagedep;
7077	struct allocdirect *adp;
7078	struct worklist *wk, *wkn;
7079	struct ufsmount *ump;
7080
7081	if ((wk = LIST_FIRST(&bp->b_dep)) == NULL)
7082		goto done;
7083	ump = VFSTOUFS(wk->wk_mp);
7084	ACQUIRE_LOCK(ump);
7085	LIST_FOREACH_SAFE(wk, &bp->b_dep, wk_list, wkn) {
7086		switch (wk->wk_type) {
7087		case D_INDIRDEP:
7088			indirdep = WK_INDIRDEP(wk);
7089			if (bp->b_lblkno >= 0 ||
7090			    bp->b_blkno != indirdep->ir_savebp->b_lblkno)
7091				panic("deallocate_dependencies: not indir");
7092			cancel_indirdep(indirdep, bp, freeblks);
7093			continue;
7094
7095		case D_PAGEDEP:
7096			pagedep = WK_PAGEDEP(wk);
7097			if (cancel_pagedep(pagedep, freeblks, off)) {
7098				FREE_LOCK(ump);
7099				return (ERESTART);
7100			}
7101			continue;
7102
7103		case D_ALLOCINDIR:
7104			/*
7105			 * Simply remove the allocindir, we'll find it via
7106			 * the indirdep where we can clear pointers if
7107			 * needed.
7108			 */
7109			WORKLIST_REMOVE(wk);
7110			continue;
7111
7112		case D_FREEWORK:
7113			/*
7114			 * A truncation is waiting for the zero'd pointers
7115			 * to be written.  It can be freed when the freeblks
7116			 * is journaled.
7117			 */
7118			WORKLIST_REMOVE(wk);
7119			wk->wk_state |= ONDEPLIST;
7120			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
7121			break;
7122
7123		case D_ALLOCDIRECT:
7124			adp = WK_ALLOCDIRECT(wk);
7125			if (off != 0)
7126				continue;
7127			/* FALLTHROUGH */
7128		default:
7129			panic("deallocate_dependencies: Unexpected type %s",
7130			    TYPENAME(wk->wk_type));
7131			/* NOTREACHED */
7132		}
7133	}
7134	FREE_LOCK(ump);
7135done:
7136	/*
7137	 * Don't throw away this buf, we were partially truncating and
7138	 * some deps may always remain.
7139	 */
7140	if (off) {
7141		allocbuf(bp, off);
7142		bp->b_vflags |= BV_SCANNED;
7143		return (EBUSY);
7144	}
7145	bp->b_flags |= B_INVAL | B_NOCACHE;
7146
7147	return (0);
7148}
7149
7150/*
7151 * An allocdirect is being canceled due to a truncate.  We must make sure
7152 * the journal entry is released in concert with the blkfree that releases
7153 * the storage.  Completed journal entries must not be released until the
7154 * space is no longer pointed to by the inode or in the bitmap.
7155 */
7156static void
7157cancel_allocdirect(adphead, adp, freeblks)
7158	struct allocdirectlst *adphead;
7159	struct allocdirect *adp;
7160	struct freeblks *freeblks;
7161{
7162	struct freework *freework;
7163	struct newblk *newblk;
7164	struct worklist *wk;
7165
7166	TAILQ_REMOVE(adphead, adp, ad_next);
7167	newblk = (struct newblk *)adp;
7168	freework = NULL;
7169	/*
7170	 * Find the correct freework structure.
7171	 */
7172	LIST_FOREACH(wk, &freeblks->fb_freeworkhd, wk_list) {
7173		if (wk->wk_type != D_FREEWORK)
7174			continue;
7175		freework = WK_FREEWORK(wk);
7176		if (freework->fw_blkno == newblk->nb_newblkno)
7177			break;
7178	}
7179	if (freework == NULL)
7180		panic("cancel_allocdirect: Freework not found");
7181	/*
7182	 * If a newblk exists at all we still have the journal entry that
7183	 * initiated the allocation so we do not need to journal the free.
7184	 */
7185	cancel_jfreeblk(freeblks, freework->fw_blkno);
7186	/*
7187	 * If the journal hasn't been written the jnewblk must be passed
7188	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
7189	 * this by linking the journal dependency into the freework to be
7190	 * freed when freework_freeblock() is called.  If the journal has
7191	 * been written we can simply reclaim the journal space when the
7192	 * freeblks work is complete.
7193	 */
7194	freework->fw_jnewblk = cancel_newblk(newblk, &freework->fw_list,
7195	    &freeblks->fb_jwork);
7196	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
7197}
7198
7199
7200/*
7201 * Cancel a new block allocation.  May be an indirect or direct block.  We
7202 * remove it from various lists and return any journal record that needs to
7203 * be resolved by the caller.
7204 *
7205 * A special consideration is made for indirects which were never pointed
7206 * at on disk and will never be found once this block is released.
7207 */
7208static struct jnewblk *
7209cancel_newblk(newblk, wk, wkhd)
7210	struct newblk *newblk;
7211	struct worklist *wk;
7212	struct workhead *wkhd;
7213{
7214	struct jnewblk *jnewblk;
7215
7216	CTR1(KTR_SUJ, "cancel_newblk: blkno %jd", newblk->nb_newblkno);
7217
7218	newblk->nb_state |= GOINGAWAY;
7219	/*
7220	 * Previously we traversed the completedhd on each indirdep
7221	 * attached to this newblk to cancel them and gather journal
7222	 * work.  Since we need only the oldest journal segment and
7223	 * the lowest point on the tree will always have the oldest
7224	 * journal segment we are free to release the segments
7225	 * of any subordinates and may leave the indirdep list to
7226	 * indirdep_complete() when this newblk is freed.
7227	 */
7228	if (newblk->nb_state & ONDEPLIST) {
7229		newblk->nb_state &= ~ONDEPLIST;
7230		LIST_REMOVE(newblk, nb_deps);
7231	}
7232	if (newblk->nb_state & ONWORKLIST)
7233		WORKLIST_REMOVE(&newblk->nb_list);
7234	/*
7235	 * If the journal entry hasn't been written we save a pointer to
7236	 * the dependency that frees it until it is written or the
7237	 * superseding operation completes.
7238	 */
7239	jnewblk = newblk->nb_jnewblk;
7240	if (jnewblk != NULL && wk != NULL) {
7241		newblk->nb_jnewblk = NULL;
7242		jnewblk->jn_dep = wk;
7243	}
7244	if (!LIST_EMPTY(&newblk->nb_jwork))
7245		jwork_move(wkhd, &newblk->nb_jwork);
7246	/*
7247	 * When truncating we must free the newdirblk early to remove
7248	 * the pagedep from the hash before returning.
7249	 */
7250	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7251		free_newdirblk(WK_NEWDIRBLK(wk));
7252	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7253		panic("cancel_newblk: extra newdirblk");
7254
7255	return (jnewblk);
7256}
7257
7258/*
7259 * Schedule the freefrag associated with a newblk to be released once
7260 * the pointers are written and the previous block is no longer needed.
7261 */
7262static void
7263newblk_freefrag(newblk)
7264	struct newblk *newblk;
7265{
7266	struct freefrag *freefrag;
7267
7268	if (newblk->nb_freefrag == NULL)
7269		return;
7270	freefrag = newblk->nb_freefrag;
7271	newblk->nb_freefrag = NULL;
7272	freefrag->ff_state |= COMPLETE;
7273	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
7274		add_to_worklist(&freefrag->ff_list, 0);
7275}
7276
7277/*
7278 * Free a newblk. Generate a new freefrag work request if appropriate.
7279 * This must be called after the inode pointer and any direct block pointers
7280 * are valid or fully removed via truncate or frag extension.
7281 */
7282static void
7283free_newblk(newblk)
7284	struct newblk *newblk;
7285{
7286	struct indirdep *indirdep;
7287	struct worklist *wk;
7288
7289	KASSERT(newblk->nb_jnewblk == NULL,
7290	    ("free_newblk: jnewblk %p still attached", newblk->nb_jnewblk));
7291	KASSERT(newblk->nb_list.wk_type != D_NEWBLK,
7292	    ("free_newblk: unclaimed newblk"));
7293	LOCK_OWNED(VFSTOUFS(newblk->nb_list.wk_mp));
7294	newblk_freefrag(newblk);
7295	if (newblk->nb_state & ONDEPLIST)
7296		LIST_REMOVE(newblk, nb_deps);
7297	if (newblk->nb_state & ONWORKLIST)
7298		WORKLIST_REMOVE(&newblk->nb_list);
7299	LIST_REMOVE(newblk, nb_hash);
7300	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7301		free_newdirblk(WK_NEWDIRBLK(wk));
7302	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7303		panic("free_newblk: extra newdirblk");
7304	while ((indirdep = LIST_FIRST(&newblk->nb_indirdeps)) != NULL)
7305		indirdep_complete(indirdep);
7306	handle_jwork(&newblk->nb_jwork);
7307	WORKITEM_FREE(newblk, D_NEWBLK);
7308}
7309
7310/*
7311 * Free a newdirblk. Clear the NEWBLOCK flag on its associated pagedep.
7312 * This routine must be called with splbio interrupts blocked.
7313 */
7314static void
7315free_newdirblk(newdirblk)
7316	struct newdirblk *newdirblk;
7317{
7318	struct pagedep *pagedep;
7319	struct diradd *dap;
7320	struct worklist *wk;
7321
7322	LOCK_OWNED(VFSTOUFS(newdirblk->db_list.wk_mp));
7323	WORKLIST_REMOVE(&newdirblk->db_list);
7324	/*
7325	 * If the pagedep is still linked onto the directory buffer
7326	 * dependency chain, then some of the entries on the
7327	 * pd_pendinghd list may not be committed to disk yet. In
7328	 * this case, we will simply clear the NEWBLOCK flag and
7329	 * let the pd_pendinghd list be processed when the pagedep
7330	 * is next written. If the pagedep is no longer on the buffer
7331	 * dependency chain, then all the entries on the pd_pending
7332	 * list are committed to disk and we can free them here.
7333	 */
7334	pagedep = newdirblk->db_pagedep;
7335	pagedep->pd_state &= ~NEWBLOCK;
7336	if ((pagedep->pd_state & ONWORKLIST) == 0) {
7337		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
7338			free_diradd(dap, NULL);
7339		/*
7340		 * If no dependencies remain, the pagedep will be freed.
7341		 */
7342		free_pagedep(pagedep);
7343	}
7344	/* Should only ever be one item in the list. */
7345	while ((wk = LIST_FIRST(&newdirblk->db_mkdir)) != NULL) {
7346		WORKLIST_REMOVE(wk);
7347		handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
7348	}
7349	WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
7350}
7351
7352/*
7353 * Prepare an inode to be freed. The actual free operation is not
7354 * done until the zero'ed inode has been written to disk.
7355 */
7356void
7357softdep_freefile(pvp, ino, mode)
7358	struct vnode *pvp;
7359	ino_t ino;
7360	int mode;
7361{
7362	struct inode *ip = VTOI(pvp);
7363	struct inodedep *inodedep;
7364	struct freefile *freefile;
7365	struct freeblks *freeblks;
7366	struct ufsmount *ump;
7367
7368	ump = ip->i_ump;
7369	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
7370	    ("softdep_freefile called on non-softdep filesystem"));
7371	/*
7372	 * This sets up the inode de-allocation dependency.
7373	 */
7374	freefile = malloc(sizeof(struct freefile),
7375		M_FREEFILE, M_SOFTDEP_FLAGS);
7376	workitem_alloc(&freefile->fx_list, D_FREEFILE, pvp->v_mount);
7377	freefile->fx_mode = mode;
7378	freefile->fx_oldinum = ino;
7379	freefile->fx_devvp = ip->i_devvp;
7380	LIST_INIT(&freefile->fx_jwork);
7381	UFS_LOCK(ump);
7382	ip->i_fs->fs_pendinginodes += 1;
7383	UFS_UNLOCK(ump);
7384
7385	/*
7386	 * If the inodedep does not exist, then the zero'ed inode has
7387	 * been written to disk. If the allocated inode has never been
7388	 * written to disk, then the on-disk inode is zero'ed. In either
7389	 * case we can free the file immediately.  If the journal was
7390	 * canceled before being written the inode will never make it to
7391	 * disk and we must send the canceled journal entrys to
7392	 * ffs_freefile() to be cleared in conjunction with the bitmap.
7393	 * Any blocks waiting on the inode to write can be safely freed
7394	 * here as it will never been written.
7395	 */
7396	ACQUIRE_LOCK(ump);
7397	inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7398	if (inodedep) {
7399		/*
7400		 * Clear out freeblks that no longer need to reference
7401		 * this inode.
7402		 */
7403		while ((freeblks =
7404		    TAILQ_FIRST(&inodedep->id_freeblklst)) != NULL) {
7405			TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks,
7406			    fb_next);
7407			freeblks->fb_state &= ~ONDEPLIST;
7408		}
7409		/*
7410		 * Remove this inode from the unlinked list.
7411		 */
7412		if (inodedep->id_state & UNLINKED) {
7413			/*
7414			 * Save the journal work to be freed with the bitmap
7415			 * before we clear UNLINKED.  Otherwise it can be lost
7416			 * if the inode block is written.
7417			 */
7418			handle_bufwait(inodedep, &freefile->fx_jwork);
7419			clear_unlinked_inodedep(inodedep);
7420			/*
7421			 * Re-acquire inodedep as we've dropped the
7422			 * soft updates lock in clear_unlinked_inodedep().
7423			 */
7424			inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7425		}
7426	}
7427	if (inodedep == NULL || check_inode_unwritten(inodedep)) {
7428		FREE_LOCK(ump);
7429		handle_workitem_freefile(freefile);
7430		return;
7431	}
7432	if ((inodedep->id_state & DEPCOMPLETE) == 0)
7433		inodedep->id_state |= GOINGAWAY;
7434	WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
7435	FREE_LOCK(ump);
7436	if (ip->i_number == ino)
7437		ip->i_flag |= IN_MODIFIED;
7438}
7439
7440/*
7441 * Check to see if an inode has never been written to disk. If
7442 * so free the inodedep and return success, otherwise return failure.
7443 * This routine must be called with splbio interrupts blocked.
7444 *
7445 * If we still have a bitmap dependency, then the inode has never
7446 * been written to disk. Drop the dependency as it is no longer
7447 * necessary since the inode is being deallocated. We set the
7448 * ALLCOMPLETE flags since the bitmap now properly shows that the
7449 * inode is not allocated. Even if the inode is actively being
7450 * written, it has been rolled back to its zero'ed state, so we
7451 * are ensured that a zero inode is what is on the disk. For short
7452 * lived files, this change will usually result in removing all the
7453 * dependencies from the inode so that it can be freed immediately.
7454 */
7455static int
7456check_inode_unwritten(inodedep)
7457	struct inodedep *inodedep;
7458{
7459
7460	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7461
7462	if ((inodedep->id_state & (DEPCOMPLETE | UNLINKED)) != 0 ||
7463	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
7464	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
7465	    !LIST_EMPTY(&inodedep->id_bufwait) ||
7466	    !LIST_EMPTY(&inodedep->id_inowait) ||
7467	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7468	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7469	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7470	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7471	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7472	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7473	    inodedep->id_mkdiradd != NULL ||
7474	    inodedep->id_nlinkdelta != 0)
7475		return (0);
7476	/*
7477	 * Another process might be in initiate_write_inodeblock_ufs[12]
7478	 * trying to allocate memory without holding "Softdep Lock".
7479	 */
7480	if ((inodedep->id_state & IOSTARTED) != 0 &&
7481	    inodedep->id_savedino1 == NULL)
7482		return (0);
7483
7484	if (inodedep->id_state & ONDEPLIST)
7485		LIST_REMOVE(inodedep, id_deps);
7486	inodedep->id_state &= ~ONDEPLIST;
7487	inodedep->id_state |= ALLCOMPLETE;
7488	inodedep->id_bmsafemap = NULL;
7489	if (inodedep->id_state & ONWORKLIST)
7490		WORKLIST_REMOVE(&inodedep->id_list);
7491	if (inodedep->id_savedino1 != NULL) {
7492		free(inodedep->id_savedino1, M_SAVEDINO);
7493		inodedep->id_savedino1 = NULL;
7494	}
7495	if (free_inodedep(inodedep) == 0)
7496		panic("check_inode_unwritten: busy inode");
7497	return (1);
7498}
7499
7500/*
7501 * Try to free an inodedep structure. Return 1 if it could be freed.
7502 */
7503static int
7504free_inodedep(inodedep)
7505	struct inodedep *inodedep;
7506{
7507
7508	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7509	if ((inodedep->id_state & (ONWORKLIST | UNLINKED)) != 0 ||
7510	    (inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
7511	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
7512	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
7513	    !LIST_EMPTY(&inodedep->id_bufwait) ||
7514	    !LIST_EMPTY(&inodedep->id_inowait) ||
7515	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7516	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7517	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7518	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7519	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7520	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7521	    inodedep->id_mkdiradd != NULL ||
7522	    inodedep->id_nlinkdelta != 0 ||
7523	    inodedep->id_savedino1 != NULL)
7524		return (0);
7525	if (inodedep->id_state & ONDEPLIST)
7526		LIST_REMOVE(inodedep, id_deps);
7527	LIST_REMOVE(inodedep, id_hash);
7528	WORKITEM_FREE(inodedep, D_INODEDEP);
7529	return (1);
7530}
7531
7532/*
7533 * Free the block referenced by a freework structure.  The parent freeblks
7534 * structure is released and completed when the final cg bitmap reaches
7535 * the disk.  This routine may be freeing a jnewblk which never made it to
7536 * disk in which case we do not have to wait as the operation is undone
7537 * in memory immediately.
7538 */
7539static void
7540freework_freeblock(freework)
7541	struct freework *freework;
7542{
7543	struct freeblks *freeblks;
7544	struct jnewblk *jnewblk;
7545	struct ufsmount *ump;
7546	struct workhead wkhd;
7547	struct fs *fs;
7548	int bsize;
7549	int needj;
7550
7551	ump = VFSTOUFS(freework->fw_list.wk_mp);
7552	LOCK_OWNED(ump);
7553	/*
7554	 * Handle partial truncate separately.
7555	 */
7556	if (freework->fw_indir) {
7557		complete_trunc_indir(freework);
7558		return;
7559	}
7560	freeblks = freework->fw_freeblks;
7561	fs = ump->um_fs;
7562	needj = MOUNTEDSUJ(freeblks->fb_list.wk_mp) != 0;
7563	bsize = lfragtosize(fs, freework->fw_frags);
7564	LIST_INIT(&wkhd);
7565	/*
7566	 * DEPCOMPLETE is cleared in indirblk_insert() if the block lives
7567	 * on the indirblk hashtable and prevents premature freeing.
7568	 */
7569	freework->fw_state |= DEPCOMPLETE;
7570	/*
7571	 * SUJ needs to wait for the segment referencing freed indirect
7572	 * blocks to expire so that we know the checker will not confuse
7573	 * a re-allocated indirect block with its old contents.
7574	 */
7575	if (needj && freework->fw_lbn <= -NDADDR)
7576		indirblk_insert(freework);
7577	/*
7578	 * If we are canceling an existing jnewblk pass it to the free
7579	 * routine, otherwise pass the freeblk which will ultimately
7580	 * release the freeblks.  If we're not journaling, we can just
7581	 * free the freeblks immediately.
7582	 */
7583	jnewblk = freework->fw_jnewblk;
7584	if (jnewblk != NULL) {
7585		cancel_jnewblk(jnewblk, &wkhd);
7586		needj = 0;
7587	} else if (needj) {
7588		freework->fw_state |= DELAYEDFREE;
7589		freeblks->fb_cgwait++;
7590		WORKLIST_INSERT(&wkhd, &freework->fw_list);
7591	}
7592	FREE_LOCK(ump);
7593	freeblks_free(ump, freeblks, btodb(bsize));
7594	CTR4(KTR_SUJ,
7595	    "freework_freeblock: ino %d blkno %jd lbn %jd size %ld",
7596	    freeblks->fb_inum, freework->fw_blkno, freework->fw_lbn, bsize);
7597	ffs_blkfree(ump, fs, freeblks->fb_devvp, freework->fw_blkno, bsize,
7598	    freeblks->fb_inum, freeblks->fb_vtype, &wkhd);
7599	ACQUIRE_LOCK(ump);
7600	/*
7601	 * The jnewblk will be discarded and the bits in the map never
7602	 * made it to disk.  We can immediately free the freeblk.
7603	 */
7604	if (needj == 0)
7605		handle_written_freework(freework);
7606}
7607
7608/*
7609 * We enqueue freework items that need processing back on the freeblks and
7610 * add the freeblks to the worklist.  This makes it easier to find all work
7611 * required to flush a truncation in process_truncates().
7612 */
7613static void
7614freework_enqueue(freework)
7615	struct freework *freework;
7616{
7617	struct freeblks *freeblks;
7618
7619	freeblks = freework->fw_freeblks;
7620	if ((freework->fw_state & INPROGRESS) == 0)
7621		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
7622	if ((freeblks->fb_state &
7623	    (ONWORKLIST | INPROGRESS | ALLCOMPLETE)) == ALLCOMPLETE &&
7624	    LIST_EMPTY(&freeblks->fb_jblkdephd))
7625		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7626}
7627
7628/*
7629 * Start, continue, or finish the process of freeing an indirect block tree.
7630 * The free operation may be paused at any point with fw_off containing the
7631 * offset to restart from.  This enables us to implement some flow control
7632 * for large truncates which may fan out and generate a huge number of
7633 * dependencies.
7634 */
7635static void
7636handle_workitem_indirblk(freework)
7637	struct freework *freework;
7638{
7639	struct freeblks *freeblks;
7640	struct ufsmount *ump;
7641	struct fs *fs;
7642
7643	freeblks = freework->fw_freeblks;
7644	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7645	fs = ump->um_fs;
7646	if (freework->fw_state & DEPCOMPLETE) {
7647		handle_written_freework(freework);
7648		return;
7649	}
7650	if (freework->fw_off == NINDIR(fs)) {
7651		freework_freeblock(freework);
7652		return;
7653	}
7654	freework->fw_state |= INPROGRESS;
7655	FREE_LOCK(ump);
7656	indir_trunc(freework, fsbtodb(fs, freework->fw_blkno),
7657	    freework->fw_lbn);
7658	ACQUIRE_LOCK(ump);
7659}
7660
7661/*
7662 * Called when a freework structure attached to a cg buf is written.  The
7663 * ref on either the parent or the freeblks structure is released and
7664 * the freeblks is added back to the worklist if there is more work to do.
7665 */
7666static void
7667handle_written_freework(freework)
7668	struct freework *freework;
7669{
7670	struct freeblks *freeblks;
7671	struct freework *parent;
7672
7673	freeblks = freework->fw_freeblks;
7674	parent = freework->fw_parent;
7675	if (freework->fw_state & DELAYEDFREE)
7676		freeblks->fb_cgwait--;
7677	freework->fw_state |= COMPLETE;
7678	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
7679		WORKITEM_FREE(freework, D_FREEWORK);
7680	if (parent) {
7681		if (--parent->fw_ref == 0)
7682			freework_enqueue(parent);
7683		return;
7684	}
7685	if (--freeblks->fb_ref != 0)
7686		return;
7687	if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST | INPROGRESS)) ==
7688	    ALLCOMPLETE && LIST_EMPTY(&freeblks->fb_jblkdephd))
7689		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7690}
7691
7692/*
7693 * This workitem routine performs the block de-allocation.
7694 * The workitem is added to the pending list after the updated
7695 * inode block has been written to disk.  As mentioned above,
7696 * checks regarding the number of blocks de-allocated (compared
7697 * to the number of blocks allocated for the file) are also
7698 * performed in this function.
7699 */
7700static int
7701handle_workitem_freeblocks(freeblks, flags)
7702	struct freeblks *freeblks;
7703	int flags;
7704{
7705	struct freework *freework;
7706	struct newblk *newblk;
7707	struct allocindir *aip;
7708	struct ufsmount *ump;
7709	struct worklist *wk;
7710
7711	KASSERT(LIST_EMPTY(&freeblks->fb_jblkdephd),
7712	    ("handle_workitem_freeblocks: Journal entries not written."));
7713	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7714	ACQUIRE_LOCK(ump);
7715	while ((wk = LIST_FIRST(&freeblks->fb_freeworkhd)) != NULL) {
7716		WORKLIST_REMOVE(wk);
7717		switch (wk->wk_type) {
7718		case D_DIRREM:
7719			wk->wk_state |= COMPLETE;
7720			add_to_worklist(wk, 0);
7721			continue;
7722
7723		case D_ALLOCDIRECT:
7724			free_newblk(WK_NEWBLK(wk));
7725			continue;
7726
7727		case D_ALLOCINDIR:
7728			aip = WK_ALLOCINDIR(wk);
7729			freework = NULL;
7730			if (aip->ai_state & DELAYEDFREE) {
7731				FREE_LOCK(ump);
7732				freework = newfreework(ump, freeblks, NULL,
7733				    aip->ai_lbn, aip->ai_newblkno,
7734				    ump->um_fs->fs_frag, 0, 0);
7735				ACQUIRE_LOCK(ump);
7736			}
7737			newblk = WK_NEWBLK(wk);
7738			if (newblk->nb_jnewblk) {
7739				freework->fw_jnewblk = newblk->nb_jnewblk;
7740				newblk->nb_jnewblk->jn_dep = &freework->fw_list;
7741				newblk->nb_jnewblk = NULL;
7742			}
7743			free_newblk(newblk);
7744			continue;
7745
7746		case D_FREEWORK:
7747			freework = WK_FREEWORK(wk);
7748			if (freework->fw_lbn <= -NDADDR)
7749				handle_workitem_indirblk(freework);
7750			else
7751				freework_freeblock(freework);
7752			continue;
7753		default:
7754			panic("handle_workitem_freeblocks: Unknown type %s",
7755			    TYPENAME(wk->wk_type));
7756		}
7757	}
7758	if (freeblks->fb_ref != 0) {
7759		freeblks->fb_state &= ~INPROGRESS;
7760		wake_worklist(&freeblks->fb_list);
7761		freeblks = NULL;
7762	}
7763	FREE_LOCK(ump);
7764	if (freeblks)
7765		return handle_complete_freeblocks(freeblks, flags);
7766	return (0);
7767}
7768
7769/*
7770 * Handle completion of block free via truncate.  This allows fs_pending
7771 * to track the actual free block count more closely than if we only updated
7772 * it at the end.  We must be careful to handle cases where the block count
7773 * on free was incorrect.
7774 */
7775static void
7776freeblks_free(ump, freeblks, blocks)
7777	struct ufsmount *ump;
7778	struct freeblks *freeblks;
7779	int blocks;
7780{
7781	struct fs *fs;
7782	ufs2_daddr_t remain;
7783
7784	UFS_LOCK(ump);
7785	remain = -freeblks->fb_chkcnt;
7786	freeblks->fb_chkcnt += blocks;
7787	if (remain > 0) {
7788		if (remain < blocks)
7789			blocks = remain;
7790		fs = ump->um_fs;
7791		fs->fs_pendingblocks -= blocks;
7792	}
7793	UFS_UNLOCK(ump);
7794}
7795
7796/*
7797 * Once all of the freework workitems are complete we can retire the
7798 * freeblocks dependency and any journal work awaiting completion.  This
7799 * can not be called until all other dependencies are stable on disk.
7800 */
7801static int
7802handle_complete_freeblocks(freeblks, flags)
7803	struct freeblks *freeblks;
7804	int flags;
7805{
7806	struct inodedep *inodedep;
7807	struct inode *ip;
7808	struct vnode *vp;
7809	struct fs *fs;
7810	struct ufsmount *ump;
7811	ufs2_daddr_t spare;
7812
7813	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7814	fs = ump->um_fs;
7815	flags = LK_EXCLUSIVE | flags;
7816	spare = freeblks->fb_chkcnt;
7817
7818	/*
7819	 * If we did not release the expected number of blocks we may have
7820	 * to adjust the inode block count here.  Only do so if it wasn't
7821	 * a truncation to zero and the modrev still matches.
7822	 */
7823	if (spare && freeblks->fb_len != 0) {
7824		if (ffs_vgetf(freeblks->fb_list.wk_mp, freeblks->fb_inum,
7825		    flags, &vp, FFSV_FORCEINSMQ) != 0)
7826			return (EBUSY);
7827		ip = VTOI(vp);
7828		if (DIP(ip, i_modrev) == freeblks->fb_modrev) {
7829			DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - spare);
7830			ip->i_flag |= IN_CHANGE;
7831			/*
7832			 * We must wait so this happens before the
7833			 * journal is reclaimed.
7834			 */
7835			ffs_update(vp, 1);
7836		}
7837		vput(vp);
7838	}
7839	if (spare < 0) {
7840		UFS_LOCK(ump);
7841		fs->fs_pendingblocks += spare;
7842		UFS_UNLOCK(ump);
7843	}
7844#ifdef QUOTA
7845	/* Handle spare. */
7846	if (spare)
7847		quotaadj(freeblks->fb_quota, ump, -spare);
7848	quotarele(freeblks->fb_quota);
7849#endif
7850	ACQUIRE_LOCK(ump);
7851	if (freeblks->fb_state & ONDEPLIST) {
7852		inodedep_lookup(freeblks->fb_list.wk_mp, freeblks->fb_inum,
7853		    0, &inodedep);
7854		TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks, fb_next);
7855		freeblks->fb_state &= ~ONDEPLIST;
7856		if (TAILQ_EMPTY(&inodedep->id_freeblklst))
7857			free_inodedep(inodedep);
7858	}
7859	/*
7860	 * All of the freeblock deps must be complete prior to this call
7861	 * so it's now safe to complete earlier outstanding journal entries.
7862	 */
7863	handle_jwork(&freeblks->fb_jwork);
7864	WORKITEM_FREE(freeblks, D_FREEBLKS);
7865	FREE_LOCK(ump);
7866	return (0);
7867}
7868
7869/*
7870 * Release blocks associated with the freeblks and stored in the indirect
7871 * block dbn. If level is greater than SINGLE, the block is an indirect block
7872 * and recursive calls to indirtrunc must be used to cleanse other indirect
7873 * blocks.
7874 *
7875 * This handles partial and complete truncation of blocks.  Partial is noted
7876 * with goingaway == 0.  In this case the freework is completed after the
7877 * zero'd indirects are written to disk.  For full truncation the freework
7878 * is completed after the block is freed.
7879 */
7880static void
7881indir_trunc(freework, dbn, lbn)
7882	struct freework *freework;
7883	ufs2_daddr_t dbn;
7884	ufs_lbn_t lbn;
7885{
7886	struct freework *nfreework;
7887	struct workhead wkhd;
7888	struct freeblks *freeblks;
7889	struct buf *bp;
7890	struct fs *fs;
7891	struct indirdep *indirdep;
7892	struct ufsmount *ump;
7893	ufs1_daddr_t *bap1 = 0;
7894	ufs2_daddr_t nb, nnb, *bap2 = 0;
7895	ufs_lbn_t lbnadd, nlbn;
7896	int i, nblocks, ufs1fmt;
7897	int freedblocks;
7898	int goingaway;
7899	int freedeps;
7900	int needj;
7901	int level;
7902	int cnt;
7903
7904	freeblks = freework->fw_freeblks;
7905	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7906	fs = ump->um_fs;
7907	/*
7908	 * Get buffer of block pointers to be freed.  There are three cases:
7909	 *
7910	 * 1) Partial truncate caches the indirdep pointer in the freework
7911	 *    which provides us a back copy to the save bp which holds the
7912	 *    pointers we want to clear.  When this completes the zero
7913	 *    pointers are written to the real copy.
7914	 * 2) The indirect is being completely truncated, cancel_indirdep()
7915	 *    eliminated the real copy and placed the indirdep on the saved
7916	 *    copy.  The indirdep and buf are discarded when this completes.
7917	 * 3) The indirect was not in memory, we read a copy off of the disk
7918	 *    using the devvp and drop and invalidate the buffer when we're
7919	 *    done.
7920	 */
7921	goingaway = 1;
7922	indirdep = NULL;
7923	if (freework->fw_indir != NULL) {
7924		goingaway = 0;
7925		indirdep = freework->fw_indir;
7926		bp = indirdep->ir_savebp;
7927		if (bp == NULL || bp->b_blkno != dbn)
7928			panic("indir_trunc: Bad saved buf %p blkno %jd",
7929			    bp, (intmax_t)dbn);
7930	} else if ((bp = incore(&freeblks->fb_devvp->v_bufobj, dbn)) != NULL) {
7931		/*
7932		 * The lock prevents the buf dep list from changing and
7933	 	 * indirects on devvp should only ever have one dependency.
7934		 */
7935		indirdep = WK_INDIRDEP(LIST_FIRST(&bp->b_dep));
7936		if (indirdep == NULL || (indirdep->ir_state & GOINGAWAY) == 0)
7937			panic("indir_trunc: Bad indirdep %p from buf %p",
7938			    indirdep, bp);
7939	} else if (bread(freeblks->fb_devvp, dbn, (int)fs->fs_bsize,
7940	    NOCRED, &bp) != 0) {
7941		brelse(bp);
7942		return;
7943	}
7944	ACQUIRE_LOCK(ump);
7945	/* Protects against a race with complete_trunc_indir(). */
7946	freework->fw_state &= ~INPROGRESS;
7947	/*
7948	 * If we have an indirdep we need to enforce the truncation order
7949	 * and discard it when it is complete.
7950	 */
7951	if (indirdep) {
7952		if (freework != TAILQ_FIRST(&indirdep->ir_trunc) &&
7953		    !TAILQ_EMPTY(&indirdep->ir_trunc)) {
7954			/*
7955			 * Add the complete truncate to the list on the
7956			 * indirdep to enforce in-order processing.
7957			 */
7958			if (freework->fw_indir == NULL)
7959				TAILQ_INSERT_TAIL(&indirdep->ir_trunc,
7960				    freework, fw_next);
7961			FREE_LOCK(ump);
7962			return;
7963		}
7964		/*
7965		 * If we're goingaway, free the indirdep.  Otherwise it will
7966		 * linger until the write completes.
7967		 */
7968		if (goingaway) {
7969			free_indirdep(indirdep);
7970			ump->softdep_numindirdeps -= 1;
7971		}
7972	}
7973	FREE_LOCK(ump);
7974	/* Initialize pointers depending on block size. */
7975	if (ump->um_fstype == UFS1) {
7976		bap1 = (ufs1_daddr_t *)bp->b_data;
7977		nb = bap1[freework->fw_off];
7978		ufs1fmt = 1;
7979	} else {
7980		bap2 = (ufs2_daddr_t *)bp->b_data;
7981		nb = bap2[freework->fw_off];
7982		ufs1fmt = 0;
7983	}
7984	level = lbn_level(lbn);
7985	needj = MOUNTEDSUJ(UFSTOVFS(ump)) != 0;
7986	lbnadd = lbn_offset(fs, level);
7987	nblocks = btodb(fs->fs_bsize);
7988	nfreework = freework;
7989	freedeps = 0;
7990	cnt = 0;
7991	/*
7992	 * Reclaim blocks.  Traverses into nested indirect levels and
7993	 * arranges for the current level to be freed when subordinates
7994	 * are free when journaling.
7995	 */
7996	for (i = freework->fw_off; i < NINDIR(fs); i++, nb = nnb) {
7997		if (i != NINDIR(fs) - 1) {
7998			if (ufs1fmt)
7999				nnb = bap1[i+1];
8000			else
8001				nnb = bap2[i+1];
8002		} else
8003			nnb = 0;
8004		if (nb == 0)
8005			continue;
8006		cnt++;
8007		if (level != 0) {
8008			nlbn = (lbn + 1) - (i * lbnadd);
8009			if (needj != 0) {
8010				nfreework = newfreework(ump, freeblks, freework,
8011				    nlbn, nb, fs->fs_frag, 0, 0);
8012				freedeps++;
8013			}
8014			indir_trunc(nfreework, fsbtodb(fs, nb), nlbn);
8015		} else {
8016			struct freedep *freedep;
8017
8018			/*
8019			 * Attempt to aggregate freedep dependencies for
8020			 * all blocks being released to the same CG.
8021			 */
8022			LIST_INIT(&wkhd);
8023			if (needj != 0 &&
8024			    (nnb == 0 || (dtog(fs, nb) != dtog(fs, nnb)))) {
8025				freedep = newfreedep(freework);
8026				WORKLIST_INSERT_UNLOCKED(&wkhd,
8027				    &freedep->fd_list);
8028				freedeps++;
8029			}
8030			CTR3(KTR_SUJ,
8031			    "indir_trunc: ino %d blkno %jd size %ld",
8032			    freeblks->fb_inum, nb, fs->fs_bsize);
8033			ffs_blkfree(ump, fs, freeblks->fb_devvp, nb,
8034			    fs->fs_bsize, freeblks->fb_inum,
8035			    freeblks->fb_vtype, &wkhd);
8036		}
8037	}
8038	if (goingaway) {
8039		bp->b_flags |= B_INVAL | B_NOCACHE;
8040		brelse(bp);
8041	}
8042	freedblocks = 0;
8043	if (level == 0)
8044		freedblocks = (nblocks * cnt);
8045	if (needj == 0)
8046		freedblocks += nblocks;
8047	freeblks_free(ump, freeblks, freedblocks);
8048	/*
8049	 * If we are journaling set up the ref counts and offset so this
8050	 * indirect can be completed when its children are free.
8051	 */
8052	if (needj) {
8053		ACQUIRE_LOCK(ump);
8054		freework->fw_off = i;
8055		freework->fw_ref += freedeps;
8056		freework->fw_ref -= NINDIR(fs) + 1;
8057		if (level == 0)
8058			freeblks->fb_cgwait += freedeps;
8059		if (freework->fw_ref == 0)
8060			freework_freeblock(freework);
8061		FREE_LOCK(ump);
8062		return;
8063	}
8064	/*
8065	 * If we're not journaling we can free the indirect now.
8066	 */
8067	dbn = dbtofsb(fs, dbn);
8068	CTR3(KTR_SUJ,
8069	    "indir_trunc 2: ino %d blkno %jd size %ld",
8070	    freeblks->fb_inum, dbn, fs->fs_bsize);
8071	ffs_blkfree(ump, fs, freeblks->fb_devvp, dbn, fs->fs_bsize,
8072	    freeblks->fb_inum, freeblks->fb_vtype, NULL);
8073	/* Non SUJ softdep does single-threaded truncations. */
8074	if (freework->fw_blkno == dbn) {
8075		freework->fw_state |= ALLCOMPLETE;
8076		ACQUIRE_LOCK(ump);
8077		handle_written_freework(freework);
8078		FREE_LOCK(ump);
8079	}
8080	return;
8081}
8082
8083/*
8084 * Cancel an allocindir when it is removed via truncation.  When bp is not
8085 * NULL the indirect never appeared on disk and is scheduled to be freed
8086 * independently of the indir so we can more easily track journal work.
8087 */
8088static void
8089cancel_allocindir(aip, bp, freeblks, trunc)
8090	struct allocindir *aip;
8091	struct buf *bp;
8092	struct freeblks *freeblks;
8093	int trunc;
8094{
8095	struct indirdep *indirdep;
8096	struct freefrag *freefrag;
8097	struct newblk *newblk;
8098
8099	newblk = (struct newblk *)aip;
8100	LIST_REMOVE(aip, ai_next);
8101	/*
8102	 * We must eliminate the pointer in bp if it must be freed on its
8103	 * own due to partial truncate or pending journal work.
8104	 */
8105	if (bp && (trunc || newblk->nb_jnewblk)) {
8106		/*
8107		 * Clear the pointer and mark the aip to be freed
8108		 * directly if it never existed on disk.
8109		 */
8110		aip->ai_state |= DELAYEDFREE;
8111		indirdep = aip->ai_indirdep;
8112		if (indirdep->ir_state & UFS1FMT)
8113			((ufs1_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8114		else
8115			((ufs2_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8116	}
8117	/*
8118	 * When truncating the previous pointer will be freed via
8119	 * savedbp.  Eliminate the freefrag which would dup free.
8120	 */
8121	if (trunc && (freefrag = newblk->nb_freefrag) != NULL) {
8122		newblk->nb_freefrag = NULL;
8123		if (freefrag->ff_jdep)
8124			cancel_jfreefrag(
8125			    WK_JFREEFRAG(freefrag->ff_jdep));
8126		jwork_move(&freeblks->fb_jwork, &freefrag->ff_jwork);
8127		WORKITEM_FREE(freefrag, D_FREEFRAG);
8128	}
8129	/*
8130	 * If the journal hasn't been written the jnewblk must be passed
8131	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
8132	 * this by leaving the journal dependency on the newblk to be freed
8133	 * when a freework is created in handle_workitem_freeblocks().
8134	 */
8135	cancel_newblk(newblk, NULL, &freeblks->fb_jwork);
8136	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
8137}
8138
8139/*
8140 * Create the mkdir dependencies for . and .. in a new directory.  Link them
8141 * in to a newdirblk so any subsequent additions are tracked properly.  The
8142 * caller is responsible for adding the mkdir1 dependency to the journal
8143 * and updating id_mkdiradd.  This function returns with the soft updates
8144 * lock held.
8145 */
8146static struct mkdir *
8147setup_newdir(dap, newinum, dinum, newdirbp, mkdirp)
8148	struct diradd *dap;
8149	ino_t newinum;
8150	ino_t dinum;
8151	struct buf *newdirbp;
8152	struct mkdir **mkdirp;
8153{
8154	struct newblk *newblk;
8155	struct pagedep *pagedep;
8156	struct inodedep *inodedep;
8157	struct newdirblk *newdirblk = 0;
8158	struct mkdir *mkdir1, *mkdir2;
8159	struct worklist *wk;
8160	struct jaddref *jaddref;
8161	struct ufsmount *ump;
8162	struct mount *mp;
8163
8164	mp = dap->da_list.wk_mp;
8165	ump = VFSTOUFS(mp);
8166	newdirblk = malloc(sizeof(struct newdirblk), M_NEWDIRBLK,
8167	    M_SOFTDEP_FLAGS);
8168	workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8169	LIST_INIT(&newdirblk->db_mkdir);
8170	mkdir1 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8171	workitem_alloc(&mkdir1->md_list, D_MKDIR, mp);
8172	mkdir1->md_state = ATTACHED | MKDIR_BODY;
8173	mkdir1->md_diradd = dap;
8174	mkdir1->md_jaddref = NULL;
8175	mkdir2 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8176	workitem_alloc(&mkdir2->md_list, D_MKDIR, mp);
8177	mkdir2->md_state = ATTACHED | MKDIR_PARENT;
8178	mkdir2->md_diradd = dap;
8179	mkdir2->md_jaddref = NULL;
8180	if (MOUNTEDSUJ(mp) == 0) {
8181		mkdir1->md_state |= DEPCOMPLETE;
8182		mkdir2->md_state |= DEPCOMPLETE;
8183	}
8184	/*
8185	 * Dependency on "." and ".." being written to disk.
8186	 */
8187	mkdir1->md_buf = newdirbp;
8188	ACQUIRE_LOCK(VFSTOUFS(mp));
8189	LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir1, md_mkdirs);
8190	/*
8191	 * We must link the pagedep, allocdirect, and newdirblk for
8192	 * the initial file page so the pointer to the new directory
8193	 * is not written until the directory contents are live and
8194	 * any subsequent additions are not marked live until the
8195	 * block is reachable via the inode.
8196	 */
8197	if (pagedep_lookup(mp, newdirbp, newinum, 0, 0, &pagedep) == 0)
8198		panic("setup_newdir: lost pagedep");
8199	LIST_FOREACH(wk, &newdirbp->b_dep, wk_list)
8200		if (wk->wk_type == D_ALLOCDIRECT)
8201			break;
8202	if (wk == NULL)
8203		panic("setup_newdir: lost allocdirect");
8204	if (pagedep->pd_state & NEWBLOCK)
8205		panic("setup_newdir: NEWBLOCK already set");
8206	newblk = WK_NEWBLK(wk);
8207	pagedep->pd_state |= NEWBLOCK;
8208	pagedep->pd_newdirblk = newdirblk;
8209	newdirblk->db_pagedep = pagedep;
8210	WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8211	WORKLIST_INSERT(&newdirblk->db_mkdir, &mkdir1->md_list);
8212	/*
8213	 * Look up the inodedep for the parent directory so that we
8214	 * can link mkdir2 into the pending dotdot jaddref or
8215	 * the inode write if there is none.  If the inode is
8216	 * ALLCOMPLETE and no jaddref is present all dependencies have
8217	 * been satisfied and mkdir2 can be freed.
8218	 */
8219	inodedep_lookup(mp, dinum, 0, &inodedep);
8220	if (MOUNTEDSUJ(mp)) {
8221		if (inodedep == NULL)
8222			panic("setup_newdir: Lost parent.");
8223		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8224		    inoreflst);
8225		KASSERT(jaddref != NULL && jaddref->ja_parent == newinum &&
8226		    (jaddref->ja_state & MKDIR_PARENT),
8227		    ("setup_newdir: bad dotdot jaddref %p", jaddref));
8228		LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8229		mkdir2->md_jaddref = jaddref;
8230		jaddref->ja_mkdir = mkdir2;
8231	} else if (inodedep == NULL ||
8232	    (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
8233		dap->da_state &= ~MKDIR_PARENT;
8234		WORKITEM_FREE(mkdir2, D_MKDIR);
8235		mkdir2 = NULL;
8236	} else {
8237		LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8238		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir2->md_list);
8239	}
8240	*mkdirp = mkdir2;
8241
8242	return (mkdir1);
8243}
8244
8245/*
8246 * Directory entry addition dependencies.
8247 *
8248 * When adding a new directory entry, the inode (with its incremented link
8249 * count) must be written to disk before the directory entry's pointer to it.
8250 * Also, if the inode is newly allocated, the corresponding freemap must be
8251 * updated (on disk) before the directory entry's pointer. These requirements
8252 * are met via undo/redo on the directory entry's pointer, which consists
8253 * simply of the inode number.
8254 *
8255 * As directory entries are added and deleted, the free space within a
8256 * directory block can become fragmented.  The ufs filesystem will compact
8257 * a fragmented directory block to make space for a new entry. When this
8258 * occurs, the offsets of previously added entries change. Any "diradd"
8259 * dependency structures corresponding to these entries must be updated with
8260 * the new offsets.
8261 */
8262
8263/*
8264 * This routine is called after the in-memory inode's link
8265 * count has been incremented, but before the directory entry's
8266 * pointer to the inode has been set.
8267 */
8268int
8269softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
8270	struct buf *bp;		/* buffer containing directory block */
8271	struct inode *dp;	/* inode for directory */
8272	off_t diroffset;	/* offset of new entry in directory */
8273	ino_t newinum;		/* inode referenced by new directory entry */
8274	struct buf *newdirbp;	/* non-NULL => contents of new mkdir */
8275	int isnewblk;		/* entry is in a newly allocated block */
8276{
8277	int offset;		/* offset of new entry within directory block */
8278	ufs_lbn_t lbn;		/* block in directory containing new entry */
8279	struct fs *fs;
8280	struct diradd *dap;
8281	struct newblk *newblk;
8282	struct pagedep *pagedep;
8283	struct inodedep *inodedep;
8284	struct newdirblk *newdirblk = 0;
8285	struct mkdir *mkdir1, *mkdir2;
8286	struct jaddref *jaddref;
8287	struct ufsmount *ump;
8288	struct mount *mp;
8289	int isindir;
8290
8291	ump = dp->i_ump;
8292	mp = UFSTOVFS(ump);
8293	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8294	    ("softdep_setup_directory_add called on non-softdep filesystem"));
8295	/*
8296	 * Whiteouts have no dependencies.
8297	 */
8298	if (newinum == WINO) {
8299		if (newdirbp != NULL)
8300			bdwrite(newdirbp);
8301		return (0);
8302	}
8303	jaddref = NULL;
8304	mkdir1 = mkdir2 = NULL;
8305	fs = dp->i_fs;
8306	lbn = lblkno(fs, diroffset);
8307	offset = blkoff(fs, diroffset);
8308	dap = malloc(sizeof(struct diradd), M_DIRADD,
8309		M_SOFTDEP_FLAGS|M_ZERO);
8310	workitem_alloc(&dap->da_list, D_DIRADD, mp);
8311	dap->da_offset = offset;
8312	dap->da_newinum = newinum;
8313	dap->da_state = ATTACHED;
8314	LIST_INIT(&dap->da_jwork);
8315	isindir = bp->b_lblkno >= NDADDR;
8316	if (isnewblk &&
8317	    (isindir ? blkoff(fs, diroffset) : fragoff(fs, diroffset)) == 0) {
8318		newdirblk = malloc(sizeof(struct newdirblk),
8319		    M_NEWDIRBLK, M_SOFTDEP_FLAGS);
8320		workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8321		LIST_INIT(&newdirblk->db_mkdir);
8322	}
8323	/*
8324	 * If we're creating a new directory setup the dependencies and set
8325	 * the dap state to wait for them.  Otherwise it's COMPLETE and
8326	 * we can move on.
8327	 */
8328	if (newdirbp == NULL) {
8329		dap->da_state |= DEPCOMPLETE;
8330		ACQUIRE_LOCK(ump);
8331	} else {
8332		dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
8333		mkdir1 = setup_newdir(dap, newinum, dp->i_number, newdirbp,
8334		    &mkdir2);
8335	}
8336	/*
8337	 * Link into parent directory pagedep to await its being written.
8338	 */
8339	pagedep_lookup(mp, bp, dp->i_number, lbn, DEPALLOC, &pagedep);
8340#ifdef DEBUG
8341	if (diradd_lookup(pagedep, offset) != NULL)
8342		panic("softdep_setup_directory_add: %p already at off %d\n",
8343		    diradd_lookup(pagedep, offset), offset);
8344#endif
8345	dap->da_pagedep = pagedep;
8346	LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
8347	    da_pdlist);
8348	inodedep_lookup(mp, newinum, DEPALLOC | NODELAY, &inodedep);
8349	/*
8350	 * If we're journaling, link the diradd into the jaddref so it
8351	 * may be completed after the journal entry is written.  Otherwise,
8352	 * link the diradd into its inodedep.  If the inode is not yet
8353	 * written place it on the bufwait list, otherwise do the post-inode
8354	 * write processing to put it on the id_pendinghd list.
8355	 */
8356	if (MOUNTEDSUJ(mp)) {
8357		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8358		    inoreflst);
8359		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
8360		    ("softdep_setup_directory_add: bad jaddref %p", jaddref));
8361		jaddref->ja_diroff = diroffset;
8362		jaddref->ja_diradd = dap;
8363		add_to_journal(&jaddref->ja_list);
8364	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
8365		diradd_inode_written(dap, inodedep);
8366	else
8367		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
8368	/*
8369	 * Add the journal entries for . and .. links now that the primary
8370	 * link is written.
8371	 */
8372	if (mkdir1 != NULL && MOUNTEDSUJ(mp)) {
8373		jaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
8374		    inoreflst, if_deps);
8375		KASSERT(jaddref != NULL &&
8376		    jaddref->ja_ino == jaddref->ja_parent &&
8377		    (jaddref->ja_state & MKDIR_BODY),
8378		    ("softdep_setup_directory_add: bad dot jaddref %p",
8379		    jaddref));
8380		mkdir1->md_jaddref = jaddref;
8381		jaddref->ja_mkdir = mkdir1;
8382		/*
8383		 * It is important that the dotdot journal entry
8384		 * is added prior to the dot entry since dot writes
8385		 * both the dot and dotdot links.  These both must
8386		 * be added after the primary link for the journal
8387		 * to remain consistent.
8388		 */
8389		add_to_journal(&mkdir2->md_jaddref->ja_list);
8390		add_to_journal(&jaddref->ja_list);
8391	}
8392	/*
8393	 * If we are adding a new directory remember this diradd so that if
8394	 * we rename it we can keep the dot and dotdot dependencies.  If
8395	 * we are adding a new name for an inode that has a mkdiradd we
8396	 * must be in rename and we have to move the dot and dotdot
8397	 * dependencies to this new name.  The old name is being orphaned
8398	 * soon.
8399	 */
8400	if (mkdir1 != NULL) {
8401		if (inodedep->id_mkdiradd != NULL)
8402			panic("softdep_setup_directory_add: Existing mkdir");
8403		inodedep->id_mkdiradd = dap;
8404	} else if (inodedep->id_mkdiradd)
8405		merge_diradd(inodedep, dap);
8406	if (newdirblk) {
8407		/*
8408		 * There is nothing to do if we are already tracking
8409		 * this block.
8410		 */
8411		if ((pagedep->pd_state & NEWBLOCK) != 0) {
8412			WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
8413			FREE_LOCK(ump);
8414			return (0);
8415		}
8416		if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk)
8417		    == 0)
8418			panic("softdep_setup_directory_add: lost entry");
8419		WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8420		pagedep->pd_state |= NEWBLOCK;
8421		pagedep->pd_newdirblk = newdirblk;
8422		newdirblk->db_pagedep = pagedep;
8423		FREE_LOCK(ump);
8424		/*
8425		 * If we extended into an indirect signal direnter to sync.
8426		 */
8427		if (isindir)
8428			return (1);
8429		return (0);
8430	}
8431	FREE_LOCK(ump);
8432	return (0);
8433}
8434
8435/*
8436 * This procedure is called to change the offset of a directory
8437 * entry when compacting a directory block which must be owned
8438 * exclusively by the caller. Note that the actual entry movement
8439 * must be done in this procedure to ensure that no I/O completions
8440 * occur while the move is in progress.
8441 */
8442void
8443softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
8444	struct buf *bp;		/* Buffer holding directory block. */
8445	struct inode *dp;	/* inode for directory */
8446	caddr_t base;		/* address of dp->i_offset */
8447	caddr_t oldloc;		/* address of old directory location */
8448	caddr_t newloc;		/* address of new directory location */
8449	int entrysize;		/* size of directory entry */
8450{
8451	int offset, oldoffset, newoffset;
8452	struct pagedep *pagedep;
8453	struct jmvref *jmvref;
8454	struct diradd *dap;
8455	struct direct *de;
8456	struct mount *mp;
8457	ufs_lbn_t lbn;
8458	int flags;
8459
8460	mp = UFSTOVFS(dp->i_ump);
8461	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8462	    ("softdep_change_directoryentry_offset called on "
8463	     "non-softdep filesystem"));
8464	de = (struct direct *)oldloc;
8465	jmvref = NULL;
8466	flags = 0;
8467	/*
8468	 * Moves are always journaled as it would be too complex to
8469	 * determine if any affected adds or removes are present in the
8470	 * journal.
8471	 */
8472	if (MOUNTEDSUJ(mp)) {
8473		flags = DEPALLOC;
8474		jmvref = newjmvref(dp, de->d_ino,
8475		    dp->i_offset + (oldloc - base),
8476		    dp->i_offset + (newloc - base));
8477	}
8478	lbn = lblkno(dp->i_fs, dp->i_offset);
8479	offset = blkoff(dp->i_fs, dp->i_offset);
8480	oldoffset = offset + (oldloc - base);
8481	newoffset = offset + (newloc - base);
8482	ACQUIRE_LOCK(dp->i_ump);
8483	if (pagedep_lookup(mp, bp, dp->i_number, lbn, flags, &pagedep) == 0)
8484		goto done;
8485	dap = diradd_lookup(pagedep, oldoffset);
8486	if (dap) {
8487		dap->da_offset = newoffset;
8488		newoffset = DIRADDHASH(newoffset);
8489		oldoffset = DIRADDHASH(oldoffset);
8490		if ((dap->da_state & ALLCOMPLETE) != ALLCOMPLETE &&
8491		    newoffset != oldoffset) {
8492			LIST_REMOVE(dap, da_pdlist);
8493			LIST_INSERT_HEAD(&pagedep->pd_diraddhd[newoffset],
8494			    dap, da_pdlist);
8495		}
8496	}
8497done:
8498	if (jmvref) {
8499		jmvref->jm_pagedep = pagedep;
8500		LIST_INSERT_HEAD(&pagedep->pd_jmvrefhd, jmvref, jm_deps);
8501		add_to_journal(&jmvref->jm_list);
8502	}
8503	bcopy(oldloc, newloc, entrysize);
8504	FREE_LOCK(dp->i_ump);
8505}
8506
8507/*
8508 * Move the mkdir dependencies and journal work from one diradd to another
8509 * when renaming a directory.  The new name must depend on the mkdir deps
8510 * completing as the old name did.  Directories can only have one valid link
8511 * at a time so one must be canonical.
8512 */
8513static void
8514merge_diradd(inodedep, newdap)
8515	struct inodedep *inodedep;
8516	struct diradd *newdap;
8517{
8518	struct diradd *olddap;
8519	struct mkdir *mkdir, *nextmd;
8520	struct ufsmount *ump;
8521	short state;
8522
8523	olddap = inodedep->id_mkdiradd;
8524	inodedep->id_mkdiradd = newdap;
8525	if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8526		newdap->da_state &= ~DEPCOMPLETE;
8527		ump = VFSTOUFS(inodedep->id_list.wk_mp);
8528		for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
8529		     mkdir = nextmd) {
8530			nextmd = LIST_NEXT(mkdir, md_mkdirs);
8531			if (mkdir->md_diradd != olddap)
8532				continue;
8533			mkdir->md_diradd = newdap;
8534			state = mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY);
8535			newdap->da_state |= state;
8536			olddap->da_state &= ~state;
8537			if ((olddap->da_state &
8538			    (MKDIR_PARENT | MKDIR_BODY)) == 0)
8539				break;
8540		}
8541		if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8542			panic("merge_diradd: unfound ref");
8543	}
8544	/*
8545	 * Any mkdir related journal items are not safe to be freed until
8546	 * the new name is stable.
8547	 */
8548	jwork_move(&newdap->da_jwork, &olddap->da_jwork);
8549	olddap->da_state |= DEPCOMPLETE;
8550	complete_diradd(olddap);
8551}
8552
8553/*
8554 * Move the diradd to the pending list when all diradd dependencies are
8555 * complete.
8556 */
8557static void
8558complete_diradd(dap)
8559	struct diradd *dap;
8560{
8561	struct pagedep *pagedep;
8562
8563	if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
8564		if (dap->da_state & DIRCHG)
8565			pagedep = dap->da_previous->dm_pagedep;
8566		else
8567			pagedep = dap->da_pagedep;
8568		LIST_REMOVE(dap, da_pdlist);
8569		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
8570	}
8571}
8572
8573/*
8574 * Cancel a diradd when a dirrem overlaps with it.  We must cancel the journal
8575 * add entries and conditonally journal the remove.
8576 */
8577static void
8578cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref)
8579	struct diradd *dap;
8580	struct dirrem *dirrem;
8581	struct jremref *jremref;
8582	struct jremref *dotremref;
8583	struct jremref *dotdotremref;
8584{
8585	struct inodedep *inodedep;
8586	struct jaddref *jaddref;
8587	struct inoref *inoref;
8588	struct ufsmount *ump;
8589	struct mkdir *mkdir;
8590
8591	/*
8592	 * If no remove references were allocated we're on a non-journaled
8593	 * filesystem and can skip the cancel step.
8594	 */
8595	if (jremref == NULL) {
8596		free_diradd(dap, NULL);
8597		return;
8598	}
8599	/*
8600	 * Cancel the primary name an free it if it does not require
8601	 * journaling.
8602	 */
8603	if (inodedep_lookup(dap->da_list.wk_mp, dap->da_newinum,
8604	    0, &inodedep) != 0) {
8605		/* Abort the addref that reference this diradd.  */
8606		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
8607			if (inoref->if_list.wk_type != D_JADDREF)
8608				continue;
8609			jaddref = (struct jaddref *)inoref;
8610			if (jaddref->ja_diradd != dap)
8611				continue;
8612			if (cancel_jaddref(jaddref, inodedep,
8613			    &dirrem->dm_jwork) == 0) {
8614				free_jremref(jremref);
8615				jremref = NULL;
8616			}
8617			break;
8618		}
8619	}
8620	/*
8621	 * Cancel subordinate names and free them if they do not require
8622	 * journaling.
8623	 */
8624	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8625		ump = VFSTOUFS(dap->da_list.wk_mp);
8626		LIST_FOREACH(mkdir, &ump->softdep_mkdirlisthd, md_mkdirs) {
8627			if (mkdir->md_diradd != dap)
8628				continue;
8629			if ((jaddref = mkdir->md_jaddref) == NULL)
8630				continue;
8631			mkdir->md_jaddref = NULL;
8632			if (mkdir->md_state & MKDIR_PARENT) {
8633				if (cancel_jaddref(jaddref, NULL,
8634				    &dirrem->dm_jwork) == 0) {
8635					free_jremref(dotdotremref);
8636					dotdotremref = NULL;
8637				}
8638			} else {
8639				if (cancel_jaddref(jaddref, inodedep,
8640				    &dirrem->dm_jwork) == 0) {
8641					free_jremref(dotremref);
8642					dotremref = NULL;
8643				}
8644			}
8645		}
8646	}
8647
8648	if (jremref)
8649		journal_jremref(dirrem, jremref, inodedep);
8650	if (dotremref)
8651		journal_jremref(dirrem, dotremref, inodedep);
8652	if (dotdotremref)
8653		journal_jremref(dirrem, dotdotremref, NULL);
8654	jwork_move(&dirrem->dm_jwork, &dap->da_jwork);
8655	free_diradd(dap, &dirrem->dm_jwork);
8656}
8657
8658/*
8659 * Free a diradd dependency structure. This routine must be called
8660 * with splbio interrupts blocked.
8661 */
8662static void
8663free_diradd(dap, wkhd)
8664	struct diradd *dap;
8665	struct workhead *wkhd;
8666{
8667	struct dirrem *dirrem;
8668	struct pagedep *pagedep;
8669	struct inodedep *inodedep;
8670	struct mkdir *mkdir, *nextmd;
8671	struct ufsmount *ump;
8672
8673	ump = VFSTOUFS(dap->da_list.wk_mp);
8674	LOCK_OWNED(ump);
8675	LIST_REMOVE(dap, da_pdlist);
8676	if (dap->da_state & ONWORKLIST)
8677		WORKLIST_REMOVE(&dap->da_list);
8678	if ((dap->da_state & DIRCHG) == 0) {
8679		pagedep = dap->da_pagedep;
8680	} else {
8681		dirrem = dap->da_previous;
8682		pagedep = dirrem->dm_pagedep;
8683		dirrem->dm_dirinum = pagedep->pd_ino;
8684		dirrem->dm_state |= COMPLETE;
8685		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
8686			add_to_worklist(&dirrem->dm_list, 0);
8687	}
8688	if (inodedep_lookup(pagedep->pd_list.wk_mp, dap->da_newinum,
8689	    0, &inodedep) != 0)
8690		if (inodedep->id_mkdiradd == dap)
8691			inodedep->id_mkdiradd = NULL;
8692	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8693		for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
8694		     mkdir = nextmd) {
8695			nextmd = LIST_NEXT(mkdir, md_mkdirs);
8696			if (mkdir->md_diradd != dap)
8697				continue;
8698			dap->da_state &=
8699			    ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
8700			LIST_REMOVE(mkdir, md_mkdirs);
8701			if (mkdir->md_state & ONWORKLIST)
8702				WORKLIST_REMOVE(&mkdir->md_list);
8703			if (mkdir->md_jaddref != NULL)
8704				panic("free_diradd: Unexpected jaddref");
8705			WORKITEM_FREE(mkdir, D_MKDIR);
8706			if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
8707				break;
8708		}
8709		if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8710			panic("free_diradd: unfound ref");
8711	}
8712	if (inodedep)
8713		free_inodedep(inodedep);
8714	/*
8715	 * Free any journal segments waiting for the directory write.
8716	 */
8717	handle_jwork(&dap->da_jwork);
8718	WORKITEM_FREE(dap, D_DIRADD);
8719}
8720
8721/*
8722 * Directory entry removal dependencies.
8723 *
8724 * When removing a directory entry, the entry's inode pointer must be
8725 * zero'ed on disk before the corresponding inode's link count is decremented
8726 * (possibly freeing the inode for re-use). This dependency is handled by
8727 * updating the directory entry but delaying the inode count reduction until
8728 * after the directory block has been written to disk. After this point, the
8729 * inode count can be decremented whenever it is convenient.
8730 */
8731
8732/*
8733 * This routine should be called immediately after removing
8734 * a directory entry.  The inode's link count should not be
8735 * decremented by the calling procedure -- the soft updates
8736 * code will do this task when it is safe.
8737 */
8738void
8739softdep_setup_remove(bp, dp, ip, isrmdir)
8740	struct buf *bp;		/* buffer containing directory block */
8741	struct inode *dp;	/* inode for the directory being modified */
8742	struct inode *ip;	/* inode for directory entry being removed */
8743	int isrmdir;		/* indicates if doing RMDIR */
8744{
8745	struct dirrem *dirrem, *prevdirrem;
8746	struct inodedep *inodedep;
8747	int direct;
8748
8749	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ip->i_ump)) != 0,
8750	    ("softdep_setup_remove called on non-softdep filesystem"));
8751	/*
8752	 * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.  We want
8753	 * newdirrem() to setup the full directory remove which requires
8754	 * isrmdir > 1.
8755	 */
8756	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
8757	/*
8758	 * Add the dirrem to the inodedep's pending remove list for quick
8759	 * discovery later.
8760	 */
8761	if (inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, 0,
8762	    &inodedep) == 0)
8763		panic("softdep_setup_remove: Lost inodedep.");
8764	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
8765	dirrem->dm_state |= ONDEPLIST;
8766	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
8767
8768	/*
8769	 * If the COMPLETE flag is clear, then there were no active
8770	 * entries and we want to roll back to a zeroed entry until
8771	 * the new inode is committed to disk. If the COMPLETE flag is
8772	 * set then we have deleted an entry that never made it to
8773	 * disk. If the entry we deleted resulted from a name change,
8774	 * then the old name still resides on disk. We cannot delete
8775	 * its inode (returned to us in prevdirrem) until the zeroed
8776	 * directory entry gets to disk. The new inode has never been
8777	 * referenced on the disk, so can be deleted immediately.
8778	 */
8779	if ((dirrem->dm_state & COMPLETE) == 0) {
8780		LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
8781		    dm_next);
8782		FREE_LOCK(ip->i_ump);
8783	} else {
8784		if (prevdirrem != NULL)
8785			LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
8786			    prevdirrem, dm_next);
8787		dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
8788		direct = LIST_EMPTY(&dirrem->dm_jremrefhd);
8789		FREE_LOCK(ip->i_ump);
8790		if (direct)
8791			handle_workitem_remove(dirrem, 0);
8792	}
8793}
8794
8795/*
8796 * Check for an entry matching 'offset' on both the pd_dirraddhd list and the
8797 * pd_pendinghd list of a pagedep.
8798 */
8799static struct diradd *
8800diradd_lookup(pagedep, offset)
8801	struct pagedep *pagedep;
8802	int offset;
8803{
8804	struct diradd *dap;
8805
8806	LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
8807		if (dap->da_offset == offset)
8808			return (dap);
8809	LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
8810		if (dap->da_offset == offset)
8811			return (dap);
8812	return (NULL);
8813}
8814
8815/*
8816 * Search for a .. diradd dependency in a directory that is being removed.
8817 * If the directory was renamed to a new parent we have a diradd rather
8818 * than a mkdir for the .. entry.  We need to cancel it now before
8819 * it is found in truncate().
8820 */
8821static struct jremref *
8822cancel_diradd_dotdot(ip, dirrem, jremref)
8823	struct inode *ip;
8824	struct dirrem *dirrem;
8825	struct jremref *jremref;
8826{
8827	struct pagedep *pagedep;
8828	struct diradd *dap;
8829	struct worklist *wk;
8830
8831	if (pagedep_lookup(UFSTOVFS(ip->i_ump), NULL, ip->i_number, 0, 0,
8832	    &pagedep) == 0)
8833		return (jremref);
8834	dap = diradd_lookup(pagedep, DOTDOT_OFFSET);
8835	if (dap == NULL)
8836		return (jremref);
8837	cancel_diradd(dap, dirrem, jremref, NULL, NULL);
8838	/*
8839	 * Mark any journal work as belonging to the parent so it is freed
8840	 * with the .. reference.
8841	 */
8842	LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
8843		wk->wk_state |= MKDIR_PARENT;
8844	return (NULL);
8845}
8846
8847/*
8848 * Cancel the MKDIR_PARENT mkdir component of a diradd when we're going to
8849 * replace it with a dirrem/diradd pair as a result of re-parenting a
8850 * directory.  This ensures that we don't simultaneously have a mkdir and
8851 * a diradd for the same .. entry.
8852 */
8853static struct jremref *
8854cancel_mkdir_dotdot(ip, dirrem, jremref)
8855	struct inode *ip;
8856	struct dirrem *dirrem;
8857	struct jremref *jremref;
8858{
8859	struct inodedep *inodedep;
8860	struct jaddref *jaddref;
8861	struct ufsmount *ump;
8862	struct mkdir *mkdir;
8863	struct diradd *dap;
8864
8865	if (inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, 0,
8866	    &inodedep) == 0)
8867		return (jremref);
8868	dap = inodedep->id_mkdiradd;
8869	if (dap == NULL || (dap->da_state & MKDIR_PARENT) == 0)
8870		return (jremref);
8871	ump = VFSTOUFS(inodedep->id_list.wk_mp);
8872	for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
8873	    mkdir = LIST_NEXT(mkdir, md_mkdirs))
8874		if (mkdir->md_diradd == dap && mkdir->md_state & MKDIR_PARENT)
8875			break;
8876	if (mkdir == NULL)
8877		panic("cancel_mkdir_dotdot: Unable to find mkdir\n");
8878	if ((jaddref = mkdir->md_jaddref) != NULL) {
8879		mkdir->md_jaddref = NULL;
8880		jaddref->ja_state &= ~MKDIR_PARENT;
8881		if (inodedep_lookup(UFSTOVFS(ip->i_ump), jaddref->ja_ino, 0,
8882		    &inodedep) == 0)
8883			panic("cancel_mkdir_dotdot: Lost parent inodedep");
8884		if (cancel_jaddref(jaddref, inodedep, &dirrem->dm_jwork)) {
8885			journal_jremref(dirrem, jremref, inodedep);
8886			jremref = NULL;
8887		}
8888	}
8889	if (mkdir->md_state & ONWORKLIST)
8890		WORKLIST_REMOVE(&mkdir->md_list);
8891	mkdir->md_state |= ALLCOMPLETE;
8892	complete_mkdir(mkdir);
8893	return (jremref);
8894}
8895
8896static void
8897journal_jremref(dirrem, jremref, inodedep)
8898	struct dirrem *dirrem;
8899	struct jremref *jremref;
8900	struct inodedep *inodedep;
8901{
8902
8903	if (inodedep == NULL)
8904		if (inodedep_lookup(jremref->jr_list.wk_mp,
8905		    jremref->jr_ref.if_ino, 0, &inodedep) == 0)
8906			panic("journal_jremref: Lost inodedep");
8907	LIST_INSERT_HEAD(&dirrem->dm_jremrefhd, jremref, jr_deps);
8908	TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
8909	add_to_journal(&jremref->jr_list);
8910}
8911
8912static void
8913dirrem_journal(dirrem, jremref, dotremref, dotdotremref)
8914	struct dirrem *dirrem;
8915	struct jremref *jremref;
8916	struct jremref *dotremref;
8917	struct jremref *dotdotremref;
8918{
8919	struct inodedep *inodedep;
8920
8921
8922	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino, 0,
8923	    &inodedep) == 0)
8924		panic("dirrem_journal: Lost inodedep");
8925	journal_jremref(dirrem, jremref, inodedep);
8926	if (dotremref)
8927		journal_jremref(dirrem, dotremref, inodedep);
8928	if (dotdotremref)
8929		journal_jremref(dirrem, dotdotremref, NULL);
8930}
8931
8932/*
8933 * Allocate a new dirrem if appropriate and return it along with
8934 * its associated pagedep. Called without a lock, returns with lock.
8935 */
8936static struct dirrem *
8937newdirrem(bp, dp, ip, isrmdir, prevdirremp)
8938	struct buf *bp;		/* buffer containing directory block */
8939	struct inode *dp;	/* inode for the directory being modified */
8940	struct inode *ip;	/* inode for directory entry being removed */
8941	int isrmdir;		/* indicates if doing RMDIR */
8942	struct dirrem **prevdirremp; /* previously referenced inode, if any */
8943{
8944	int offset;
8945	ufs_lbn_t lbn;
8946	struct diradd *dap;
8947	struct dirrem *dirrem;
8948	struct pagedep *pagedep;
8949	struct jremref *jremref;
8950	struct jremref *dotremref;
8951	struct jremref *dotdotremref;
8952	struct vnode *dvp;
8953
8954	/*
8955	 * Whiteouts have no deletion dependencies.
8956	 */
8957	if (ip == NULL)
8958		panic("newdirrem: whiteout");
8959	dvp = ITOV(dp);
8960	/*
8961	 * If we are over our limit, try to improve the situation.
8962	 * Limiting the number of dirrem structures will also limit
8963	 * the number of freefile and freeblks structures.
8964	 */
8965	ACQUIRE_LOCK(ip->i_ump);
8966	if (!IS_SNAPSHOT(ip) && dep_current[D_DIRREM] > max_softdeps / 2)
8967		(void) request_cleanup(ITOV(dp)->v_mount, FLUSH_BLOCKS);
8968	FREE_LOCK(ip->i_ump);
8969	dirrem = malloc(sizeof(struct dirrem),
8970		M_DIRREM, M_SOFTDEP_FLAGS|M_ZERO);
8971	workitem_alloc(&dirrem->dm_list, D_DIRREM, dvp->v_mount);
8972	LIST_INIT(&dirrem->dm_jremrefhd);
8973	LIST_INIT(&dirrem->dm_jwork);
8974	dirrem->dm_state = isrmdir ? RMDIR : 0;
8975	dirrem->dm_oldinum = ip->i_number;
8976	*prevdirremp = NULL;
8977	/*
8978	 * Allocate remove reference structures to track journal write
8979	 * dependencies.  We will always have one for the link and
8980	 * when doing directories we will always have one more for dot.
8981	 * When renaming a directory we skip the dotdot link change so
8982	 * this is not needed.
8983	 */
8984	jremref = dotremref = dotdotremref = NULL;
8985	if (DOINGSUJ(dvp)) {
8986		if (isrmdir) {
8987			jremref = newjremref(dirrem, dp, ip, dp->i_offset,
8988			    ip->i_effnlink + 2);
8989			dotremref = newjremref(dirrem, ip, ip, DOT_OFFSET,
8990			    ip->i_effnlink + 1);
8991			dotdotremref = newjremref(dirrem, ip, dp, DOTDOT_OFFSET,
8992			    dp->i_effnlink + 1);
8993			dotdotremref->jr_state |= MKDIR_PARENT;
8994		} else
8995			jremref = newjremref(dirrem, dp, ip, dp->i_offset,
8996			    ip->i_effnlink + 1);
8997	}
8998	ACQUIRE_LOCK(ip->i_ump);
8999	lbn = lblkno(dp->i_fs, dp->i_offset);
9000	offset = blkoff(dp->i_fs, dp->i_offset);
9001	pagedep_lookup(UFSTOVFS(dp->i_ump), bp, dp->i_number, lbn, DEPALLOC,
9002	    &pagedep);
9003	dirrem->dm_pagedep = pagedep;
9004	dirrem->dm_offset = offset;
9005	/*
9006	 * If we're renaming a .. link to a new directory, cancel any
9007	 * existing MKDIR_PARENT mkdir.  If it has already been canceled
9008	 * the jremref is preserved for any potential diradd in this
9009	 * location.  This can not coincide with a rmdir.
9010	 */
9011	if (dp->i_offset == DOTDOT_OFFSET) {
9012		if (isrmdir)
9013			panic("newdirrem: .. directory change during remove?");
9014		jremref = cancel_mkdir_dotdot(dp, dirrem, jremref);
9015	}
9016	/*
9017	 * If we're removing a directory search for the .. dependency now and
9018	 * cancel it.  Any pending journal work will be added to the dirrem
9019	 * to be completed when the workitem remove completes.
9020	 */
9021	if (isrmdir)
9022		dotdotremref = cancel_diradd_dotdot(ip, dirrem, dotdotremref);
9023	/*
9024	 * Check for a diradd dependency for the same directory entry.
9025	 * If present, then both dependencies become obsolete and can
9026	 * be de-allocated.
9027	 */
9028	dap = diradd_lookup(pagedep, offset);
9029	if (dap == NULL) {
9030		/*
9031		 * Link the jremref structures into the dirrem so they are
9032		 * written prior to the pagedep.
9033		 */
9034		if (jremref)
9035			dirrem_journal(dirrem, jremref, dotremref,
9036			    dotdotremref);
9037		return (dirrem);
9038	}
9039	/*
9040	 * Must be ATTACHED at this point.
9041	 */
9042	if ((dap->da_state & ATTACHED) == 0)
9043		panic("newdirrem: not ATTACHED");
9044	if (dap->da_newinum != ip->i_number)
9045		panic("newdirrem: inum %ju should be %ju",
9046		    (uintmax_t)ip->i_number, (uintmax_t)dap->da_newinum);
9047	/*
9048	 * If we are deleting a changed name that never made it to disk,
9049	 * then return the dirrem describing the previous inode (which
9050	 * represents the inode currently referenced from this entry on disk).
9051	 */
9052	if ((dap->da_state & DIRCHG) != 0) {
9053		*prevdirremp = dap->da_previous;
9054		dap->da_state &= ~DIRCHG;
9055		dap->da_pagedep = pagedep;
9056	}
9057	/*
9058	 * We are deleting an entry that never made it to disk.
9059	 * Mark it COMPLETE so we can delete its inode immediately.
9060	 */
9061	dirrem->dm_state |= COMPLETE;
9062	cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref);
9063#ifdef SUJ_DEBUG
9064	if (isrmdir == 0) {
9065		struct worklist *wk;
9066
9067		LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9068			if (wk->wk_state & (MKDIR_BODY | MKDIR_PARENT))
9069				panic("bad wk %p (0x%X)\n", wk, wk->wk_state);
9070	}
9071#endif
9072
9073	return (dirrem);
9074}
9075
9076/*
9077 * Directory entry change dependencies.
9078 *
9079 * Changing an existing directory entry requires that an add operation
9080 * be completed first followed by a deletion. The semantics for the addition
9081 * are identical to the description of adding a new entry above except
9082 * that the rollback is to the old inode number rather than zero. Once
9083 * the addition dependency is completed, the removal is done as described
9084 * in the removal routine above.
9085 */
9086
9087/*
9088 * This routine should be called immediately after changing
9089 * a directory entry.  The inode's link count should not be
9090 * decremented by the calling procedure -- the soft updates
9091 * code will perform this task when it is safe.
9092 */
9093void
9094softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
9095	struct buf *bp;		/* buffer containing directory block */
9096	struct inode *dp;	/* inode for the directory being modified */
9097	struct inode *ip;	/* inode for directory entry being removed */
9098	ino_t newinum;		/* new inode number for changed entry */
9099	int isrmdir;		/* indicates if doing RMDIR */
9100{
9101	int offset;
9102	struct diradd *dap = NULL;
9103	struct dirrem *dirrem, *prevdirrem;
9104	struct pagedep *pagedep;
9105	struct inodedep *inodedep;
9106	struct jaddref *jaddref;
9107	struct mount *mp;
9108
9109	offset = blkoff(dp->i_fs, dp->i_offset);
9110	mp = UFSTOVFS(dp->i_ump);
9111	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
9112	   ("softdep_setup_directory_change called on non-softdep filesystem"));
9113
9114	/*
9115	 * Whiteouts do not need diradd dependencies.
9116	 */
9117	if (newinum != WINO) {
9118		dap = malloc(sizeof(struct diradd),
9119		    M_DIRADD, M_SOFTDEP_FLAGS|M_ZERO);
9120		workitem_alloc(&dap->da_list, D_DIRADD, mp);
9121		dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
9122		dap->da_offset = offset;
9123		dap->da_newinum = newinum;
9124		LIST_INIT(&dap->da_jwork);
9125	}
9126
9127	/*
9128	 * Allocate a new dirrem and ACQUIRE_LOCK.
9129	 */
9130	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9131	pagedep = dirrem->dm_pagedep;
9132	/*
9133	 * The possible values for isrmdir:
9134	 *	0 - non-directory file rename
9135	 *	1 - directory rename within same directory
9136	 *   inum - directory rename to new directory of given inode number
9137	 * When renaming to a new directory, we are both deleting and
9138	 * creating a new directory entry, so the link count on the new
9139	 * directory should not change. Thus we do not need the followup
9140	 * dirrem which is usually done in handle_workitem_remove. We set
9141	 * the DIRCHG flag to tell handle_workitem_remove to skip the
9142	 * followup dirrem.
9143	 */
9144	if (isrmdir > 1)
9145		dirrem->dm_state |= DIRCHG;
9146
9147	/*
9148	 * Whiteouts have no additional dependencies,
9149	 * so just put the dirrem on the correct list.
9150	 */
9151	if (newinum == WINO) {
9152		if ((dirrem->dm_state & COMPLETE) == 0) {
9153			LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
9154			    dm_next);
9155		} else {
9156			dirrem->dm_dirinum = pagedep->pd_ino;
9157			if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9158				add_to_worklist(&dirrem->dm_list, 0);
9159		}
9160		FREE_LOCK(dp->i_ump);
9161		return;
9162	}
9163	/*
9164	 * Add the dirrem to the inodedep's pending remove list for quick
9165	 * discovery later.  A valid nlinkdelta ensures that this lookup
9166	 * will not fail.
9167	 */
9168	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9169		panic("softdep_setup_directory_change: Lost inodedep.");
9170	dirrem->dm_state |= ONDEPLIST;
9171	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9172
9173	/*
9174	 * If the COMPLETE flag is clear, then there were no active
9175	 * entries and we want to roll back to the previous inode until
9176	 * the new inode is committed to disk. If the COMPLETE flag is
9177	 * set, then we have deleted an entry that never made it to disk.
9178	 * If the entry we deleted resulted from a name change, then the old
9179	 * inode reference still resides on disk. Any rollback that we do
9180	 * needs to be to that old inode (returned to us in prevdirrem). If
9181	 * the entry we deleted resulted from a create, then there is
9182	 * no entry on the disk, so we want to roll back to zero rather
9183	 * than the uncommitted inode. In either of the COMPLETE cases we
9184	 * want to immediately free the unwritten and unreferenced inode.
9185	 */
9186	if ((dirrem->dm_state & COMPLETE) == 0) {
9187		dap->da_previous = dirrem;
9188	} else {
9189		if (prevdirrem != NULL) {
9190			dap->da_previous = prevdirrem;
9191		} else {
9192			dap->da_state &= ~DIRCHG;
9193			dap->da_pagedep = pagedep;
9194		}
9195		dirrem->dm_dirinum = pagedep->pd_ino;
9196		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9197			add_to_worklist(&dirrem->dm_list, 0);
9198	}
9199	/*
9200	 * Lookup the jaddref for this journal entry.  We must finish
9201	 * initializing it and make the diradd write dependent on it.
9202	 * If we're not journaling, put it on the id_bufwait list if the
9203	 * inode is not yet written. If it is written, do the post-inode
9204	 * write processing to put it on the id_pendinghd list.
9205	 */
9206	inodedep_lookup(mp, newinum, DEPALLOC | NODELAY, &inodedep);
9207	if (MOUNTEDSUJ(mp)) {
9208		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
9209		    inoreflst);
9210		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
9211		    ("softdep_setup_directory_change: bad jaddref %p",
9212		    jaddref));
9213		jaddref->ja_diroff = dp->i_offset;
9214		jaddref->ja_diradd = dap;
9215		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9216		    dap, da_pdlist);
9217		add_to_journal(&jaddref->ja_list);
9218	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
9219		dap->da_state |= COMPLETE;
9220		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
9221		WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
9222	} else {
9223		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9224		    dap, da_pdlist);
9225		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
9226	}
9227	/*
9228	 * If we're making a new name for a directory that has not been
9229	 * committed when need to move the dot and dotdot references to
9230	 * this new name.
9231	 */
9232	if (inodedep->id_mkdiradd && dp->i_offset != DOTDOT_OFFSET)
9233		merge_diradd(inodedep, dap);
9234	FREE_LOCK(dp->i_ump);
9235}
9236
9237/*
9238 * Called whenever the link count on an inode is changed.
9239 * It creates an inode dependency so that the new reference(s)
9240 * to the inode cannot be committed to disk until the updated
9241 * inode has been written.
9242 */
9243void
9244softdep_change_linkcnt(ip)
9245	struct inode *ip;	/* the inode with the increased link count */
9246{
9247	struct inodedep *inodedep;
9248	int dflags;
9249
9250	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ip->i_ump)) != 0,
9251	    ("softdep_change_linkcnt called on non-softdep filesystem"));
9252	ACQUIRE_LOCK(ip->i_ump);
9253	dflags = DEPALLOC;
9254	if (IS_SNAPSHOT(ip))
9255		dflags |= NODELAY;
9256	inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, dflags, &inodedep);
9257	if (ip->i_nlink < ip->i_effnlink)
9258		panic("softdep_change_linkcnt: bad delta");
9259	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9260	FREE_LOCK(ip->i_ump);
9261}
9262
9263/*
9264 * Attach a sbdep dependency to the superblock buf so that we can keep
9265 * track of the head of the linked list of referenced but unlinked inodes.
9266 */
9267void
9268softdep_setup_sbupdate(ump, fs, bp)
9269	struct ufsmount *ump;
9270	struct fs *fs;
9271	struct buf *bp;
9272{
9273	struct sbdep *sbdep;
9274	struct worklist *wk;
9275
9276	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9277	    ("softdep_setup_sbupdate called on non-softdep filesystem"));
9278	LIST_FOREACH(wk, &bp->b_dep, wk_list)
9279		if (wk->wk_type == D_SBDEP)
9280			break;
9281	if (wk != NULL)
9282		return;
9283	sbdep = malloc(sizeof(struct sbdep), M_SBDEP, M_SOFTDEP_FLAGS);
9284	workitem_alloc(&sbdep->sb_list, D_SBDEP, UFSTOVFS(ump));
9285	sbdep->sb_fs = fs;
9286	sbdep->sb_ump = ump;
9287	ACQUIRE_LOCK(ump);
9288	WORKLIST_INSERT(&bp->b_dep, &sbdep->sb_list);
9289	FREE_LOCK(ump);
9290}
9291
9292/*
9293 * Return the first unlinked inodedep which is ready to be the head of the
9294 * list.  The inodedep and all those after it must have valid next pointers.
9295 */
9296static struct inodedep *
9297first_unlinked_inodedep(ump)
9298	struct ufsmount *ump;
9299{
9300	struct inodedep *inodedep;
9301	struct inodedep *idp;
9302
9303	LOCK_OWNED(ump);
9304	for (inodedep = TAILQ_LAST(&ump->softdep_unlinked, inodedeplst);
9305	    inodedep; inodedep = idp) {
9306		if ((inodedep->id_state & UNLINKNEXT) == 0)
9307			return (NULL);
9308		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9309		if (idp == NULL || (idp->id_state & UNLINKNEXT) == 0)
9310			break;
9311		if ((inodedep->id_state & UNLINKPREV) == 0)
9312			break;
9313	}
9314	return (inodedep);
9315}
9316
9317/*
9318 * Set the sujfree unlinked head pointer prior to writing a superblock.
9319 */
9320static void
9321initiate_write_sbdep(sbdep)
9322	struct sbdep *sbdep;
9323{
9324	struct inodedep *inodedep;
9325	struct fs *bpfs;
9326	struct fs *fs;
9327
9328	bpfs = sbdep->sb_fs;
9329	fs = sbdep->sb_ump->um_fs;
9330	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9331	if (inodedep) {
9332		fs->fs_sujfree = inodedep->id_ino;
9333		inodedep->id_state |= UNLINKPREV;
9334	} else
9335		fs->fs_sujfree = 0;
9336	bpfs->fs_sujfree = fs->fs_sujfree;
9337}
9338
9339/*
9340 * After a superblock is written determine whether it must be written again
9341 * due to a changing unlinked list head.
9342 */
9343static int
9344handle_written_sbdep(sbdep, bp)
9345	struct sbdep *sbdep;
9346	struct buf *bp;
9347{
9348	struct inodedep *inodedep;
9349	struct mount *mp;
9350	struct fs *fs;
9351
9352	LOCK_OWNED(sbdep->sb_ump);
9353	fs = sbdep->sb_fs;
9354	mp = UFSTOVFS(sbdep->sb_ump);
9355	/*
9356	 * If the superblock doesn't match the in-memory list start over.
9357	 */
9358	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9359	if ((inodedep && fs->fs_sujfree != inodedep->id_ino) ||
9360	    (inodedep == NULL && fs->fs_sujfree != 0)) {
9361		bdirty(bp);
9362		return (1);
9363	}
9364	WORKITEM_FREE(sbdep, D_SBDEP);
9365	if (fs->fs_sujfree == 0)
9366		return (0);
9367	/*
9368	 * Now that we have a record of this inode in stable store allow it
9369	 * to be written to free up pending work.  Inodes may see a lot of
9370	 * write activity after they are unlinked which we must not hold up.
9371	 */
9372	for (; inodedep != NULL; inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
9373		if ((inodedep->id_state & UNLINKLINKS) != UNLINKLINKS)
9374			panic("handle_written_sbdep: Bad inodedep %p (0x%X)",
9375			    inodedep, inodedep->id_state);
9376		if (inodedep->id_state & UNLINKONLIST)
9377			break;
9378		inodedep->id_state |= DEPCOMPLETE | UNLINKONLIST;
9379	}
9380
9381	return (0);
9382}
9383
9384/*
9385 * Mark an inodedep as unlinked and insert it into the in-memory unlinked list.
9386 */
9387static void
9388unlinked_inodedep(mp, inodedep)
9389	struct mount *mp;
9390	struct inodedep *inodedep;
9391{
9392	struct ufsmount *ump;
9393
9394	ump = VFSTOUFS(mp);
9395	LOCK_OWNED(ump);
9396	if (MOUNTEDSUJ(mp) == 0)
9397		return;
9398	ump->um_fs->fs_fmod = 1;
9399	if (inodedep->id_state & UNLINKED)
9400		panic("unlinked_inodedep: %p already unlinked\n", inodedep);
9401	inodedep->id_state |= UNLINKED;
9402	TAILQ_INSERT_HEAD(&ump->softdep_unlinked, inodedep, id_unlinked);
9403}
9404
9405/*
9406 * Remove an inodedep from the unlinked inodedep list.  This may require
9407 * disk writes if the inode has made it that far.
9408 */
9409static void
9410clear_unlinked_inodedep(inodedep)
9411	struct inodedep *inodedep;
9412{
9413	struct ufsmount *ump;
9414	struct inodedep *idp;
9415	struct inodedep *idn;
9416	struct fs *fs;
9417	struct buf *bp;
9418	ino_t ino;
9419	ino_t nino;
9420	ino_t pino;
9421	int error;
9422
9423	ump = VFSTOUFS(inodedep->id_list.wk_mp);
9424	fs = ump->um_fs;
9425	ino = inodedep->id_ino;
9426	error = 0;
9427	for (;;) {
9428		LOCK_OWNED(ump);
9429		KASSERT((inodedep->id_state & UNLINKED) != 0,
9430		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
9431		    inodedep));
9432		/*
9433		 * If nothing has yet been written simply remove us from
9434		 * the in memory list and return.  This is the most common
9435		 * case where handle_workitem_remove() loses the final
9436		 * reference.
9437		 */
9438		if ((inodedep->id_state & UNLINKLINKS) == 0)
9439			break;
9440		/*
9441		 * If we have a NEXT pointer and no PREV pointer we can simply
9442		 * clear NEXT's PREV and remove ourselves from the list.  Be
9443		 * careful not to clear PREV if the superblock points at
9444		 * next as well.
9445		 */
9446		idn = TAILQ_NEXT(inodedep, id_unlinked);
9447		if ((inodedep->id_state & UNLINKLINKS) == UNLINKNEXT) {
9448			if (idn && fs->fs_sujfree != idn->id_ino)
9449				idn->id_state &= ~UNLINKPREV;
9450			break;
9451		}
9452		/*
9453		 * Here we have an inodedep which is actually linked into
9454		 * the list.  We must remove it by forcing a write to the
9455		 * link before us, whether it be the superblock or an inode.
9456		 * Unfortunately the list may change while we're waiting
9457		 * on the buf lock for either resource so we must loop until
9458		 * we lock the right one.  If both the superblock and an
9459		 * inode point to this inode we must clear the inode first
9460		 * followed by the superblock.
9461		 */
9462		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9463		pino = 0;
9464		if (idp && (idp->id_state & UNLINKNEXT))
9465			pino = idp->id_ino;
9466		FREE_LOCK(ump);
9467		if (pino == 0) {
9468			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9469			    (int)fs->fs_sbsize, 0, 0, 0);
9470		} else {
9471			error = bread(ump->um_devvp,
9472			    fsbtodb(fs, ino_to_fsba(fs, pino)),
9473			    (int)fs->fs_bsize, NOCRED, &bp);
9474			if (error)
9475				brelse(bp);
9476		}
9477		ACQUIRE_LOCK(ump);
9478		if (error)
9479			break;
9480		/* If the list has changed restart the loop. */
9481		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9482		nino = 0;
9483		if (idp && (idp->id_state & UNLINKNEXT))
9484			nino = idp->id_ino;
9485		if (nino != pino ||
9486		    (inodedep->id_state & UNLINKPREV) != UNLINKPREV) {
9487			FREE_LOCK(ump);
9488			brelse(bp);
9489			ACQUIRE_LOCK(ump);
9490			continue;
9491		}
9492		nino = 0;
9493		idn = TAILQ_NEXT(inodedep, id_unlinked);
9494		if (idn)
9495			nino = idn->id_ino;
9496		/*
9497		 * Remove us from the in memory list.  After this we cannot
9498		 * access the inodedep.
9499		 */
9500		KASSERT((inodedep->id_state & UNLINKED) != 0,
9501		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
9502		    inodedep));
9503		inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9504		TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9505		FREE_LOCK(ump);
9506		/*
9507		 * The predecessor's next pointer is manually updated here
9508		 * so that the NEXT flag is never cleared for an element
9509		 * that is in the list.
9510		 */
9511		if (pino == 0) {
9512			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9513			ffs_oldfscompat_write((struct fs *)bp->b_data, ump);
9514			softdep_setup_sbupdate(ump, (struct fs *)bp->b_data,
9515			    bp);
9516		} else if (fs->fs_magic == FS_UFS1_MAGIC)
9517			((struct ufs1_dinode *)bp->b_data +
9518			    ino_to_fsbo(fs, pino))->di_freelink = nino;
9519		else
9520			((struct ufs2_dinode *)bp->b_data +
9521			    ino_to_fsbo(fs, pino))->di_freelink = nino;
9522		/*
9523		 * If the bwrite fails we have no recourse to recover.  The
9524		 * filesystem is corrupted already.
9525		 */
9526		bwrite(bp);
9527		ACQUIRE_LOCK(ump);
9528		/*
9529		 * If the superblock pointer still needs to be cleared force
9530		 * a write here.
9531		 */
9532		if (fs->fs_sujfree == ino) {
9533			FREE_LOCK(ump);
9534			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9535			    (int)fs->fs_sbsize, 0, 0, 0);
9536			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9537			ffs_oldfscompat_write((struct fs *)bp->b_data, ump);
9538			softdep_setup_sbupdate(ump, (struct fs *)bp->b_data,
9539			    bp);
9540			bwrite(bp);
9541			ACQUIRE_LOCK(ump);
9542		}
9543
9544		if (fs->fs_sujfree != ino)
9545			return;
9546		panic("clear_unlinked_inodedep: Failed to clear free head");
9547	}
9548	if (inodedep->id_ino == fs->fs_sujfree)
9549		panic("clear_unlinked_inodedep: Freeing head of free list");
9550	inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9551	TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9552	return;
9553}
9554
9555/*
9556 * This workitem decrements the inode's link count.
9557 * If the link count reaches zero, the file is removed.
9558 */
9559static int
9560handle_workitem_remove(dirrem, flags)
9561	struct dirrem *dirrem;
9562	int flags;
9563{
9564	struct inodedep *inodedep;
9565	struct workhead dotdotwk;
9566	struct worklist *wk;
9567	struct ufsmount *ump;
9568	struct mount *mp;
9569	struct vnode *vp;
9570	struct inode *ip;
9571	ino_t oldinum;
9572
9573	if (dirrem->dm_state & ONWORKLIST)
9574		panic("handle_workitem_remove: dirrem %p still on worklist",
9575		    dirrem);
9576	oldinum = dirrem->dm_oldinum;
9577	mp = dirrem->dm_list.wk_mp;
9578	ump = VFSTOUFS(mp);
9579	flags |= LK_EXCLUSIVE;
9580	if (ffs_vgetf(mp, oldinum, flags, &vp, FFSV_FORCEINSMQ) != 0)
9581		return (EBUSY);
9582	ip = VTOI(vp);
9583	ACQUIRE_LOCK(ump);
9584	if ((inodedep_lookup(mp, oldinum, 0, &inodedep)) == 0)
9585		panic("handle_workitem_remove: lost inodedep");
9586	if (dirrem->dm_state & ONDEPLIST)
9587		LIST_REMOVE(dirrem, dm_inonext);
9588	KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
9589	    ("handle_workitem_remove:  Journal entries not written."));
9590
9591	/*
9592	 * Move all dependencies waiting on the remove to complete
9593	 * from the dirrem to the inode inowait list to be completed
9594	 * after the inode has been updated and written to disk.  Any
9595	 * marked MKDIR_PARENT are saved to be completed when the .. ref
9596	 * is removed.
9597	 */
9598	LIST_INIT(&dotdotwk);
9599	while ((wk = LIST_FIRST(&dirrem->dm_jwork)) != NULL) {
9600		WORKLIST_REMOVE(wk);
9601		if (wk->wk_state & MKDIR_PARENT) {
9602			wk->wk_state &= ~MKDIR_PARENT;
9603			WORKLIST_INSERT(&dotdotwk, wk);
9604			continue;
9605		}
9606		WORKLIST_INSERT(&inodedep->id_inowait, wk);
9607	}
9608	LIST_SWAP(&dirrem->dm_jwork, &dotdotwk, worklist, wk_list);
9609	/*
9610	 * Normal file deletion.
9611	 */
9612	if ((dirrem->dm_state & RMDIR) == 0) {
9613		ip->i_nlink--;
9614		DIP_SET(ip, i_nlink, ip->i_nlink);
9615		ip->i_flag |= IN_CHANGE;
9616		if (ip->i_nlink < ip->i_effnlink)
9617			panic("handle_workitem_remove: bad file delta");
9618		if (ip->i_nlink == 0)
9619			unlinked_inodedep(mp, inodedep);
9620		inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9621		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9622		    ("handle_workitem_remove: worklist not empty. %s",
9623		    TYPENAME(LIST_FIRST(&dirrem->dm_jwork)->wk_type)));
9624		WORKITEM_FREE(dirrem, D_DIRREM);
9625		FREE_LOCK(ump);
9626		goto out;
9627	}
9628	/*
9629	 * Directory deletion. Decrement reference count for both the
9630	 * just deleted parent directory entry and the reference for ".".
9631	 * Arrange to have the reference count on the parent decremented
9632	 * to account for the loss of "..".
9633	 */
9634	ip->i_nlink -= 2;
9635	DIP_SET(ip, i_nlink, ip->i_nlink);
9636	ip->i_flag |= IN_CHANGE;
9637	if (ip->i_nlink < ip->i_effnlink)
9638		panic("handle_workitem_remove: bad dir delta");
9639	if (ip->i_nlink == 0)
9640		unlinked_inodedep(mp, inodedep);
9641	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9642	/*
9643	 * Rename a directory to a new parent. Since, we are both deleting
9644	 * and creating a new directory entry, the link count on the new
9645	 * directory should not change. Thus we skip the followup dirrem.
9646	 */
9647	if (dirrem->dm_state & DIRCHG) {
9648		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9649		    ("handle_workitem_remove: DIRCHG and worklist not empty."));
9650		WORKITEM_FREE(dirrem, D_DIRREM);
9651		FREE_LOCK(ump);
9652		goto out;
9653	}
9654	dirrem->dm_state = ONDEPLIST;
9655	dirrem->dm_oldinum = dirrem->dm_dirinum;
9656	/*
9657	 * Place the dirrem on the parent's diremhd list.
9658	 */
9659	if (inodedep_lookup(mp, dirrem->dm_oldinum, 0, &inodedep) == 0)
9660		panic("handle_workitem_remove: lost dir inodedep");
9661	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9662	/*
9663	 * If the allocated inode has never been written to disk, then
9664	 * the on-disk inode is zero'ed and we can remove the file
9665	 * immediately.  When journaling if the inode has been marked
9666	 * unlinked and not DEPCOMPLETE we know it can never be written.
9667	 */
9668	inodedep_lookup(mp, oldinum, 0, &inodedep);
9669	if (inodedep == NULL ||
9670	    (inodedep->id_state & (DEPCOMPLETE | UNLINKED)) == UNLINKED ||
9671	    check_inode_unwritten(inodedep)) {
9672		FREE_LOCK(ump);
9673		vput(vp);
9674		return handle_workitem_remove(dirrem, flags);
9675	}
9676	WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
9677	FREE_LOCK(ump);
9678	ip->i_flag |= IN_CHANGE;
9679out:
9680	ffs_update(vp, 0);
9681	vput(vp);
9682	return (0);
9683}
9684
9685/*
9686 * Inode de-allocation dependencies.
9687 *
9688 * When an inode's link count is reduced to zero, it can be de-allocated. We
9689 * found it convenient to postpone de-allocation until after the inode is
9690 * written to disk with its new link count (zero).  At this point, all of the
9691 * on-disk inode's block pointers are nullified and, with careful dependency
9692 * list ordering, all dependencies related to the inode will be satisfied and
9693 * the corresponding dependency structures de-allocated.  So, if/when the
9694 * inode is reused, there will be no mixing of old dependencies with new
9695 * ones.  This artificial dependency is set up by the block de-allocation
9696 * procedure above (softdep_setup_freeblocks) and completed by the
9697 * following procedure.
9698 */
9699static void
9700handle_workitem_freefile(freefile)
9701	struct freefile *freefile;
9702{
9703	struct workhead wkhd;
9704	struct fs *fs;
9705	struct inodedep *idp;
9706	struct ufsmount *ump;
9707	int error;
9708
9709	ump = VFSTOUFS(freefile->fx_list.wk_mp);
9710	fs = ump->um_fs;
9711#ifdef DEBUG
9712	ACQUIRE_LOCK(ump);
9713	error = inodedep_lookup(UFSTOVFS(ump), freefile->fx_oldinum, 0, &idp);
9714	FREE_LOCK(ump);
9715	if (error)
9716		panic("handle_workitem_freefile: inodedep %p survived", idp);
9717#endif
9718	UFS_LOCK(ump);
9719	fs->fs_pendinginodes -= 1;
9720	UFS_UNLOCK(ump);
9721	LIST_INIT(&wkhd);
9722	LIST_SWAP(&freefile->fx_jwork, &wkhd, worklist, wk_list);
9723	if ((error = ffs_freefile(ump, fs, freefile->fx_devvp,
9724	    freefile->fx_oldinum, freefile->fx_mode, &wkhd)) != 0)
9725		softdep_error("handle_workitem_freefile", error);
9726	ACQUIRE_LOCK(ump);
9727	WORKITEM_FREE(freefile, D_FREEFILE);
9728	FREE_LOCK(ump);
9729}
9730
9731
9732/*
9733 * Helper function which unlinks marker element from work list and returns
9734 * the next element on the list.
9735 */
9736static __inline struct worklist *
9737markernext(struct worklist *marker)
9738{
9739	struct worklist *next;
9740
9741	next = LIST_NEXT(marker, wk_list);
9742	LIST_REMOVE(marker, wk_list);
9743	return next;
9744}
9745
9746/*
9747 * Disk writes.
9748 *
9749 * The dependency structures constructed above are most actively used when file
9750 * system blocks are written to disk.  No constraints are placed on when a
9751 * block can be written, but unsatisfied update dependencies are made safe by
9752 * modifying (or replacing) the source memory for the duration of the disk
9753 * write.  When the disk write completes, the memory block is again brought
9754 * up-to-date.
9755 *
9756 * In-core inode structure reclamation.
9757 *
9758 * Because there are a finite number of "in-core" inode structures, they are
9759 * reused regularly.  By transferring all inode-related dependencies to the
9760 * in-memory inode block and indexing them separately (via "inodedep"s), we
9761 * can allow "in-core" inode structures to be reused at any time and avoid
9762 * any increase in contention.
9763 *
9764 * Called just before entering the device driver to initiate a new disk I/O.
9765 * The buffer must be locked, thus, no I/O completion operations can occur
9766 * while we are manipulating its associated dependencies.
9767 */
9768static void
9769softdep_disk_io_initiation(bp)
9770	struct buf *bp;		/* structure describing disk write to occur */
9771{
9772	struct worklist *wk;
9773	struct worklist marker;
9774	struct inodedep *inodedep;
9775	struct freeblks *freeblks;
9776	struct jblkdep *jblkdep;
9777	struct newblk *newblk;
9778	struct ufsmount *ump;
9779
9780	/*
9781	 * We only care about write operations. There should never
9782	 * be dependencies for reads.
9783	 */
9784	if (bp->b_iocmd != BIO_WRITE)
9785		panic("softdep_disk_io_initiation: not write");
9786
9787	if (bp->b_vflags & BV_BKGRDINPROG)
9788		panic("softdep_disk_io_initiation: Writing buffer with "
9789		    "background write in progress: %p", bp);
9790
9791	if ((wk = LIST_FIRST(&bp->b_dep)) == NULL)
9792		return;
9793	ump = VFSTOUFS(wk->wk_mp);
9794
9795	marker.wk_type = D_LAST + 1;	/* Not a normal workitem */
9796	PHOLD(curproc);			/* Don't swap out kernel stack */
9797	ACQUIRE_LOCK(ump);
9798	/*
9799	 * Do any necessary pre-I/O processing.
9800	 */
9801	for (wk = LIST_FIRST(&bp->b_dep); wk != NULL;
9802	     wk = markernext(&marker)) {
9803		LIST_INSERT_AFTER(wk, &marker, wk_list);
9804		switch (wk->wk_type) {
9805
9806		case D_PAGEDEP:
9807			initiate_write_filepage(WK_PAGEDEP(wk), bp);
9808			continue;
9809
9810		case D_INODEDEP:
9811			inodedep = WK_INODEDEP(wk);
9812			if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC)
9813				initiate_write_inodeblock_ufs1(inodedep, bp);
9814			else
9815				initiate_write_inodeblock_ufs2(inodedep, bp);
9816			continue;
9817
9818		case D_INDIRDEP:
9819			initiate_write_indirdep(WK_INDIRDEP(wk), bp);
9820			continue;
9821
9822		case D_BMSAFEMAP:
9823			initiate_write_bmsafemap(WK_BMSAFEMAP(wk), bp);
9824			continue;
9825
9826		case D_JSEG:
9827			WK_JSEG(wk)->js_buf = NULL;
9828			continue;
9829
9830		case D_FREEBLKS:
9831			freeblks = WK_FREEBLKS(wk);
9832			jblkdep = LIST_FIRST(&freeblks->fb_jblkdephd);
9833			/*
9834			 * We have to wait for the freeblks to be journaled
9835			 * before we can write an inodeblock with updated
9836			 * pointers.  Be careful to arrange the marker so
9837			 * we revisit the freeblks if it's not removed by
9838			 * the first jwait().
9839			 */
9840			if (jblkdep != NULL) {
9841				LIST_REMOVE(&marker, wk_list);
9842				LIST_INSERT_BEFORE(wk, &marker, wk_list);
9843				jwait(&jblkdep->jb_list, MNT_WAIT);
9844			}
9845			continue;
9846		case D_ALLOCDIRECT:
9847		case D_ALLOCINDIR:
9848			/*
9849			 * We have to wait for the jnewblk to be journaled
9850			 * before we can write to a block if the contents
9851			 * may be confused with an earlier file's indirect
9852			 * at recovery time.  Handle the marker as described
9853			 * above.
9854			 */
9855			newblk = WK_NEWBLK(wk);
9856			if (newblk->nb_jnewblk != NULL &&
9857			    indirblk_lookup(newblk->nb_list.wk_mp,
9858			    newblk->nb_newblkno)) {
9859				LIST_REMOVE(&marker, wk_list);
9860				LIST_INSERT_BEFORE(wk, &marker, wk_list);
9861				jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
9862			}
9863			continue;
9864
9865		case D_SBDEP:
9866			initiate_write_sbdep(WK_SBDEP(wk));
9867			continue;
9868
9869		case D_MKDIR:
9870		case D_FREEWORK:
9871		case D_FREEDEP:
9872		case D_JSEGDEP:
9873			continue;
9874
9875		default:
9876			panic("handle_disk_io_initiation: Unexpected type %s",
9877			    TYPENAME(wk->wk_type));
9878			/* NOTREACHED */
9879		}
9880	}
9881	FREE_LOCK(ump);
9882	PRELE(curproc);			/* Allow swapout of kernel stack */
9883}
9884
9885/*
9886 * Called from within the procedure above to deal with unsatisfied
9887 * allocation dependencies in a directory. The buffer must be locked,
9888 * thus, no I/O completion operations can occur while we are
9889 * manipulating its associated dependencies.
9890 */
9891static void
9892initiate_write_filepage(pagedep, bp)
9893	struct pagedep *pagedep;
9894	struct buf *bp;
9895{
9896	struct jremref *jremref;
9897	struct jmvref *jmvref;
9898	struct dirrem *dirrem;
9899	struct diradd *dap;
9900	struct direct *ep;
9901	int i;
9902
9903	if (pagedep->pd_state & IOSTARTED) {
9904		/*
9905		 * This can only happen if there is a driver that does not
9906		 * understand chaining. Here biodone will reissue the call
9907		 * to strategy for the incomplete buffers.
9908		 */
9909		printf("initiate_write_filepage: already started\n");
9910		return;
9911	}
9912	pagedep->pd_state |= IOSTARTED;
9913	/*
9914	 * Wait for all journal remove dependencies to hit the disk.
9915	 * We can not allow any potentially conflicting directory adds
9916	 * to be visible before removes and rollback is too difficult.
9917	 * The soft updates lock may be dropped and re-acquired, however
9918	 * we hold the buf locked so the dependency can not go away.
9919	 */
9920	LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next)
9921		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL)
9922			jwait(&jremref->jr_list, MNT_WAIT);
9923	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL)
9924		jwait(&jmvref->jm_list, MNT_WAIT);
9925	for (i = 0; i < DAHASHSZ; i++) {
9926		LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
9927			ep = (struct direct *)
9928			    ((char *)bp->b_data + dap->da_offset);
9929			if (ep->d_ino != dap->da_newinum)
9930				panic("%s: dir inum %ju != new %ju",
9931				    "initiate_write_filepage",
9932				    (uintmax_t)ep->d_ino,
9933				    (uintmax_t)dap->da_newinum);
9934			if (dap->da_state & DIRCHG)
9935				ep->d_ino = dap->da_previous->dm_oldinum;
9936			else
9937				ep->d_ino = 0;
9938			dap->da_state &= ~ATTACHED;
9939			dap->da_state |= UNDONE;
9940		}
9941	}
9942}
9943
9944/*
9945 * Version of initiate_write_inodeblock that handles UFS1 dinodes.
9946 * Note that any bug fixes made to this routine must be done in the
9947 * version found below.
9948 *
9949 * Called from within the procedure above to deal with unsatisfied
9950 * allocation dependencies in an inodeblock. The buffer must be
9951 * locked, thus, no I/O completion operations can occur while we
9952 * are manipulating its associated dependencies.
9953 */
9954static void
9955initiate_write_inodeblock_ufs1(inodedep, bp)
9956	struct inodedep *inodedep;
9957	struct buf *bp;			/* The inode block */
9958{
9959	struct allocdirect *adp, *lastadp;
9960	struct ufs1_dinode *dp;
9961	struct ufs1_dinode *sip;
9962	struct inoref *inoref;
9963	struct ufsmount *ump;
9964	struct fs *fs;
9965	ufs_lbn_t i;
9966#ifdef INVARIANTS
9967	ufs_lbn_t prevlbn = 0;
9968#endif
9969	int deplist;
9970
9971	if (inodedep->id_state & IOSTARTED)
9972		panic("initiate_write_inodeblock_ufs1: already started");
9973	inodedep->id_state |= IOSTARTED;
9974	fs = inodedep->id_fs;
9975	ump = VFSTOUFS(inodedep->id_list.wk_mp);
9976	LOCK_OWNED(ump);
9977	dp = (struct ufs1_dinode *)bp->b_data +
9978	    ino_to_fsbo(fs, inodedep->id_ino);
9979
9980	/*
9981	 * If we're on the unlinked list but have not yet written our
9982	 * next pointer initialize it here.
9983	 */
9984	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
9985		struct inodedep *inon;
9986
9987		inon = TAILQ_NEXT(inodedep, id_unlinked);
9988		dp->di_freelink = inon ? inon->id_ino : 0;
9989	}
9990	/*
9991	 * If the bitmap is not yet written, then the allocated
9992	 * inode cannot be written to disk.
9993	 */
9994	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
9995		if (inodedep->id_savedino1 != NULL)
9996			panic("initiate_write_inodeblock_ufs1: I/O underway");
9997		FREE_LOCK(ump);
9998		sip = malloc(sizeof(struct ufs1_dinode),
9999		    M_SAVEDINO, M_SOFTDEP_FLAGS);
10000		ACQUIRE_LOCK(ump);
10001		inodedep->id_savedino1 = sip;
10002		*inodedep->id_savedino1 = *dp;
10003		bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
10004		dp->di_gen = inodedep->id_savedino1->di_gen;
10005		dp->di_freelink = inodedep->id_savedino1->di_freelink;
10006		return;
10007	}
10008	/*
10009	 * If no dependencies, then there is nothing to roll back.
10010	 */
10011	inodedep->id_savedsize = dp->di_size;
10012	inodedep->id_savedextsize = 0;
10013	inodedep->id_savednlink = dp->di_nlink;
10014	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10015	    TAILQ_EMPTY(&inodedep->id_inoreflst))
10016		return;
10017	/*
10018	 * Revert the link count to that of the first unwritten journal entry.
10019	 */
10020	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10021	if (inoref)
10022		dp->di_nlink = inoref->if_nlink;
10023	/*
10024	 * Set the dependencies to busy.
10025	 */
10026	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10027	     adp = TAILQ_NEXT(adp, ad_next)) {
10028#ifdef INVARIANTS
10029		if (deplist != 0 && prevlbn >= adp->ad_offset)
10030			panic("softdep_write_inodeblock: lbn order");
10031		prevlbn = adp->ad_offset;
10032		if (adp->ad_offset < NDADDR &&
10033		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10034			panic("%s: direct pointer #%jd mismatch %d != %jd",
10035			    "softdep_write_inodeblock",
10036			    (intmax_t)adp->ad_offset,
10037			    dp->di_db[adp->ad_offset],
10038			    (intmax_t)adp->ad_newblkno);
10039		if (adp->ad_offset >= NDADDR &&
10040		    dp->di_ib[adp->ad_offset - NDADDR] != adp->ad_newblkno)
10041			panic("%s: indirect pointer #%jd mismatch %d != %jd",
10042			    "softdep_write_inodeblock",
10043			    (intmax_t)adp->ad_offset - NDADDR,
10044			    dp->di_ib[adp->ad_offset - NDADDR],
10045			    (intmax_t)adp->ad_newblkno);
10046		deplist |= 1 << adp->ad_offset;
10047		if ((adp->ad_state & ATTACHED) == 0)
10048			panic("softdep_write_inodeblock: Unknown state 0x%x",
10049			    adp->ad_state);
10050#endif /* INVARIANTS */
10051		adp->ad_state &= ~ATTACHED;
10052		adp->ad_state |= UNDONE;
10053	}
10054	/*
10055	 * The on-disk inode cannot claim to be any larger than the last
10056	 * fragment that has been written. Otherwise, the on-disk inode
10057	 * might have fragments that were not the last block in the file
10058	 * which would corrupt the filesystem.
10059	 */
10060	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10061	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10062		if (adp->ad_offset >= NDADDR)
10063			break;
10064		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10065		/* keep going until hitting a rollback to a frag */
10066		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10067			continue;
10068		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10069		for (i = adp->ad_offset + 1; i < NDADDR; i++) {
10070#ifdef INVARIANTS
10071			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10072				panic("softdep_write_inodeblock: lost dep1");
10073#endif /* INVARIANTS */
10074			dp->di_db[i] = 0;
10075		}
10076		for (i = 0; i < NIADDR; i++) {
10077#ifdef INVARIANTS
10078			if (dp->di_ib[i] != 0 &&
10079			    (deplist & ((1 << NDADDR) << i)) == 0)
10080				panic("softdep_write_inodeblock: lost dep2");
10081#endif /* INVARIANTS */
10082			dp->di_ib[i] = 0;
10083		}
10084		return;
10085	}
10086	/*
10087	 * If we have zero'ed out the last allocated block of the file,
10088	 * roll back the size to the last currently allocated block.
10089	 * We know that this last allocated block is a full-sized as
10090	 * we already checked for fragments in the loop above.
10091	 */
10092	if (lastadp != NULL &&
10093	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10094		for (i = lastadp->ad_offset; i >= 0; i--)
10095			if (dp->di_db[i] != 0)
10096				break;
10097		dp->di_size = (i + 1) * fs->fs_bsize;
10098	}
10099	/*
10100	 * The only dependencies are for indirect blocks.
10101	 *
10102	 * The file size for indirect block additions is not guaranteed.
10103	 * Such a guarantee would be non-trivial to achieve. The conventional
10104	 * synchronous write implementation also does not make this guarantee.
10105	 * Fsck should catch and fix discrepancies. Arguably, the file size
10106	 * can be over-estimated without destroying integrity when the file
10107	 * moves into the indirect blocks (i.e., is large). If we want to
10108	 * postpone fsck, we are stuck with this argument.
10109	 */
10110	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10111		dp->di_ib[adp->ad_offset - NDADDR] = 0;
10112}
10113
10114/*
10115 * Version of initiate_write_inodeblock that handles UFS2 dinodes.
10116 * Note that any bug fixes made to this routine must be done in the
10117 * version found above.
10118 *
10119 * Called from within the procedure above to deal with unsatisfied
10120 * allocation dependencies in an inodeblock. The buffer must be
10121 * locked, thus, no I/O completion operations can occur while we
10122 * are manipulating its associated dependencies.
10123 */
10124static void
10125initiate_write_inodeblock_ufs2(inodedep, bp)
10126	struct inodedep *inodedep;
10127	struct buf *bp;			/* The inode block */
10128{
10129	struct allocdirect *adp, *lastadp;
10130	struct ufs2_dinode *dp;
10131	struct ufs2_dinode *sip;
10132	struct inoref *inoref;
10133	struct ufsmount *ump;
10134	struct fs *fs;
10135	ufs_lbn_t i;
10136#ifdef INVARIANTS
10137	ufs_lbn_t prevlbn = 0;
10138#endif
10139	int deplist;
10140
10141	if (inodedep->id_state & IOSTARTED)
10142		panic("initiate_write_inodeblock_ufs2: already started");
10143	inodedep->id_state |= IOSTARTED;
10144	fs = inodedep->id_fs;
10145	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10146	LOCK_OWNED(ump);
10147	dp = (struct ufs2_dinode *)bp->b_data +
10148	    ino_to_fsbo(fs, inodedep->id_ino);
10149
10150	/*
10151	 * If we're on the unlinked list but have not yet written our
10152	 * next pointer initialize it here.
10153	 */
10154	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10155		struct inodedep *inon;
10156
10157		inon = TAILQ_NEXT(inodedep, id_unlinked);
10158		dp->di_freelink = inon ? inon->id_ino : 0;
10159	}
10160	/*
10161	 * If the bitmap is not yet written, then the allocated
10162	 * inode cannot be written to disk.
10163	 */
10164	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10165		if (inodedep->id_savedino2 != NULL)
10166			panic("initiate_write_inodeblock_ufs2: I/O underway");
10167		FREE_LOCK(ump);
10168		sip = malloc(sizeof(struct ufs2_dinode),
10169		    M_SAVEDINO, M_SOFTDEP_FLAGS);
10170		ACQUIRE_LOCK(ump);
10171		inodedep->id_savedino2 = sip;
10172		*inodedep->id_savedino2 = *dp;
10173		bzero((caddr_t)dp, sizeof(struct ufs2_dinode));
10174		dp->di_gen = inodedep->id_savedino2->di_gen;
10175		dp->di_freelink = inodedep->id_savedino2->di_freelink;
10176		return;
10177	}
10178	/*
10179	 * If no dependencies, then there is nothing to roll back.
10180	 */
10181	inodedep->id_savedsize = dp->di_size;
10182	inodedep->id_savedextsize = dp->di_extsize;
10183	inodedep->id_savednlink = dp->di_nlink;
10184	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10185	    TAILQ_EMPTY(&inodedep->id_extupdt) &&
10186	    TAILQ_EMPTY(&inodedep->id_inoreflst))
10187		return;
10188	/*
10189	 * Revert the link count to that of the first unwritten journal entry.
10190	 */
10191	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10192	if (inoref)
10193		dp->di_nlink = inoref->if_nlink;
10194
10195	/*
10196	 * Set the ext data dependencies to busy.
10197	 */
10198	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10199	     adp = TAILQ_NEXT(adp, ad_next)) {
10200#ifdef INVARIANTS
10201		if (deplist != 0 && prevlbn >= adp->ad_offset)
10202			panic("softdep_write_inodeblock: lbn order");
10203		prevlbn = adp->ad_offset;
10204		if (dp->di_extb[adp->ad_offset] != adp->ad_newblkno)
10205			panic("%s: direct pointer #%jd mismatch %jd != %jd",
10206			    "softdep_write_inodeblock",
10207			    (intmax_t)adp->ad_offset,
10208			    (intmax_t)dp->di_extb[adp->ad_offset],
10209			    (intmax_t)adp->ad_newblkno);
10210		deplist |= 1 << adp->ad_offset;
10211		if ((adp->ad_state & ATTACHED) == 0)
10212			panic("softdep_write_inodeblock: Unknown state 0x%x",
10213			    adp->ad_state);
10214#endif /* INVARIANTS */
10215		adp->ad_state &= ~ATTACHED;
10216		adp->ad_state |= UNDONE;
10217	}
10218	/*
10219	 * The on-disk inode cannot claim to be any larger than the last
10220	 * fragment that has been written. Otherwise, the on-disk inode
10221	 * might have fragments that were not the last block in the ext
10222	 * data which would corrupt the filesystem.
10223	 */
10224	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10225	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10226		dp->di_extb[adp->ad_offset] = adp->ad_oldblkno;
10227		/* keep going until hitting a rollback to a frag */
10228		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10229			continue;
10230		dp->di_extsize = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10231		for (i = adp->ad_offset + 1; i < NXADDR; i++) {
10232#ifdef INVARIANTS
10233			if (dp->di_extb[i] != 0 && (deplist & (1 << i)) == 0)
10234				panic("softdep_write_inodeblock: lost dep1");
10235#endif /* INVARIANTS */
10236			dp->di_extb[i] = 0;
10237		}
10238		lastadp = NULL;
10239		break;
10240	}
10241	/*
10242	 * If we have zero'ed out the last allocated block of the ext
10243	 * data, roll back the size to the last currently allocated block.
10244	 * We know that this last allocated block is a full-sized as
10245	 * we already checked for fragments in the loop above.
10246	 */
10247	if (lastadp != NULL &&
10248	    dp->di_extsize <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10249		for (i = lastadp->ad_offset; i >= 0; i--)
10250			if (dp->di_extb[i] != 0)
10251				break;
10252		dp->di_extsize = (i + 1) * fs->fs_bsize;
10253	}
10254	/*
10255	 * Set the file data dependencies to busy.
10256	 */
10257	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10258	     adp = TAILQ_NEXT(adp, ad_next)) {
10259#ifdef INVARIANTS
10260		if (deplist != 0 && prevlbn >= adp->ad_offset)
10261			panic("softdep_write_inodeblock: lbn order");
10262		if ((adp->ad_state & ATTACHED) == 0)
10263			panic("inodedep %p and adp %p not attached", inodedep, adp);
10264		prevlbn = adp->ad_offset;
10265		if (adp->ad_offset < NDADDR &&
10266		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10267			panic("%s: direct pointer #%jd mismatch %jd != %jd",
10268			    "softdep_write_inodeblock",
10269			    (intmax_t)adp->ad_offset,
10270			    (intmax_t)dp->di_db[adp->ad_offset],
10271			    (intmax_t)adp->ad_newblkno);
10272		if (adp->ad_offset >= NDADDR &&
10273		    dp->di_ib[adp->ad_offset - NDADDR] != adp->ad_newblkno)
10274			panic("%s indirect pointer #%jd mismatch %jd != %jd",
10275			    "softdep_write_inodeblock:",
10276			    (intmax_t)adp->ad_offset - NDADDR,
10277			    (intmax_t)dp->di_ib[adp->ad_offset - NDADDR],
10278			    (intmax_t)adp->ad_newblkno);
10279		deplist |= 1 << adp->ad_offset;
10280		if ((adp->ad_state & ATTACHED) == 0)
10281			panic("softdep_write_inodeblock: Unknown state 0x%x",
10282			    adp->ad_state);
10283#endif /* INVARIANTS */
10284		adp->ad_state &= ~ATTACHED;
10285		adp->ad_state |= UNDONE;
10286	}
10287	/*
10288	 * The on-disk inode cannot claim to be any larger than the last
10289	 * fragment that has been written. Otherwise, the on-disk inode
10290	 * might have fragments that were not the last block in the file
10291	 * which would corrupt the filesystem.
10292	 */
10293	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10294	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10295		if (adp->ad_offset >= NDADDR)
10296			break;
10297		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10298		/* keep going until hitting a rollback to a frag */
10299		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10300			continue;
10301		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10302		for (i = adp->ad_offset + 1; i < NDADDR; i++) {
10303#ifdef INVARIANTS
10304			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10305				panic("softdep_write_inodeblock: lost dep2");
10306#endif /* INVARIANTS */
10307			dp->di_db[i] = 0;
10308		}
10309		for (i = 0; i < NIADDR; i++) {
10310#ifdef INVARIANTS
10311			if (dp->di_ib[i] != 0 &&
10312			    (deplist & ((1 << NDADDR) << i)) == 0)
10313				panic("softdep_write_inodeblock: lost dep3");
10314#endif /* INVARIANTS */
10315			dp->di_ib[i] = 0;
10316		}
10317		return;
10318	}
10319	/*
10320	 * If we have zero'ed out the last allocated block of the file,
10321	 * roll back the size to the last currently allocated block.
10322	 * We know that this last allocated block is a full-sized as
10323	 * we already checked for fragments in the loop above.
10324	 */
10325	if (lastadp != NULL &&
10326	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10327		for (i = lastadp->ad_offset; i >= 0; i--)
10328			if (dp->di_db[i] != 0)
10329				break;
10330		dp->di_size = (i + 1) * fs->fs_bsize;
10331	}
10332	/*
10333	 * The only dependencies are for indirect blocks.
10334	 *
10335	 * The file size for indirect block additions is not guaranteed.
10336	 * Such a guarantee would be non-trivial to achieve. The conventional
10337	 * synchronous write implementation also does not make this guarantee.
10338	 * Fsck should catch and fix discrepancies. Arguably, the file size
10339	 * can be over-estimated without destroying integrity when the file
10340	 * moves into the indirect blocks (i.e., is large). If we want to
10341	 * postpone fsck, we are stuck with this argument.
10342	 */
10343	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10344		dp->di_ib[adp->ad_offset - NDADDR] = 0;
10345}
10346
10347/*
10348 * Cancel an indirdep as a result of truncation.  Release all of the
10349 * children allocindirs and place their journal work on the appropriate
10350 * list.
10351 */
10352static void
10353cancel_indirdep(indirdep, bp, freeblks)
10354	struct indirdep *indirdep;
10355	struct buf *bp;
10356	struct freeblks *freeblks;
10357{
10358	struct allocindir *aip;
10359
10360	/*
10361	 * None of the indirect pointers will ever be visible,
10362	 * so they can simply be tossed. GOINGAWAY ensures
10363	 * that allocated pointers will be saved in the buffer
10364	 * cache until they are freed. Note that they will
10365	 * only be able to be found by their physical address
10366	 * since the inode mapping the logical address will
10367	 * be gone. The save buffer used for the safe copy
10368	 * was allocated in setup_allocindir_phase2 using
10369	 * the physical address so it could be used for this
10370	 * purpose. Hence we swap the safe copy with the real
10371	 * copy, allowing the safe copy to be freed and holding
10372	 * on to the real copy for later use in indir_trunc.
10373	 */
10374	if (indirdep->ir_state & GOINGAWAY)
10375		panic("cancel_indirdep: already gone");
10376	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
10377		indirdep->ir_state |= DEPCOMPLETE;
10378		LIST_REMOVE(indirdep, ir_next);
10379	}
10380	indirdep->ir_state |= GOINGAWAY;
10381	VFSTOUFS(indirdep->ir_list.wk_mp)->softdep_numindirdeps += 1;
10382	/*
10383	 * Pass in bp for blocks still have journal writes
10384	 * pending so we can cancel them on their own.
10385	 */
10386	while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != 0)
10387		cancel_allocindir(aip, bp, freeblks, 0);
10388	while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != 0)
10389		cancel_allocindir(aip, NULL, freeblks, 0);
10390	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != 0)
10391		cancel_allocindir(aip, NULL, freeblks, 0);
10392	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != 0)
10393		cancel_allocindir(aip, NULL, freeblks, 0);
10394	/*
10395	 * If there are pending partial truncations we need to keep the
10396	 * old block copy around until they complete.  This is because
10397	 * the current b_data is not a perfect superset of the available
10398	 * blocks.
10399	 */
10400	if (TAILQ_EMPTY(&indirdep->ir_trunc))
10401		bcopy(bp->b_data, indirdep->ir_savebp->b_data, bp->b_bcount);
10402	else
10403		bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10404	WORKLIST_REMOVE(&indirdep->ir_list);
10405	WORKLIST_INSERT(&indirdep->ir_savebp->b_dep, &indirdep->ir_list);
10406	indirdep->ir_bp = NULL;
10407	indirdep->ir_freeblks = freeblks;
10408}
10409
10410/*
10411 * Free an indirdep once it no longer has new pointers to track.
10412 */
10413static void
10414free_indirdep(indirdep)
10415	struct indirdep *indirdep;
10416{
10417
10418	KASSERT(TAILQ_EMPTY(&indirdep->ir_trunc),
10419	    ("free_indirdep: Indir trunc list not empty."));
10420	KASSERT(LIST_EMPTY(&indirdep->ir_completehd),
10421	    ("free_indirdep: Complete head not empty."));
10422	KASSERT(LIST_EMPTY(&indirdep->ir_writehd),
10423	    ("free_indirdep: write head not empty."));
10424	KASSERT(LIST_EMPTY(&indirdep->ir_donehd),
10425	    ("free_indirdep: done head not empty."));
10426	KASSERT(LIST_EMPTY(&indirdep->ir_deplisthd),
10427	    ("free_indirdep: deplist head not empty."));
10428	KASSERT((indirdep->ir_state & DEPCOMPLETE),
10429	    ("free_indirdep: %p still on newblk list.", indirdep));
10430	KASSERT(indirdep->ir_saveddata == NULL,
10431	    ("free_indirdep: %p still has saved data.", indirdep));
10432	if (indirdep->ir_state & ONWORKLIST)
10433		WORKLIST_REMOVE(&indirdep->ir_list);
10434	WORKITEM_FREE(indirdep, D_INDIRDEP);
10435}
10436
10437/*
10438 * Called before a write to an indirdep.  This routine is responsible for
10439 * rolling back pointers to a safe state which includes only those
10440 * allocindirs which have been completed.
10441 */
10442static void
10443initiate_write_indirdep(indirdep, bp)
10444	struct indirdep *indirdep;
10445	struct buf *bp;
10446{
10447	struct ufsmount *ump;
10448
10449	indirdep->ir_state |= IOSTARTED;
10450	if (indirdep->ir_state & GOINGAWAY)
10451		panic("disk_io_initiation: indirdep gone");
10452	/*
10453	 * If there are no remaining dependencies, this will be writing
10454	 * the real pointers.
10455	 */
10456	if (LIST_EMPTY(&indirdep->ir_deplisthd) &&
10457	    TAILQ_EMPTY(&indirdep->ir_trunc))
10458		return;
10459	/*
10460	 * Replace up-to-date version with safe version.
10461	 */
10462	if (indirdep->ir_saveddata == NULL) {
10463		ump = VFSTOUFS(indirdep->ir_list.wk_mp);
10464		LOCK_OWNED(ump);
10465		FREE_LOCK(ump);
10466		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
10467		    M_SOFTDEP_FLAGS);
10468		ACQUIRE_LOCK(ump);
10469	}
10470	indirdep->ir_state &= ~ATTACHED;
10471	indirdep->ir_state |= UNDONE;
10472	bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10473	bcopy(indirdep->ir_savebp->b_data, bp->b_data,
10474	    bp->b_bcount);
10475}
10476
10477/*
10478 * Called when an inode has been cleared in a cg bitmap.  This finally
10479 * eliminates any canceled jaddrefs
10480 */
10481void
10482softdep_setup_inofree(mp, bp, ino, wkhd)
10483	struct mount *mp;
10484	struct buf *bp;
10485	ino_t ino;
10486	struct workhead *wkhd;
10487{
10488	struct worklist *wk, *wkn;
10489	struct inodedep *inodedep;
10490	struct ufsmount *ump;
10491	uint8_t *inosused;
10492	struct cg *cgp;
10493	struct fs *fs;
10494
10495	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
10496	    ("softdep_setup_inofree called on non-softdep filesystem"));
10497	ump = VFSTOUFS(mp);
10498	ACQUIRE_LOCK(ump);
10499	fs = ump->um_fs;
10500	cgp = (struct cg *)bp->b_data;
10501	inosused = cg_inosused(cgp);
10502	if (isset(inosused, ino % fs->fs_ipg))
10503		panic("softdep_setup_inofree: inode %ju not freed.",
10504		    (uintmax_t)ino);
10505	if (inodedep_lookup(mp, ino, 0, &inodedep))
10506		panic("softdep_setup_inofree: ino %ju has existing inodedep %p",
10507		    (uintmax_t)ino, inodedep);
10508	if (wkhd) {
10509		LIST_FOREACH_SAFE(wk, wkhd, wk_list, wkn) {
10510			if (wk->wk_type != D_JADDREF)
10511				continue;
10512			WORKLIST_REMOVE(wk);
10513			/*
10514			 * We can free immediately even if the jaddref
10515			 * isn't attached in a background write as now
10516			 * the bitmaps are reconciled.
10517			 */
10518			wk->wk_state |= COMPLETE | ATTACHED;
10519			free_jaddref(WK_JADDREF(wk));
10520		}
10521		jwork_move(&bp->b_dep, wkhd);
10522	}
10523	FREE_LOCK(ump);
10524}
10525
10526
10527/*
10528 * Called via ffs_blkfree() after a set of frags has been cleared from a cg
10529 * map.  Any dependencies waiting for the write to clear are added to the
10530 * buf's list and any jnewblks that are being canceled are discarded
10531 * immediately.
10532 */
10533void
10534softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
10535	struct mount *mp;
10536	struct buf *bp;
10537	ufs2_daddr_t blkno;
10538	int frags;
10539	struct workhead *wkhd;
10540{
10541	struct bmsafemap *bmsafemap;
10542	struct jnewblk *jnewblk;
10543	struct ufsmount *ump;
10544	struct worklist *wk;
10545	struct fs *fs;
10546#ifdef SUJ_DEBUG
10547	uint8_t *blksfree;
10548	struct cg *cgp;
10549	ufs2_daddr_t jstart;
10550	ufs2_daddr_t jend;
10551	ufs2_daddr_t end;
10552	long bno;
10553	int i;
10554#endif
10555
10556	CTR3(KTR_SUJ,
10557	    "softdep_setup_blkfree: blkno %jd frags %d wk head %p",
10558	    blkno, frags, wkhd);
10559
10560	ump = VFSTOUFS(mp);
10561	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
10562	    ("softdep_setup_blkfree called on non-softdep filesystem"));
10563	ACQUIRE_LOCK(ump);
10564	/* Lookup the bmsafemap so we track when it is dirty. */
10565	fs = ump->um_fs;
10566	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10567	/*
10568	 * Detach any jnewblks which have been canceled.  They must linger
10569	 * until the bitmap is cleared again by ffs_blkfree() to prevent
10570	 * an unjournaled allocation from hitting the disk.
10571	 */
10572	if (wkhd) {
10573		while ((wk = LIST_FIRST(wkhd)) != NULL) {
10574			CTR2(KTR_SUJ,
10575			    "softdep_setup_blkfree: blkno %jd wk type %d",
10576			    blkno, wk->wk_type);
10577			WORKLIST_REMOVE(wk);
10578			if (wk->wk_type != D_JNEWBLK) {
10579				WORKLIST_INSERT(&bmsafemap->sm_freehd, wk);
10580				continue;
10581			}
10582			jnewblk = WK_JNEWBLK(wk);
10583			KASSERT(jnewblk->jn_state & GOINGAWAY,
10584			    ("softdep_setup_blkfree: jnewblk not canceled."));
10585#ifdef SUJ_DEBUG
10586			/*
10587			 * Assert that this block is free in the bitmap
10588			 * before we discard the jnewblk.
10589			 */
10590			cgp = (struct cg *)bp->b_data;
10591			blksfree = cg_blksfree(cgp);
10592			bno = dtogd(fs, jnewblk->jn_blkno);
10593			for (i = jnewblk->jn_oldfrags;
10594			    i < jnewblk->jn_frags; i++) {
10595				if (isset(blksfree, bno + i))
10596					continue;
10597				panic("softdep_setup_blkfree: not free");
10598			}
10599#endif
10600			/*
10601			 * Even if it's not attached we can free immediately
10602			 * as the new bitmap is correct.
10603			 */
10604			wk->wk_state |= COMPLETE | ATTACHED;
10605			free_jnewblk(jnewblk);
10606		}
10607	}
10608
10609#ifdef SUJ_DEBUG
10610	/*
10611	 * Assert that we are not freeing a block which has an outstanding
10612	 * allocation dependency.
10613	 */
10614	fs = VFSTOUFS(mp)->um_fs;
10615	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10616	end = blkno + frags;
10617	LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
10618		/*
10619		 * Don't match against blocks that will be freed when the
10620		 * background write is done.
10621		 */
10622		if ((jnewblk->jn_state & (ATTACHED | COMPLETE | DEPCOMPLETE)) ==
10623		    (COMPLETE | DEPCOMPLETE))
10624			continue;
10625		jstart = jnewblk->jn_blkno + jnewblk->jn_oldfrags;
10626		jend = jnewblk->jn_blkno + jnewblk->jn_frags;
10627		if ((blkno >= jstart && blkno < jend) ||
10628		    (end > jstart && end <= jend)) {
10629			printf("state 0x%X %jd - %d %d dep %p\n",
10630			    jnewblk->jn_state, jnewblk->jn_blkno,
10631			    jnewblk->jn_oldfrags, jnewblk->jn_frags,
10632			    jnewblk->jn_dep);
10633			panic("softdep_setup_blkfree: "
10634			    "%jd-%jd(%d) overlaps with %jd-%jd",
10635			    blkno, end, frags, jstart, jend);
10636		}
10637	}
10638#endif
10639	FREE_LOCK(ump);
10640}
10641
10642/*
10643 * Revert a block allocation when the journal record that describes it
10644 * is not yet written.
10645 */
10646static int
10647jnewblk_rollback(jnewblk, fs, cgp, blksfree)
10648	struct jnewblk *jnewblk;
10649	struct fs *fs;
10650	struct cg *cgp;
10651	uint8_t *blksfree;
10652{
10653	ufs1_daddr_t fragno;
10654	long cgbno, bbase;
10655	int frags, blk;
10656	int i;
10657
10658	frags = 0;
10659	cgbno = dtogd(fs, jnewblk->jn_blkno);
10660	/*
10661	 * We have to test which frags need to be rolled back.  We may
10662	 * be operating on a stale copy when doing background writes.
10663	 */
10664	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++)
10665		if (isclr(blksfree, cgbno + i))
10666			frags++;
10667	if (frags == 0)
10668		return (0);
10669	/*
10670	 * This is mostly ffs_blkfree() sans some validation and
10671	 * superblock updates.
10672	 */
10673	if (frags == fs->fs_frag) {
10674		fragno = fragstoblks(fs, cgbno);
10675		ffs_setblock(fs, blksfree, fragno);
10676		ffs_clusteracct(fs, cgp, fragno, 1);
10677		cgp->cg_cs.cs_nbfree++;
10678	} else {
10679		cgbno += jnewblk->jn_oldfrags;
10680		bbase = cgbno - fragnum(fs, cgbno);
10681		/* Decrement the old frags.  */
10682		blk = blkmap(fs, blksfree, bbase);
10683		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
10684		/* Deallocate the fragment */
10685		for (i = 0; i < frags; i++)
10686			setbit(blksfree, cgbno + i);
10687		cgp->cg_cs.cs_nffree += frags;
10688		/* Add back in counts associated with the new frags */
10689		blk = blkmap(fs, blksfree, bbase);
10690		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
10691		/* If a complete block has been reassembled, account for it. */
10692		fragno = fragstoblks(fs, bbase);
10693		if (ffs_isblock(fs, blksfree, fragno)) {
10694			cgp->cg_cs.cs_nffree -= fs->fs_frag;
10695			ffs_clusteracct(fs, cgp, fragno, 1);
10696			cgp->cg_cs.cs_nbfree++;
10697		}
10698	}
10699	stat_jnewblk++;
10700	jnewblk->jn_state &= ~ATTACHED;
10701	jnewblk->jn_state |= UNDONE;
10702
10703	return (frags);
10704}
10705
10706static void
10707initiate_write_bmsafemap(bmsafemap, bp)
10708	struct bmsafemap *bmsafemap;
10709	struct buf *bp;			/* The cg block. */
10710{
10711	struct jaddref *jaddref;
10712	struct jnewblk *jnewblk;
10713	uint8_t *inosused;
10714	uint8_t *blksfree;
10715	struct cg *cgp;
10716	struct fs *fs;
10717	ino_t ino;
10718
10719	if (bmsafemap->sm_state & IOSTARTED)
10720		return;
10721	bmsafemap->sm_state |= IOSTARTED;
10722	/*
10723	 * Clear any inode allocations which are pending journal writes.
10724	 */
10725	if (LIST_FIRST(&bmsafemap->sm_jaddrefhd) != NULL) {
10726		cgp = (struct cg *)bp->b_data;
10727		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
10728		inosused = cg_inosused(cgp);
10729		LIST_FOREACH(jaddref, &bmsafemap->sm_jaddrefhd, ja_bmdeps) {
10730			ino = jaddref->ja_ino % fs->fs_ipg;
10731			if (isset(inosused, ino)) {
10732				if ((jaddref->ja_mode & IFMT) == IFDIR)
10733					cgp->cg_cs.cs_ndir--;
10734				cgp->cg_cs.cs_nifree++;
10735				clrbit(inosused, ino);
10736				jaddref->ja_state &= ~ATTACHED;
10737				jaddref->ja_state |= UNDONE;
10738				stat_jaddref++;
10739			} else
10740				panic("initiate_write_bmsafemap: inode %ju "
10741				    "marked free", (uintmax_t)jaddref->ja_ino);
10742		}
10743	}
10744	/*
10745	 * Clear any block allocations which are pending journal writes.
10746	 */
10747	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
10748		cgp = (struct cg *)bp->b_data;
10749		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
10750		blksfree = cg_blksfree(cgp);
10751		LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
10752			if (jnewblk_rollback(jnewblk, fs, cgp, blksfree))
10753				continue;
10754			panic("initiate_write_bmsafemap: block %jd "
10755			    "marked free", jnewblk->jn_blkno);
10756		}
10757	}
10758	/*
10759	 * Move allocation lists to the written lists so they can be
10760	 * cleared once the block write is complete.
10761	 */
10762	LIST_SWAP(&bmsafemap->sm_inodedephd, &bmsafemap->sm_inodedepwr,
10763	    inodedep, id_deps);
10764	LIST_SWAP(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
10765	    newblk, nb_deps);
10766	LIST_SWAP(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr, worklist,
10767	    wk_list);
10768}
10769
10770/*
10771 * This routine is called during the completion interrupt
10772 * service routine for a disk write (from the procedure called
10773 * by the device driver to inform the filesystem caches of
10774 * a request completion).  It should be called early in this
10775 * procedure, before the block is made available to other
10776 * processes or other routines are called.
10777 *
10778 */
10779static void
10780softdep_disk_write_complete(bp)
10781	struct buf *bp;		/* describes the completed disk write */
10782{
10783	struct worklist *wk;
10784	struct worklist *owk;
10785	struct ufsmount *ump;
10786	struct workhead reattach;
10787	struct freeblks *freeblks;
10788	struct buf *sbp;
10789
10790	/*
10791	 * If an error occurred while doing the write, then the data
10792	 * has not hit the disk and the dependencies cannot be unrolled.
10793	 */
10794	if ((bp->b_ioflags & BIO_ERROR) != 0 && (bp->b_flags & B_INVAL) == 0)
10795		return;
10796	if ((wk = LIST_FIRST(&bp->b_dep)) == NULL)
10797		return;
10798	ump = VFSTOUFS(wk->wk_mp);
10799	LIST_INIT(&reattach);
10800	/*
10801	 * This lock must not be released anywhere in this code segment.
10802	 */
10803	sbp = NULL;
10804	owk = NULL;
10805	ACQUIRE_LOCK(ump);
10806	while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
10807		WORKLIST_REMOVE(wk);
10808		dep_write[wk->wk_type]++;
10809		if (wk == owk)
10810			panic("duplicate worklist: %p\n", wk);
10811		owk = wk;
10812		switch (wk->wk_type) {
10813
10814		case D_PAGEDEP:
10815			if (handle_written_filepage(WK_PAGEDEP(wk), bp))
10816				WORKLIST_INSERT(&reattach, wk);
10817			continue;
10818
10819		case D_INODEDEP:
10820			if (handle_written_inodeblock(WK_INODEDEP(wk), bp))
10821				WORKLIST_INSERT(&reattach, wk);
10822			continue;
10823
10824		case D_BMSAFEMAP:
10825			if (handle_written_bmsafemap(WK_BMSAFEMAP(wk), bp))
10826				WORKLIST_INSERT(&reattach, wk);
10827			continue;
10828
10829		case D_MKDIR:
10830			handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
10831			continue;
10832
10833		case D_ALLOCDIRECT:
10834			wk->wk_state |= COMPLETE;
10835			handle_allocdirect_partdone(WK_ALLOCDIRECT(wk), NULL);
10836			continue;
10837
10838		case D_ALLOCINDIR:
10839			wk->wk_state |= COMPLETE;
10840			handle_allocindir_partdone(WK_ALLOCINDIR(wk));
10841			continue;
10842
10843		case D_INDIRDEP:
10844			if (handle_written_indirdep(WK_INDIRDEP(wk), bp, &sbp))
10845				WORKLIST_INSERT(&reattach, wk);
10846			continue;
10847
10848		case D_FREEBLKS:
10849			wk->wk_state |= COMPLETE;
10850			freeblks = WK_FREEBLKS(wk);
10851			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE &&
10852			    LIST_EMPTY(&freeblks->fb_jblkdephd))
10853				add_to_worklist(wk, WK_NODELAY);
10854			continue;
10855
10856		case D_FREEWORK:
10857			handle_written_freework(WK_FREEWORK(wk));
10858			break;
10859
10860		case D_JSEGDEP:
10861			free_jsegdep(WK_JSEGDEP(wk));
10862			continue;
10863
10864		case D_JSEG:
10865			handle_written_jseg(WK_JSEG(wk), bp);
10866			continue;
10867
10868		case D_SBDEP:
10869			if (handle_written_sbdep(WK_SBDEP(wk), bp))
10870				WORKLIST_INSERT(&reattach, wk);
10871			continue;
10872
10873		case D_FREEDEP:
10874			free_freedep(WK_FREEDEP(wk));
10875			continue;
10876
10877		default:
10878			panic("handle_disk_write_complete: Unknown type %s",
10879			    TYPENAME(wk->wk_type));
10880			/* NOTREACHED */
10881		}
10882	}
10883	/*
10884	 * Reattach any requests that must be redone.
10885	 */
10886	while ((wk = LIST_FIRST(&reattach)) != NULL) {
10887		WORKLIST_REMOVE(wk);
10888		WORKLIST_INSERT(&bp->b_dep, wk);
10889	}
10890	FREE_LOCK(ump);
10891	if (sbp)
10892		brelse(sbp);
10893}
10894
10895/*
10896 * Called from within softdep_disk_write_complete above. Note that
10897 * this routine is always called from interrupt level with further
10898 * splbio interrupts blocked.
10899 */
10900static void
10901handle_allocdirect_partdone(adp, wkhd)
10902	struct allocdirect *adp;	/* the completed allocdirect */
10903	struct workhead *wkhd;		/* Work to do when inode is writtne. */
10904{
10905	struct allocdirectlst *listhead;
10906	struct allocdirect *listadp;
10907	struct inodedep *inodedep;
10908	long bsize;
10909
10910	if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
10911		return;
10912	/*
10913	 * The on-disk inode cannot claim to be any larger than the last
10914	 * fragment that has been written. Otherwise, the on-disk inode
10915	 * might have fragments that were not the last block in the file
10916	 * which would corrupt the filesystem. Thus, we cannot free any
10917	 * allocdirects after one whose ad_oldblkno claims a fragment as
10918	 * these blocks must be rolled back to zero before writing the inode.
10919	 * We check the currently active set of allocdirects in id_inoupdt
10920	 * or id_extupdt as appropriate.
10921	 */
10922	inodedep = adp->ad_inodedep;
10923	bsize = inodedep->id_fs->fs_bsize;
10924	if (adp->ad_state & EXTDATA)
10925		listhead = &inodedep->id_extupdt;
10926	else
10927		listhead = &inodedep->id_inoupdt;
10928	TAILQ_FOREACH(listadp, listhead, ad_next) {
10929		/* found our block */
10930		if (listadp == adp)
10931			break;
10932		/* continue if ad_oldlbn is not a fragment */
10933		if (listadp->ad_oldsize == 0 ||
10934		    listadp->ad_oldsize == bsize)
10935			continue;
10936		/* hit a fragment */
10937		return;
10938	}
10939	/*
10940	 * If we have reached the end of the current list without
10941	 * finding the just finished dependency, then it must be
10942	 * on the future dependency list. Future dependencies cannot
10943	 * be freed until they are moved to the current list.
10944	 */
10945	if (listadp == NULL) {
10946#ifdef DEBUG
10947		if (adp->ad_state & EXTDATA)
10948			listhead = &inodedep->id_newextupdt;
10949		else
10950			listhead = &inodedep->id_newinoupdt;
10951		TAILQ_FOREACH(listadp, listhead, ad_next)
10952			/* found our block */
10953			if (listadp == adp)
10954				break;
10955		if (listadp == NULL)
10956			panic("handle_allocdirect_partdone: lost dep");
10957#endif /* DEBUG */
10958		return;
10959	}
10960	/*
10961	 * If we have found the just finished dependency, then queue
10962	 * it along with anything that follows it that is complete.
10963	 * Since the pointer has not yet been written in the inode
10964	 * as the dependency prevents it, place the allocdirect on the
10965	 * bufwait list where it will be freed once the pointer is
10966	 * valid.
10967	 */
10968	if (wkhd == NULL)
10969		wkhd = &inodedep->id_bufwait;
10970	for (; adp; adp = listadp) {
10971		listadp = TAILQ_NEXT(adp, ad_next);
10972		if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
10973			return;
10974		TAILQ_REMOVE(listhead, adp, ad_next);
10975		WORKLIST_INSERT(wkhd, &adp->ad_block.nb_list);
10976	}
10977}
10978
10979/*
10980 * Called from within softdep_disk_write_complete above.  This routine
10981 * completes successfully written allocindirs.
10982 */
10983static void
10984handle_allocindir_partdone(aip)
10985	struct allocindir *aip;		/* the completed allocindir */
10986{
10987	struct indirdep *indirdep;
10988
10989	if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
10990		return;
10991	indirdep = aip->ai_indirdep;
10992	LIST_REMOVE(aip, ai_next);
10993	/*
10994	 * Don't set a pointer while the buffer is undergoing IO or while
10995	 * we have active truncations.
10996	 */
10997	if (indirdep->ir_state & UNDONE || !TAILQ_EMPTY(&indirdep->ir_trunc)) {
10998		LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
10999		return;
11000	}
11001	if (indirdep->ir_state & UFS1FMT)
11002		((ufs1_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11003		    aip->ai_newblkno;
11004	else
11005		((ufs2_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11006		    aip->ai_newblkno;
11007	/*
11008	 * Await the pointer write before freeing the allocindir.
11009	 */
11010	LIST_INSERT_HEAD(&indirdep->ir_writehd, aip, ai_next);
11011}
11012
11013/*
11014 * Release segments held on a jwork list.
11015 */
11016static void
11017handle_jwork(wkhd)
11018	struct workhead *wkhd;
11019{
11020	struct worklist *wk;
11021
11022	while ((wk = LIST_FIRST(wkhd)) != NULL) {
11023		WORKLIST_REMOVE(wk);
11024		switch (wk->wk_type) {
11025		case D_JSEGDEP:
11026			free_jsegdep(WK_JSEGDEP(wk));
11027			continue;
11028		case D_FREEDEP:
11029			free_freedep(WK_FREEDEP(wk));
11030			continue;
11031		case D_FREEFRAG:
11032			rele_jseg(WK_JSEG(WK_FREEFRAG(wk)->ff_jdep));
11033			WORKITEM_FREE(wk, D_FREEFRAG);
11034			continue;
11035		case D_FREEWORK:
11036			handle_written_freework(WK_FREEWORK(wk));
11037			continue;
11038		default:
11039			panic("handle_jwork: Unknown type %s\n",
11040			    TYPENAME(wk->wk_type));
11041		}
11042	}
11043}
11044
11045/*
11046 * Handle the bufwait list on an inode when it is safe to release items
11047 * held there.  This normally happens after an inode block is written but
11048 * may be delayed and handled later if there are pending journal items that
11049 * are not yet safe to be released.
11050 */
11051static struct freefile *
11052handle_bufwait(inodedep, refhd)
11053	struct inodedep *inodedep;
11054	struct workhead *refhd;
11055{
11056	struct jaddref *jaddref;
11057	struct freefile *freefile;
11058	struct worklist *wk;
11059
11060	freefile = NULL;
11061	while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
11062		WORKLIST_REMOVE(wk);
11063		switch (wk->wk_type) {
11064		case D_FREEFILE:
11065			/*
11066			 * We defer adding freefile to the worklist
11067			 * until all other additions have been made to
11068			 * ensure that it will be done after all the
11069			 * old blocks have been freed.
11070			 */
11071			if (freefile != NULL)
11072				panic("handle_bufwait: freefile");
11073			freefile = WK_FREEFILE(wk);
11074			continue;
11075
11076		case D_MKDIR:
11077			handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
11078			continue;
11079
11080		case D_DIRADD:
11081			diradd_inode_written(WK_DIRADD(wk), inodedep);
11082			continue;
11083
11084		case D_FREEFRAG:
11085			wk->wk_state |= COMPLETE;
11086			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE)
11087				add_to_worklist(wk, 0);
11088			continue;
11089
11090		case D_DIRREM:
11091			wk->wk_state |= COMPLETE;
11092			add_to_worklist(wk, 0);
11093			continue;
11094
11095		case D_ALLOCDIRECT:
11096		case D_ALLOCINDIR:
11097			free_newblk(WK_NEWBLK(wk));
11098			continue;
11099
11100		case D_JNEWBLK:
11101			wk->wk_state |= COMPLETE;
11102			free_jnewblk(WK_JNEWBLK(wk));
11103			continue;
11104
11105		/*
11106		 * Save freed journal segments and add references on
11107		 * the supplied list which will delay their release
11108		 * until the cg bitmap is cleared on disk.
11109		 */
11110		case D_JSEGDEP:
11111			if (refhd == NULL)
11112				free_jsegdep(WK_JSEGDEP(wk));
11113			else
11114				WORKLIST_INSERT(refhd, wk);
11115			continue;
11116
11117		case D_JADDREF:
11118			jaddref = WK_JADDREF(wk);
11119			TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
11120			    if_deps);
11121			/*
11122			 * Transfer any jaddrefs to the list to be freed with
11123			 * the bitmap if we're handling a removed file.
11124			 */
11125			if (refhd == NULL) {
11126				wk->wk_state |= COMPLETE;
11127				free_jaddref(jaddref);
11128			} else
11129				WORKLIST_INSERT(refhd, wk);
11130			continue;
11131
11132		default:
11133			panic("handle_bufwait: Unknown type %p(%s)",
11134			    wk, TYPENAME(wk->wk_type));
11135			/* NOTREACHED */
11136		}
11137	}
11138	return (freefile);
11139}
11140/*
11141 * Called from within softdep_disk_write_complete above to restore
11142 * in-memory inode block contents to their most up-to-date state. Note
11143 * that this routine is always called from interrupt level with further
11144 * splbio interrupts blocked.
11145 */
11146static int
11147handle_written_inodeblock(inodedep, bp)
11148	struct inodedep *inodedep;
11149	struct buf *bp;		/* buffer containing the inode block */
11150{
11151	struct freefile *freefile;
11152	struct allocdirect *adp, *nextadp;
11153	struct ufs1_dinode *dp1 = NULL;
11154	struct ufs2_dinode *dp2 = NULL;
11155	struct workhead wkhd;
11156	int hadchanges, fstype;
11157	ino_t freelink;
11158
11159	LIST_INIT(&wkhd);
11160	hadchanges = 0;
11161	freefile = NULL;
11162	if ((inodedep->id_state & IOSTARTED) == 0)
11163		panic("handle_written_inodeblock: not started");
11164	inodedep->id_state &= ~IOSTARTED;
11165	if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC) {
11166		fstype = UFS1;
11167		dp1 = (struct ufs1_dinode *)bp->b_data +
11168		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11169		freelink = dp1->di_freelink;
11170	} else {
11171		fstype = UFS2;
11172		dp2 = (struct ufs2_dinode *)bp->b_data +
11173		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11174		freelink = dp2->di_freelink;
11175	}
11176	/*
11177	 * Leave this inodeblock dirty until it's in the list.
11178	 */
11179	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) == UNLINKED) {
11180		struct inodedep *inon;
11181
11182		inon = TAILQ_NEXT(inodedep, id_unlinked);
11183		if ((inon == NULL && freelink == 0) ||
11184		    (inon && inon->id_ino == freelink)) {
11185			if (inon)
11186				inon->id_state |= UNLINKPREV;
11187			inodedep->id_state |= UNLINKNEXT;
11188		}
11189		hadchanges = 1;
11190	}
11191	/*
11192	 * If we had to rollback the inode allocation because of
11193	 * bitmaps being incomplete, then simply restore it.
11194	 * Keep the block dirty so that it will not be reclaimed until
11195	 * all associated dependencies have been cleared and the
11196	 * corresponding updates written to disk.
11197	 */
11198	if (inodedep->id_savedino1 != NULL) {
11199		hadchanges = 1;
11200		if (fstype == UFS1)
11201			*dp1 = *inodedep->id_savedino1;
11202		else
11203			*dp2 = *inodedep->id_savedino2;
11204		free(inodedep->id_savedino1, M_SAVEDINO);
11205		inodedep->id_savedino1 = NULL;
11206		if ((bp->b_flags & B_DELWRI) == 0)
11207			stat_inode_bitmap++;
11208		bdirty(bp);
11209		/*
11210		 * If the inode is clear here and GOINGAWAY it will never
11211		 * be written.  Process the bufwait and clear any pending
11212		 * work which may include the freefile.
11213		 */
11214		if (inodedep->id_state & GOINGAWAY)
11215			goto bufwait;
11216		return (1);
11217	}
11218	inodedep->id_state |= COMPLETE;
11219	/*
11220	 * Roll forward anything that had to be rolled back before
11221	 * the inode could be updated.
11222	 */
11223	for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
11224		nextadp = TAILQ_NEXT(adp, ad_next);
11225		if (adp->ad_state & ATTACHED)
11226			panic("handle_written_inodeblock: new entry");
11227		if (fstype == UFS1) {
11228			if (adp->ad_offset < NDADDR) {
11229				if (dp1->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11230					panic("%s %s #%jd mismatch %d != %jd",
11231					    "handle_written_inodeblock:",
11232					    "direct pointer",
11233					    (intmax_t)adp->ad_offset,
11234					    dp1->di_db[adp->ad_offset],
11235					    (intmax_t)adp->ad_oldblkno);
11236				dp1->di_db[adp->ad_offset] = adp->ad_newblkno;
11237			} else {
11238				if (dp1->di_ib[adp->ad_offset - NDADDR] != 0)
11239					panic("%s: %s #%jd allocated as %d",
11240					    "handle_written_inodeblock",
11241					    "indirect pointer",
11242					    (intmax_t)adp->ad_offset - NDADDR,
11243					    dp1->di_ib[adp->ad_offset - NDADDR]);
11244				dp1->di_ib[adp->ad_offset - NDADDR] =
11245				    adp->ad_newblkno;
11246			}
11247		} else {
11248			if (adp->ad_offset < NDADDR) {
11249				if (dp2->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11250					panic("%s: %s #%jd %s %jd != %jd",
11251					    "handle_written_inodeblock",
11252					    "direct pointer",
11253					    (intmax_t)adp->ad_offset, "mismatch",
11254					    (intmax_t)dp2->di_db[adp->ad_offset],
11255					    (intmax_t)adp->ad_oldblkno);
11256				dp2->di_db[adp->ad_offset] = adp->ad_newblkno;
11257			} else {
11258				if (dp2->di_ib[adp->ad_offset - NDADDR] != 0)
11259					panic("%s: %s #%jd allocated as %jd",
11260					    "handle_written_inodeblock",
11261					    "indirect pointer",
11262					    (intmax_t)adp->ad_offset - NDADDR,
11263					    (intmax_t)
11264					    dp2->di_ib[adp->ad_offset - NDADDR]);
11265				dp2->di_ib[adp->ad_offset - NDADDR] =
11266				    adp->ad_newblkno;
11267			}
11268		}
11269		adp->ad_state &= ~UNDONE;
11270		adp->ad_state |= ATTACHED;
11271		hadchanges = 1;
11272	}
11273	for (adp = TAILQ_FIRST(&inodedep->id_extupdt); adp; adp = nextadp) {
11274		nextadp = TAILQ_NEXT(adp, ad_next);
11275		if (adp->ad_state & ATTACHED)
11276			panic("handle_written_inodeblock: new entry");
11277		if (dp2->di_extb[adp->ad_offset] != adp->ad_oldblkno)
11278			panic("%s: direct pointers #%jd %s %jd != %jd",
11279			    "handle_written_inodeblock",
11280			    (intmax_t)adp->ad_offset, "mismatch",
11281			    (intmax_t)dp2->di_extb[adp->ad_offset],
11282			    (intmax_t)adp->ad_oldblkno);
11283		dp2->di_extb[adp->ad_offset] = adp->ad_newblkno;
11284		adp->ad_state &= ~UNDONE;
11285		adp->ad_state |= ATTACHED;
11286		hadchanges = 1;
11287	}
11288	if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
11289		stat_direct_blk_ptrs++;
11290	/*
11291	 * Reset the file size to its most up-to-date value.
11292	 */
11293	if (inodedep->id_savedsize == -1 || inodedep->id_savedextsize == -1)
11294		panic("handle_written_inodeblock: bad size");
11295	if (inodedep->id_savednlink > LINK_MAX)
11296		panic("handle_written_inodeblock: Invalid link count "
11297		    "%d for inodedep %p", inodedep->id_savednlink, inodedep);
11298	if (fstype == UFS1) {
11299		if (dp1->di_nlink != inodedep->id_savednlink) {
11300			dp1->di_nlink = inodedep->id_savednlink;
11301			hadchanges = 1;
11302		}
11303		if (dp1->di_size != inodedep->id_savedsize) {
11304			dp1->di_size = inodedep->id_savedsize;
11305			hadchanges = 1;
11306		}
11307	} else {
11308		if (dp2->di_nlink != inodedep->id_savednlink) {
11309			dp2->di_nlink = inodedep->id_savednlink;
11310			hadchanges = 1;
11311		}
11312		if (dp2->di_size != inodedep->id_savedsize) {
11313			dp2->di_size = inodedep->id_savedsize;
11314			hadchanges = 1;
11315		}
11316		if (dp2->di_extsize != inodedep->id_savedextsize) {
11317			dp2->di_extsize = inodedep->id_savedextsize;
11318			hadchanges = 1;
11319		}
11320	}
11321	inodedep->id_savedsize = -1;
11322	inodedep->id_savedextsize = -1;
11323	inodedep->id_savednlink = -1;
11324	/*
11325	 * If there were any rollbacks in the inode block, then it must be
11326	 * marked dirty so that its will eventually get written back in
11327	 * its correct form.
11328	 */
11329	if (hadchanges)
11330		bdirty(bp);
11331bufwait:
11332	/*
11333	 * Process any allocdirects that completed during the update.
11334	 */
11335	if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
11336		handle_allocdirect_partdone(adp, &wkhd);
11337	if ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
11338		handle_allocdirect_partdone(adp, &wkhd);
11339	/*
11340	 * Process deallocations that were held pending until the
11341	 * inode had been written to disk. Freeing of the inode
11342	 * is delayed until after all blocks have been freed to
11343	 * avoid creation of new <vfsid, inum, lbn> triples
11344	 * before the old ones have been deleted.  Completely
11345	 * unlinked inodes are not processed until the unlinked
11346	 * inode list is written or the last reference is removed.
11347	 */
11348	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) != UNLINKED) {
11349		freefile = handle_bufwait(inodedep, NULL);
11350		if (freefile && !LIST_EMPTY(&wkhd)) {
11351			WORKLIST_INSERT(&wkhd, &freefile->fx_list);
11352			freefile = NULL;
11353		}
11354	}
11355	/*
11356	 * Move rolled forward dependency completions to the bufwait list
11357	 * now that those that were already written have been processed.
11358	 */
11359	if (!LIST_EMPTY(&wkhd) && hadchanges == 0)
11360		panic("handle_written_inodeblock: bufwait but no changes");
11361	jwork_move(&inodedep->id_bufwait, &wkhd);
11362
11363	if (freefile != NULL) {
11364		/*
11365		 * If the inode is goingaway it was never written.  Fake up
11366		 * the state here so free_inodedep() can succeed.
11367		 */
11368		if (inodedep->id_state & GOINGAWAY)
11369			inodedep->id_state |= COMPLETE | DEPCOMPLETE;
11370		if (free_inodedep(inodedep) == 0)
11371			panic("handle_written_inodeblock: live inodedep %p",
11372			    inodedep);
11373		add_to_worklist(&freefile->fx_list, 0);
11374		return (0);
11375	}
11376
11377	/*
11378	 * If no outstanding dependencies, free it.
11379	 */
11380	if (free_inodedep(inodedep) ||
11381	    (TAILQ_FIRST(&inodedep->id_inoreflst) == 0 &&
11382	     TAILQ_FIRST(&inodedep->id_inoupdt) == 0 &&
11383	     TAILQ_FIRST(&inodedep->id_extupdt) == 0 &&
11384	     LIST_FIRST(&inodedep->id_bufwait) == 0))
11385		return (0);
11386	return (hadchanges);
11387}
11388
11389static int
11390handle_written_indirdep(indirdep, bp, bpp)
11391	struct indirdep *indirdep;
11392	struct buf *bp;
11393	struct buf **bpp;
11394{
11395	struct allocindir *aip;
11396	struct buf *sbp;
11397	int chgs;
11398
11399	if (indirdep->ir_state & GOINGAWAY)
11400		panic("handle_written_indirdep: indirdep gone");
11401	if ((indirdep->ir_state & IOSTARTED) == 0)
11402		panic("handle_written_indirdep: IO not started");
11403	chgs = 0;
11404	/*
11405	 * If there were rollbacks revert them here.
11406	 */
11407	if (indirdep->ir_saveddata) {
11408		bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
11409		if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11410			free(indirdep->ir_saveddata, M_INDIRDEP);
11411			indirdep->ir_saveddata = NULL;
11412		}
11413		chgs = 1;
11414	}
11415	indirdep->ir_state &= ~(UNDONE | IOSTARTED);
11416	indirdep->ir_state |= ATTACHED;
11417	/*
11418	 * Move allocindirs with written pointers to the completehd if
11419	 * the indirdep's pointer is not yet written.  Otherwise
11420	 * free them here.
11421	 */
11422	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != 0) {
11423		LIST_REMOVE(aip, ai_next);
11424		if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
11425			LIST_INSERT_HEAD(&indirdep->ir_completehd, aip,
11426			    ai_next);
11427			newblk_freefrag(&aip->ai_block);
11428			continue;
11429		}
11430		free_newblk(&aip->ai_block);
11431	}
11432	/*
11433	 * Move allocindirs that have finished dependency processing from
11434	 * the done list to the write list after updating the pointers.
11435	 */
11436	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11437		while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != 0) {
11438			handle_allocindir_partdone(aip);
11439			if (aip == LIST_FIRST(&indirdep->ir_donehd))
11440				panic("disk_write_complete: not gone");
11441			chgs = 1;
11442		}
11443	}
11444	/*
11445	 * Preserve the indirdep if there were any changes or if it is not
11446	 * yet valid on disk.
11447	 */
11448	if (chgs) {
11449		stat_indir_blk_ptrs++;
11450		bdirty(bp);
11451		return (1);
11452	}
11453	/*
11454	 * If there were no changes we can discard the savedbp and detach
11455	 * ourselves from the buf.  We are only carrying completed pointers
11456	 * in this case.
11457	 */
11458	sbp = indirdep->ir_savebp;
11459	sbp->b_flags |= B_INVAL | B_NOCACHE;
11460	indirdep->ir_savebp = NULL;
11461	indirdep->ir_bp = NULL;
11462	if (*bpp != NULL)
11463		panic("handle_written_indirdep: bp already exists.");
11464	*bpp = sbp;
11465	/*
11466	 * The indirdep may not be freed until its parent points at it.
11467	 */
11468	if (indirdep->ir_state & DEPCOMPLETE)
11469		free_indirdep(indirdep);
11470
11471	return (0);
11472}
11473
11474/*
11475 * Process a diradd entry after its dependent inode has been written.
11476 * This routine must be called with splbio interrupts blocked.
11477 */
11478static void
11479diradd_inode_written(dap, inodedep)
11480	struct diradd *dap;
11481	struct inodedep *inodedep;
11482{
11483
11484	dap->da_state |= COMPLETE;
11485	complete_diradd(dap);
11486	WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
11487}
11488
11489/*
11490 * Returns true if the bmsafemap will have rollbacks when written.  Must only
11491 * be called with the soft updates lock and the buf lock on the cg held.
11492 */
11493static int
11494bmsafemap_backgroundwrite(bmsafemap, bp)
11495	struct bmsafemap *bmsafemap;
11496	struct buf *bp;
11497{
11498	int dirty;
11499
11500	LOCK_OWNED(VFSTOUFS(bmsafemap->sm_list.wk_mp));
11501	dirty = !LIST_EMPTY(&bmsafemap->sm_jaddrefhd) |
11502	    !LIST_EMPTY(&bmsafemap->sm_jnewblkhd);
11503	/*
11504	 * If we're initiating a background write we need to process the
11505	 * rollbacks as they exist now, not as they exist when IO starts.
11506	 * No other consumers will look at the contents of the shadowed
11507	 * buf so this is safe to do here.
11508	 */
11509	if (bp->b_xflags & BX_BKGRDMARKER)
11510		initiate_write_bmsafemap(bmsafemap, bp);
11511
11512	return (dirty);
11513}
11514
11515/*
11516 * Re-apply an allocation when a cg write is complete.
11517 */
11518static int
11519jnewblk_rollforward(jnewblk, fs, cgp, blksfree)
11520	struct jnewblk *jnewblk;
11521	struct fs *fs;
11522	struct cg *cgp;
11523	uint8_t *blksfree;
11524{
11525	ufs1_daddr_t fragno;
11526	ufs2_daddr_t blkno;
11527	long cgbno, bbase;
11528	int frags, blk;
11529	int i;
11530
11531	frags = 0;
11532	cgbno = dtogd(fs, jnewblk->jn_blkno);
11533	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++) {
11534		if (isclr(blksfree, cgbno + i))
11535			panic("jnewblk_rollforward: re-allocated fragment");
11536		frags++;
11537	}
11538	if (frags == fs->fs_frag) {
11539		blkno = fragstoblks(fs, cgbno);
11540		ffs_clrblock(fs, blksfree, (long)blkno);
11541		ffs_clusteracct(fs, cgp, blkno, -1);
11542		cgp->cg_cs.cs_nbfree--;
11543	} else {
11544		bbase = cgbno - fragnum(fs, cgbno);
11545		cgbno += jnewblk->jn_oldfrags;
11546                /* If a complete block had been reassembled, account for it. */
11547		fragno = fragstoblks(fs, bbase);
11548		if (ffs_isblock(fs, blksfree, fragno)) {
11549			cgp->cg_cs.cs_nffree += fs->fs_frag;
11550			ffs_clusteracct(fs, cgp, fragno, -1);
11551			cgp->cg_cs.cs_nbfree--;
11552		}
11553		/* Decrement the old frags.  */
11554		blk = blkmap(fs, blksfree, bbase);
11555		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
11556		/* Allocate the fragment */
11557		for (i = 0; i < frags; i++)
11558			clrbit(blksfree, cgbno + i);
11559		cgp->cg_cs.cs_nffree -= frags;
11560		/* Add back in counts associated with the new frags */
11561		blk = blkmap(fs, blksfree, bbase);
11562		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
11563	}
11564	return (frags);
11565}
11566
11567/*
11568 * Complete a write to a bmsafemap structure.  Roll forward any bitmap
11569 * changes if it's not a background write.  Set all written dependencies
11570 * to DEPCOMPLETE and free the structure if possible.
11571 */
11572static int
11573handle_written_bmsafemap(bmsafemap, bp)
11574	struct bmsafemap *bmsafemap;
11575	struct buf *bp;
11576{
11577	struct newblk *newblk;
11578	struct inodedep *inodedep;
11579	struct jaddref *jaddref, *jatmp;
11580	struct jnewblk *jnewblk, *jntmp;
11581	struct ufsmount *ump;
11582	uint8_t *inosused;
11583	uint8_t *blksfree;
11584	struct cg *cgp;
11585	struct fs *fs;
11586	ino_t ino;
11587	int foreground;
11588	int chgs;
11589
11590	if ((bmsafemap->sm_state & IOSTARTED) == 0)
11591		panic("initiate_write_bmsafemap: Not started\n");
11592	ump = VFSTOUFS(bmsafemap->sm_list.wk_mp);
11593	chgs = 0;
11594	bmsafemap->sm_state &= ~IOSTARTED;
11595	foreground = (bp->b_xflags & BX_BKGRDMARKER) == 0;
11596	/*
11597	 * Release journal work that was waiting on the write.
11598	 */
11599	handle_jwork(&bmsafemap->sm_freewr);
11600
11601	/*
11602	 * Restore unwritten inode allocation pending jaddref writes.
11603	 */
11604	if (!LIST_EMPTY(&bmsafemap->sm_jaddrefhd)) {
11605		cgp = (struct cg *)bp->b_data;
11606		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11607		inosused = cg_inosused(cgp);
11608		LIST_FOREACH_SAFE(jaddref, &bmsafemap->sm_jaddrefhd,
11609		    ja_bmdeps, jatmp) {
11610			if ((jaddref->ja_state & UNDONE) == 0)
11611				continue;
11612			ino = jaddref->ja_ino % fs->fs_ipg;
11613			if (isset(inosused, ino))
11614				panic("handle_written_bmsafemap: "
11615				    "re-allocated inode");
11616			/* Do the roll-forward only if it's a real copy. */
11617			if (foreground) {
11618				if ((jaddref->ja_mode & IFMT) == IFDIR)
11619					cgp->cg_cs.cs_ndir++;
11620				cgp->cg_cs.cs_nifree--;
11621				setbit(inosused, ino);
11622				chgs = 1;
11623			}
11624			jaddref->ja_state &= ~UNDONE;
11625			jaddref->ja_state |= ATTACHED;
11626			free_jaddref(jaddref);
11627		}
11628	}
11629	/*
11630	 * Restore any block allocations which are pending journal writes.
11631	 */
11632	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
11633		cgp = (struct cg *)bp->b_data;
11634		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11635		blksfree = cg_blksfree(cgp);
11636		LIST_FOREACH_SAFE(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps,
11637		    jntmp) {
11638			if ((jnewblk->jn_state & UNDONE) == 0)
11639				continue;
11640			/* Do the roll-forward only if it's a real copy. */
11641			if (foreground &&
11642			    jnewblk_rollforward(jnewblk, fs, cgp, blksfree))
11643				chgs = 1;
11644			jnewblk->jn_state &= ~(UNDONE | NEWBLOCK);
11645			jnewblk->jn_state |= ATTACHED;
11646			free_jnewblk(jnewblk);
11647		}
11648	}
11649	while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkwr))) {
11650		newblk->nb_state |= DEPCOMPLETE;
11651		newblk->nb_state &= ~ONDEPLIST;
11652		newblk->nb_bmsafemap = NULL;
11653		LIST_REMOVE(newblk, nb_deps);
11654		if (newblk->nb_list.wk_type == D_ALLOCDIRECT)
11655			handle_allocdirect_partdone(
11656			    WK_ALLOCDIRECT(&newblk->nb_list), NULL);
11657		else if (newblk->nb_list.wk_type == D_ALLOCINDIR)
11658			handle_allocindir_partdone(
11659			    WK_ALLOCINDIR(&newblk->nb_list));
11660		else if (newblk->nb_list.wk_type != D_NEWBLK)
11661			panic("handle_written_bmsafemap: Unexpected type: %s",
11662			    TYPENAME(newblk->nb_list.wk_type));
11663	}
11664	while ((inodedep = LIST_FIRST(&bmsafemap->sm_inodedepwr)) != NULL) {
11665		inodedep->id_state |= DEPCOMPLETE;
11666		inodedep->id_state &= ~ONDEPLIST;
11667		LIST_REMOVE(inodedep, id_deps);
11668		inodedep->id_bmsafemap = NULL;
11669	}
11670	LIST_REMOVE(bmsafemap, sm_next);
11671	if (chgs == 0 && LIST_EMPTY(&bmsafemap->sm_jaddrefhd) &&
11672	    LIST_EMPTY(&bmsafemap->sm_jnewblkhd) &&
11673	    LIST_EMPTY(&bmsafemap->sm_newblkhd) &&
11674	    LIST_EMPTY(&bmsafemap->sm_inodedephd) &&
11675	    LIST_EMPTY(&bmsafemap->sm_freehd)) {
11676		LIST_REMOVE(bmsafemap, sm_hash);
11677		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
11678		return (0);
11679	}
11680	LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
11681	if (foreground)
11682		bdirty(bp);
11683	return (1);
11684}
11685
11686/*
11687 * Try to free a mkdir dependency.
11688 */
11689static void
11690complete_mkdir(mkdir)
11691	struct mkdir *mkdir;
11692{
11693	struct diradd *dap;
11694
11695	if ((mkdir->md_state & ALLCOMPLETE) != ALLCOMPLETE)
11696		return;
11697	LIST_REMOVE(mkdir, md_mkdirs);
11698	dap = mkdir->md_diradd;
11699	dap->da_state &= ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
11700	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0) {
11701		dap->da_state |= DEPCOMPLETE;
11702		complete_diradd(dap);
11703	}
11704	WORKITEM_FREE(mkdir, D_MKDIR);
11705}
11706
11707/*
11708 * Handle the completion of a mkdir dependency.
11709 */
11710static void
11711handle_written_mkdir(mkdir, type)
11712	struct mkdir *mkdir;
11713	int type;
11714{
11715
11716	if ((mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY)) != type)
11717		panic("handle_written_mkdir: bad type");
11718	mkdir->md_state |= COMPLETE;
11719	complete_mkdir(mkdir);
11720}
11721
11722static int
11723free_pagedep(pagedep)
11724	struct pagedep *pagedep;
11725{
11726	int i;
11727
11728	if (pagedep->pd_state & NEWBLOCK)
11729		return (0);
11730	if (!LIST_EMPTY(&pagedep->pd_dirremhd))
11731		return (0);
11732	for (i = 0; i < DAHASHSZ; i++)
11733		if (!LIST_EMPTY(&pagedep->pd_diraddhd[i]))
11734			return (0);
11735	if (!LIST_EMPTY(&pagedep->pd_pendinghd))
11736		return (0);
11737	if (!LIST_EMPTY(&pagedep->pd_jmvrefhd))
11738		return (0);
11739	if (pagedep->pd_state & ONWORKLIST)
11740		WORKLIST_REMOVE(&pagedep->pd_list);
11741	LIST_REMOVE(pagedep, pd_hash);
11742	WORKITEM_FREE(pagedep, D_PAGEDEP);
11743
11744	return (1);
11745}
11746
11747/*
11748 * Called from within softdep_disk_write_complete above.
11749 * A write operation was just completed. Removed inodes can
11750 * now be freed and associated block pointers may be committed.
11751 * Note that this routine is always called from interrupt level
11752 * with further splbio interrupts blocked.
11753 */
11754static int
11755handle_written_filepage(pagedep, bp)
11756	struct pagedep *pagedep;
11757	struct buf *bp;		/* buffer containing the written page */
11758{
11759	struct dirrem *dirrem;
11760	struct diradd *dap, *nextdap;
11761	struct direct *ep;
11762	int i, chgs;
11763
11764	if ((pagedep->pd_state & IOSTARTED) == 0)
11765		panic("handle_written_filepage: not started");
11766	pagedep->pd_state &= ~IOSTARTED;
11767	/*
11768	 * Process any directory removals that have been committed.
11769	 */
11770	while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
11771		LIST_REMOVE(dirrem, dm_next);
11772		dirrem->dm_state |= COMPLETE;
11773		dirrem->dm_dirinum = pagedep->pd_ino;
11774		KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
11775		    ("handle_written_filepage: Journal entries not written."));
11776		add_to_worklist(&dirrem->dm_list, 0);
11777	}
11778	/*
11779	 * Free any directory additions that have been committed.
11780	 * If it is a newly allocated block, we have to wait until
11781	 * the on-disk directory inode claims the new block.
11782	 */
11783	if ((pagedep->pd_state & NEWBLOCK) == 0)
11784		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
11785			free_diradd(dap, NULL);
11786	/*
11787	 * Uncommitted directory entries must be restored.
11788	 */
11789	for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
11790		for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
11791		     dap = nextdap) {
11792			nextdap = LIST_NEXT(dap, da_pdlist);
11793			if (dap->da_state & ATTACHED)
11794				panic("handle_written_filepage: attached");
11795			ep = (struct direct *)
11796			    ((char *)bp->b_data + dap->da_offset);
11797			ep->d_ino = dap->da_newinum;
11798			dap->da_state &= ~UNDONE;
11799			dap->da_state |= ATTACHED;
11800			chgs = 1;
11801			/*
11802			 * If the inode referenced by the directory has
11803			 * been written out, then the dependency can be
11804			 * moved to the pending list.
11805			 */
11806			if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
11807				LIST_REMOVE(dap, da_pdlist);
11808				LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
11809				    da_pdlist);
11810			}
11811		}
11812	}
11813	/*
11814	 * If there were any rollbacks in the directory, then it must be
11815	 * marked dirty so that its will eventually get written back in
11816	 * its correct form.
11817	 */
11818	if (chgs) {
11819		if ((bp->b_flags & B_DELWRI) == 0)
11820			stat_dir_entry++;
11821		bdirty(bp);
11822		return (1);
11823	}
11824	/*
11825	 * If we are not waiting for a new directory block to be
11826	 * claimed by its inode, then the pagedep will be freed.
11827	 * Otherwise it will remain to track any new entries on
11828	 * the page in case they are fsync'ed.
11829	 */
11830	free_pagedep(pagedep);
11831	return (0);
11832}
11833
11834/*
11835 * Writing back in-core inode structures.
11836 *
11837 * The filesystem only accesses an inode's contents when it occupies an
11838 * "in-core" inode structure.  These "in-core" structures are separate from
11839 * the page frames used to cache inode blocks.  Only the latter are
11840 * transferred to/from the disk.  So, when the updated contents of the
11841 * "in-core" inode structure are copied to the corresponding in-memory inode
11842 * block, the dependencies are also transferred.  The following procedure is
11843 * called when copying a dirty "in-core" inode to a cached inode block.
11844 */
11845
11846/*
11847 * Called when an inode is loaded from disk. If the effective link count
11848 * differed from the actual link count when it was last flushed, then we
11849 * need to ensure that the correct effective link count is put back.
11850 */
11851void
11852softdep_load_inodeblock(ip)
11853	struct inode *ip;	/* the "in_core" copy of the inode */
11854{
11855	struct inodedep *inodedep;
11856
11857	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ip->i_ump)) != 0,
11858	    ("softdep_load_inodeblock called on non-softdep filesystem"));
11859	/*
11860	 * Check for alternate nlink count.
11861	 */
11862	ip->i_effnlink = ip->i_nlink;
11863	ACQUIRE_LOCK(ip->i_ump);
11864	if (inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, 0,
11865	    &inodedep) == 0) {
11866		FREE_LOCK(ip->i_ump);
11867		return;
11868	}
11869	ip->i_effnlink -= inodedep->id_nlinkdelta;
11870	FREE_LOCK(ip->i_ump);
11871}
11872
11873/*
11874 * This routine is called just before the "in-core" inode
11875 * information is to be copied to the in-memory inode block.
11876 * Recall that an inode block contains several inodes. If
11877 * the force flag is set, then the dependencies will be
11878 * cleared so that the update can always be made. Note that
11879 * the buffer is locked when this routine is called, so we
11880 * will never be in the middle of writing the inode block
11881 * to disk.
11882 */
11883void
11884softdep_update_inodeblock(ip, bp, waitfor)
11885	struct inode *ip;	/* the "in_core" copy of the inode */
11886	struct buf *bp;		/* the buffer containing the inode block */
11887	int waitfor;		/* nonzero => update must be allowed */
11888{
11889	struct inodedep *inodedep;
11890	struct inoref *inoref;
11891	struct ufsmount *ump;
11892	struct worklist *wk;
11893	struct mount *mp;
11894	struct buf *ibp;
11895	struct fs *fs;
11896	int error;
11897
11898	ump = ip->i_ump;
11899	mp = UFSTOVFS(ump);
11900	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
11901	    ("softdep_update_inodeblock called on non-softdep filesystem"));
11902	fs = ip->i_fs;
11903	/*
11904	 * Preserve the freelink that is on disk.  clear_unlinked_inodedep()
11905	 * does not have access to the in-core ip so must write directly into
11906	 * the inode block buffer when setting freelink.
11907	 */
11908	if (fs->fs_magic == FS_UFS1_MAGIC)
11909		DIP_SET(ip, i_freelink, ((struct ufs1_dinode *)bp->b_data +
11910		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
11911	else
11912		DIP_SET(ip, i_freelink, ((struct ufs2_dinode *)bp->b_data +
11913		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
11914	/*
11915	 * If the effective link count is not equal to the actual link
11916	 * count, then we must track the difference in an inodedep while
11917	 * the inode is (potentially) tossed out of the cache. Otherwise,
11918	 * if there is no existing inodedep, then there are no dependencies
11919	 * to track.
11920	 */
11921	ACQUIRE_LOCK(ump);
11922again:
11923	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
11924		FREE_LOCK(ump);
11925		if (ip->i_effnlink != ip->i_nlink)
11926			panic("softdep_update_inodeblock: bad link count");
11927		return;
11928	}
11929	if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink)
11930		panic("softdep_update_inodeblock: bad delta");
11931	/*
11932	 * If we're flushing all dependencies we must also move any waiting
11933	 * for journal writes onto the bufwait list prior to I/O.
11934	 */
11935	if (waitfor) {
11936		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
11937			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
11938			    == DEPCOMPLETE) {
11939				jwait(&inoref->if_list, MNT_WAIT);
11940				goto again;
11941			}
11942		}
11943	}
11944	/*
11945	 * Changes have been initiated. Anything depending on these
11946	 * changes cannot occur until this inode has been written.
11947	 */
11948	inodedep->id_state &= ~COMPLETE;
11949	if ((inodedep->id_state & ONWORKLIST) == 0)
11950		WORKLIST_INSERT(&bp->b_dep, &inodedep->id_list);
11951	/*
11952	 * Any new dependencies associated with the incore inode must
11953	 * now be moved to the list associated with the buffer holding
11954	 * the in-memory copy of the inode. Once merged process any
11955	 * allocdirects that are completed by the merger.
11956	 */
11957	merge_inode_lists(&inodedep->id_newinoupdt, &inodedep->id_inoupdt);
11958	if (!TAILQ_EMPTY(&inodedep->id_inoupdt))
11959		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt),
11960		    NULL);
11961	merge_inode_lists(&inodedep->id_newextupdt, &inodedep->id_extupdt);
11962	if (!TAILQ_EMPTY(&inodedep->id_extupdt))
11963		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_extupdt),
11964		    NULL);
11965	/*
11966	 * Now that the inode has been pushed into the buffer, the
11967	 * operations dependent on the inode being written to disk
11968	 * can be moved to the id_bufwait so that they will be
11969	 * processed when the buffer I/O completes.
11970	 */
11971	while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
11972		WORKLIST_REMOVE(wk);
11973		WORKLIST_INSERT(&inodedep->id_bufwait, wk);
11974	}
11975	/*
11976	 * Newly allocated inodes cannot be written until the bitmap
11977	 * that allocates them have been written (indicated by
11978	 * DEPCOMPLETE being set in id_state). If we are doing a
11979	 * forced sync (e.g., an fsync on a file), we force the bitmap
11980	 * to be written so that the update can be done.
11981	 */
11982	if (waitfor == 0) {
11983		FREE_LOCK(ump);
11984		return;
11985	}
11986retry:
11987	if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) != 0) {
11988		FREE_LOCK(ump);
11989		return;
11990	}
11991	ibp = inodedep->id_bmsafemap->sm_buf;
11992	ibp = getdirtybuf(ibp, LOCK_PTR(ump), MNT_WAIT);
11993	if (ibp == NULL) {
11994		/*
11995		 * If ibp came back as NULL, the dependency could have been
11996		 * freed while we slept.  Look it up again, and check to see
11997		 * that it has completed.
11998		 */
11999		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
12000			goto retry;
12001		FREE_LOCK(ump);
12002		return;
12003	}
12004	FREE_LOCK(ump);
12005	if ((error = bwrite(ibp)) != 0)
12006		softdep_error("softdep_update_inodeblock: bwrite", error);
12007}
12008
12009/*
12010 * Merge the a new inode dependency list (such as id_newinoupdt) into an
12011 * old inode dependency list (such as id_inoupdt). This routine must be
12012 * called with splbio interrupts blocked.
12013 */
12014static void
12015merge_inode_lists(newlisthead, oldlisthead)
12016	struct allocdirectlst *newlisthead;
12017	struct allocdirectlst *oldlisthead;
12018{
12019	struct allocdirect *listadp, *newadp;
12020
12021	newadp = TAILQ_FIRST(newlisthead);
12022	for (listadp = TAILQ_FIRST(oldlisthead); listadp && newadp;) {
12023		if (listadp->ad_offset < newadp->ad_offset) {
12024			listadp = TAILQ_NEXT(listadp, ad_next);
12025			continue;
12026		}
12027		TAILQ_REMOVE(newlisthead, newadp, ad_next);
12028		TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
12029		if (listadp->ad_offset == newadp->ad_offset) {
12030			allocdirect_merge(oldlisthead, newadp,
12031			    listadp);
12032			listadp = newadp;
12033		}
12034		newadp = TAILQ_FIRST(newlisthead);
12035	}
12036	while ((newadp = TAILQ_FIRST(newlisthead)) != NULL) {
12037		TAILQ_REMOVE(newlisthead, newadp, ad_next);
12038		TAILQ_INSERT_TAIL(oldlisthead, newadp, ad_next);
12039	}
12040}
12041
12042/*
12043 * If we are doing an fsync, then we must ensure that any directory
12044 * entries for the inode have been written after the inode gets to disk.
12045 */
12046int
12047softdep_fsync(vp)
12048	struct vnode *vp;	/* the "in_core" copy of the inode */
12049{
12050	struct inodedep *inodedep;
12051	struct pagedep *pagedep;
12052	struct inoref *inoref;
12053	struct ufsmount *ump;
12054	struct worklist *wk;
12055	struct diradd *dap;
12056	struct mount *mp;
12057	struct vnode *pvp;
12058	struct inode *ip;
12059	struct buf *bp;
12060	struct fs *fs;
12061	struct thread *td = curthread;
12062	int error, flushparent, pagedep_new_block;
12063	ino_t parentino;
12064	ufs_lbn_t lbn;
12065
12066	ip = VTOI(vp);
12067	fs = ip->i_fs;
12068	ump = ip->i_ump;
12069	mp = vp->v_mount;
12070	if (MOUNTEDSOFTDEP(mp) == 0)
12071		return (0);
12072	ACQUIRE_LOCK(ump);
12073restart:
12074	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12075		FREE_LOCK(ump);
12076		return (0);
12077	}
12078	TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12079		if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12080		    == DEPCOMPLETE) {
12081			jwait(&inoref->if_list, MNT_WAIT);
12082			goto restart;
12083		}
12084	}
12085	if (!LIST_EMPTY(&inodedep->id_inowait) ||
12086	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
12087	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
12088	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
12089	    !TAILQ_EMPTY(&inodedep->id_newinoupdt))
12090		panic("softdep_fsync: pending ops %p", inodedep);
12091	for (error = 0, flushparent = 0; ; ) {
12092		if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
12093			break;
12094		if (wk->wk_type != D_DIRADD)
12095			panic("softdep_fsync: Unexpected type %s",
12096			    TYPENAME(wk->wk_type));
12097		dap = WK_DIRADD(wk);
12098		/*
12099		 * Flush our parent if this directory entry has a MKDIR_PARENT
12100		 * dependency or is contained in a newly allocated block.
12101		 */
12102		if (dap->da_state & DIRCHG)
12103			pagedep = dap->da_previous->dm_pagedep;
12104		else
12105			pagedep = dap->da_pagedep;
12106		parentino = pagedep->pd_ino;
12107		lbn = pagedep->pd_lbn;
12108		if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE)
12109			panic("softdep_fsync: dirty");
12110		if ((dap->da_state & MKDIR_PARENT) ||
12111		    (pagedep->pd_state & NEWBLOCK))
12112			flushparent = 1;
12113		else
12114			flushparent = 0;
12115		/*
12116		 * If we are being fsync'ed as part of vgone'ing this vnode,
12117		 * then we will not be able to release and recover the
12118		 * vnode below, so we just have to give up on writing its
12119		 * directory entry out. It will eventually be written, just
12120		 * not now, but then the user was not asking to have it
12121		 * written, so we are not breaking any promises.
12122		 */
12123		if (vp->v_iflag & VI_DOOMED)
12124			break;
12125		/*
12126		 * We prevent deadlock by always fetching inodes from the
12127		 * root, moving down the directory tree. Thus, when fetching
12128		 * our parent directory, we first try to get the lock. If
12129		 * that fails, we must unlock ourselves before requesting
12130		 * the lock on our parent. See the comment in ufs_lookup
12131		 * for details on possible races.
12132		 */
12133		FREE_LOCK(ump);
12134		if (ffs_vgetf(mp, parentino, LK_NOWAIT | LK_EXCLUSIVE, &pvp,
12135		    FFSV_FORCEINSMQ)) {
12136			error = vfs_busy(mp, MBF_NOWAIT);
12137			if (error != 0) {
12138				vfs_ref(mp);
12139				VOP_UNLOCK(vp, 0);
12140				error = vfs_busy(mp, 0);
12141				vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
12142				vfs_rel(mp);
12143				if (error != 0)
12144					return (ENOENT);
12145				if (vp->v_iflag & VI_DOOMED) {
12146					vfs_unbusy(mp);
12147					return (ENOENT);
12148				}
12149			}
12150			VOP_UNLOCK(vp, 0);
12151			error = ffs_vgetf(mp, parentino, LK_EXCLUSIVE,
12152			    &pvp, FFSV_FORCEINSMQ);
12153			vfs_unbusy(mp);
12154			vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
12155			if (vp->v_iflag & VI_DOOMED) {
12156				if (error == 0)
12157					vput(pvp);
12158				error = ENOENT;
12159			}
12160			if (error != 0)
12161				return (error);
12162		}
12163		/*
12164		 * All MKDIR_PARENT dependencies and all the NEWBLOCK pagedeps
12165		 * that are contained in direct blocks will be resolved by
12166		 * doing a ffs_update. Pagedeps contained in indirect blocks
12167		 * may require a complete sync'ing of the directory. So, we
12168		 * try the cheap and fast ffs_update first, and if that fails,
12169		 * then we do the slower ffs_syncvnode of the directory.
12170		 */
12171		if (flushparent) {
12172			int locked;
12173
12174			if ((error = ffs_update(pvp, 1)) != 0) {
12175				vput(pvp);
12176				return (error);
12177			}
12178			ACQUIRE_LOCK(ump);
12179			locked = 1;
12180			if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0) {
12181				if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) != NULL) {
12182					if (wk->wk_type != D_DIRADD)
12183						panic("softdep_fsync: Unexpected type %s",
12184						      TYPENAME(wk->wk_type));
12185					dap = WK_DIRADD(wk);
12186					if (dap->da_state & DIRCHG)
12187						pagedep = dap->da_previous->dm_pagedep;
12188					else
12189						pagedep = dap->da_pagedep;
12190					pagedep_new_block = pagedep->pd_state & NEWBLOCK;
12191					FREE_LOCK(ump);
12192					locked = 0;
12193					if (pagedep_new_block && (error =
12194					    ffs_syncvnode(pvp, MNT_WAIT, 0))) {
12195						vput(pvp);
12196						return (error);
12197					}
12198				}
12199			}
12200			if (locked)
12201				FREE_LOCK(ump);
12202		}
12203		/*
12204		 * Flush directory page containing the inode's name.
12205		 */
12206		error = bread(pvp, lbn, blksize(fs, VTOI(pvp), lbn), td->td_ucred,
12207		    &bp);
12208		if (error == 0)
12209			error = bwrite(bp);
12210		else
12211			brelse(bp);
12212		vput(pvp);
12213		if (error != 0)
12214			return (error);
12215		ACQUIRE_LOCK(ump);
12216		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
12217			break;
12218	}
12219	FREE_LOCK(ump);
12220	return (0);
12221}
12222
12223/*
12224 * Flush all the dirty bitmaps associated with the block device
12225 * before flushing the rest of the dirty blocks so as to reduce
12226 * the number of dependencies that will have to be rolled back.
12227 *
12228 * XXX Unused?
12229 */
12230void
12231softdep_fsync_mountdev(vp)
12232	struct vnode *vp;
12233{
12234	struct buf *bp, *nbp;
12235	struct worklist *wk;
12236	struct bufobj *bo;
12237
12238	if (!vn_isdisk(vp, NULL))
12239		panic("softdep_fsync_mountdev: vnode not a disk");
12240	bo = &vp->v_bufobj;
12241restart:
12242	BO_LOCK(bo);
12243	TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
12244		/*
12245		 * If it is already scheduled, skip to the next buffer.
12246		 */
12247		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL))
12248			continue;
12249
12250		if ((bp->b_flags & B_DELWRI) == 0)
12251			panic("softdep_fsync_mountdev: not dirty");
12252		/*
12253		 * We are only interested in bitmaps with outstanding
12254		 * dependencies.
12255		 */
12256		if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
12257		    wk->wk_type != D_BMSAFEMAP ||
12258		    (bp->b_vflags & BV_BKGRDINPROG)) {
12259			BUF_UNLOCK(bp);
12260			continue;
12261		}
12262		BO_UNLOCK(bo);
12263		bremfree(bp);
12264		(void) bawrite(bp);
12265		goto restart;
12266	}
12267	drain_output(vp);
12268	BO_UNLOCK(bo);
12269}
12270
12271/*
12272 * Sync all cylinder groups that were dirty at the time this function is
12273 * called.  Newly dirtied cgs will be inserted before the sentinel.  This
12274 * is used to flush freedep activity that may be holding up writes to a
12275 * indirect block.
12276 */
12277static int
12278sync_cgs(mp, waitfor)
12279	struct mount *mp;
12280	int waitfor;
12281{
12282	struct bmsafemap *bmsafemap;
12283	struct bmsafemap *sentinel;
12284	struct ufsmount *ump;
12285	struct buf *bp;
12286	int error;
12287
12288	sentinel = malloc(sizeof(*sentinel), M_BMSAFEMAP, M_ZERO | M_WAITOK);
12289	sentinel->sm_cg = -1;
12290	ump = VFSTOUFS(mp);
12291	error = 0;
12292	ACQUIRE_LOCK(ump);
12293	LIST_INSERT_HEAD(&ump->softdep_dirtycg, sentinel, sm_next);
12294	for (bmsafemap = LIST_NEXT(sentinel, sm_next); bmsafemap != NULL;
12295	    bmsafemap = LIST_NEXT(sentinel, sm_next)) {
12296		/* Skip sentinels and cgs with no work to release. */
12297		if (bmsafemap->sm_cg == -1 ||
12298		    (LIST_EMPTY(&bmsafemap->sm_freehd) &&
12299		    LIST_EMPTY(&bmsafemap->sm_freewr))) {
12300			LIST_REMOVE(sentinel, sm_next);
12301			LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12302			continue;
12303		}
12304		/*
12305		 * If we don't get the lock and we're waiting try again, if
12306		 * not move on to the next buf and try to sync it.
12307		 */
12308		bp = getdirtybuf(bmsafemap->sm_buf, LOCK_PTR(ump), waitfor);
12309		if (bp == NULL && waitfor == MNT_WAIT)
12310			continue;
12311		LIST_REMOVE(sentinel, sm_next);
12312		LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12313		if (bp == NULL)
12314			continue;
12315		FREE_LOCK(ump);
12316		if (waitfor == MNT_NOWAIT)
12317			bawrite(bp);
12318		else
12319			error = bwrite(bp);
12320		ACQUIRE_LOCK(ump);
12321		if (error)
12322			break;
12323	}
12324	LIST_REMOVE(sentinel, sm_next);
12325	FREE_LOCK(ump);
12326	free(sentinel, M_BMSAFEMAP);
12327	return (error);
12328}
12329
12330/*
12331 * This routine is called when we are trying to synchronously flush a
12332 * file. This routine must eliminate any filesystem metadata dependencies
12333 * so that the syncing routine can succeed.
12334 */
12335int
12336softdep_sync_metadata(struct vnode *vp)
12337{
12338	struct inode *ip;
12339	int error;
12340
12341	ip = VTOI(vp);
12342	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ip->i_ump)) != 0,
12343	    ("softdep_sync_metadata called on non-softdep filesystem"));
12344	/*
12345	 * Ensure that any direct block dependencies have been cleared,
12346	 * truncations are started, and inode references are journaled.
12347	 */
12348	ACQUIRE_LOCK(ip->i_ump);
12349	/*
12350	 * Write all journal records to prevent rollbacks on devvp.
12351	 */
12352	if (vp->v_type == VCHR)
12353		softdep_flushjournal(vp->v_mount);
12354	error = flush_inodedep_deps(vp, vp->v_mount, ip->i_number);
12355	/*
12356	 * Ensure that all truncates are written so we won't find deps on
12357	 * indirect blocks.
12358	 */
12359	process_truncates(vp);
12360	FREE_LOCK(ip->i_ump);
12361
12362	return (error);
12363}
12364
12365/*
12366 * This routine is called when we are attempting to sync a buf with
12367 * dependencies.  If waitfor is MNT_NOWAIT it attempts to schedule any
12368 * other IO it can but returns EBUSY if the buffer is not yet able to
12369 * be written.  Dependencies which will not cause rollbacks will always
12370 * return 0.
12371 */
12372int
12373softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
12374{
12375	struct indirdep *indirdep;
12376	struct pagedep *pagedep;
12377	struct allocindir *aip;
12378	struct newblk *newblk;
12379	struct ufsmount *ump;
12380	struct buf *nbp;
12381	struct worklist *wk;
12382	int i, error;
12383
12384	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12385	    ("softdep_sync_buf called on non-softdep filesystem"));
12386	/*
12387	 * For VCHR we just don't want to force flush any dependencies that
12388	 * will cause rollbacks.
12389	 */
12390	if (vp->v_type == VCHR) {
12391		if (waitfor == MNT_NOWAIT && softdep_count_dependencies(bp, 0))
12392			return (EBUSY);
12393		return (0);
12394	}
12395	ump = VTOI(vp)->i_ump;
12396	ACQUIRE_LOCK(ump);
12397	/*
12398	 * As we hold the buffer locked, none of its dependencies
12399	 * will disappear.
12400	 */
12401	error = 0;
12402top:
12403	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
12404		switch (wk->wk_type) {
12405
12406		case D_ALLOCDIRECT:
12407		case D_ALLOCINDIR:
12408			newblk = WK_NEWBLK(wk);
12409			if (newblk->nb_jnewblk != NULL) {
12410				if (waitfor == MNT_NOWAIT) {
12411					error = EBUSY;
12412					goto out_unlock;
12413				}
12414				jwait(&newblk->nb_jnewblk->jn_list, waitfor);
12415				goto top;
12416			}
12417			if (newblk->nb_state & DEPCOMPLETE ||
12418			    waitfor == MNT_NOWAIT)
12419				continue;
12420			nbp = newblk->nb_bmsafemap->sm_buf;
12421			nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
12422			if (nbp == NULL)
12423				goto top;
12424			FREE_LOCK(ump);
12425			if ((error = bwrite(nbp)) != 0)
12426				goto out;
12427			ACQUIRE_LOCK(ump);
12428			continue;
12429
12430		case D_INDIRDEP:
12431			indirdep = WK_INDIRDEP(wk);
12432			if (waitfor == MNT_NOWAIT) {
12433				if (!TAILQ_EMPTY(&indirdep->ir_trunc) ||
12434				    !LIST_EMPTY(&indirdep->ir_deplisthd)) {
12435					error = EBUSY;
12436					goto out_unlock;
12437				}
12438			}
12439			if (!TAILQ_EMPTY(&indirdep->ir_trunc))
12440				panic("softdep_sync_buf: truncation pending.");
12441		restart:
12442			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
12443				newblk = (struct newblk *)aip;
12444				if (newblk->nb_jnewblk != NULL) {
12445					jwait(&newblk->nb_jnewblk->jn_list,
12446					    waitfor);
12447					goto restart;
12448				}
12449				if (newblk->nb_state & DEPCOMPLETE)
12450					continue;
12451				nbp = newblk->nb_bmsafemap->sm_buf;
12452				nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
12453				if (nbp == NULL)
12454					goto restart;
12455				FREE_LOCK(ump);
12456				if ((error = bwrite(nbp)) != 0)
12457					goto out;
12458				ACQUIRE_LOCK(ump);
12459				goto restart;
12460			}
12461			continue;
12462
12463		case D_PAGEDEP:
12464			/*
12465			 * Only flush directory entries in synchronous passes.
12466			 */
12467			if (waitfor != MNT_WAIT) {
12468				error = EBUSY;
12469				goto out_unlock;
12470			}
12471			/*
12472			 * While syncing snapshots, we must allow recursive
12473			 * lookups.
12474			 */
12475			BUF_AREC(bp);
12476			/*
12477			 * We are trying to sync a directory that may
12478			 * have dependencies on both its own metadata
12479			 * and/or dependencies on the inodes of any
12480			 * recently allocated files. We walk its diradd
12481			 * lists pushing out the associated inode.
12482			 */
12483			pagedep = WK_PAGEDEP(wk);
12484			for (i = 0; i < DAHASHSZ; i++) {
12485				if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
12486					continue;
12487				if ((error = flush_pagedep_deps(vp, wk->wk_mp,
12488				    &pagedep->pd_diraddhd[i]))) {
12489					BUF_NOREC(bp);
12490					goto out_unlock;
12491				}
12492			}
12493			BUF_NOREC(bp);
12494			continue;
12495
12496		case D_FREEWORK:
12497		case D_FREEDEP:
12498		case D_JSEGDEP:
12499		case D_JNEWBLK:
12500			continue;
12501
12502		default:
12503			panic("softdep_sync_buf: Unknown type %s",
12504			    TYPENAME(wk->wk_type));
12505			/* NOTREACHED */
12506		}
12507	}
12508out_unlock:
12509	FREE_LOCK(ump);
12510out:
12511	return (error);
12512}
12513
12514/*
12515 * Flush the dependencies associated with an inodedep.
12516 * Called with splbio blocked.
12517 */
12518static int
12519flush_inodedep_deps(vp, mp, ino)
12520	struct vnode *vp;
12521	struct mount *mp;
12522	ino_t ino;
12523{
12524	struct inodedep *inodedep;
12525	struct inoref *inoref;
12526	struct ufsmount *ump;
12527	int error, waitfor;
12528
12529	/*
12530	 * This work is done in two passes. The first pass grabs most
12531	 * of the buffers and begins asynchronously writing them. The
12532	 * only way to wait for these asynchronous writes is to sleep
12533	 * on the filesystem vnode which may stay busy for a long time
12534	 * if the filesystem is active. So, instead, we make a second
12535	 * pass over the dependencies blocking on each write. In the
12536	 * usual case we will be blocking against a write that we
12537	 * initiated, so when it is done the dependency will have been
12538	 * resolved. Thus the second pass is expected to end quickly.
12539	 * We give a brief window at the top of the loop to allow
12540	 * any pending I/O to complete.
12541	 */
12542	ump = VFSTOUFS(mp);
12543	LOCK_OWNED(ump);
12544	for (error = 0, waitfor = MNT_NOWAIT; ; ) {
12545		if (error)
12546			return (error);
12547		FREE_LOCK(ump);
12548		ACQUIRE_LOCK(ump);
12549restart:
12550		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
12551			return (0);
12552		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12553			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12554			    == DEPCOMPLETE) {
12555				jwait(&inoref->if_list, MNT_WAIT);
12556				goto restart;
12557			}
12558		}
12559		if (flush_deplist(&inodedep->id_inoupdt, waitfor, &error) ||
12560		    flush_deplist(&inodedep->id_newinoupdt, waitfor, &error) ||
12561		    flush_deplist(&inodedep->id_extupdt, waitfor, &error) ||
12562		    flush_deplist(&inodedep->id_newextupdt, waitfor, &error))
12563			continue;
12564		/*
12565		 * If pass2, we are done, otherwise do pass 2.
12566		 */
12567		if (waitfor == MNT_WAIT)
12568			break;
12569		waitfor = MNT_WAIT;
12570	}
12571	/*
12572	 * Try freeing inodedep in case all dependencies have been removed.
12573	 */
12574	if (inodedep_lookup(mp, ino, 0, &inodedep) != 0)
12575		(void) free_inodedep(inodedep);
12576	return (0);
12577}
12578
12579/*
12580 * Flush an inode dependency list.
12581 * Called with splbio blocked.
12582 */
12583static int
12584flush_deplist(listhead, waitfor, errorp)
12585	struct allocdirectlst *listhead;
12586	int waitfor;
12587	int *errorp;
12588{
12589	struct allocdirect *adp;
12590	struct newblk *newblk;
12591	struct ufsmount *ump;
12592	struct buf *bp;
12593
12594	if ((adp = TAILQ_FIRST(listhead)) == NULL)
12595		return (0);
12596	ump = VFSTOUFS(adp->ad_list.wk_mp);
12597	LOCK_OWNED(ump);
12598	TAILQ_FOREACH(adp, listhead, ad_next) {
12599		newblk = (struct newblk *)adp;
12600		if (newblk->nb_jnewblk != NULL) {
12601			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
12602			return (1);
12603		}
12604		if (newblk->nb_state & DEPCOMPLETE)
12605			continue;
12606		bp = newblk->nb_bmsafemap->sm_buf;
12607		bp = getdirtybuf(bp, LOCK_PTR(ump), waitfor);
12608		if (bp == NULL) {
12609			if (waitfor == MNT_NOWAIT)
12610				continue;
12611			return (1);
12612		}
12613		FREE_LOCK(ump);
12614		if (waitfor == MNT_NOWAIT)
12615			bawrite(bp);
12616		else
12617			*errorp = bwrite(bp);
12618		ACQUIRE_LOCK(ump);
12619		return (1);
12620	}
12621	return (0);
12622}
12623
12624/*
12625 * Flush dependencies associated with an allocdirect block.
12626 */
12627static int
12628flush_newblk_dep(vp, mp, lbn)
12629	struct vnode *vp;
12630	struct mount *mp;
12631	ufs_lbn_t lbn;
12632{
12633	struct newblk *newblk;
12634	struct ufsmount *ump;
12635	struct bufobj *bo;
12636	struct inode *ip;
12637	struct buf *bp;
12638	ufs2_daddr_t blkno;
12639	int error;
12640
12641	error = 0;
12642	bo = &vp->v_bufobj;
12643	ip = VTOI(vp);
12644	blkno = DIP(ip, i_db[lbn]);
12645	if (blkno == 0)
12646		panic("flush_newblk_dep: Missing block");
12647	ump = VFSTOUFS(mp);
12648	ACQUIRE_LOCK(ump);
12649	/*
12650	 * Loop until all dependencies related to this block are satisfied.
12651	 * We must be careful to restart after each sleep in case a write
12652	 * completes some part of this process for us.
12653	 */
12654	for (;;) {
12655		if (newblk_lookup(mp, blkno, 0, &newblk) == 0) {
12656			FREE_LOCK(ump);
12657			break;
12658		}
12659		if (newblk->nb_list.wk_type != D_ALLOCDIRECT)
12660			panic("flush_newblk_deps: Bad newblk %p", newblk);
12661		/*
12662		 * Flush the journal.
12663		 */
12664		if (newblk->nb_jnewblk != NULL) {
12665			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
12666			continue;
12667		}
12668		/*
12669		 * Write the bitmap dependency.
12670		 */
12671		if ((newblk->nb_state & DEPCOMPLETE) == 0) {
12672			bp = newblk->nb_bmsafemap->sm_buf;
12673			bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
12674			if (bp == NULL)
12675				continue;
12676			FREE_LOCK(ump);
12677			error = bwrite(bp);
12678			if (error)
12679				break;
12680			ACQUIRE_LOCK(ump);
12681			continue;
12682		}
12683		/*
12684		 * Write the buffer.
12685		 */
12686		FREE_LOCK(ump);
12687		BO_LOCK(bo);
12688		bp = gbincore(bo, lbn);
12689		if (bp != NULL) {
12690			error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
12691			    LK_INTERLOCK, BO_LOCKPTR(bo));
12692			if (error == ENOLCK) {
12693				ACQUIRE_LOCK(ump);
12694				continue; /* Slept, retry */
12695			}
12696			if (error != 0)
12697				break;	/* Failed */
12698			if (bp->b_flags & B_DELWRI) {
12699				bremfree(bp);
12700				error = bwrite(bp);
12701				if (error)
12702					break;
12703			} else
12704				BUF_UNLOCK(bp);
12705		} else
12706			BO_UNLOCK(bo);
12707		/*
12708		 * We have to wait for the direct pointers to
12709		 * point at the newdirblk before the dependency
12710		 * will go away.
12711		 */
12712		error = ffs_update(vp, 1);
12713		if (error)
12714			break;
12715		ACQUIRE_LOCK(ump);
12716	}
12717	return (error);
12718}
12719
12720/*
12721 * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
12722 * Called with splbio blocked.
12723 */
12724static int
12725flush_pagedep_deps(pvp, mp, diraddhdp)
12726	struct vnode *pvp;
12727	struct mount *mp;
12728	struct diraddhd *diraddhdp;
12729{
12730	struct inodedep *inodedep;
12731	struct inoref *inoref;
12732	struct ufsmount *ump;
12733	struct diradd *dap;
12734	struct vnode *vp;
12735	int error = 0;
12736	struct buf *bp;
12737	ino_t inum;
12738	struct diraddhd unfinished;
12739
12740	LIST_INIT(&unfinished);
12741	ump = VFSTOUFS(mp);
12742	LOCK_OWNED(ump);
12743restart:
12744	while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
12745		/*
12746		 * Flush ourselves if this directory entry
12747		 * has a MKDIR_PARENT dependency.
12748		 */
12749		if (dap->da_state & MKDIR_PARENT) {
12750			FREE_LOCK(ump);
12751			if ((error = ffs_update(pvp, 1)) != 0)
12752				break;
12753			ACQUIRE_LOCK(ump);
12754			/*
12755			 * If that cleared dependencies, go on to next.
12756			 */
12757			if (dap != LIST_FIRST(diraddhdp))
12758				continue;
12759			/*
12760			 * All MKDIR_PARENT dependencies and all the
12761			 * NEWBLOCK pagedeps that are contained in direct
12762			 * blocks were resolved by doing above ffs_update.
12763			 * Pagedeps contained in indirect blocks may
12764			 * require a complete sync'ing of the directory.
12765			 * We are in the midst of doing a complete sync,
12766			 * so if they are not resolved in this pass we
12767			 * defer them for now as they will be sync'ed by
12768			 * our caller shortly.
12769			 */
12770			LIST_REMOVE(dap, da_pdlist);
12771			LIST_INSERT_HEAD(&unfinished, dap, da_pdlist);
12772			continue;
12773		}
12774		/*
12775		 * A newly allocated directory must have its "." and
12776		 * ".." entries written out before its name can be
12777		 * committed in its parent.
12778		 */
12779		inum = dap->da_newinum;
12780		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
12781			panic("flush_pagedep_deps: lost inode1");
12782		/*
12783		 * Wait for any pending journal adds to complete so we don't
12784		 * cause rollbacks while syncing.
12785		 */
12786		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12787			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12788			    == DEPCOMPLETE) {
12789				jwait(&inoref->if_list, MNT_WAIT);
12790				goto restart;
12791			}
12792		}
12793		if (dap->da_state & MKDIR_BODY) {
12794			FREE_LOCK(ump);
12795			if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
12796			    FFSV_FORCEINSMQ)))
12797				break;
12798			error = flush_newblk_dep(vp, mp, 0);
12799			/*
12800			 * If we still have the dependency we might need to
12801			 * update the vnode to sync the new link count to
12802			 * disk.
12803			 */
12804			if (error == 0 && dap == LIST_FIRST(diraddhdp))
12805				error = ffs_update(vp, 1);
12806			vput(vp);
12807			if (error != 0)
12808				break;
12809			ACQUIRE_LOCK(ump);
12810			/*
12811			 * If that cleared dependencies, go on to next.
12812			 */
12813			if (dap != LIST_FIRST(diraddhdp))
12814				continue;
12815			if (dap->da_state & MKDIR_BODY) {
12816				inodedep_lookup(UFSTOVFS(ump), inum, 0,
12817				    &inodedep);
12818				panic("flush_pagedep_deps: MKDIR_BODY "
12819				    "inodedep %p dap %p vp %p",
12820				    inodedep, dap, vp);
12821			}
12822		}
12823		/*
12824		 * Flush the inode on which the directory entry depends.
12825		 * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
12826		 * the only remaining dependency is that the updated inode
12827		 * count must get pushed to disk. The inode has already
12828		 * been pushed into its inode buffer (via VOP_UPDATE) at
12829		 * the time of the reference count change. So we need only
12830		 * locate that buffer, ensure that there will be no rollback
12831		 * caused by a bitmap dependency, then write the inode buffer.
12832		 */
12833retry:
12834		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
12835			panic("flush_pagedep_deps: lost inode");
12836		/*
12837		 * If the inode still has bitmap dependencies,
12838		 * push them to disk.
12839		 */
12840		if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) == 0) {
12841			bp = inodedep->id_bmsafemap->sm_buf;
12842			bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
12843			if (bp == NULL)
12844				goto retry;
12845			FREE_LOCK(ump);
12846			if ((error = bwrite(bp)) != 0)
12847				break;
12848			ACQUIRE_LOCK(ump);
12849			if (dap != LIST_FIRST(diraddhdp))
12850				continue;
12851		}
12852		/*
12853		 * If the inode is still sitting in a buffer waiting
12854		 * to be written or waiting for the link count to be
12855		 * adjusted update it here to flush it to disk.
12856		 */
12857		if (dap == LIST_FIRST(diraddhdp)) {
12858			FREE_LOCK(ump);
12859			if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
12860			    FFSV_FORCEINSMQ)))
12861				break;
12862			error = ffs_update(vp, 1);
12863			vput(vp);
12864			if (error)
12865				break;
12866			ACQUIRE_LOCK(ump);
12867		}
12868		/*
12869		 * If we have failed to get rid of all the dependencies
12870		 * then something is seriously wrong.
12871		 */
12872		if (dap == LIST_FIRST(diraddhdp)) {
12873			inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep);
12874			panic("flush_pagedep_deps: failed to flush "
12875			    "inodedep %p ino %ju dap %p",
12876			    inodedep, (uintmax_t)inum, dap);
12877		}
12878	}
12879	if (error)
12880		ACQUIRE_LOCK(ump);
12881	while ((dap = LIST_FIRST(&unfinished)) != NULL) {
12882		LIST_REMOVE(dap, da_pdlist);
12883		LIST_INSERT_HEAD(diraddhdp, dap, da_pdlist);
12884	}
12885	return (error);
12886}
12887
12888/*
12889 * A large burst of file addition or deletion activity can drive the
12890 * memory load excessively high. First attempt to slow things down
12891 * using the techniques below. If that fails, this routine requests
12892 * the offending operations to fall back to running synchronously
12893 * until the memory load returns to a reasonable level.
12894 */
12895int
12896softdep_slowdown(vp)
12897	struct vnode *vp;
12898{
12899	struct ufsmount *ump;
12900	int jlow;
12901	int max_softdeps_hard;
12902
12903	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12904	    ("softdep_slowdown called on non-softdep filesystem"));
12905	ump = VFSTOUFS(vp->v_mount);
12906	ACQUIRE_LOCK(ump);
12907	jlow = 0;
12908	/*
12909	 * Check for journal space if needed.
12910	 */
12911	if (DOINGSUJ(vp)) {
12912		if (journal_space(ump, 0) == 0)
12913			jlow = 1;
12914	}
12915	max_softdeps_hard = max_softdeps * 11 / 10;
12916	if (dep_current[D_DIRREM] < max_softdeps_hard / 2 &&
12917	    dep_current[D_INODEDEP] < max_softdeps_hard &&
12918	    VFSTOUFS(vp->v_mount)->softdep_numindirdeps < maxindirdeps &&
12919	    dep_current[D_FREEBLKS] < max_softdeps_hard && jlow == 0) {
12920		FREE_LOCK(ump);
12921  		return (0);
12922	}
12923	if (VFSTOUFS(vp->v_mount)->softdep_numindirdeps >= maxindirdeps || jlow)
12924		softdep_speedup();
12925	stat_sync_limit_hit += 1;
12926	FREE_LOCK(ump);
12927	if (DOINGSUJ(vp))
12928		return (0);
12929	return (1);
12930}
12931
12932/*
12933 * Called by the allocation routines when they are about to fail
12934 * in the hope that we can free up the requested resource (inodes
12935 * or disk space).
12936 *
12937 * First check to see if the work list has anything on it. If it has,
12938 * clean up entries until we successfully free the requested resource.
12939 * Because this process holds inodes locked, we cannot handle any remove
12940 * requests that might block on a locked inode as that could lead to
12941 * deadlock. If the worklist yields none of the requested resource,
12942 * start syncing out vnodes to free up the needed space.
12943 */
12944int
12945softdep_request_cleanup(fs, vp, cred, resource)
12946	struct fs *fs;
12947	struct vnode *vp;
12948	struct ucred *cred;
12949	int resource;
12950{
12951	struct ufsmount *ump;
12952	struct mount *mp;
12953	struct vnode *lvp, *mvp;
12954	long starttime;
12955	ufs2_daddr_t needed;
12956	int error;
12957
12958	/*
12959	 * If we are being called because of a process doing a
12960	 * copy-on-write, then it is not safe to process any
12961	 * worklist items as we will recurse into the copyonwrite
12962	 * routine.  This will result in an incoherent snapshot.
12963	 * If the vnode that we hold is a snapshot, we must avoid
12964	 * handling other resources that could cause deadlock.
12965	 */
12966	if ((curthread->td_pflags & TDP_COWINPROGRESS) || IS_SNAPSHOT(VTOI(vp)))
12967		return (0);
12968
12969	if (resource == FLUSH_BLOCKS_WAIT)
12970		stat_cleanup_blkrequests += 1;
12971	else
12972		stat_cleanup_inorequests += 1;
12973
12974	mp = vp->v_mount;
12975	ump = VFSTOUFS(mp);
12976	mtx_assert(UFS_MTX(ump), MA_OWNED);
12977	UFS_UNLOCK(ump);
12978	error = ffs_update(vp, 1);
12979	if (error != 0 || MOUNTEDSOFTDEP(mp) == 0) {
12980		UFS_LOCK(ump);
12981		return (0);
12982	}
12983	/*
12984	 * If we are in need of resources, consider pausing for
12985	 * tickdelay to give ourselves some breathing room.
12986	 */
12987	ACQUIRE_LOCK(ump);
12988	process_removes(vp);
12989	process_truncates(vp);
12990	request_cleanup(UFSTOVFS(ump), resource);
12991	FREE_LOCK(ump);
12992	/*
12993	 * Now clean up at least as many resources as we will need.
12994	 *
12995	 * When requested to clean up inodes, the number that are needed
12996	 * is set by the number of simultaneous writers (mnt_writeopcount)
12997	 * plus a bit of slop (2) in case some more writers show up while
12998	 * we are cleaning.
12999	 *
13000	 * When requested to free up space, the amount of space that
13001	 * we need is enough blocks to allocate a full-sized segment
13002	 * (fs_contigsumsize). The number of such segments that will
13003	 * be needed is set by the number of simultaneous writers
13004	 * (mnt_writeopcount) plus a bit of slop (2) in case some more
13005	 * writers show up while we are cleaning.
13006	 *
13007	 * Additionally, if we are unpriviledged and allocating space,
13008	 * we need to ensure that we clean up enough blocks to get the
13009	 * needed number of blocks over the threshhold of the minimum
13010	 * number of blocks required to be kept free by the filesystem
13011	 * (fs_minfree).
13012	 */
13013	if (resource == FLUSH_INODES_WAIT) {
13014		needed = vp->v_mount->mnt_writeopcount + 2;
13015	} else if (resource == FLUSH_BLOCKS_WAIT) {
13016		needed = (vp->v_mount->mnt_writeopcount + 2) *
13017		    fs->fs_contigsumsize;
13018		if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE, 0))
13019			needed += fragstoblks(fs,
13020			    roundup((fs->fs_dsize * fs->fs_minfree / 100) -
13021			    fs->fs_cstotal.cs_nffree, fs->fs_frag));
13022	} else {
13023		UFS_LOCK(ump);
13024		printf("softdep_request_cleanup: Unknown resource type %d\n",
13025		    resource);
13026		return (0);
13027	}
13028	starttime = time_second;
13029retry:
13030	if ((resource == FLUSH_BLOCKS_WAIT && ump->softdep_on_worklist > 0 &&
13031	    fs->fs_cstotal.cs_nbfree <= needed) ||
13032	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13033	    fs->fs_cstotal.cs_nifree <= needed)) {
13034		ACQUIRE_LOCK(ump);
13035		if (ump->softdep_on_worklist > 0 &&
13036		    process_worklist_item(UFSTOVFS(ump),
13037		    ump->softdep_on_worklist, LK_NOWAIT) != 0)
13038			stat_worklist_push += 1;
13039		FREE_LOCK(ump);
13040	}
13041	/*
13042	 * If we still need resources and there are no more worklist
13043	 * entries to process to obtain them, we have to start flushing
13044	 * the dirty vnodes to force the release of additional requests
13045	 * to the worklist that we can then process to reap addition
13046	 * resources. We walk the vnodes associated with the mount point
13047	 * until we get the needed worklist requests that we can reap.
13048	 */
13049	if ((resource == FLUSH_BLOCKS_WAIT &&
13050	     fs->fs_cstotal.cs_nbfree <= needed) ||
13051	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13052	     fs->fs_cstotal.cs_nifree <= needed)) {
13053		MNT_VNODE_FOREACH_ALL(lvp, mp, mvp) {
13054			if (TAILQ_FIRST(&lvp->v_bufobj.bo_dirty.bv_hd) == 0) {
13055				VI_UNLOCK(lvp);
13056				continue;
13057			}
13058			if (vget(lvp, LK_EXCLUSIVE | LK_INTERLOCK | LK_NOWAIT,
13059			    curthread))
13060				continue;
13061			if (lvp->v_vflag & VV_NOSYNC) {	/* unlinked */
13062				vput(lvp);
13063				continue;
13064			}
13065			(void) ffs_syncvnode(lvp, MNT_NOWAIT, 0);
13066			vput(lvp);
13067		}
13068		lvp = ump->um_devvp;
13069		if (vn_lock(lvp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
13070			VOP_FSYNC(lvp, MNT_NOWAIT, curthread);
13071			VOP_UNLOCK(lvp, 0);
13072		}
13073		if (ump->softdep_on_worklist > 0) {
13074			stat_cleanup_retries += 1;
13075			goto retry;
13076		}
13077		stat_cleanup_failures += 1;
13078	}
13079	if (time_second - starttime > stat_cleanup_high_delay)
13080		stat_cleanup_high_delay = time_second - starttime;
13081	UFS_LOCK(ump);
13082	return (1);
13083}
13084
13085/*
13086 * If memory utilization has gotten too high, deliberately slow things
13087 * down and speed up the I/O processing.
13088 */
13089static int
13090request_cleanup(mp, resource)
13091	struct mount *mp;
13092	int resource;
13093{
13094	struct thread *td = curthread;
13095	struct ufsmount *ump;
13096
13097	ump = VFSTOUFS(mp);
13098	LOCK_OWNED(ump);
13099	/*
13100	 * We never hold up the filesystem syncer or buf daemon.
13101	 */
13102	if (td->td_pflags & (TDP_SOFTDEP|TDP_NORUNNINGBUF))
13103		return (0);
13104	/*
13105	 * First check to see if the work list has gotten backlogged.
13106	 * If it has, co-opt this process to help clean up two entries.
13107	 * Because this process may hold inodes locked, we cannot
13108	 * handle any remove requests that might block on a locked
13109	 * inode as that could lead to deadlock.  We set TDP_SOFTDEP
13110	 * to avoid recursively processing the worklist.
13111	 */
13112	if (ump->softdep_on_worklist > max_softdeps / 10) {
13113		td->td_pflags |= TDP_SOFTDEP;
13114		process_worklist_item(mp, 2, LK_NOWAIT);
13115		td->td_pflags &= ~TDP_SOFTDEP;
13116		stat_worklist_push += 2;
13117		return(1);
13118	}
13119	/*
13120	 * Next, we attempt to speed up the syncer process. If that
13121	 * is successful, then we allow the process to continue.
13122	 */
13123	if (softdep_speedup() &&
13124	    resource != FLUSH_BLOCKS_WAIT &&
13125	    resource != FLUSH_INODES_WAIT)
13126		return(0);
13127	/*
13128	 * If we are resource constrained on inode dependencies, try
13129	 * flushing some dirty inodes. Otherwise, we are constrained
13130	 * by file deletions, so try accelerating flushes of directories
13131	 * with removal dependencies. We would like to do the cleanup
13132	 * here, but we probably hold an inode locked at this point and
13133	 * that might deadlock against one that we try to clean. So,
13134	 * the best that we can do is request the syncer daemon to do
13135	 * the cleanup for us.
13136	 */
13137	switch (resource) {
13138
13139	case FLUSH_INODES:
13140	case FLUSH_INODES_WAIT:
13141		stat_ino_limit_push += 1;
13142		req_clear_inodedeps += 1;
13143		stat_countp = &stat_ino_limit_hit;
13144		break;
13145
13146	case FLUSH_BLOCKS:
13147	case FLUSH_BLOCKS_WAIT:
13148		stat_blk_limit_push += 1;
13149		req_clear_remove += 1;
13150		stat_countp = &stat_blk_limit_hit;
13151		break;
13152
13153	default:
13154		panic("request_cleanup: unknown type");
13155	}
13156	/*
13157	 * Hopefully the syncer daemon will catch up and awaken us.
13158	 * We wait at most tickdelay before proceeding in any case.
13159	 */
13160	proc_waiting += 1;
13161	if (callout_pending(&softdep_callout) == FALSE)
13162		callout_reset(&softdep_callout, tickdelay > 2 ? tickdelay : 2,
13163		    pause_timer, 0);
13164
13165	msleep((caddr_t)&proc_waiting, &lk, PPAUSE, "softupdate", 0);
13166	proc_waiting -= 1;
13167	return (1);
13168}
13169
13170/*
13171 * Awaken processes pausing in request_cleanup and clear proc_waiting
13172 * to indicate that there is no longer a timer running. Pause_timer
13173 * will be called with the global softdep mutex (&lk) locked.
13174 */
13175static void
13176pause_timer(arg)
13177	void *arg;
13178{
13179
13180	rw_assert(&lk, RA_WLOCKED);
13181	/*
13182	 * The callout_ API has acquired mtx and will hold it around this
13183	 * function call.
13184	 */
13185	*stat_countp += 1;
13186	wakeup_one(&proc_waiting);
13187	if (proc_waiting > 0)
13188		callout_reset(&softdep_callout, tickdelay > 2 ? tickdelay : 2,
13189		    pause_timer, 0);
13190}
13191
13192/*
13193 * If requested, try removing inode or removal dependencies.
13194 */
13195static void
13196check_clear_deps(mp)
13197	struct mount *mp;
13198{
13199
13200	rw_assert(&lk, RA_WLOCKED);
13201	/*
13202	 * If we are suspended, it may be because of our using
13203	 * too many inodedeps, so help clear them out.
13204	 */
13205	if (MOUNTEDSUJ(mp) && VFSTOUFS(mp)->softdep_jblocks->jb_suspended)
13206		clear_inodedeps(mp);
13207	/*
13208	 * General requests for cleanup of backed up dependencies
13209	 */
13210	if (req_clear_inodedeps) {
13211		req_clear_inodedeps -= 1;
13212		clear_inodedeps(mp);
13213		wakeup_one(&proc_waiting);
13214	}
13215	if (req_clear_remove) {
13216		req_clear_remove -= 1;
13217		clear_remove(mp);
13218		wakeup_one(&proc_waiting);
13219	}
13220}
13221
13222/*
13223 * Flush out a directory with at least one removal dependency in an effort to
13224 * reduce the number of dirrem, freefile, and freeblks dependency structures.
13225 */
13226static void
13227clear_remove(mp)
13228	struct mount *mp;
13229{
13230	struct pagedep_hashhead *pagedephd;
13231	struct pagedep *pagedep;
13232	struct ufsmount *ump;
13233	struct vnode *vp;
13234	struct bufobj *bo;
13235	int error, cnt;
13236	ino_t ino;
13237
13238	ump = VFSTOUFS(mp);
13239	LOCK_OWNED(ump);
13240
13241	for (cnt = 0; cnt <= ump->pagedep_hash_size; cnt++) {
13242		pagedephd = &ump->pagedep_hashtbl[ump->pagedep_nextclean++];
13243		if (ump->pagedep_nextclean > ump->pagedep_hash_size)
13244			ump->pagedep_nextclean = 0;
13245		LIST_FOREACH(pagedep, pagedephd, pd_hash) {
13246			if (LIST_EMPTY(&pagedep->pd_dirremhd))
13247				continue;
13248			ino = pagedep->pd_ino;
13249			if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13250				continue;
13251			FREE_LOCK(ump);
13252
13253			/*
13254			 * Let unmount clear deps
13255			 */
13256			error = vfs_busy(mp, MBF_NOWAIT);
13257			if (error != 0)
13258				goto finish_write;
13259			error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13260			     FFSV_FORCEINSMQ);
13261			vfs_unbusy(mp);
13262			if (error != 0) {
13263				softdep_error("clear_remove: vget", error);
13264				goto finish_write;
13265			}
13266			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13267				softdep_error("clear_remove: fsync", error);
13268			bo = &vp->v_bufobj;
13269			BO_LOCK(bo);
13270			drain_output(vp);
13271			BO_UNLOCK(bo);
13272			vput(vp);
13273		finish_write:
13274			vn_finished_write(mp);
13275			ACQUIRE_LOCK(ump);
13276			return;
13277		}
13278	}
13279}
13280
13281/*
13282 * Clear out a block of dirty inodes in an effort to reduce
13283 * the number of inodedep dependency structures.
13284 */
13285static void
13286clear_inodedeps(mp)
13287	struct mount *mp;
13288{
13289	struct inodedep_hashhead *inodedephd;
13290	struct inodedep *inodedep;
13291	struct ufsmount *ump;
13292	struct vnode *vp;
13293	struct fs *fs;
13294	int error, cnt;
13295	ino_t firstino, lastino, ino;
13296
13297	ump = VFSTOUFS(mp);
13298	fs = ump->um_fs;
13299	LOCK_OWNED(ump);
13300	/*
13301	 * Pick a random inode dependency to be cleared.
13302	 * We will then gather up all the inodes in its block
13303	 * that have dependencies and flush them out.
13304	 */
13305	for (cnt = 0; cnt <= ump->inodedep_hash_size; cnt++) {
13306		inodedephd = &ump->inodedep_hashtbl[ump->inodedep_nextclean++];
13307		if (ump->inodedep_nextclean > ump->inodedep_hash_size)
13308			ump->inodedep_nextclean = 0;
13309		if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
13310			break;
13311	}
13312	if (inodedep == NULL)
13313		return;
13314	/*
13315	 * Find the last inode in the block with dependencies.
13316	 */
13317	firstino = inodedep->id_ino & ~(INOPB(fs) - 1);
13318	for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
13319		if (inodedep_lookup(mp, lastino, 0, &inodedep) != 0)
13320			break;
13321	/*
13322	 * Asynchronously push all but the last inode with dependencies.
13323	 * Synchronously push the last inode with dependencies to ensure
13324	 * that the inode block gets written to free up the inodedeps.
13325	 */
13326	for (ino = firstino; ino <= lastino; ino++) {
13327		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
13328			continue;
13329		if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13330			continue;
13331		FREE_LOCK(ump);
13332		error = vfs_busy(mp, MBF_NOWAIT); /* Let unmount clear deps */
13333		if (error != 0) {
13334			vn_finished_write(mp);
13335			ACQUIRE_LOCK(ump);
13336			return;
13337		}
13338		if ((error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13339		    FFSV_FORCEINSMQ)) != 0) {
13340			softdep_error("clear_inodedeps: vget", error);
13341			vfs_unbusy(mp);
13342			vn_finished_write(mp);
13343			ACQUIRE_LOCK(ump);
13344			return;
13345		}
13346		vfs_unbusy(mp);
13347		if (ino == lastino) {
13348			if ((error = ffs_syncvnode(vp, MNT_WAIT, 0)))
13349				softdep_error("clear_inodedeps: fsync1", error);
13350		} else {
13351			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13352				softdep_error("clear_inodedeps: fsync2", error);
13353			BO_LOCK(&vp->v_bufobj);
13354			drain_output(vp);
13355			BO_UNLOCK(&vp->v_bufobj);
13356		}
13357		vput(vp);
13358		vn_finished_write(mp);
13359		ACQUIRE_LOCK(ump);
13360	}
13361}
13362
13363void
13364softdep_buf_append(bp, wkhd)
13365	struct buf *bp;
13366	struct workhead *wkhd;
13367{
13368	struct worklist *wk;
13369	struct ufsmount *ump;
13370
13371	if ((wk = LIST_FIRST(wkhd)) == NULL)
13372		return;
13373	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
13374	    ("softdep_buf_append called on non-softdep filesystem"));
13375	ump = VFSTOUFS(wk->wk_mp);
13376	ACQUIRE_LOCK(ump);
13377	while ((wk = LIST_FIRST(wkhd)) != NULL) {
13378		WORKLIST_REMOVE(wk);
13379		WORKLIST_INSERT(&bp->b_dep, wk);
13380	}
13381	FREE_LOCK(ump);
13382
13383}
13384
13385void
13386softdep_inode_append(ip, cred, wkhd)
13387	struct inode *ip;
13388	struct ucred *cred;
13389	struct workhead *wkhd;
13390{
13391	struct buf *bp;
13392	struct fs *fs;
13393	int error;
13394
13395	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ip->i_ump)) != 0,
13396	    ("softdep_inode_append called on non-softdep filesystem"));
13397	fs = ip->i_fs;
13398	error = bread(ip->i_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
13399	    (int)fs->fs_bsize, cred, &bp);
13400	if (error) {
13401		bqrelse(bp);
13402		softdep_freework(wkhd);
13403		return;
13404	}
13405	softdep_buf_append(bp, wkhd);
13406	bqrelse(bp);
13407}
13408
13409void
13410softdep_freework(wkhd)
13411	struct workhead *wkhd;
13412{
13413	struct worklist *wk;
13414	struct ufsmount *ump;
13415
13416	if ((wk = LIST_FIRST(wkhd)) == NULL)
13417		return;
13418	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
13419	    ("softdep_freework called on non-softdep filesystem"));
13420	ump = VFSTOUFS(wk->wk_mp);
13421	ACQUIRE_LOCK(ump);
13422	handle_jwork(wkhd);
13423	FREE_LOCK(ump);
13424}
13425
13426/*
13427 * Function to determine if the buffer has outstanding dependencies
13428 * that will cause a roll-back if the buffer is written. If wantcount
13429 * is set, return number of dependencies, otherwise just yes or no.
13430 */
13431static int
13432softdep_count_dependencies(bp, wantcount)
13433	struct buf *bp;
13434	int wantcount;
13435{
13436	struct worklist *wk;
13437	struct ufsmount *ump;
13438	struct bmsafemap *bmsafemap;
13439	struct freework *freework;
13440	struct inodedep *inodedep;
13441	struct indirdep *indirdep;
13442	struct freeblks *freeblks;
13443	struct allocindir *aip;
13444	struct pagedep *pagedep;
13445	struct dirrem *dirrem;
13446	struct newblk *newblk;
13447	struct mkdir *mkdir;
13448	struct diradd *dap;
13449	int i, retval;
13450
13451	retval = 0;
13452	if ((wk = LIST_FIRST(&bp->b_dep)) == NULL)
13453		return (0);
13454	ump = VFSTOUFS(wk->wk_mp);
13455	ACQUIRE_LOCK(ump);
13456	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
13457		switch (wk->wk_type) {
13458
13459		case D_INODEDEP:
13460			inodedep = WK_INODEDEP(wk);
13461			if ((inodedep->id_state & DEPCOMPLETE) == 0) {
13462				/* bitmap allocation dependency */
13463				retval += 1;
13464				if (!wantcount)
13465					goto out;
13466			}
13467			if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
13468				/* direct block pointer dependency */
13469				retval += 1;
13470				if (!wantcount)
13471					goto out;
13472			}
13473			if (TAILQ_FIRST(&inodedep->id_extupdt)) {
13474				/* direct block pointer dependency */
13475				retval += 1;
13476				if (!wantcount)
13477					goto out;
13478			}
13479			if (TAILQ_FIRST(&inodedep->id_inoreflst)) {
13480				/* Add reference dependency. */
13481				retval += 1;
13482				if (!wantcount)
13483					goto out;
13484			}
13485			continue;
13486
13487		case D_INDIRDEP:
13488			indirdep = WK_INDIRDEP(wk);
13489
13490			TAILQ_FOREACH(freework, &indirdep->ir_trunc, fw_next) {
13491				/* indirect truncation dependency */
13492				retval += 1;
13493				if (!wantcount)
13494					goto out;
13495			}
13496
13497			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
13498				/* indirect block pointer dependency */
13499				retval += 1;
13500				if (!wantcount)
13501					goto out;
13502			}
13503			continue;
13504
13505		case D_PAGEDEP:
13506			pagedep = WK_PAGEDEP(wk);
13507			LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
13508				if (LIST_FIRST(&dirrem->dm_jremrefhd)) {
13509					/* Journal remove ref dependency. */
13510					retval += 1;
13511					if (!wantcount)
13512						goto out;
13513				}
13514			}
13515			for (i = 0; i < DAHASHSZ; i++) {
13516
13517				LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
13518					/* directory entry dependency */
13519					retval += 1;
13520					if (!wantcount)
13521						goto out;
13522				}
13523			}
13524			continue;
13525
13526		case D_BMSAFEMAP:
13527			bmsafemap = WK_BMSAFEMAP(wk);
13528			if (LIST_FIRST(&bmsafemap->sm_jaddrefhd)) {
13529				/* Add reference dependency. */
13530				retval += 1;
13531				if (!wantcount)
13532					goto out;
13533			}
13534			if (LIST_FIRST(&bmsafemap->sm_jnewblkhd)) {
13535				/* Allocate block dependency. */
13536				retval += 1;
13537				if (!wantcount)
13538					goto out;
13539			}
13540			continue;
13541
13542		case D_FREEBLKS:
13543			freeblks = WK_FREEBLKS(wk);
13544			if (LIST_FIRST(&freeblks->fb_jblkdephd)) {
13545				/* Freeblk journal dependency. */
13546				retval += 1;
13547				if (!wantcount)
13548					goto out;
13549			}
13550			continue;
13551
13552		case D_ALLOCDIRECT:
13553		case D_ALLOCINDIR:
13554			newblk = WK_NEWBLK(wk);
13555			if (newblk->nb_jnewblk) {
13556				/* Journal allocate dependency. */
13557				retval += 1;
13558				if (!wantcount)
13559					goto out;
13560			}
13561			continue;
13562
13563		case D_MKDIR:
13564			mkdir = WK_MKDIR(wk);
13565			if (mkdir->md_jaddref) {
13566				/* Journal reference dependency. */
13567				retval += 1;
13568				if (!wantcount)
13569					goto out;
13570			}
13571			continue;
13572
13573		case D_FREEWORK:
13574		case D_FREEDEP:
13575		case D_JSEGDEP:
13576		case D_JSEG:
13577		case D_SBDEP:
13578			/* never a dependency on these blocks */
13579			continue;
13580
13581		default:
13582			panic("softdep_count_dependencies: Unexpected type %s",
13583			    TYPENAME(wk->wk_type));
13584			/* NOTREACHED */
13585		}
13586	}
13587out:
13588	FREE_LOCK(ump);
13589	return retval;
13590}
13591
13592/*
13593 * Acquire exclusive access to a buffer.
13594 * Must be called with a locked mtx parameter.
13595 * Return acquired buffer or NULL on failure.
13596 */
13597static struct buf *
13598getdirtybuf(bp, lock, waitfor)
13599	struct buf *bp;
13600	struct rwlock *lock;
13601	int waitfor;
13602{
13603	int error;
13604
13605	if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0) {
13606		if (waitfor != MNT_WAIT)
13607			return (NULL);
13608		error = BUF_LOCK(bp,
13609		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, lock);
13610		/*
13611		 * Even if we sucessfully acquire bp here, we have dropped
13612		 * lock, which may violates our guarantee.
13613		 */
13614		if (error == 0)
13615			BUF_UNLOCK(bp);
13616		else if (error != ENOLCK)
13617			panic("getdirtybuf: inconsistent lock: %d", error);
13618		rw_wlock(lock);
13619		return (NULL);
13620	}
13621	if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
13622		if (lock != BO_LOCKPTR(bp->b_bufobj) && waitfor == MNT_WAIT) {
13623			rw_wunlock(lock);
13624			BO_LOCK(bp->b_bufobj);
13625			BUF_UNLOCK(bp);
13626			if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
13627				bp->b_vflags |= BV_BKGRDWAIT;
13628				msleep(&bp->b_xflags, BO_LOCKPTR(bp->b_bufobj),
13629				       PRIBIO | PDROP, "getbuf", 0);
13630			} else
13631				BO_UNLOCK(bp->b_bufobj);
13632			rw_wlock(lock);
13633			return (NULL);
13634		}
13635		BUF_UNLOCK(bp);
13636		if (waitfor != MNT_WAIT)
13637			return (NULL);
13638		/*
13639		 * The lock argument must be bp->b_vp's mutex in
13640		 * this case.
13641		 */
13642#ifdef	DEBUG_VFS_LOCKS
13643		if (bp->b_vp->v_type != VCHR)
13644			ASSERT_BO_WLOCKED(bp->b_bufobj);
13645#endif
13646		bp->b_vflags |= BV_BKGRDWAIT;
13647		rw_sleep(&bp->b_xflags, lock, PRIBIO, "getbuf", 0);
13648		return (NULL);
13649	}
13650	if ((bp->b_flags & B_DELWRI) == 0) {
13651		BUF_UNLOCK(bp);
13652		return (NULL);
13653	}
13654	bremfree(bp);
13655	return (bp);
13656}
13657
13658
13659/*
13660 * Check if it is safe to suspend the file system now.  On entry,
13661 * the vnode interlock for devvp should be held.  Return 0 with
13662 * the mount interlock held if the file system can be suspended now,
13663 * otherwise return EAGAIN with the mount interlock held.
13664 */
13665int
13666softdep_check_suspend(struct mount *mp,
13667		      struct vnode *devvp,
13668		      int softdep_depcnt,
13669		      int softdep_accdepcnt,
13670		      int secondary_writes,
13671		      int secondary_accwrites)
13672{
13673	struct bufobj *bo;
13674	struct ufsmount *ump;
13675	int error;
13676
13677	bo = &devvp->v_bufobj;
13678	ASSERT_BO_WLOCKED(bo);
13679
13680	/*
13681	 * If we are not running with soft updates, then we need only
13682	 * deal with secondary writes as we try to suspend.
13683	 */
13684	if (MOUNTEDSOFTDEP(mp) == 0) {
13685		MNT_ILOCK(mp);
13686		while (mp->mnt_secondary_writes != 0) {
13687			BO_UNLOCK(bo);
13688			msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
13689			    (PUSER - 1) | PDROP, "secwr", 0);
13690			BO_LOCK(bo);
13691			MNT_ILOCK(mp);
13692		}
13693
13694		/*
13695		 * Reasons for needing more work before suspend:
13696		 * - Dirty buffers on devvp.
13697		 * - Secondary writes occurred after start of vnode sync loop
13698		 */
13699		error = 0;
13700		if (bo->bo_numoutput > 0 ||
13701		    bo->bo_dirty.bv_cnt > 0 ||
13702		    secondary_writes != 0 ||
13703		    mp->mnt_secondary_writes != 0 ||
13704		    secondary_accwrites != mp->mnt_secondary_accwrites)
13705			error = EAGAIN;
13706		BO_UNLOCK(bo);
13707		return (error);
13708	}
13709
13710	/*
13711	 * If we are running with soft updates, then we need to coordinate
13712	 * with them as we try to suspend.
13713	 */
13714	ump = VFSTOUFS(mp);
13715	for (;;) {
13716		if (!TRY_ACQUIRE_LOCK(ump)) {
13717			BO_UNLOCK(bo);
13718			ACQUIRE_LOCK(ump);
13719			FREE_LOCK(ump);
13720			BO_LOCK(bo);
13721			continue;
13722		}
13723		MNT_ILOCK(mp);
13724		if (mp->mnt_secondary_writes != 0) {
13725			FREE_LOCK(ump);
13726			BO_UNLOCK(bo);
13727			msleep(&mp->mnt_secondary_writes,
13728			       MNT_MTX(mp),
13729			       (PUSER - 1) | PDROP, "secwr", 0);
13730			BO_LOCK(bo);
13731			continue;
13732		}
13733		break;
13734	}
13735
13736	/*
13737	 * Reasons for needing more work before suspend:
13738	 * - Dirty buffers on devvp.
13739	 * - Softdep activity occurred after start of vnode sync loop
13740	 * - Secondary writes occurred after start of vnode sync loop
13741	 */
13742	error = 0;
13743	if (bo->bo_numoutput > 0 ||
13744	    bo->bo_dirty.bv_cnt > 0 ||
13745	    softdep_depcnt != 0 ||
13746	    ump->softdep_deps != 0 ||
13747	    softdep_accdepcnt != ump->softdep_accdeps ||
13748	    secondary_writes != 0 ||
13749	    mp->mnt_secondary_writes != 0 ||
13750	    secondary_accwrites != mp->mnt_secondary_accwrites)
13751		error = EAGAIN;
13752	FREE_LOCK(ump);
13753	BO_UNLOCK(bo);
13754	return (error);
13755}
13756
13757
13758/*
13759 * Get the number of dependency structures for the file system, both
13760 * the current number and the total number allocated.  These will
13761 * later be used to detect that softdep processing has occurred.
13762 */
13763void
13764softdep_get_depcounts(struct mount *mp,
13765		      int *softdep_depsp,
13766		      int *softdep_accdepsp)
13767{
13768	struct ufsmount *ump;
13769
13770	if (MOUNTEDSOFTDEP(mp) == 0) {
13771		*softdep_depsp = 0;
13772		*softdep_accdepsp = 0;
13773		return;
13774	}
13775	ump = VFSTOUFS(mp);
13776	ACQUIRE_LOCK(ump);
13777	*softdep_depsp = ump->softdep_deps;
13778	*softdep_accdepsp = ump->softdep_accdeps;
13779	FREE_LOCK(ump);
13780}
13781
13782/*
13783 * Wait for pending output on a vnode to complete.
13784 * Must be called with vnode lock and interlock locked.
13785 *
13786 * XXX: Should just be a call to bufobj_wwait().
13787 */
13788static void
13789drain_output(vp)
13790	struct vnode *vp;
13791{
13792	struct bufobj *bo;
13793
13794	bo = &vp->v_bufobj;
13795	ASSERT_VOP_LOCKED(vp, "drain_output");
13796	ASSERT_BO_WLOCKED(bo);
13797
13798	while (bo->bo_numoutput) {
13799		bo->bo_flag |= BO_WWAIT;
13800		msleep((caddr_t)&bo->bo_numoutput,
13801		    BO_LOCKPTR(bo), PRIBIO + 1, "drainvp", 0);
13802	}
13803}
13804
13805/*
13806 * Called whenever a buffer that is being invalidated or reallocated
13807 * contains dependencies. This should only happen if an I/O error has
13808 * occurred. The routine is called with the buffer locked.
13809 */
13810static void
13811softdep_deallocate_dependencies(bp)
13812	struct buf *bp;
13813{
13814
13815	if ((bp->b_ioflags & BIO_ERROR) == 0)
13816		panic("softdep_deallocate_dependencies: dangling deps");
13817	if (bp->b_vp != NULL && bp->b_vp->v_mount != NULL)
13818		softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntonname, bp->b_error);
13819	else
13820		printf("softdep_deallocate_dependencies: "
13821		    "got error %d while accessing filesystem\n", bp->b_error);
13822	if (bp->b_error != ENXIO)
13823		panic("softdep_deallocate_dependencies: unrecovered I/O error");
13824}
13825
13826/*
13827 * Function to handle asynchronous write errors in the filesystem.
13828 */
13829static void
13830softdep_error(func, error)
13831	char *func;
13832	int error;
13833{
13834
13835	/* XXX should do something better! */
13836	printf("%s: got error %d while accessing filesystem\n", func, error);
13837}
13838
13839#ifdef DDB
13840
13841static void
13842inodedep_print(struct inodedep *inodedep, int verbose)
13843{
13844	db_printf("%p fs %p st %x ino %jd inoblk %jd delta %d nlink %d"
13845	    " saveino %p\n",
13846	    inodedep, inodedep->id_fs, inodedep->id_state,
13847	    (intmax_t)inodedep->id_ino,
13848	    (intmax_t)fsbtodb(inodedep->id_fs,
13849	    ino_to_fsba(inodedep->id_fs, inodedep->id_ino)),
13850	    inodedep->id_nlinkdelta, inodedep->id_savednlink,
13851	    inodedep->id_savedino1);
13852
13853	if (verbose == 0)
13854		return;
13855
13856	db_printf("\tpendinghd %p, bufwait %p, inowait %p, inoreflst %p, "
13857	    "mkdiradd %p\n",
13858	    LIST_FIRST(&inodedep->id_pendinghd),
13859	    LIST_FIRST(&inodedep->id_bufwait),
13860	    LIST_FIRST(&inodedep->id_inowait),
13861	    TAILQ_FIRST(&inodedep->id_inoreflst),
13862	    inodedep->id_mkdiradd);
13863	db_printf("\tinoupdt %p, newinoupdt %p, extupdt %p, newextupdt %p\n",
13864	    TAILQ_FIRST(&inodedep->id_inoupdt),
13865	    TAILQ_FIRST(&inodedep->id_newinoupdt),
13866	    TAILQ_FIRST(&inodedep->id_extupdt),
13867	    TAILQ_FIRST(&inodedep->id_newextupdt));
13868}
13869
13870DB_SHOW_COMMAND(inodedep, db_show_inodedep)
13871{
13872
13873	if (have_addr == 0) {
13874		db_printf("Address required\n");
13875		return;
13876	}
13877	inodedep_print((struct inodedep*)addr, 1);
13878}
13879
13880DB_SHOW_COMMAND(inodedeps, db_show_inodedeps)
13881{
13882	struct inodedep_hashhead *inodedephd;
13883	struct inodedep *inodedep;
13884	struct ufsmount *ump;
13885	int cnt;
13886
13887	if (have_addr == 0) {
13888		db_printf("Address required\n");
13889		return;
13890	}
13891	ump = (struct ufsmount *)addr;
13892	for (cnt = 0; cnt < ump->inodedep_hash_size; cnt++) {
13893		inodedephd = &ump->inodedep_hashtbl[cnt];
13894		LIST_FOREACH(inodedep, inodedephd, id_hash) {
13895			inodedep_print(inodedep, 0);
13896		}
13897	}
13898}
13899
13900DB_SHOW_COMMAND(worklist, db_show_worklist)
13901{
13902	struct worklist *wk;
13903
13904	if (have_addr == 0) {
13905		db_printf("Address required\n");
13906		return;
13907	}
13908	wk = (struct worklist *)addr;
13909	printf("worklist: %p type %s state 0x%X\n",
13910	    wk, TYPENAME(wk->wk_type), wk->wk_state);
13911}
13912
13913DB_SHOW_COMMAND(workhead, db_show_workhead)
13914{
13915	struct workhead *wkhd;
13916	struct worklist *wk;
13917	int i;
13918
13919	if (have_addr == 0) {
13920		db_printf("Address required\n");
13921		return;
13922	}
13923	wkhd = (struct workhead *)addr;
13924	wk = LIST_FIRST(wkhd);
13925	for (i = 0; i < 100 && wk != NULL; i++, wk = LIST_NEXT(wk, wk_list))
13926		db_printf("worklist: %p type %s state 0x%X",
13927		    wk, TYPENAME(wk->wk_type), wk->wk_state);
13928	if (i == 100)
13929		db_printf("workhead overflow");
13930	printf("\n");
13931}
13932
13933
13934DB_SHOW_COMMAND(mkdirs, db_show_mkdirs)
13935{
13936	struct mkdirlist *mkdirlisthd;
13937	struct jaddref *jaddref;
13938	struct diradd *diradd;
13939	struct mkdir *mkdir;
13940
13941	if (have_addr == 0) {
13942		db_printf("Address required\n");
13943		return;
13944	}
13945	mkdirlisthd = (struct mkdirlist *)addr;
13946	LIST_FOREACH(mkdir, mkdirlisthd, md_mkdirs) {
13947		diradd = mkdir->md_diradd;
13948		db_printf("mkdir: %p state 0x%X dap %p state 0x%X",
13949		    mkdir, mkdir->md_state, diradd, diradd->da_state);
13950		if ((jaddref = mkdir->md_jaddref) != NULL)
13951			db_printf(" jaddref %p jaddref state 0x%X",
13952			    jaddref, jaddref->ja_state);
13953		db_printf("\n");
13954	}
13955}
13956
13957/* exported to ffs_vfsops.c */
13958extern void db_print_ffs(struct ufsmount *ump);
13959void
13960db_print_ffs(struct ufsmount *ump)
13961{
13962	db_printf("mp %p %s devvp %p fs %p su_wl %d su_deps %d su_req %d\n",
13963	    ump->um_mountp, ump->um_mountp->mnt_stat.f_mntonname,
13964	    ump->um_devvp, ump->um_fs, ump->softdep_on_worklist,
13965	    ump->softdep_deps, ump->softdep_req);
13966}
13967
13968#endif /* DDB */
13969
13970#endif /* SOFTUPDATES */
13971