ffs_softdep.c revision 156203
1/*-
2 * Copyright 1998, 2000 Marshall Kirk McKusick. All Rights Reserved.
3 *
4 * The soft updates code is derived from the appendix of a University
5 * of Michigan technical report (Gregory R. Ganger and Yale N. Patt,
6 * "Soft Updates: A Solution to the Metadata Update Problem in File
7 * Systems", CSE-TR-254-95, August 1995).
8 *
9 * Further information about soft updates can be obtained from:
10 *
11 *	Marshall Kirk McKusick		http://www.mckusick.com/softdep/
12 *	1614 Oxford Street		mckusick@mckusick.com
13 *	Berkeley, CA 94709-1608		+1-510-843-9542
14 *	USA
15 *
16 * Redistribution and use in source and binary forms, with or without
17 * modification, are permitted provided that the following conditions
18 * are met:
19 *
20 * 1. Redistributions of source code must retain the above copyright
21 *    notice, this list of conditions and the following disclaimer.
22 * 2. Redistributions in binary form must reproduce the above copyright
23 *    notice, this list of conditions and the following disclaimer in the
24 *    documentation and/or other materials provided with the distribution.
25 *
26 * THIS SOFTWARE IS PROVIDED BY MARSHALL KIRK MCKUSICK ``AS IS'' AND ANY
27 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
28 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
29 * DISCLAIMED.  IN NO EVENT SHALL MARSHALL KIRK MCKUSICK BE LIABLE FOR
30 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * SUCH DAMAGE.
37 *
38 *	from: @(#)ffs_softdep.c	9.59 (McKusick) 6/21/00
39 */
40
41#include <sys/cdefs.h>
42__FBSDID("$FreeBSD: head/sys/ufs/ffs/ffs_softdep.c 156203 2006-03-02 05:50:23Z jeff $");
43
44/*
45 * For now we want the safety net that the DIAGNOSTIC and DEBUG flags provide.
46 */
47#ifndef DIAGNOSTIC
48#define DIAGNOSTIC
49#endif
50#ifndef DEBUG
51#define DEBUG
52#endif
53
54#include <sys/param.h>
55#include <sys/kernel.h>
56#include <sys/systm.h>
57#include <sys/bio.h>
58#include <sys/buf.h>
59#include <sys/kdb.h>
60#include <sys/kthread.h>
61#include <sys/lock.h>
62#include <sys/malloc.h>
63#include <sys/mount.h>
64#include <sys/mutex.h>
65#include <sys/proc.h>
66#include <sys/stat.h>
67#include <sys/sysctl.h>
68#include <sys/syslog.h>
69#include <sys/vnode.h>
70#include <sys/conf.h>
71#include <ufs/ufs/dir.h>
72#include <ufs/ufs/extattr.h>
73#include <ufs/ufs/quota.h>
74#include <ufs/ufs/inode.h>
75#include <ufs/ufs/ufsmount.h>
76#include <ufs/ffs/fs.h>
77#include <ufs/ffs/softdep.h>
78#include <ufs/ffs/ffs_extern.h>
79#include <ufs/ufs/ufs_extern.h>
80
81#include <vm/vm.h>
82
83#include "opt_ffs.h"
84
85#ifndef SOFTUPDATES
86
87int
88softdep_flushfiles(oldmnt, flags, td)
89	struct mount *oldmnt;
90	int flags;
91	struct thread *td;
92{
93
94	panic("softdep_flushfiles called");
95}
96
97int
98softdep_mount(devvp, mp, fs, cred)
99	struct vnode *devvp;
100	struct mount *mp;
101	struct fs *fs;
102	struct ucred *cred;
103{
104
105	return (0);
106}
107
108void
109softdep_initialize()
110{
111
112	return;
113}
114
115void
116softdep_uninitialize()
117{
118
119	return;
120}
121
122void
123softdep_setup_inomapdep(bp, ip, newinum)
124	struct buf *bp;
125	struct inode *ip;
126	ino_t newinum;
127{
128
129	panic("softdep_setup_inomapdep called");
130}
131
132void
133softdep_setup_blkmapdep(bp, mp, newblkno)
134	struct buf *bp;
135	struct mount *mp;
136	ufs2_daddr_t newblkno;
137{
138
139	panic("softdep_setup_blkmapdep called");
140}
141
142void
143softdep_setup_allocdirect(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
144	struct inode *ip;
145	ufs_lbn_t lbn;
146	ufs2_daddr_t newblkno;
147	ufs2_daddr_t oldblkno;
148	long newsize;
149	long oldsize;
150	struct buf *bp;
151{
152
153	panic("softdep_setup_allocdirect called");
154}
155
156void
157softdep_setup_allocext(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
158	struct inode *ip;
159	ufs_lbn_t lbn;
160	ufs2_daddr_t newblkno;
161	ufs2_daddr_t oldblkno;
162	long newsize;
163	long oldsize;
164	struct buf *bp;
165{
166
167	panic("softdep_setup_allocdirect called");
168}
169
170void
171softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
172	struct inode *ip;
173	ufs_lbn_t lbn;
174	struct buf *bp;
175	int ptrno;
176	ufs2_daddr_t newblkno;
177	ufs2_daddr_t oldblkno;
178	struct buf *nbp;
179{
180
181	panic("softdep_setup_allocindir_page called");
182}
183
184void
185softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
186	struct buf *nbp;
187	struct inode *ip;
188	struct buf *bp;
189	int ptrno;
190	ufs2_daddr_t newblkno;
191{
192
193	panic("softdep_setup_allocindir_meta called");
194}
195
196void
197softdep_setup_freeblocks(ip, length, flags)
198	struct inode *ip;
199	off_t length;
200	int flags;
201{
202
203	panic("softdep_setup_freeblocks called");
204}
205
206void
207softdep_freefile(pvp, ino, mode)
208		struct vnode *pvp;
209		ino_t ino;
210		int mode;
211{
212
213	panic("softdep_freefile called");
214}
215
216int
217softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
218	struct buf *bp;
219	struct inode *dp;
220	off_t diroffset;
221	ino_t newinum;
222	struct buf *newdirbp;
223	int isnewblk;
224{
225
226	panic("softdep_setup_directory_add called");
227}
228
229void
230softdep_change_directoryentry_offset(dp, base, oldloc, newloc, entrysize)
231	struct inode *dp;
232	caddr_t base;
233	caddr_t oldloc;
234	caddr_t newloc;
235	int entrysize;
236{
237
238	panic("softdep_change_directoryentry_offset called");
239}
240
241void
242softdep_setup_remove(bp, dp, ip, isrmdir)
243	struct buf *bp;
244	struct inode *dp;
245	struct inode *ip;
246	int isrmdir;
247{
248
249	panic("softdep_setup_remove called");
250}
251
252void
253softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
254	struct buf *bp;
255	struct inode *dp;
256	struct inode *ip;
257	ino_t newinum;
258	int isrmdir;
259{
260
261	panic("softdep_setup_directory_change called");
262}
263
264void
265softdep_change_linkcnt(ip)
266	struct inode *ip;
267{
268
269	panic("softdep_change_linkcnt called");
270}
271
272void
273softdep_load_inodeblock(ip)
274	struct inode *ip;
275{
276
277	panic("softdep_load_inodeblock called");
278}
279
280void
281softdep_update_inodeblock(ip, bp, waitfor)
282	struct inode *ip;
283	struct buf *bp;
284	int waitfor;
285{
286
287	panic("softdep_update_inodeblock called");
288}
289
290int
291softdep_fsync(vp)
292	struct vnode *vp;	/* the "in_core" copy of the inode */
293{
294
295	return (0);
296}
297
298void
299softdep_fsync_mountdev(vp)
300	struct vnode *vp;
301{
302
303	return;
304}
305
306int
307softdep_flushworklist(oldmnt, countp, td)
308	struct mount *oldmnt;
309	int *countp;
310	struct thread *td;
311{
312
313	*countp = 0;
314	return (0);
315}
316
317int
318softdep_sync_metadata(struct vnode *vp)
319{
320
321	return (0);
322}
323
324int
325softdep_slowdown(vp)
326	struct vnode *vp;
327{
328
329	panic("softdep_slowdown called");
330}
331
332void
333softdep_releasefile(ip)
334	struct inode *ip;	/* inode with the zero effective link count */
335{
336
337	panic("softdep_releasefile called");
338}
339
340int
341softdep_request_cleanup(fs, vp)
342	struct fs *fs;
343	struct vnode *vp;
344{
345
346	return (0);
347}
348
349#else
350/*
351 * These definitions need to be adapted to the system to which
352 * this file is being ported.
353 */
354/*
355 * malloc types defined for the softdep system.
356 */
357static MALLOC_DEFINE(M_PAGEDEP, "pagedep","File page dependencies");
358static MALLOC_DEFINE(M_INODEDEP, "inodedep","Inode dependencies");
359static MALLOC_DEFINE(M_NEWBLK, "newblk","New block allocation");
360static MALLOC_DEFINE(M_BMSAFEMAP, "bmsafemap","Block or frag allocated from cyl group map");
361static MALLOC_DEFINE(M_ALLOCDIRECT, "allocdirect","Block or frag dependency for an inode");
362static MALLOC_DEFINE(M_INDIRDEP, "indirdep","Indirect block dependencies");
363static MALLOC_DEFINE(M_ALLOCINDIR, "allocindir","Block dependency for an indirect block");
364static MALLOC_DEFINE(M_FREEFRAG, "freefrag","Previously used frag for an inode");
365static MALLOC_DEFINE(M_FREEBLKS, "freeblks","Blocks freed from an inode");
366static MALLOC_DEFINE(M_FREEFILE, "freefile","Inode deallocated");
367static MALLOC_DEFINE(M_DIRADD, "diradd","New directory entry");
368static MALLOC_DEFINE(M_MKDIR, "mkdir","New directory");
369static MALLOC_DEFINE(M_DIRREM, "dirrem","Directory entry deleted");
370static MALLOC_DEFINE(M_NEWDIRBLK, "newdirblk","Unclaimed new directory block");
371static MALLOC_DEFINE(M_SAVEDINO, "savedino","Saved inodes");
372
373#define M_SOFTDEP_FLAGS	(M_WAITOK | M_USE_RESERVE)
374
375#define	D_PAGEDEP	0
376#define	D_INODEDEP	1
377#define	D_NEWBLK	2
378#define	D_BMSAFEMAP	3
379#define	D_ALLOCDIRECT	4
380#define	D_INDIRDEP	5
381#define	D_ALLOCINDIR	6
382#define	D_FREEFRAG	7
383#define	D_FREEBLKS	8
384#define	D_FREEFILE	9
385#define	D_DIRADD	10
386#define	D_MKDIR		11
387#define	D_DIRREM	12
388#define	D_NEWDIRBLK	13
389#define	D_LAST		D_NEWDIRBLK
390
391/*
392 * translate from workitem type to memory type
393 * MUST match the defines above, such that memtype[D_XXX] == M_XXX
394 */
395static struct malloc_type *memtype[] = {
396	M_PAGEDEP,
397	M_INODEDEP,
398	M_NEWBLK,
399	M_BMSAFEMAP,
400	M_ALLOCDIRECT,
401	M_INDIRDEP,
402	M_ALLOCINDIR,
403	M_FREEFRAG,
404	M_FREEBLKS,
405	M_FREEFILE,
406	M_DIRADD,
407	M_MKDIR,
408	M_DIRREM,
409	M_NEWDIRBLK
410};
411
412#define DtoM(type) (memtype[type])
413
414/*
415 * Names of malloc types.
416 */
417#define TYPENAME(type)  \
418	((unsigned)(type) < D_LAST ? memtype[type]->ks_shortdesc : "???")
419/*
420 * End system adaptation definitions.
421 */
422
423/*
424 * Forward declarations.
425 */
426struct inodedep_hashhead;
427struct newblk_hashhead;
428struct pagedep_hashhead;
429
430/*
431 * Internal function prototypes.
432 */
433static	void softdep_error(char *, int);
434static	void drain_output(struct vnode *);
435static	struct buf *getdirtybuf(struct buf *, struct mtx *, int);
436static	void clear_remove(struct thread *);
437static	void clear_inodedeps(struct thread *);
438static	int flush_pagedep_deps(struct vnode *, struct mount *,
439	    struct diraddhd *);
440static	int flush_inodedep_deps(struct mount *, ino_t);
441static	int flush_deplist(struct allocdirectlst *, int, int *);
442static	int handle_written_filepage(struct pagedep *, struct buf *);
443static  void diradd_inode_written(struct diradd *, struct inodedep *);
444static	int handle_written_inodeblock(struct inodedep *, struct buf *);
445static	void handle_allocdirect_partdone(struct allocdirect *);
446static	void handle_allocindir_partdone(struct allocindir *);
447static	void initiate_write_filepage(struct pagedep *, struct buf *);
448static	void handle_written_mkdir(struct mkdir *, int);
449static	void initiate_write_inodeblock_ufs1(struct inodedep *, struct buf *);
450static	void initiate_write_inodeblock_ufs2(struct inodedep *, struct buf *);
451static	void handle_workitem_freefile(struct freefile *);
452static	void handle_workitem_remove(struct dirrem *, struct vnode *);
453static	struct dirrem *newdirrem(struct buf *, struct inode *,
454	    struct inode *, int, struct dirrem **);
455static	void free_diradd(struct diradd *);
456static	void free_allocindir(struct allocindir *, struct inodedep *);
457static	void free_newdirblk(struct newdirblk *);
458static	int indir_trunc(struct freeblks *, ufs2_daddr_t, int, ufs_lbn_t,
459	    ufs2_daddr_t *);
460static	void deallocate_dependencies(struct buf *, struct inodedep *);
461static	void free_allocdirect(struct allocdirectlst *,
462	    struct allocdirect *, int);
463static	int check_inode_unwritten(struct inodedep *);
464static	int free_inodedep(struct inodedep *);
465static	void handle_workitem_freeblocks(struct freeblks *, int);
466static	void merge_inode_lists(struct allocdirectlst *,struct allocdirectlst *);
467static	void setup_allocindir_phase2(struct buf *, struct inode *,
468	    struct allocindir *);
469static	struct allocindir *newallocindir(struct inode *, int, ufs2_daddr_t,
470	    ufs2_daddr_t);
471static	void handle_workitem_freefrag(struct freefrag *);
472static	struct freefrag *newfreefrag(struct inode *, ufs2_daddr_t, long);
473static	void allocdirect_merge(struct allocdirectlst *,
474	    struct allocdirect *, struct allocdirect *);
475static	struct bmsafemap *bmsafemap_lookup(struct mount *, struct buf *);
476static	int newblk_find(struct newblk_hashhead *, struct fs *, ufs2_daddr_t,
477	    struct newblk **);
478static	int newblk_lookup(struct fs *, ufs2_daddr_t, int, struct newblk **);
479static	int inodedep_find(struct inodedep_hashhead *, struct fs *, ino_t,
480	    struct inodedep **);
481static	int inodedep_lookup(struct mount *, ino_t, int, struct inodedep **);
482static	int pagedep_lookup(struct inode *, ufs_lbn_t, int, struct pagedep **);
483static	int pagedep_find(struct pagedep_hashhead *, ino_t, ufs_lbn_t,
484	    struct mount *mp, int, struct pagedep **);
485static	void pause_timer(void *);
486static	int request_cleanup(struct mount *, int);
487static	int process_worklist_item(struct mount *, int);
488static	void add_to_worklist(struct worklist *);
489static	void softdep_flush(void);
490static	int softdep_speedup(void);
491
492/*
493 * Exported softdep operations.
494 */
495static	void softdep_disk_io_initiation(struct buf *);
496static	void softdep_disk_write_complete(struct buf *);
497static	void softdep_deallocate_dependencies(struct buf *);
498static	int softdep_count_dependencies(struct buf *bp, int);
499
500static struct mtx lk;
501MTX_SYSINIT(softdep_lock, &lk, "Softdep Lock", MTX_DEF);
502
503#define ACQUIRE_LOCK(lk)		mtx_lock(lk)
504#define FREE_LOCK(lk)			mtx_unlock(lk)
505
506/*
507 * Worklist queue management.
508 * These routines require that the lock be held.
509 */
510#ifndef /* NOT */ DEBUG
511#define WORKLIST_INSERT(head, item) do {	\
512	(item)->wk_state |= ONWORKLIST;		\
513	LIST_INSERT_HEAD(head, item, wk_list);	\
514} while (0)
515#define WORKLIST_REMOVE(item) do {		\
516	(item)->wk_state &= ~ONWORKLIST;	\
517	LIST_REMOVE(item, wk_list);		\
518} while (0)
519#else /* DEBUG */
520static	void worklist_insert(struct workhead *, struct worklist *);
521static	void worklist_remove(struct worklist *);
522
523#define WORKLIST_INSERT(head, item) worklist_insert(head, item)
524#define WORKLIST_REMOVE(item) worklist_remove(item)
525
526static void
527worklist_insert(head, item)
528	struct workhead *head;
529	struct worklist *item;
530{
531
532	mtx_assert(&lk, MA_OWNED);
533	if (item->wk_state & ONWORKLIST)
534		panic("worklist_insert: already on list");
535	item->wk_state |= ONWORKLIST;
536	LIST_INSERT_HEAD(head, item, wk_list);
537}
538
539static void
540worklist_remove(item)
541	struct worklist *item;
542{
543
544	mtx_assert(&lk, MA_OWNED);
545	if ((item->wk_state & ONWORKLIST) == 0)
546		panic("worklist_remove: not on list");
547	item->wk_state &= ~ONWORKLIST;
548	LIST_REMOVE(item, wk_list);
549}
550#endif /* DEBUG */
551
552/*
553 * Routines for tracking and managing workitems.
554 */
555static	void workitem_free(struct worklist *, int);
556static	void workitem_alloc(struct worklist *, int, struct mount *);
557
558#define	WORKITEM_FREE(item, type) workitem_free((struct worklist *)(item), (type))
559
560static void
561workitem_free(item, type)
562	struct worklist *item;
563	int type;
564{
565	struct ufsmount *ump;
566	mtx_assert(&lk, MA_OWNED);
567
568#ifdef DEBUG
569	if (item->wk_state & ONWORKLIST)
570		panic("workitem_free: still on list");
571	if (item->wk_type != type)
572		panic("workitem_free: type mismatch");
573#endif
574	ump = VFSTOUFS(item->wk_mp);
575	if (--ump->softdep_deps == 0 && ump->softdep_req)
576		wakeup(&ump->softdep_deps);
577	FREE(item, DtoM(type));
578}
579
580static void
581workitem_alloc(item, type, mp)
582	struct worklist *item;
583	int type;
584	struct mount *mp;
585{
586	item->wk_type = type;
587	item->wk_mp = mp;
588	item->wk_state = 0;
589	ACQUIRE_LOCK(&lk);
590	VFSTOUFS(mp)->softdep_deps++;
591	FREE_LOCK(&lk);
592}
593
594/*
595 * Workitem queue management
596 */
597static int max_softdeps;	/* maximum number of structs before slowdown */
598static int maxindirdeps = 50;	/* max number of indirdeps before slowdown */
599static int tickdelay = 2;	/* number of ticks to pause during slowdown */
600static int proc_waiting;	/* tracks whether we have a timeout posted */
601static int *stat_countp;	/* statistic to count in proc_waiting timeout */
602static struct callout_handle handle; /* handle on posted proc_waiting timeout */
603static int req_pending;
604static int req_clear_inodedeps;	/* syncer process flush some inodedeps */
605#define FLUSH_INODES		1
606static int req_clear_remove;	/* syncer process flush some freeblks */
607#define FLUSH_REMOVE		2
608#define FLUSH_REMOVE_WAIT	3
609/*
610 * runtime statistics
611 */
612static int stat_worklist_push;	/* number of worklist cleanups */
613static int stat_blk_limit_push;	/* number of times block limit neared */
614static int stat_ino_limit_push;	/* number of times inode limit neared */
615static int stat_blk_limit_hit;	/* number of times block slowdown imposed */
616static int stat_ino_limit_hit;	/* number of times inode slowdown imposed */
617static int stat_sync_limit_hit;	/* number of synchronous slowdowns imposed */
618static int stat_indir_blk_ptrs;	/* bufs redirtied as indir ptrs not written */
619static int stat_inode_bitmap;	/* bufs redirtied as inode bitmap not written */
620static int stat_direct_blk_ptrs;/* bufs redirtied as direct ptrs not written */
621static int stat_dir_entry;	/* bufs redirtied as dir entry cannot write */
622
623SYSCTL_INT(_debug, OID_AUTO, max_softdeps, CTLFLAG_RW, &max_softdeps, 0, "");
624SYSCTL_INT(_debug, OID_AUTO, tickdelay, CTLFLAG_RW, &tickdelay, 0, "");
625SYSCTL_INT(_debug, OID_AUTO, maxindirdeps, CTLFLAG_RW, &maxindirdeps, 0, "");
626SYSCTL_INT(_debug, OID_AUTO, worklist_push, CTLFLAG_RW, &stat_worklist_push, 0,"");
627SYSCTL_INT(_debug, OID_AUTO, blk_limit_push, CTLFLAG_RW, &stat_blk_limit_push, 0,"");
628SYSCTL_INT(_debug, OID_AUTO, ino_limit_push, CTLFLAG_RW, &stat_ino_limit_push, 0,"");
629SYSCTL_INT(_debug, OID_AUTO, blk_limit_hit, CTLFLAG_RW, &stat_blk_limit_hit, 0, "");
630SYSCTL_INT(_debug, OID_AUTO, ino_limit_hit, CTLFLAG_RW, &stat_ino_limit_hit, 0, "");
631SYSCTL_INT(_debug, OID_AUTO, sync_limit_hit, CTLFLAG_RW, &stat_sync_limit_hit, 0, "");
632SYSCTL_INT(_debug, OID_AUTO, indir_blk_ptrs, CTLFLAG_RW, &stat_indir_blk_ptrs, 0, "");
633SYSCTL_INT(_debug, OID_AUTO, inode_bitmap, CTLFLAG_RW, &stat_inode_bitmap, 0, "");
634SYSCTL_INT(_debug, OID_AUTO, direct_blk_ptrs, CTLFLAG_RW, &stat_direct_blk_ptrs, 0, "");
635SYSCTL_INT(_debug, OID_AUTO, dir_entry, CTLFLAG_RW, &stat_dir_entry, 0, "");
636/* SYSCTL_INT(_debug, OID_AUTO, worklist_num, CTLFLAG_RD, &softdep_on_worklist, 0, ""); */
637
638SYSCTL_DECL(_vfs_ffs);
639
640static int compute_summary_at_mount = 0;	/* Whether to recompute the summary at mount time */
641SYSCTL_INT(_vfs_ffs, OID_AUTO, compute_summary_at_mount, CTLFLAG_RW,
642	   &compute_summary_at_mount, 0, "Recompute summary at mount");
643
644static struct proc *softdepproc;
645static struct kproc_desc softdep_kp = {
646	"softdepflush",
647	softdep_flush,
648	&softdepproc
649};
650SYSINIT(sdproc, SI_SUB_KTHREAD_UPDATE, SI_ORDER_ANY, kproc_start, &softdep_kp)
651
652static void
653softdep_flush(void)
654{
655	struct mount *nmp;
656	struct mount *mp;
657	struct thread *td;
658	int remaining;
659
660	td = curthread;
661	td->td_pflags |= TDP_NORUNNINGBUF;
662
663	for (;;) {
664		kthread_suspend_check(softdepproc);
665		ACQUIRE_LOCK(&lk);
666		/*
667		 * If requested, try removing inode or removal dependencies.
668		 */
669		if (req_clear_inodedeps) {
670			clear_inodedeps(td);
671			req_clear_inodedeps -= 1;
672			wakeup_one(&proc_waiting);
673		}
674		if (req_clear_remove) {
675			clear_remove(td);
676			req_clear_remove -= 1;
677			wakeup_one(&proc_waiting);
678		}
679		FREE_LOCK(&lk);
680		remaining = 0;
681		mtx_lock(&mountlist_mtx);
682		for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp)  {
683			nmp = TAILQ_NEXT(mp, mnt_list);
684			if ((mp->mnt_flag & MNT_SOFTDEP) == 0)
685				continue;
686			if (vfs_busy(mp, LK_NOWAIT, &mountlist_mtx, td))
687				continue;
688			softdep_process_worklist(mp, 0);
689			remaining += VFSTOUFS(mp)->softdep_on_worklist;
690			mtx_lock(&mountlist_mtx);
691			nmp = TAILQ_NEXT(mp, mnt_list);
692			vfs_unbusy(mp, td);
693		}
694		mtx_unlock(&mountlist_mtx);
695		if (remaining)
696			continue;
697		ACQUIRE_LOCK(&lk);
698		if (!req_pending)
699			msleep(&req_pending, &lk, PVM, "sdflush", hz);
700		req_pending = 0;
701		FREE_LOCK(&lk);
702	}
703}
704
705static int
706softdep_speedup(void)
707{
708	ACQUIRE_LOCK(&lk);
709	if (req_pending == 0) {
710		req_pending = 1;
711		wakeup(&req_pending);
712	}
713	FREE_LOCK(&lk);
714
715	return speedup_syncer();
716}
717
718/*
719 * Add an item to the end of the work queue.
720 * This routine requires that the lock be held.
721 * This is the only routine that adds items to the list.
722 * The following routine is the only one that removes items
723 * and does so in order from first to last.
724 */
725static void
726add_to_worklist(wk)
727	struct worklist *wk;
728{
729	struct ufsmount *ump;
730
731	mtx_assert(&lk, MA_OWNED);
732	ump = VFSTOUFS(wk->wk_mp);
733	if (wk->wk_state & ONWORKLIST)
734		panic("add_to_worklist: already on list");
735	wk->wk_state |= ONWORKLIST;
736	if (LIST_FIRST(&ump->softdep_workitem_pending) == NULL)
737		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
738	else
739		LIST_INSERT_AFTER(ump->softdep_worklist_tail, wk, wk_list);
740	ump->softdep_worklist_tail = wk;
741	ump->softdep_on_worklist += 1;
742}
743
744/*
745 * Process that runs once per second to handle items in the background queue.
746 *
747 * Note that we ensure that everything is done in the order in which they
748 * appear in the queue. The code below depends on this property to ensure
749 * that blocks of a file are freed before the inode itself is freed. This
750 * ordering ensures that no new <vfsid, inum, lbn> triples will be generated
751 * until all the old ones have been purged from the dependency lists.
752 */
753int
754softdep_process_worklist(mp, full)
755	struct mount *mp;
756	int full;
757{
758	struct thread *td = curthread;
759	int cnt, matchcnt, loopcount;
760	struct ufsmount *ump;
761	long starttime;
762
763	KASSERT(mp != NULL, ("softdep_process_worklist: NULL mp"));
764	/*
765	 * Record the process identifier of our caller so that we can give
766	 * this process preferential treatment in request_cleanup below.
767	 */
768	matchcnt = 0;
769	ump = VFSTOUFS(mp);
770	ACQUIRE_LOCK(&lk);
771	loopcount = 1;
772	starttime = time_second;
773	while (ump->softdep_on_worklist > 0) {
774		if ((cnt = process_worklist_item(mp, 0)) == -1)
775			break;
776		else
777			matchcnt += cnt;
778		/*
779		 * If requested, try removing inode or removal dependencies.
780		 */
781		if (req_clear_inodedeps) {
782			clear_inodedeps(td);
783			req_clear_inodedeps -= 1;
784			wakeup_one(&proc_waiting);
785		}
786		if (req_clear_remove) {
787			clear_remove(td);
788			req_clear_remove -= 1;
789			wakeup_one(&proc_waiting);
790		}
791		/*
792		 * We do not generally want to stop for buffer space, but if
793		 * we are really being a buffer hog, we will stop and wait.
794		 */
795		if (loopcount++ % 128 == 0) {
796			FREE_LOCK(&lk);
797			bwillwrite();
798			ACQUIRE_LOCK(&lk);
799		}
800		/*
801		 * Never allow processing to run for more than one
802		 * second. Otherwise the other mountpoints may get
803		 * excessively backlogged.
804		 */
805		if (!full && starttime != time_second) {
806			matchcnt = -1;
807			break;
808		}
809	}
810	FREE_LOCK(&lk);
811	return (matchcnt);
812}
813
814/*
815 * Process one item on the worklist.
816 */
817static int
818process_worklist_item(mp, flags)
819	struct mount *mp;
820	int flags;
821{
822	struct worklist *wk, *wkend;
823	struct ufsmount *ump;
824	struct vnode *vp;
825	int matchcnt = 0;
826
827	mtx_assert(&lk, MA_OWNED);
828	KASSERT(mp != NULL, ("process_worklist_item: NULL mp"));
829	/*
830	 * If we are being called because of a process doing a
831	 * copy-on-write, then it is not safe to write as we may
832	 * recurse into the copy-on-write routine.
833	 */
834	if (curthread->td_pflags & TDP_COWINPROGRESS)
835		return (-1);
836	/*
837	 * Normally we just process each item on the worklist in order.
838	 * However, if we are in a situation where we cannot lock any
839	 * inodes, we have to skip over any dirrem requests whose
840	 * vnodes are resident and locked.
841	 */
842	ump = VFSTOUFS(mp);
843	vp = NULL;
844	LIST_FOREACH(wk, &ump->softdep_workitem_pending, wk_list) {
845		if (wk->wk_state & INPROGRESS)
846			continue;
847		if ((flags & LK_NOWAIT) == 0 || wk->wk_type != D_DIRREM)
848			break;
849		wk->wk_state |= INPROGRESS;
850		FREE_LOCK(&lk);
851		ffs_vget(mp, WK_DIRREM(wk)->dm_oldinum,
852		    LK_NOWAIT | LK_EXCLUSIVE, &vp);
853		ACQUIRE_LOCK(&lk);
854		wk->wk_state &= ~INPROGRESS;
855		if (vp != NULL)
856			break;
857	}
858	if (wk == 0)
859		return (-1);
860	/*
861	 * Remove the item to be processed. If we are removing the last
862	 * item on the list, we need to recalculate the tail pointer.
863	 * As this happens rarely and usually when the list is short,
864	 * we just run down the list to find it rather than tracking it
865	 * in the above loop.
866	 */
867	WORKLIST_REMOVE(wk);
868	if (wk == ump->softdep_worklist_tail) {
869		LIST_FOREACH(wkend, &ump->softdep_workitem_pending, wk_list)
870			if (LIST_NEXT(wkend, wk_list) == NULL)
871				break;
872		ump->softdep_worklist_tail = wkend;
873	}
874	ump->softdep_on_worklist -= 1;
875	FREE_LOCK(&lk);
876	if (vn_write_suspend_wait(NULL, mp, V_NOWAIT))
877		panic("process_worklist_item: suspended filesystem");
878	matchcnt++;
879	switch (wk->wk_type) {
880
881	case D_DIRREM:
882		/* removal of a directory entry */
883		handle_workitem_remove(WK_DIRREM(wk), vp);
884		break;
885
886	case D_FREEBLKS:
887		/* releasing blocks and/or fragments from a file */
888		handle_workitem_freeblocks(WK_FREEBLKS(wk), flags & LK_NOWAIT);
889		break;
890
891	case D_FREEFRAG:
892		/* releasing a fragment when replaced as a file grows */
893		handle_workitem_freefrag(WK_FREEFRAG(wk));
894		break;
895
896	case D_FREEFILE:
897		/* releasing an inode when its link count drops to 0 */
898		handle_workitem_freefile(WK_FREEFILE(wk));
899		break;
900
901	default:
902		panic("%s_process_worklist: Unknown type %s",
903		    "softdep", TYPENAME(wk->wk_type));
904		/* NOTREACHED */
905	}
906	ACQUIRE_LOCK(&lk);
907	return (matchcnt);
908}
909
910/*
911 * Move dependencies from one buffer to another.
912 */
913void
914softdep_move_dependencies(oldbp, newbp)
915	struct buf *oldbp;
916	struct buf *newbp;
917{
918	struct worklist *wk, *wktail;
919
920	if (LIST_FIRST(&newbp->b_dep) != NULL)
921		panic("softdep_move_dependencies: need merge code");
922	wktail = 0;
923	ACQUIRE_LOCK(&lk);
924	while ((wk = LIST_FIRST(&oldbp->b_dep)) != NULL) {
925		LIST_REMOVE(wk, wk_list);
926		if (wktail == 0)
927			LIST_INSERT_HEAD(&newbp->b_dep, wk, wk_list);
928		else
929			LIST_INSERT_AFTER(wktail, wk, wk_list);
930		wktail = wk;
931	}
932	FREE_LOCK(&lk);
933}
934
935/*
936 * Purge the work list of all items associated with a particular mount point.
937 */
938int
939softdep_flushworklist(oldmnt, countp, td)
940	struct mount *oldmnt;
941	int *countp;
942	struct thread *td;
943{
944	struct vnode *devvp;
945	int count, error = 0;
946	struct ufsmount *ump;
947
948	/*
949	 * Alternately flush the block device associated with the mount
950	 * point and process any dependencies that the flushing
951	 * creates. We continue until no more worklist dependencies
952	 * are found.
953	 */
954	*countp = 0;
955	ump = VFSTOUFS(oldmnt);
956	devvp = ump->um_devvp;
957	while ((count = softdep_process_worklist(oldmnt, 1)) > 0) {
958		*countp += count;
959		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY, td);
960		error = VOP_FSYNC(devvp, MNT_WAIT, td);
961		VOP_UNLOCK(devvp, 0, td);
962		if (error)
963			break;
964	}
965	return (error);
966}
967
968int
969softdep_waitidle(struct mount *mp)
970{
971	struct ufsmount *ump;
972	int error;
973	int i;
974
975	ump = VFSTOUFS(mp);
976	ACQUIRE_LOCK(&lk);
977	for (i = 0; i < 10 && ump->softdep_deps; i++) {
978		ump->softdep_req = 1;
979		if (ump->softdep_on_worklist)
980			panic("softdep_waitidle: work added after flush.");
981		msleep(&ump->softdep_deps, &lk, PVM, "softdeps", 1);
982	}
983	ump->softdep_req = 0;
984	FREE_LOCK(&lk);
985	error = 0;
986	if (i == 10) {
987		error = EBUSY;
988		printf("softdep_waitidle: Failed to flush worklist for %p",
989		    mp);
990	}
991
992	return (error);
993}
994
995/*
996 * Flush all vnodes and worklist items associated with a specified mount point.
997 */
998int
999softdep_flushfiles(oldmnt, flags, td)
1000	struct mount *oldmnt;
1001	int flags;
1002	struct thread *td;
1003{
1004	int error, count, loopcnt;
1005
1006	error = 0;
1007
1008	/*
1009	 * Alternately flush the vnodes associated with the mount
1010	 * point and process any dependencies that the flushing
1011	 * creates. In theory, this loop can happen at most twice,
1012	 * but we give it a few extra just to be sure.
1013	 */
1014	for (loopcnt = 10; loopcnt > 0; loopcnt--) {
1015		/*
1016		 * Do another flush in case any vnodes were brought in
1017		 * as part of the cleanup operations.
1018		 */
1019		if ((error = ffs_flushfiles(oldmnt, flags, td)) != 0)
1020			break;
1021		if ((error = softdep_flushworklist(oldmnt, &count, td)) != 0 ||
1022		    count == 0)
1023			break;
1024	}
1025	/*
1026	 * If we are unmounting then it is an error to fail. If we
1027	 * are simply trying to downgrade to read-only, then filesystem
1028	 * activity can keep us busy forever, so we just fail with EBUSY.
1029	 */
1030	if (loopcnt == 0) {
1031		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT)
1032			panic("softdep_flushfiles: looping");
1033		error = EBUSY;
1034	}
1035	if (!error)
1036		error = softdep_waitidle(oldmnt);
1037	return (error);
1038}
1039
1040/*
1041 * Structure hashing.
1042 *
1043 * There are three types of structures that can be looked up:
1044 *	1) pagedep structures identified by mount point, inode number,
1045 *	   and logical block.
1046 *	2) inodedep structures identified by mount point and inode number.
1047 *	3) newblk structures identified by mount point and
1048 *	   physical block number.
1049 *
1050 * The "pagedep" and "inodedep" dependency structures are hashed
1051 * separately from the file blocks and inodes to which they correspond.
1052 * This separation helps when the in-memory copy of an inode or
1053 * file block must be replaced. It also obviates the need to access
1054 * an inode or file page when simply updating (or de-allocating)
1055 * dependency structures. Lookup of newblk structures is needed to
1056 * find newly allocated blocks when trying to associate them with
1057 * their allocdirect or allocindir structure.
1058 *
1059 * The lookup routines optionally create and hash a new instance when
1060 * an existing entry is not found.
1061 */
1062#define DEPALLOC	0x0001	/* allocate structure if lookup fails */
1063#define NODELAY		0x0002	/* cannot do background work */
1064
1065/*
1066 * Structures and routines associated with pagedep caching.
1067 */
1068LIST_HEAD(pagedep_hashhead, pagedep) *pagedep_hashtbl;
1069u_long	pagedep_hash;		/* size of hash table - 1 */
1070#define	PAGEDEP_HASH(mp, inum, lbn) \
1071	(&pagedep_hashtbl[((((register_t)(mp)) >> 13) + (inum) + (lbn)) & \
1072	    pagedep_hash])
1073
1074static int
1075pagedep_find(pagedephd, ino, lbn, mp, flags, pagedeppp)
1076	struct pagedep_hashhead *pagedephd;
1077	ino_t ino;
1078	ufs_lbn_t lbn;
1079	struct mount *mp;
1080	int flags;
1081	struct pagedep **pagedeppp;
1082{
1083	struct pagedep *pagedep;
1084
1085	LIST_FOREACH(pagedep, pagedephd, pd_hash)
1086		if (ino == pagedep->pd_ino &&
1087		    lbn == pagedep->pd_lbn &&
1088		    mp == pagedep->pd_list.wk_mp)
1089			break;
1090	if (pagedep) {
1091		*pagedeppp = pagedep;
1092		if ((flags & DEPALLOC) != 0 &&
1093		    (pagedep->pd_state & ONWORKLIST) == 0)
1094			return (0);
1095		return (1);
1096	}
1097	*pagedeppp = NULL;
1098	return (0);
1099}
1100/*
1101 * Look up a pagedep. Return 1 if found, 0 if not found or found
1102 * when asked to allocate but not associated with any buffer.
1103 * If not found, allocate if DEPALLOC flag is passed.
1104 * Found or allocated entry is returned in pagedeppp.
1105 * This routine must be called with splbio interrupts blocked.
1106 */
1107static int
1108pagedep_lookup(ip, lbn, flags, pagedeppp)
1109	struct inode *ip;
1110	ufs_lbn_t lbn;
1111	int flags;
1112	struct pagedep **pagedeppp;
1113{
1114	struct pagedep *pagedep;
1115	struct pagedep_hashhead *pagedephd;
1116	struct mount *mp;
1117	int ret;
1118	int i;
1119
1120	mtx_assert(&lk, MA_OWNED);
1121	mp = ITOV(ip)->v_mount;
1122	pagedephd = PAGEDEP_HASH(mp, ip->i_number, lbn);
1123
1124	ret = pagedep_find(pagedephd, ip->i_number, lbn, mp, flags, pagedeppp);
1125	if (*pagedeppp || (flags & DEPALLOC) == 0)
1126		return (ret);
1127	FREE_LOCK(&lk);
1128	MALLOC(pagedep, struct pagedep *, sizeof(struct pagedep),
1129	    M_PAGEDEP, M_SOFTDEP_FLAGS|M_ZERO);
1130	workitem_alloc(&pagedep->pd_list, D_PAGEDEP, mp);
1131	ACQUIRE_LOCK(&lk);
1132	ret = pagedep_find(pagedephd, ip->i_number, lbn, mp, flags, pagedeppp);
1133	if (*pagedeppp) {
1134		WORKITEM_FREE(pagedep, D_PAGEDEP);
1135		return (ret);
1136	}
1137	pagedep->pd_ino = ip->i_number;
1138	pagedep->pd_lbn = lbn;
1139	LIST_INIT(&pagedep->pd_dirremhd);
1140	LIST_INIT(&pagedep->pd_pendinghd);
1141	for (i = 0; i < DAHASHSZ; i++)
1142		LIST_INIT(&pagedep->pd_diraddhd[i]);
1143	LIST_INSERT_HEAD(pagedephd, pagedep, pd_hash);
1144	*pagedeppp = pagedep;
1145	return (0);
1146}
1147
1148/*
1149 * Structures and routines associated with inodedep caching.
1150 */
1151LIST_HEAD(inodedep_hashhead, inodedep) *inodedep_hashtbl;
1152static u_long	inodedep_hash;	/* size of hash table - 1 */
1153static long	num_inodedep;	/* number of inodedep allocated */
1154#define	INODEDEP_HASH(fs, inum) \
1155      (&inodedep_hashtbl[((((register_t)(fs)) >> 13) + (inum)) & inodedep_hash])
1156
1157static int
1158inodedep_find(inodedephd, fs, inum, inodedeppp)
1159	struct inodedep_hashhead *inodedephd;
1160	struct fs *fs;
1161	ino_t inum;
1162	struct inodedep **inodedeppp;
1163{
1164	struct inodedep *inodedep;
1165
1166	LIST_FOREACH(inodedep, inodedephd, id_hash)
1167		if (inum == inodedep->id_ino && fs == inodedep->id_fs)
1168			break;
1169	if (inodedep) {
1170		*inodedeppp = inodedep;
1171		return (1);
1172	}
1173	*inodedeppp = NULL;
1174
1175	return (0);
1176}
1177/*
1178 * Look up an inodedep. Return 1 if found, 0 if not found.
1179 * If not found, allocate if DEPALLOC flag is passed.
1180 * Found or allocated entry is returned in inodedeppp.
1181 * This routine must be called with splbio interrupts blocked.
1182 */
1183static int
1184inodedep_lookup(mp, inum, flags, inodedeppp)
1185	struct mount *mp;
1186	ino_t inum;
1187	int flags;
1188	struct inodedep **inodedeppp;
1189{
1190	struct inodedep *inodedep;
1191	struct inodedep_hashhead *inodedephd;
1192	struct fs *fs;
1193
1194	mtx_assert(&lk, MA_OWNED);
1195	fs = VFSTOUFS(mp)->um_fs;
1196	inodedephd = INODEDEP_HASH(fs, inum);
1197
1198	if (inodedep_find(inodedephd, fs, inum, inodedeppp))
1199		return (1);
1200	if ((flags & DEPALLOC) == 0)
1201		return (0);
1202	/*
1203	 * If we are over our limit, try to improve the situation.
1204	 */
1205	if (num_inodedep > max_softdeps && (flags & NODELAY) == 0)
1206		request_cleanup(mp, FLUSH_INODES);
1207	FREE_LOCK(&lk);
1208	MALLOC(inodedep, struct inodedep *, sizeof(struct inodedep),
1209		M_INODEDEP, M_SOFTDEP_FLAGS);
1210	workitem_alloc(&inodedep->id_list, D_INODEDEP, mp);
1211	ACQUIRE_LOCK(&lk);
1212	if (inodedep_find(inodedephd, fs, inum, inodedeppp)) {
1213		WORKITEM_FREE(inodedep, D_INODEDEP);
1214		return (1);
1215	}
1216	num_inodedep += 1;
1217	inodedep->id_fs = fs;
1218	inodedep->id_ino = inum;
1219	inodedep->id_state = ALLCOMPLETE;
1220	inodedep->id_nlinkdelta = 0;
1221	inodedep->id_savedino1 = NULL;
1222	inodedep->id_savedsize = -1;
1223	inodedep->id_savedextsize = -1;
1224	inodedep->id_buf = NULL;
1225	LIST_INIT(&inodedep->id_pendinghd);
1226	LIST_INIT(&inodedep->id_inowait);
1227	LIST_INIT(&inodedep->id_bufwait);
1228	TAILQ_INIT(&inodedep->id_inoupdt);
1229	TAILQ_INIT(&inodedep->id_newinoupdt);
1230	TAILQ_INIT(&inodedep->id_extupdt);
1231	TAILQ_INIT(&inodedep->id_newextupdt);
1232	LIST_INSERT_HEAD(inodedephd, inodedep, id_hash);
1233	*inodedeppp = inodedep;
1234	return (0);
1235}
1236
1237/*
1238 * Structures and routines associated with newblk caching.
1239 */
1240LIST_HEAD(newblk_hashhead, newblk) *newblk_hashtbl;
1241u_long	newblk_hash;		/* size of hash table - 1 */
1242#define	NEWBLK_HASH(fs, inum) \
1243	(&newblk_hashtbl[((((register_t)(fs)) >> 13) + (inum)) & newblk_hash])
1244
1245static int
1246newblk_find(newblkhd, fs, newblkno, newblkpp)
1247	struct newblk_hashhead *newblkhd;
1248	struct fs *fs;
1249	ufs2_daddr_t newblkno;
1250	struct newblk **newblkpp;
1251{
1252	struct newblk *newblk;
1253
1254	LIST_FOREACH(newblk, newblkhd, nb_hash)
1255		if (newblkno == newblk->nb_newblkno && fs == newblk->nb_fs)
1256			break;
1257	if (newblk) {
1258		*newblkpp = newblk;
1259		return (1);
1260	}
1261	*newblkpp = NULL;
1262	return (0);
1263}
1264
1265/*
1266 * Look up a newblk. Return 1 if found, 0 if not found.
1267 * If not found, allocate if DEPALLOC flag is passed.
1268 * Found or allocated entry is returned in newblkpp.
1269 */
1270static int
1271newblk_lookup(fs, newblkno, flags, newblkpp)
1272	struct fs *fs;
1273	ufs2_daddr_t newblkno;
1274	int flags;
1275	struct newblk **newblkpp;
1276{
1277	struct newblk *newblk;
1278	struct newblk_hashhead *newblkhd;
1279
1280	newblkhd = NEWBLK_HASH(fs, newblkno);
1281	if (newblk_find(newblkhd, fs, newblkno, newblkpp))
1282		return (1);
1283	if ((flags & DEPALLOC) == 0)
1284		return (0);
1285	FREE_LOCK(&lk);
1286	MALLOC(newblk, struct newblk *, sizeof(struct newblk),
1287		M_NEWBLK, M_SOFTDEP_FLAGS);
1288	ACQUIRE_LOCK(&lk);
1289	if (newblk_find(newblkhd, fs, newblkno, newblkpp)) {
1290		FREE(newblk, M_NEWBLK);
1291		return (1);
1292	}
1293	newblk->nb_state = 0;
1294	newblk->nb_fs = fs;
1295	newblk->nb_newblkno = newblkno;
1296	LIST_INSERT_HEAD(newblkhd, newblk, nb_hash);
1297	*newblkpp = newblk;
1298	return (0);
1299}
1300
1301/*
1302 * Executed during filesystem system initialization before
1303 * mounting any filesystems.
1304 */
1305void
1306softdep_initialize()
1307{
1308
1309	LIST_INIT(&mkdirlisthd);
1310	max_softdeps = desiredvnodes * 4;
1311	pagedep_hashtbl = hashinit(desiredvnodes / 5, M_PAGEDEP,
1312	    &pagedep_hash);
1313	inodedep_hashtbl = hashinit(desiredvnodes, M_INODEDEP, &inodedep_hash);
1314	newblk_hashtbl = hashinit(64, M_NEWBLK, &newblk_hash);
1315
1316	/* initialise bioops hack */
1317	bioops.io_start = softdep_disk_io_initiation;
1318	bioops.io_complete = softdep_disk_write_complete;
1319	bioops.io_deallocate = softdep_deallocate_dependencies;
1320	bioops.io_countdeps = softdep_count_dependencies;
1321}
1322
1323/*
1324 * Executed after all filesystems have been unmounted during
1325 * filesystem module unload.
1326 */
1327void
1328softdep_uninitialize()
1329{
1330
1331	hashdestroy(pagedep_hashtbl, M_PAGEDEP, pagedep_hash);
1332	hashdestroy(inodedep_hashtbl, M_INODEDEP, inodedep_hash);
1333	hashdestroy(newblk_hashtbl, M_NEWBLK, newblk_hash);
1334}
1335
1336/*
1337 * Called at mount time to notify the dependency code that a
1338 * filesystem wishes to use it.
1339 */
1340int
1341softdep_mount(devvp, mp, fs, cred)
1342	struct vnode *devvp;
1343	struct mount *mp;
1344	struct fs *fs;
1345	struct ucred *cred;
1346{
1347	struct csum_total cstotal;
1348	struct ufsmount *ump;
1349	struct cg *cgp;
1350	struct buf *bp;
1351	int error, cyl;
1352
1353	mp->mnt_flag &= ~MNT_ASYNC;
1354	mp->mnt_flag |= MNT_SOFTDEP;
1355	ump = VFSTOUFS(mp);
1356	LIST_INIT(&ump->softdep_workitem_pending);
1357	ump->softdep_worklist_tail = NULL;
1358	ump->softdep_on_worklist = 0;
1359	ump->softdep_deps = 0;
1360	/*
1361	 * When doing soft updates, the counters in the
1362	 * superblock may have gotten out of sync. Recomputation
1363	 * can take a long time and can be deferred for background
1364	 * fsck.  However, the old behavior of scanning the cylinder
1365	 * groups and recalculating them at mount time is available
1366	 * by setting vfs.ffs.compute_summary_at_mount to one.
1367	 */
1368	if (compute_summary_at_mount == 0 || fs->fs_clean != 0)
1369		return (0);
1370	bzero(&cstotal, sizeof cstotal);
1371	for (cyl = 0; cyl < fs->fs_ncg; cyl++) {
1372		if ((error = bread(devvp, fsbtodb(fs, cgtod(fs, cyl)),
1373		    fs->fs_cgsize, cred, &bp)) != 0) {
1374			brelse(bp);
1375			return (error);
1376		}
1377		cgp = (struct cg *)bp->b_data;
1378		cstotal.cs_nffree += cgp->cg_cs.cs_nffree;
1379		cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree;
1380		cstotal.cs_nifree += cgp->cg_cs.cs_nifree;
1381		cstotal.cs_ndir += cgp->cg_cs.cs_ndir;
1382		fs->fs_cs(fs, cyl) = cgp->cg_cs;
1383		brelse(bp);
1384	}
1385#ifdef DEBUG
1386	if (bcmp(&cstotal, &fs->fs_cstotal, sizeof cstotal))
1387		printf("%s: superblock summary recomputed\n", fs->fs_fsmnt);
1388#endif
1389	bcopy(&cstotal, &fs->fs_cstotal, sizeof cstotal);
1390	return (0);
1391}
1392
1393/*
1394 * Protecting the freemaps (or bitmaps).
1395 *
1396 * To eliminate the need to execute fsck before mounting a filesystem
1397 * after a power failure, one must (conservatively) guarantee that the
1398 * on-disk copy of the bitmaps never indicate that a live inode or block is
1399 * free.  So, when a block or inode is allocated, the bitmap should be
1400 * updated (on disk) before any new pointers.  When a block or inode is
1401 * freed, the bitmap should not be updated until all pointers have been
1402 * reset.  The latter dependency is handled by the delayed de-allocation
1403 * approach described below for block and inode de-allocation.  The former
1404 * dependency is handled by calling the following procedure when a block or
1405 * inode is allocated. When an inode is allocated an "inodedep" is created
1406 * with its DEPCOMPLETE flag cleared until its bitmap is written to disk.
1407 * Each "inodedep" is also inserted into the hash indexing structure so
1408 * that any additional link additions can be made dependent on the inode
1409 * allocation.
1410 *
1411 * The ufs filesystem maintains a number of free block counts (e.g., per
1412 * cylinder group, per cylinder and per <cylinder, rotational position> pair)
1413 * in addition to the bitmaps.  These counts are used to improve efficiency
1414 * during allocation and therefore must be consistent with the bitmaps.
1415 * There is no convenient way to guarantee post-crash consistency of these
1416 * counts with simple update ordering, for two main reasons: (1) The counts
1417 * and bitmaps for a single cylinder group block are not in the same disk
1418 * sector.  If a disk write is interrupted (e.g., by power failure), one may
1419 * be written and the other not.  (2) Some of the counts are located in the
1420 * superblock rather than the cylinder group block. So, we focus our soft
1421 * updates implementation on protecting the bitmaps. When mounting a
1422 * filesystem, we recompute the auxiliary counts from the bitmaps.
1423 */
1424
1425/*
1426 * Called just after updating the cylinder group block to allocate an inode.
1427 */
1428void
1429softdep_setup_inomapdep(bp, ip, newinum)
1430	struct buf *bp;		/* buffer for cylgroup block with inode map */
1431	struct inode *ip;	/* inode related to allocation */
1432	ino_t newinum;		/* new inode number being allocated */
1433{
1434	struct inodedep *inodedep;
1435	struct bmsafemap *bmsafemap;
1436
1437	/*
1438	 * Create a dependency for the newly allocated inode.
1439	 * Panic if it already exists as something is seriously wrong.
1440	 * Otherwise add it to the dependency list for the buffer holding
1441	 * the cylinder group map from which it was allocated.
1442	 */
1443	ACQUIRE_LOCK(&lk);
1444	if ((inodedep_lookup(UFSTOVFS(ip->i_ump), newinum, DEPALLOC|NODELAY,
1445	    &inodedep)))
1446		panic("softdep_setup_inomapdep: found inode");
1447	inodedep->id_buf = bp;
1448	inodedep->id_state &= ~DEPCOMPLETE;
1449	bmsafemap = bmsafemap_lookup(inodedep->id_list.wk_mp, bp);
1450	LIST_INSERT_HEAD(&bmsafemap->sm_inodedephd, inodedep, id_deps);
1451	FREE_LOCK(&lk);
1452}
1453
1454/*
1455 * Called just after updating the cylinder group block to
1456 * allocate block or fragment.
1457 */
1458void
1459softdep_setup_blkmapdep(bp, mp, newblkno)
1460	struct buf *bp;		/* buffer for cylgroup block with block map */
1461	struct mount *mp;	/* filesystem doing allocation */
1462	ufs2_daddr_t newblkno;	/* number of newly allocated block */
1463{
1464	struct newblk *newblk;
1465	struct bmsafemap *bmsafemap;
1466	struct fs *fs;
1467
1468	fs = VFSTOUFS(mp)->um_fs;
1469	/*
1470	 * Create a dependency for the newly allocated block.
1471	 * Add it to the dependency list for the buffer holding
1472	 * the cylinder group map from which it was allocated.
1473	 */
1474	ACQUIRE_LOCK(&lk);
1475	if (newblk_lookup(fs, newblkno, DEPALLOC, &newblk) != 0)
1476		panic("softdep_setup_blkmapdep: found block");
1477	newblk->nb_bmsafemap = bmsafemap = bmsafemap_lookup(mp, bp);
1478	LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
1479	FREE_LOCK(&lk);
1480}
1481
1482/*
1483 * Find the bmsafemap associated with a cylinder group buffer.
1484 * If none exists, create one. The buffer must be locked when
1485 * this routine is called and this routine must be called with
1486 * splbio interrupts blocked.
1487 */
1488static struct bmsafemap *
1489bmsafemap_lookup(mp, bp)
1490	struct mount *mp;
1491	struct buf *bp;
1492{
1493	struct bmsafemap *bmsafemap;
1494	struct worklist *wk;
1495
1496	mtx_assert(&lk, MA_OWNED);
1497	LIST_FOREACH(wk, &bp->b_dep, wk_list)
1498		if (wk->wk_type == D_BMSAFEMAP)
1499			return (WK_BMSAFEMAP(wk));
1500	FREE_LOCK(&lk);
1501	MALLOC(bmsafemap, struct bmsafemap *, sizeof(struct bmsafemap),
1502		M_BMSAFEMAP, M_SOFTDEP_FLAGS);
1503	workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
1504	bmsafemap->sm_buf = bp;
1505	LIST_INIT(&bmsafemap->sm_allocdirecthd);
1506	LIST_INIT(&bmsafemap->sm_allocindirhd);
1507	LIST_INIT(&bmsafemap->sm_inodedephd);
1508	LIST_INIT(&bmsafemap->sm_newblkhd);
1509	ACQUIRE_LOCK(&lk);
1510	WORKLIST_INSERT(&bp->b_dep, &bmsafemap->sm_list);
1511	return (bmsafemap);
1512}
1513
1514/*
1515 * Direct block allocation dependencies.
1516 *
1517 * When a new block is allocated, the corresponding disk locations must be
1518 * initialized (with zeros or new data) before the on-disk inode points to
1519 * them.  Also, the freemap from which the block was allocated must be
1520 * updated (on disk) before the inode's pointer. These two dependencies are
1521 * independent of each other and are needed for all file blocks and indirect
1522 * blocks that are pointed to directly by the inode.  Just before the
1523 * "in-core" version of the inode is updated with a newly allocated block
1524 * number, a procedure (below) is called to setup allocation dependency
1525 * structures.  These structures are removed when the corresponding
1526 * dependencies are satisfied or when the block allocation becomes obsolete
1527 * (i.e., the file is deleted, the block is de-allocated, or the block is a
1528 * fragment that gets upgraded).  All of these cases are handled in
1529 * procedures described later.
1530 *
1531 * When a file extension causes a fragment to be upgraded, either to a larger
1532 * fragment or to a full block, the on-disk location may change (if the
1533 * previous fragment could not simply be extended). In this case, the old
1534 * fragment must be de-allocated, but not until after the inode's pointer has
1535 * been updated. In most cases, this is handled by later procedures, which
1536 * will construct a "freefrag" structure to be added to the workitem queue
1537 * when the inode update is complete (or obsolete).  The main exception to
1538 * this is when an allocation occurs while a pending allocation dependency
1539 * (for the same block pointer) remains.  This case is handled in the main
1540 * allocation dependency setup procedure by immediately freeing the
1541 * unreferenced fragments.
1542 */
1543void
1544softdep_setup_allocdirect(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
1545	struct inode *ip;	/* inode to which block is being added */
1546	ufs_lbn_t lbn;		/* block pointer within inode */
1547	ufs2_daddr_t newblkno;	/* disk block number being added */
1548	ufs2_daddr_t oldblkno;	/* previous block number, 0 unless frag */
1549	long newsize;		/* size of new block */
1550	long oldsize;		/* size of new block */
1551	struct buf *bp;		/* bp for allocated block */
1552{
1553	struct allocdirect *adp, *oldadp;
1554	struct allocdirectlst *adphead;
1555	struct bmsafemap *bmsafemap;
1556	struct inodedep *inodedep;
1557	struct pagedep *pagedep;
1558	struct newblk *newblk;
1559	struct mount *mp;
1560
1561	mp = UFSTOVFS(ip->i_ump);
1562	MALLOC(adp, struct allocdirect *, sizeof(struct allocdirect),
1563		M_ALLOCDIRECT, M_SOFTDEP_FLAGS|M_ZERO);
1564	workitem_alloc(&adp->ad_list, D_ALLOCDIRECT, mp);
1565	adp->ad_lbn = lbn;
1566	adp->ad_newblkno = newblkno;
1567	adp->ad_oldblkno = oldblkno;
1568	adp->ad_newsize = newsize;
1569	adp->ad_oldsize = oldsize;
1570	adp->ad_state = ATTACHED;
1571	LIST_INIT(&adp->ad_newdirblk);
1572	if (newblkno == oldblkno)
1573		adp->ad_freefrag = NULL;
1574	else
1575		adp->ad_freefrag = newfreefrag(ip, oldblkno, oldsize);
1576
1577	ACQUIRE_LOCK(&lk);
1578	if (lbn >= NDADDR) {
1579		/* allocating an indirect block */
1580		if (oldblkno != 0)
1581			panic("softdep_setup_allocdirect: non-zero indir");
1582	} else {
1583		/*
1584		 * Allocating a direct block.
1585		 *
1586		 * If we are allocating a directory block, then we must
1587		 * allocate an associated pagedep to track additions and
1588		 * deletions.
1589		 */
1590		if ((ip->i_mode & IFMT) == IFDIR &&
1591		    pagedep_lookup(ip, lbn, DEPALLOC, &pagedep) == 0)
1592			WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
1593	}
1594	if (newblk_lookup(ip->i_fs, newblkno, 0, &newblk) == 0)
1595		panic("softdep_setup_allocdirect: lost block");
1596	if (newblk->nb_state == DEPCOMPLETE) {
1597		adp->ad_state |= DEPCOMPLETE;
1598		adp->ad_buf = NULL;
1599	} else {
1600		bmsafemap = newblk->nb_bmsafemap;
1601		adp->ad_buf = bmsafemap->sm_buf;
1602		LIST_REMOVE(newblk, nb_deps);
1603		LIST_INSERT_HEAD(&bmsafemap->sm_allocdirecthd, adp, ad_deps);
1604	}
1605	LIST_REMOVE(newblk, nb_hash);
1606	FREE(newblk, M_NEWBLK);
1607
1608	inodedep_lookup(mp, ip->i_number, DEPALLOC | NODELAY, &inodedep);
1609	adp->ad_inodedep = inodedep;
1610	WORKLIST_INSERT(&bp->b_dep, &adp->ad_list);
1611	/*
1612	 * The list of allocdirects must be kept in sorted and ascending
1613	 * order so that the rollback routines can quickly determine the
1614	 * first uncommitted block (the size of the file stored on disk
1615	 * ends at the end of the lowest committed fragment, or if there
1616	 * are no fragments, at the end of the highest committed block).
1617	 * Since files generally grow, the typical case is that the new
1618	 * block is to be added at the end of the list. We speed this
1619	 * special case by checking against the last allocdirect in the
1620	 * list before laboriously traversing the list looking for the
1621	 * insertion point.
1622	 */
1623	adphead = &inodedep->id_newinoupdt;
1624	oldadp = TAILQ_LAST(adphead, allocdirectlst);
1625	if (oldadp == NULL || oldadp->ad_lbn <= lbn) {
1626		/* insert at end of list */
1627		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
1628		if (oldadp != NULL && oldadp->ad_lbn == lbn)
1629			allocdirect_merge(adphead, adp, oldadp);
1630		FREE_LOCK(&lk);
1631		return;
1632	}
1633	TAILQ_FOREACH(oldadp, adphead, ad_next) {
1634		if (oldadp->ad_lbn >= lbn)
1635			break;
1636	}
1637	if (oldadp == NULL)
1638		panic("softdep_setup_allocdirect: lost entry");
1639	/* insert in middle of list */
1640	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
1641	if (oldadp->ad_lbn == lbn)
1642		allocdirect_merge(adphead, adp, oldadp);
1643	FREE_LOCK(&lk);
1644}
1645
1646/*
1647 * Replace an old allocdirect dependency with a newer one.
1648 * This routine must be called with splbio interrupts blocked.
1649 */
1650static void
1651allocdirect_merge(adphead, newadp, oldadp)
1652	struct allocdirectlst *adphead;	/* head of list holding allocdirects */
1653	struct allocdirect *newadp;	/* allocdirect being added */
1654	struct allocdirect *oldadp;	/* existing allocdirect being checked */
1655{
1656	struct worklist *wk;
1657	struct freefrag *freefrag;
1658	struct newdirblk *newdirblk;
1659
1660	mtx_assert(&lk, MA_OWNED);
1661	if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
1662	    newadp->ad_oldsize != oldadp->ad_newsize ||
1663	    newadp->ad_lbn >= NDADDR)
1664		panic("%s %jd != new %jd || old size %ld != new %ld",
1665		    "allocdirect_merge: old blkno",
1666		    (intmax_t)newadp->ad_oldblkno,
1667		    (intmax_t)oldadp->ad_newblkno,
1668		    newadp->ad_oldsize, oldadp->ad_newsize);
1669	newadp->ad_oldblkno = oldadp->ad_oldblkno;
1670	newadp->ad_oldsize = oldadp->ad_oldsize;
1671	/*
1672	 * If the old dependency had a fragment to free or had never
1673	 * previously had a block allocated, then the new dependency
1674	 * can immediately post its freefrag and adopt the old freefrag.
1675	 * This action is done by swapping the freefrag dependencies.
1676	 * The new dependency gains the old one's freefrag, and the
1677	 * old one gets the new one and then immediately puts it on
1678	 * the worklist when it is freed by free_allocdirect. It is
1679	 * not possible to do this swap when the old dependency had a
1680	 * non-zero size but no previous fragment to free. This condition
1681	 * arises when the new block is an extension of the old block.
1682	 * Here, the first part of the fragment allocated to the new
1683	 * dependency is part of the block currently claimed on disk by
1684	 * the old dependency, so cannot legitimately be freed until the
1685	 * conditions for the new dependency are fulfilled.
1686	 */
1687	if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
1688		freefrag = newadp->ad_freefrag;
1689		newadp->ad_freefrag = oldadp->ad_freefrag;
1690		oldadp->ad_freefrag = freefrag;
1691	}
1692	/*
1693	 * If we are tracking a new directory-block allocation,
1694	 * move it from the old allocdirect to the new allocdirect.
1695	 */
1696	if ((wk = LIST_FIRST(&oldadp->ad_newdirblk)) != NULL) {
1697		newdirblk = WK_NEWDIRBLK(wk);
1698		WORKLIST_REMOVE(&newdirblk->db_list);
1699		if (LIST_FIRST(&oldadp->ad_newdirblk) != NULL)
1700			panic("allocdirect_merge: extra newdirblk");
1701		WORKLIST_INSERT(&newadp->ad_newdirblk, &newdirblk->db_list);
1702	}
1703	free_allocdirect(adphead, oldadp, 0);
1704}
1705
1706/*
1707 * Allocate a new freefrag structure if needed.
1708 */
1709static struct freefrag *
1710newfreefrag(ip, blkno, size)
1711	struct inode *ip;
1712	ufs2_daddr_t blkno;
1713	long size;
1714{
1715	struct freefrag *freefrag;
1716	struct fs *fs;
1717
1718	if (blkno == 0)
1719		return (NULL);
1720	fs = ip->i_fs;
1721	if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
1722		panic("newfreefrag: frag size");
1723	MALLOC(freefrag, struct freefrag *, sizeof(struct freefrag),
1724		M_FREEFRAG, M_SOFTDEP_FLAGS);
1725	workitem_alloc(&freefrag->ff_list, D_FREEFRAG, UFSTOVFS(ip->i_ump));
1726	freefrag->ff_inum = ip->i_number;
1727	freefrag->ff_blkno = blkno;
1728	freefrag->ff_fragsize = size;
1729	return (freefrag);
1730}
1731
1732/*
1733 * This workitem de-allocates fragments that were replaced during
1734 * file block allocation.
1735 */
1736static void
1737handle_workitem_freefrag(freefrag)
1738	struct freefrag *freefrag;
1739{
1740	struct ufsmount *ump = VFSTOUFS(freefrag->ff_list.wk_mp);
1741
1742	ffs_blkfree(ump, ump->um_fs, ump->um_devvp, freefrag->ff_blkno,
1743	    freefrag->ff_fragsize, freefrag->ff_inum);
1744	ACQUIRE_LOCK(&lk);
1745	WORKITEM_FREE(freefrag, D_FREEFRAG);
1746	FREE_LOCK(&lk);
1747}
1748
1749/*
1750 * Set up a dependency structure for an external attributes data block.
1751 * This routine follows much of the structure of softdep_setup_allocdirect.
1752 * See the description of softdep_setup_allocdirect above for details.
1753 */
1754void
1755softdep_setup_allocext(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
1756	struct inode *ip;
1757	ufs_lbn_t lbn;
1758	ufs2_daddr_t newblkno;
1759	ufs2_daddr_t oldblkno;
1760	long newsize;
1761	long oldsize;
1762	struct buf *bp;
1763{
1764	struct allocdirect *adp, *oldadp;
1765	struct allocdirectlst *adphead;
1766	struct bmsafemap *bmsafemap;
1767	struct inodedep *inodedep;
1768	struct newblk *newblk;
1769	struct mount *mp;
1770
1771	mp = UFSTOVFS(ip->i_ump);
1772	MALLOC(adp, struct allocdirect *, sizeof(struct allocdirect),
1773		M_ALLOCDIRECT, M_SOFTDEP_FLAGS|M_ZERO);
1774	workitem_alloc(&adp->ad_list, D_ALLOCDIRECT, mp);
1775	adp->ad_lbn = lbn;
1776	adp->ad_newblkno = newblkno;
1777	adp->ad_oldblkno = oldblkno;
1778	adp->ad_newsize = newsize;
1779	adp->ad_oldsize = oldsize;
1780	adp->ad_state = ATTACHED | EXTDATA;
1781	LIST_INIT(&adp->ad_newdirblk);
1782	if (newblkno == oldblkno)
1783		adp->ad_freefrag = NULL;
1784	else
1785		adp->ad_freefrag = newfreefrag(ip, oldblkno, oldsize);
1786
1787	ACQUIRE_LOCK(&lk);
1788	if (newblk_lookup(ip->i_fs, newblkno, 0, &newblk) == 0)
1789		panic("softdep_setup_allocext: lost block");
1790
1791	inodedep_lookup(mp, ip->i_number, DEPALLOC | NODELAY, &inodedep);
1792	adp->ad_inodedep = inodedep;
1793
1794	if (newblk->nb_state == DEPCOMPLETE) {
1795		adp->ad_state |= DEPCOMPLETE;
1796		adp->ad_buf = NULL;
1797	} else {
1798		bmsafemap = newblk->nb_bmsafemap;
1799		adp->ad_buf = bmsafemap->sm_buf;
1800		LIST_REMOVE(newblk, nb_deps);
1801		LIST_INSERT_HEAD(&bmsafemap->sm_allocdirecthd, adp, ad_deps);
1802	}
1803	LIST_REMOVE(newblk, nb_hash);
1804	FREE(newblk, M_NEWBLK);
1805
1806	WORKLIST_INSERT(&bp->b_dep, &adp->ad_list);
1807	if (lbn >= NXADDR)
1808		panic("softdep_setup_allocext: lbn %lld > NXADDR",
1809		    (long long)lbn);
1810	/*
1811	 * The list of allocdirects must be kept in sorted and ascending
1812	 * order so that the rollback routines can quickly determine the
1813	 * first uncommitted block (the size of the file stored on disk
1814	 * ends at the end of the lowest committed fragment, or if there
1815	 * are no fragments, at the end of the highest committed block).
1816	 * Since files generally grow, the typical case is that the new
1817	 * block is to be added at the end of the list. We speed this
1818	 * special case by checking against the last allocdirect in the
1819	 * list before laboriously traversing the list looking for the
1820	 * insertion point.
1821	 */
1822	adphead = &inodedep->id_newextupdt;
1823	oldadp = TAILQ_LAST(adphead, allocdirectlst);
1824	if (oldadp == NULL || oldadp->ad_lbn <= lbn) {
1825		/* insert at end of list */
1826		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
1827		if (oldadp != NULL && oldadp->ad_lbn == lbn)
1828			allocdirect_merge(adphead, adp, oldadp);
1829		FREE_LOCK(&lk);
1830		return;
1831	}
1832	TAILQ_FOREACH(oldadp, adphead, ad_next) {
1833		if (oldadp->ad_lbn >= lbn)
1834			break;
1835	}
1836	if (oldadp == NULL)
1837		panic("softdep_setup_allocext: lost entry");
1838	/* insert in middle of list */
1839	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
1840	if (oldadp->ad_lbn == lbn)
1841		allocdirect_merge(adphead, adp, oldadp);
1842	FREE_LOCK(&lk);
1843}
1844
1845/*
1846 * Indirect block allocation dependencies.
1847 *
1848 * The same dependencies that exist for a direct block also exist when
1849 * a new block is allocated and pointed to by an entry in a block of
1850 * indirect pointers. The undo/redo states described above are also
1851 * used here. Because an indirect block contains many pointers that
1852 * may have dependencies, a second copy of the entire in-memory indirect
1853 * block is kept. The buffer cache copy is always completely up-to-date.
1854 * The second copy, which is used only as a source for disk writes,
1855 * contains only the safe pointers (i.e., those that have no remaining
1856 * update dependencies). The second copy is freed when all pointers
1857 * are safe. The cache is not allowed to replace indirect blocks with
1858 * pending update dependencies. If a buffer containing an indirect
1859 * block with dependencies is written, these routines will mark it
1860 * dirty again. It can only be successfully written once all the
1861 * dependencies are removed. The ffs_fsync routine in conjunction with
1862 * softdep_sync_metadata work together to get all the dependencies
1863 * removed so that a file can be successfully written to disk. Three
1864 * procedures are used when setting up indirect block pointer
1865 * dependencies. The division is necessary because of the organization
1866 * of the "balloc" routine and because of the distinction between file
1867 * pages and file metadata blocks.
1868 */
1869
1870/*
1871 * Allocate a new allocindir structure.
1872 */
1873static struct allocindir *
1874newallocindir(ip, ptrno, newblkno, oldblkno)
1875	struct inode *ip;	/* inode for file being extended */
1876	int ptrno;		/* offset of pointer in indirect block */
1877	ufs2_daddr_t newblkno;	/* disk block number being added */
1878	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
1879{
1880	struct allocindir *aip;
1881
1882	MALLOC(aip, struct allocindir *, sizeof(struct allocindir),
1883		M_ALLOCINDIR, M_SOFTDEP_FLAGS|M_ZERO);
1884	workitem_alloc(&aip->ai_list, D_ALLOCINDIR, UFSTOVFS(ip->i_ump));
1885	aip->ai_state = ATTACHED;
1886	aip->ai_offset = ptrno;
1887	aip->ai_newblkno = newblkno;
1888	aip->ai_oldblkno = oldblkno;
1889	aip->ai_freefrag = newfreefrag(ip, oldblkno, ip->i_fs->fs_bsize);
1890	return (aip);
1891}
1892
1893/*
1894 * Called just before setting an indirect block pointer
1895 * to a newly allocated file page.
1896 */
1897void
1898softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
1899	struct inode *ip;	/* inode for file being extended */
1900	ufs_lbn_t lbn;		/* allocated block number within file */
1901	struct buf *bp;		/* buffer with indirect blk referencing page */
1902	int ptrno;		/* offset of pointer in indirect block */
1903	ufs2_daddr_t newblkno;	/* disk block number being added */
1904	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
1905	struct buf *nbp;	/* buffer holding allocated page */
1906{
1907	struct allocindir *aip;
1908	struct pagedep *pagedep;
1909
1910	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_page");
1911	aip = newallocindir(ip, ptrno, newblkno, oldblkno);
1912	ACQUIRE_LOCK(&lk);
1913	/*
1914	 * If we are allocating a directory page, then we must
1915	 * allocate an associated pagedep to track additions and
1916	 * deletions.
1917	 */
1918	if ((ip->i_mode & IFMT) == IFDIR &&
1919	    pagedep_lookup(ip, lbn, DEPALLOC, &pagedep) == 0)
1920		WORKLIST_INSERT(&nbp->b_dep, &pagedep->pd_list);
1921	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_list);
1922	setup_allocindir_phase2(bp, ip, aip);
1923	FREE_LOCK(&lk);
1924}
1925
1926/*
1927 * Called just before setting an indirect block pointer to a
1928 * newly allocated indirect block.
1929 */
1930void
1931softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
1932	struct buf *nbp;	/* newly allocated indirect block */
1933	struct inode *ip;	/* inode for file being extended */
1934	struct buf *bp;		/* indirect block referencing allocated block */
1935	int ptrno;		/* offset of pointer in indirect block */
1936	ufs2_daddr_t newblkno;	/* disk block number being added */
1937{
1938	struct allocindir *aip;
1939
1940	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_meta");
1941	aip = newallocindir(ip, ptrno, newblkno, 0);
1942	ACQUIRE_LOCK(&lk);
1943	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_list);
1944	setup_allocindir_phase2(bp, ip, aip);
1945	FREE_LOCK(&lk);
1946}
1947
1948/*
1949 * Called to finish the allocation of the "aip" allocated
1950 * by one of the two routines above.
1951 */
1952static void
1953setup_allocindir_phase2(bp, ip, aip)
1954	struct buf *bp;		/* in-memory copy of the indirect block */
1955	struct inode *ip;	/* inode for file being extended */
1956	struct allocindir *aip;	/* allocindir allocated by the above routines */
1957{
1958	struct worklist *wk;
1959	struct indirdep *indirdep, *newindirdep;
1960	struct bmsafemap *bmsafemap;
1961	struct allocindir *oldaip;
1962	struct freefrag *freefrag;
1963	struct newblk *newblk;
1964	ufs2_daddr_t blkno;
1965
1966	mtx_assert(&lk, MA_OWNED);
1967	if (bp->b_lblkno >= 0)
1968		panic("setup_allocindir_phase2: not indir blk");
1969	for (indirdep = NULL, newindirdep = NULL; ; ) {
1970		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
1971			if (wk->wk_type != D_INDIRDEP)
1972				continue;
1973			indirdep = WK_INDIRDEP(wk);
1974			break;
1975		}
1976		if (indirdep == NULL && newindirdep) {
1977			indirdep = newindirdep;
1978			WORKLIST_INSERT(&bp->b_dep, &indirdep->ir_list);
1979			newindirdep = NULL;
1980		}
1981		if (indirdep) {
1982			if (newblk_lookup(ip->i_fs, aip->ai_newblkno, 0,
1983			    &newblk) == 0)
1984				panic("setup_allocindir: lost block");
1985			if (newblk->nb_state == DEPCOMPLETE) {
1986				aip->ai_state |= DEPCOMPLETE;
1987				aip->ai_buf = NULL;
1988			} else {
1989				bmsafemap = newblk->nb_bmsafemap;
1990				aip->ai_buf = bmsafemap->sm_buf;
1991				LIST_REMOVE(newblk, nb_deps);
1992				LIST_INSERT_HEAD(&bmsafemap->sm_allocindirhd,
1993				    aip, ai_deps);
1994			}
1995			LIST_REMOVE(newblk, nb_hash);
1996			FREE(newblk, M_NEWBLK);
1997			aip->ai_indirdep = indirdep;
1998			/*
1999			 * Check to see if there is an existing dependency
2000			 * for this block. If there is, merge the old
2001			 * dependency into the new one.
2002			 */
2003			if (aip->ai_oldblkno == 0)
2004				oldaip = NULL;
2005			else
2006
2007				LIST_FOREACH(oldaip, &indirdep->ir_deplisthd, ai_next)
2008					if (oldaip->ai_offset == aip->ai_offset)
2009						break;
2010			freefrag = NULL;
2011			if (oldaip != NULL) {
2012				if (oldaip->ai_newblkno != aip->ai_oldblkno)
2013					panic("setup_allocindir_phase2: blkno");
2014				aip->ai_oldblkno = oldaip->ai_oldblkno;
2015				freefrag = aip->ai_freefrag;
2016				aip->ai_freefrag = oldaip->ai_freefrag;
2017				oldaip->ai_freefrag = NULL;
2018				free_allocindir(oldaip, NULL);
2019			}
2020			LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
2021			if (ip->i_ump->um_fstype == UFS1)
2022				((ufs1_daddr_t *)indirdep->ir_savebp->b_data)
2023				    [aip->ai_offset] = aip->ai_oldblkno;
2024			else
2025				((ufs2_daddr_t *)indirdep->ir_savebp->b_data)
2026				    [aip->ai_offset] = aip->ai_oldblkno;
2027			FREE_LOCK(&lk);
2028			if (freefrag != NULL)
2029				handle_workitem_freefrag(freefrag);
2030		} else
2031			FREE_LOCK(&lk);
2032		if (newindirdep) {
2033			newindirdep->ir_savebp->b_flags |= B_INVAL | B_NOCACHE;
2034			brelse(newindirdep->ir_savebp);
2035			ACQUIRE_LOCK(&lk);
2036			WORKITEM_FREE((caddr_t)newindirdep, D_INDIRDEP);
2037			if (indirdep)
2038				break;
2039			FREE_LOCK(&lk);
2040		}
2041		if (indirdep) {
2042			ACQUIRE_LOCK(&lk);
2043			break;
2044		}
2045		MALLOC(newindirdep, struct indirdep *, sizeof(struct indirdep),
2046			M_INDIRDEP, M_SOFTDEP_FLAGS);
2047		workitem_alloc(&newindirdep->ir_list, D_INDIRDEP,
2048		    UFSTOVFS(ip->i_ump));
2049		newindirdep->ir_state = ATTACHED;
2050		if (ip->i_ump->um_fstype == UFS1)
2051			newindirdep->ir_state |= UFS1FMT;
2052		LIST_INIT(&newindirdep->ir_deplisthd);
2053		LIST_INIT(&newindirdep->ir_donehd);
2054		if (bp->b_blkno == bp->b_lblkno) {
2055			ufs_bmaparray(bp->b_vp, bp->b_lblkno, &blkno, bp,
2056			    NULL, NULL);
2057			bp->b_blkno = blkno;
2058		}
2059		newindirdep->ir_savebp =
2060		    getblk(ip->i_devvp, bp->b_blkno, bp->b_bcount, 0, 0, 0);
2061		BUF_KERNPROC(newindirdep->ir_savebp);
2062		bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
2063		ACQUIRE_LOCK(&lk);
2064	}
2065}
2066
2067/*
2068 * Block de-allocation dependencies.
2069 *
2070 * When blocks are de-allocated, the on-disk pointers must be nullified before
2071 * the blocks are made available for use by other files.  (The true
2072 * requirement is that old pointers must be nullified before new on-disk
2073 * pointers are set.  We chose this slightly more stringent requirement to
2074 * reduce complexity.) Our implementation handles this dependency by updating
2075 * the inode (or indirect block) appropriately but delaying the actual block
2076 * de-allocation (i.e., freemap and free space count manipulation) until
2077 * after the updated versions reach stable storage.  After the disk is
2078 * updated, the blocks can be safely de-allocated whenever it is convenient.
2079 * This implementation handles only the common case of reducing a file's
2080 * length to zero. Other cases are handled by the conventional synchronous
2081 * write approach.
2082 *
2083 * The ffs implementation with which we worked double-checks
2084 * the state of the block pointers and file size as it reduces
2085 * a file's length.  Some of this code is replicated here in our
2086 * soft updates implementation.  The freeblks->fb_chkcnt field is
2087 * used to transfer a part of this information to the procedure
2088 * that eventually de-allocates the blocks.
2089 *
2090 * This routine should be called from the routine that shortens
2091 * a file's length, before the inode's size or block pointers
2092 * are modified. It will save the block pointer information for
2093 * later release and zero the inode so that the calling routine
2094 * can release it.
2095 */
2096void
2097softdep_setup_freeblocks(ip, length, flags)
2098	struct inode *ip;	/* The inode whose length is to be reduced */
2099	off_t length;		/* The new length for the file */
2100	int flags;		/* IO_EXT and/or IO_NORMAL */
2101{
2102	struct freeblks *freeblks;
2103	struct inodedep *inodedep;
2104	struct allocdirect *adp;
2105	struct vnode *vp;
2106	struct buf *bp;
2107	struct fs *fs;
2108	ufs2_daddr_t extblocks, datablocks;
2109	struct mount *mp;
2110	int i, delay, error;
2111
2112	fs = ip->i_fs;
2113	mp = UFSTOVFS(ip->i_ump);
2114	if (length != 0)
2115		panic("softdep_setup_freeblocks: non-zero length");
2116	MALLOC(freeblks, struct freeblks *, sizeof(struct freeblks),
2117		M_FREEBLKS, M_SOFTDEP_FLAGS|M_ZERO);
2118	workitem_alloc(&freeblks->fb_list, D_FREEBLKS, mp);
2119	freeblks->fb_state = ATTACHED;
2120	freeblks->fb_uid = ip->i_uid;
2121	freeblks->fb_previousinum = ip->i_number;
2122	freeblks->fb_devvp = ip->i_devvp;
2123	extblocks = 0;
2124	if (fs->fs_magic == FS_UFS2_MAGIC)
2125		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
2126	datablocks = DIP(ip, i_blocks) - extblocks;
2127	if ((flags & IO_NORMAL) == 0) {
2128		freeblks->fb_oldsize = 0;
2129		freeblks->fb_chkcnt = 0;
2130	} else {
2131		freeblks->fb_oldsize = ip->i_size;
2132		ip->i_size = 0;
2133		DIP_SET(ip, i_size, 0);
2134		freeblks->fb_chkcnt = datablocks;
2135		for (i = 0; i < NDADDR; i++) {
2136			freeblks->fb_dblks[i] = DIP(ip, i_db[i]);
2137			DIP_SET(ip, i_db[i], 0);
2138		}
2139		for (i = 0; i < NIADDR; i++) {
2140			freeblks->fb_iblks[i] = DIP(ip, i_ib[i]);
2141			DIP_SET(ip, i_ib[i], 0);
2142		}
2143		/*
2144		 * If the file was removed, then the space being freed was
2145		 * accounted for then (see softdep_filereleased()). If the
2146		 * file is merely being truncated, then we account for it now.
2147		 */
2148		if ((ip->i_flag & IN_SPACECOUNTED) == 0) {
2149			UFS_LOCK(ip->i_ump);
2150			fs->fs_pendingblocks += datablocks;
2151			UFS_UNLOCK(ip->i_ump);
2152		}
2153	}
2154	if ((flags & IO_EXT) == 0) {
2155		freeblks->fb_oldextsize = 0;
2156	} else {
2157		freeblks->fb_oldextsize = ip->i_din2->di_extsize;
2158		ip->i_din2->di_extsize = 0;
2159		freeblks->fb_chkcnt += extblocks;
2160		for (i = 0; i < NXADDR; i++) {
2161			freeblks->fb_eblks[i] = ip->i_din2->di_extb[i];
2162			ip->i_din2->di_extb[i] = 0;
2163		}
2164	}
2165	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - freeblks->fb_chkcnt);
2166	/*
2167	 * Push the zero'ed inode to to its disk buffer so that we are free
2168	 * to delete its dependencies below. Once the dependencies are gone
2169	 * the buffer can be safely released.
2170	 */
2171	if ((error = bread(ip->i_devvp,
2172	    fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
2173	    (int)fs->fs_bsize, NOCRED, &bp)) != 0) {
2174		brelse(bp);
2175		softdep_error("softdep_setup_freeblocks", error);
2176	}
2177	if (ip->i_ump->um_fstype == UFS1)
2178		*((struct ufs1_dinode *)bp->b_data +
2179		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din1;
2180	else
2181		*((struct ufs2_dinode *)bp->b_data +
2182		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din2;
2183	/*
2184	 * Find and eliminate any inode dependencies.
2185	 */
2186	ACQUIRE_LOCK(&lk);
2187	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
2188	if ((inodedep->id_state & IOSTARTED) != 0)
2189		panic("softdep_setup_freeblocks: inode busy");
2190	/*
2191	 * Add the freeblks structure to the list of operations that
2192	 * must await the zero'ed inode being written to disk. If we
2193	 * still have a bitmap dependency (delay == 0), then the inode
2194	 * has never been written to disk, so we can process the
2195	 * freeblks below once we have deleted the dependencies.
2196	 */
2197	delay = (inodedep->id_state & DEPCOMPLETE);
2198	if (delay)
2199		WORKLIST_INSERT(&inodedep->id_bufwait, &freeblks->fb_list);
2200	/*
2201	 * Because the file length has been truncated to zero, any
2202	 * pending block allocation dependency structures associated
2203	 * with this inode are obsolete and can simply be de-allocated.
2204	 * We must first merge the two dependency lists to get rid of
2205	 * any duplicate freefrag structures, then purge the merged list.
2206	 * If we still have a bitmap dependency, then the inode has never
2207	 * been written to disk, so we can free any fragments without delay.
2208	 */
2209	if (flags & IO_NORMAL) {
2210		merge_inode_lists(&inodedep->id_newinoupdt,
2211		    &inodedep->id_inoupdt);
2212		while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != 0)
2213			free_allocdirect(&inodedep->id_inoupdt, adp, delay);
2214	}
2215	if (flags & IO_EXT) {
2216		merge_inode_lists(&inodedep->id_newextupdt,
2217		    &inodedep->id_extupdt);
2218		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != 0)
2219			free_allocdirect(&inodedep->id_extupdt, adp, delay);
2220	}
2221	FREE_LOCK(&lk);
2222	bdwrite(bp);
2223	/*
2224	 * We must wait for any I/O in progress to finish so that
2225	 * all potential buffers on the dirty list will be visible.
2226	 * Once they are all there, walk the list and get rid of
2227	 * any dependencies.
2228	 */
2229	vp = ITOV(ip);
2230	VI_LOCK(vp);
2231	drain_output(vp);
2232restart:
2233	TAILQ_FOREACH(bp, &vp->v_bufobj.bo_dirty.bv_hd, b_bobufs) {
2234		if (((flags & IO_EXT) == 0 && (bp->b_xflags & BX_ALTDATA)) ||
2235		    ((flags & IO_NORMAL) == 0 &&
2236		      (bp->b_xflags & BX_ALTDATA) == 0))
2237			continue;
2238		if ((bp = getdirtybuf(bp, VI_MTX(vp), MNT_WAIT)) == NULL)
2239			goto restart;
2240		VI_UNLOCK(vp);
2241		ACQUIRE_LOCK(&lk);
2242		(void) inodedep_lookup(mp, ip->i_number, 0, &inodedep);
2243		deallocate_dependencies(bp, inodedep);
2244		FREE_LOCK(&lk);
2245		bp->b_flags |= B_INVAL | B_NOCACHE;
2246		brelse(bp);
2247		VI_LOCK(vp);
2248		goto restart;
2249	}
2250	VI_UNLOCK(vp);
2251	ACQUIRE_LOCK(&lk);
2252	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
2253		(void) free_inodedep(inodedep);
2254
2255	if(delay) {
2256		freeblks->fb_state |= DEPCOMPLETE;
2257		/*
2258		 * If the inode with zeroed block pointers is now on disk
2259		 * we can start freeing blocks. Add freeblks to the worklist
2260		 * instead of calling  handle_workitem_freeblocks directly as
2261		 * it is more likely that additional IO is needed to complete
2262		 * the request here than in the !delay case.
2263		 */
2264		if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
2265			add_to_worklist(&freeblks->fb_list);
2266	}
2267
2268	FREE_LOCK(&lk);
2269	/*
2270	 * If the inode has never been written to disk (delay == 0),
2271	 * then we can process the freeblks now that we have deleted
2272	 * the dependencies.
2273	 */
2274	if (!delay)
2275		handle_workitem_freeblocks(freeblks, 0);
2276}
2277
2278/*
2279 * Reclaim any dependency structures from a buffer that is about to
2280 * be reallocated to a new vnode. The buffer must be locked, thus,
2281 * no I/O completion operations can occur while we are manipulating
2282 * its associated dependencies. The mutex is held so that other I/O's
2283 * associated with related dependencies do not occur.
2284 */
2285static void
2286deallocate_dependencies(bp, inodedep)
2287	struct buf *bp;
2288	struct inodedep *inodedep;
2289{
2290	struct worklist *wk;
2291	struct indirdep *indirdep;
2292	struct allocindir *aip;
2293	struct pagedep *pagedep;
2294	struct dirrem *dirrem;
2295	struct diradd *dap;
2296	int i;
2297
2298	mtx_assert(&lk, MA_OWNED);
2299	while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
2300		switch (wk->wk_type) {
2301
2302		case D_INDIRDEP:
2303			indirdep = WK_INDIRDEP(wk);
2304			/*
2305			 * None of the indirect pointers will ever be visible,
2306			 * so they can simply be tossed. GOINGAWAY ensures
2307			 * that allocated pointers will be saved in the buffer
2308			 * cache until they are freed. Note that they will
2309			 * only be able to be found by their physical address
2310			 * since the inode mapping the logical address will
2311			 * be gone. The save buffer used for the safe copy
2312			 * was allocated in setup_allocindir_phase2 using
2313			 * the physical address so it could be used for this
2314			 * purpose. Hence we swap the safe copy with the real
2315			 * copy, allowing the safe copy to be freed and holding
2316			 * on to the real copy for later use in indir_trunc.
2317			 */
2318			if (indirdep->ir_state & GOINGAWAY)
2319				panic("deallocate_dependencies: already gone");
2320			indirdep->ir_state |= GOINGAWAY;
2321			VFSTOUFS(bp->b_vp->v_mount)->um_numindirdeps += 1;
2322			while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != 0)
2323				free_allocindir(aip, inodedep);
2324			if (bp->b_lblkno >= 0 ||
2325			    bp->b_blkno != indirdep->ir_savebp->b_lblkno)
2326				panic("deallocate_dependencies: not indir");
2327			bcopy(bp->b_data, indirdep->ir_savebp->b_data,
2328			    bp->b_bcount);
2329			WORKLIST_REMOVE(wk);
2330			WORKLIST_INSERT(&indirdep->ir_savebp->b_dep, wk);
2331			continue;
2332
2333		case D_PAGEDEP:
2334			pagedep = WK_PAGEDEP(wk);
2335			/*
2336			 * None of the directory additions will ever be
2337			 * visible, so they can simply be tossed.
2338			 */
2339			for (i = 0; i < DAHASHSZ; i++)
2340				while ((dap =
2341				    LIST_FIRST(&pagedep->pd_diraddhd[i])))
2342					free_diradd(dap);
2343			while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != 0)
2344				free_diradd(dap);
2345			/*
2346			 * Copy any directory remove dependencies to the list
2347			 * to be processed after the zero'ed inode is written.
2348			 * If the inode has already been written, then they
2349			 * can be dumped directly onto the work list.
2350			 */
2351			LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
2352				LIST_REMOVE(dirrem, dm_next);
2353				dirrem->dm_dirinum = pagedep->pd_ino;
2354				if (inodedep == NULL ||
2355				    (inodedep->id_state & ALLCOMPLETE) ==
2356				     ALLCOMPLETE)
2357					add_to_worklist(&dirrem->dm_list);
2358				else
2359					WORKLIST_INSERT(&inodedep->id_bufwait,
2360					    &dirrem->dm_list);
2361			}
2362			if ((pagedep->pd_state & NEWBLOCK) != 0) {
2363				LIST_FOREACH(wk, &inodedep->id_bufwait, wk_list)
2364					if (wk->wk_type == D_NEWDIRBLK &&
2365					    WK_NEWDIRBLK(wk)->db_pagedep ==
2366					      pagedep)
2367						break;
2368				if (wk != NULL) {
2369					WORKLIST_REMOVE(wk);
2370					free_newdirblk(WK_NEWDIRBLK(wk));
2371				} else
2372					panic("deallocate_dependencies: "
2373					      "lost pagedep");
2374			}
2375			WORKLIST_REMOVE(&pagedep->pd_list);
2376			LIST_REMOVE(pagedep, pd_hash);
2377			WORKITEM_FREE(pagedep, D_PAGEDEP);
2378			continue;
2379
2380		case D_ALLOCINDIR:
2381			free_allocindir(WK_ALLOCINDIR(wk), inodedep);
2382			continue;
2383
2384		case D_ALLOCDIRECT:
2385		case D_INODEDEP:
2386			panic("deallocate_dependencies: Unexpected type %s",
2387			    TYPENAME(wk->wk_type));
2388			/* NOTREACHED */
2389
2390		default:
2391			panic("deallocate_dependencies: Unknown type %s",
2392			    TYPENAME(wk->wk_type));
2393			/* NOTREACHED */
2394		}
2395	}
2396}
2397
2398/*
2399 * Free an allocdirect. Generate a new freefrag work request if appropriate.
2400 * This routine must be called with splbio interrupts blocked.
2401 */
2402static void
2403free_allocdirect(adphead, adp, delay)
2404	struct allocdirectlst *adphead;
2405	struct allocdirect *adp;
2406	int delay;
2407{
2408	struct newdirblk *newdirblk;
2409	struct worklist *wk;
2410
2411	mtx_assert(&lk, MA_OWNED);
2412	if ((adp->ad_state & DEPCOMPLETE) == 0)
2413		LIST_REMOVE(adp, ad_deps);
2414	TAILQ_REMOVE(adphead, adp, ad_next);
2415	if ((adp->ad_state & COMPLETE) == 0)
2416		WORKLIST_REMOVE(&adp->ad_list);
2417	if (adp->ad_freefrag != NULL) {
2418		if (delay)
2419			WORKLIST_INSERT(&adp->ad_inodedep->id_bufwait,
2420			    &adp->ad_freefrag->ff_list);
2421		else
2422			add_to_worklist(&adp->ad_freefrag->ff_list);
2423	}
2424	if ((wk = LIST_FIRST(&adp->ad_newdirblk)) != NULL) {
2425		newdirblk = WK_NEWDIRBLK(wk);
2426		WORKLIST_REMOVE(&newdirblk->db_list);
2427		if (LIST_FIRST(&adp->ad_newdirblk) != NULL)
2428			panic("free_allocdirect: extra newdirblk");
2429		if (delay)
2430			WORKLIST_INSERT(&adp->ad_inodedep->id_bufwait,
2431			    &newdirblk->db_list);
2432		else
2433			free_newdirblk(newdirblk);
2434	}
2435	WORKITEM_FREE(adp, D_ALLOCDIRECT);
2436}
2437
2438/*
2439 * Free a newdirblk. Clear the NEWBLOCK flag on its associated pagedep.
2440 * This routine must be called with splbio interrupts blocked.
2441 */
2442static void
2443free_newdirblk(newdirblk)
2444	struct newdirblk *newdirblk;
2445{
2446	struct pagedep *pagedep;
2447	struct diradd *dap;
2448	int i;
2449
2450	mtx_assert(&lk, MA_OWNED);
2451	/*
2452	 * If the pagedep is still linked onto the directory buffer
2453	 * dependency chain, then some of the entries on the
2454	 * pd_pendinghd list may not be committed to disk yet. In
2455	 * this case, we will simply clear the NEWBLOCK flag and
2456	 * let the pd_pendinghd list be processed when the pagedep
2457	 * is next written. If the pagedep is no longer on the buffer
2458	 * dependency chain, then all the entries on the pd_pending
2459	 * list are committed to disk and we can free them here.
2460	 */
2461	pagedep = newdirblk->db_pagedep;
2462	pagedep->pd_state &= ~NEWBLOCK;
2463	if ((pagedep->pd_state & ONWORKLIST) == 0)
2464		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
2465			free_diradd(dap);
2466	/*
2467	 * If no dependencies remain, the pagedep will be freed.
2468	 */
2469	for (i = 0; i < DAHASHSZ; i++)
2470		if (LIST_FIRST(&pagedep->pd_diraddhd[i]) != NULL)
2471			break;
2472	if (i == DAHASHSZ && (pagedep->pd_state & ONWORKLIST) == 0) {
2473		LIST_REMOVE(pagedep, pd_hash);
2474		WORKITEM_FREE(pagedep, D_PAGEDEP);
2475	}
2476	WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
2477}
2478
2479/*
2480 * Prepare an inode to be freed. The actual free operation is not
2481 * done until the zero'ed inode has been written to disk.
2482 */
2483void
2484softdep_freefile(pvp, ino, mode)
2485	struct vnode *pvp;
2486	ino_t ino;
2487	int mode;
2488{
2489	struct inode *ip = VTOI(pvp);
2490	struct inodedep *inodedep;
2491	struct freefile *freefile;
2492
2493	/*
2494	 * This sets up the inode de-allocation dependency.
2495	 */
2496	MALLOC(freefile, struct freefile *, sizeof(struct freefile),
2497		M_FREEFILE, M_SOFTDEP_FLAGS);
2498	workitem_alloc(&freefile->fx_list, D_FREEFILE, pvp->v_mount);
2499	freefile->fx_mode = mode;
2500	freefile->fx_oldinum = ino;
2501	freefile->fx_devvp = ip->i_devvp;
2502	if ((ip->i_flag & IN_SPACECOUNTED) == 0) {
2503		UFS_LOCK(ip->i_ump);
2504		ip->i_fs->fs_pendinginodes += 1;
2505		UFS_UNLOCK(ip->i_ump);
2506	}
2507
2508	/*
2509	 * If the inodedep does not exist, then the zero'ed inode has
2510	 * been written to disk. If the allocated inode has never been
2511	 * written to disk, then the on-disk inode is zero'ed. In either
2512	 * case we can free the file immediately.
2513	 */
2514	ACQUIRE_LOCK(&lk);
2515	if (inodedep_lookup(pvp->v_mount, ino, 0, &inodedep) == 0 ||
2516	    check_inode_unwritten(inodedep)) {
2517		FREE_LOCK(&lk);
2518		handle_workitem_freefile(freefile);
2519		return;
2520	}
2521	WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
2522	FREE_LOCK(&lk);
2523}
2524
2525/*
2526 * Check to see if an inode has never been written to disk. If
2527 * so free the inodedep and return success, otherwise return failure.
2528 * This routine must be called with splbio interrupts blocked.
2529 *
2530 * If we still have a bitmap dependency, then the inode has never
2531 * been written to disk. Drop the dependency as it is no longer
2532 * necessary since the inode is being deallocated. We set the
2533 * ALLCOMPLETE flags since the bitmap now properly shows that the
2534 * inode is not allocated. Even if the inode is actively being
2535 * written, it has been rolled back to its zero'ed state, so we
2536 * are ensured that a zero inode is what is on the disk. For short
2537 * lived files, this change will usually result in removing all the
2538 * dependencies from the inode so that it can be freed immediately.
2539 */
2540static int
2541check_inode_unwritten(inodedep)
2542	struct inodedep *inodedep;
2543{
2544
2545	mtx_assert(&lk, MA_OWNED);
2546	if ((inodedep->id_state & DEPCOMPLETE) != 0 ||
2547	    LIST_FIRST(&inodedep->id_pendinghd) != NULL ||
2548	    LIST_FIRST(&inodedep->id_bufwait) != NULL ||
2549	    LIST_FIRST(&inodedep->id_inowait) != NULL ||
2550	    TAILQ_FIRST(&inodedep->id_inoupdt) != NULL ||
2551	    TAILQ_FIRST(&inodedep->id_newinoupdt) != NULL ||
2552	    TAILQ_FIRST(&inodedep->id_extupdt) != NULL ||
2553	    TAILQ_FIRST(&inodedep->id_newextupdt) != NULL ||
2554	    inodedep->id_nlinkdelta != 0)
2555		return (0);
2556
2557	/*
2558	 * Another process might be in initiate_write_inodeblock_ufs[12]
2559	 * trying to allocate memory without holding "Softdep Lock".
2560	 */
2561	if ((inodedep->id_state & IOSTARTED) != 0 &&
2562	    inodedep->id_savedino1 == NULL)
2563		return (0);
2564
2565	inodedep->id_state |= ALLCOMPLETE;
2566	LIST_REMOVE(inodedep, id_deps);
2567	inodedep->id_buf = NULL;
2568	if (inodedep->id_state & ONWORKLIST)
2569		WORKLIST_REMOVE(&inodedep->id_list);
2570	if (inodedep->id_savedino1 != NULL) {
2571		FREE(inodedep->id_savedino1, M_SAVEDINO);
2572		inodedep->id_savedino1 = NULL;
2573	}
2574	if (free_inodedep(inodedep) == 0)
2575		panic("check_inode_unwritten: busy inode");
2576	return (1);
2577}
2578
2579/*
2580 * Try to free an inodedep structure. Return 1 if it could be freed.
2581 */
2582static int
2583free_inodedep(inodedep)
2584	struct inodedep *inodedep;
2585{
2586
2587	mtx_assert(&lk, MA_OWNED);
2588	if ((inodedep->id_state & ONWORKLIST) != 0 ||
2589	    (inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
2590	    LIST_FIRST(&inodedep->id_pendinghd) != NULL ||
2591	    LIST_FIRST(&inodedep->id_bufwait) != NULL ||
2592	    LIST_FIRST(&inodedep->id_inowait) != NULL ||
2593	    TAILQ_FIRST(&inodedep->id_inoupdt) != NULL ||
2594	    TAILQ_FIRST(&inodedep->id_newinoupdt) != NULL ||
2595	    TAILQ_FIRST(&inodedep->id_extupdt) != NULL ||
2596	    TAILQ_FIRST(&inodedep->id_newextupdt) != NULL ||
2597	    inodedep->id_nlinkdelta != 0 || inodedep->id_savedino1 != NULL)
2598		return (0);
2599	LIST_REMOVE(inodedep, id_hash);
2600	WORKITEM_FREE(inodedep, D_INODEDEP);
2601	num_inodedep -= 1;
2602	return (1);
2603}
2604
2605/*
2606 * This workitem routine performs the block de-allocation.
2607 * The workitem is added to the pending list after the updated
2608 * inode block has been written to disk.  As mentioned above,
2609 * checks regarding the number of blocks de-allocated (compared
2610 * to the number of blocks allocated for the file) are also
2611 * performed in this function.
2612 */
2613static void
2614handle_workitem_freeblocks(freeblks, flags)
2615	struct freeblks *freeblks;
2616	int flags;
2617{
2618	struct inode *ip;
2619	struct vnode *vp;
2620	struct fs *fs;
2621	struct ufsmount *ump;
2622	int i, nblocks, level, bsize;
2623	ufs2_daddr_t bn, blocksreleased = 0;
2624	int error, allerror = 0;
2625	ufs_lbn_t baselbns[NIADDR], tmpval;
2626	int fs_pendingblocks;
2627
2628	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
2629	fs = ump->um_fs;
2630	fs_pendingblocks = 0;
2631	tmpval = 1;
2632	baselbns[0] = NDADDR;
2633	for (i = 1; i < NIADDR; i++) {
2634		tmpval *= NINDIR(fs);
2635		baselbns[i] = baselbns[i - 1] + tmpval;
2636	}
2637	nblocks = btodb(fs->fs_bsize);
2638	blocksreleased = 0;
2639	/*
2640	 * Release all extended attribute blocks or frags.
2641	 */
2642	if (freeblks->fb_oldextsize > 0) {
2643		for (i = (NXADDR - 1); i >= 0; i--) {
2644			if ((bn = freeblks->fb_eblks[i]) == 0)
2645				continue;
2646			bsize = sblksize(fs, freeblks->fb_oldextsize, i);
2647			ffs_blkfree(ump, fs, freeblks->fb_devvp, bn, bsize,
2648			    freeblks->fb_previousinum);
2649			blocksreleased += btodb(bsize);
2650		}
2651	}
2652	/*
2653	 * Release all data blocks or frags.
2654	 */
2655	if (freeblks->fb_oldsize > 0) {
2656		/*
2657		 * Indirect blocks first.
2658		 */
2659		for (level = (NIADDR - 1); level >= 0; level--) {
2660			if ((bn = freeblks->fb_iblks[level]) == 0)
2661				continue;
2662			if ((error = indir_trunc(freeblks, fsbtodb(fs, bn),
2663			    level, baselbns[level], &blocksreleased)) == 0)
2664				allerror = error;
2665			ffs_blkfree(ump, fs, freeblks->fb_devvp, bn,
2666			    fs->fs_bsize, freeblks->fb_previousinum);
2667			fs_pendingblocks += nblocks;
2668			blocksreleased += nblocks;
2669		}
2670		/*
2671		 * All direct blocks or frags.
2672		 */
2673		for (i = (NDADDR - 1); i >= 0; i--) {
2674			if ((bn = freeblks->fb_dblks[i]) == 0)
2675				continue;
2676			bsize = sblksize(fs, freeblks->fb_oldsize, i);
2677			ffs_blkfree(ump, fs, freeblks->fb_devvp, bn, bsize,
2678			    freeblks->fb_previousinum);
2679			fs_pendingblocks += btodb(bsize);
2680			blocksreleased += btodb(bsize);
2681		}
2682	}
2683	UFS_LOCK(ump);
2684	fs->fs_pendingblocks -= fs_pendingblocks;
2685	UFS_UNLOCK(ump);
2686	/*
2687	 * If we still have not finished background cleanup, then check
2688	 * to see if the block count needs to be adjusted.
2689	 */
2690	if (freeblks->fb_chkcnt != blocksreleased &&
2691	    (fs->fs_flags & FS_UNCLEAN) != 0 &&
2692	    ffs_vget(freeblks->fb_list.wk_mp, freeblks->fb_previousinum,
2693	    (flags & LK_NOWAIT) | LK_EXCLUSIVE, &vp) == 0) {
2694		ip = VTOI(vp);
2695		DIP_SET(ip, i_blocks, DIP(ip, i_blocks) + \
2696		    freeblks->fb_chkcnt - blocksreleased);
2697		ip->i_flag |= IN_CHANGE;
2698		vput(vp);
2699	}
2700
2701#ifdef DIAGNOSTIC
2702	if (freeblks->fb_chkcnt != blocksreleased &&
2703	    ((fs->fs_flags & FS_UNCLEAN) == 0 || (flags & LK_NOWAIT) != 0))
2704		printf("handle_workitem_freeblocks: block count\n");
2705	if (allerror)
2706		softdep_error("handle_workitem_freeblks", allerror);
2707#endif /* DIAGNOSTIC */
2708
2709	ACQUIRE_LOCK(&lk);
2710	WORKITEM_FREE(freeblks, D_FREEBLKS);
2711	FREE_LOCK(&lk);
2712}
2713
2714/*
2715 * Release blocks associated with the inode ip and stored in the indirect
2716 * block dbn. If level is greater than SINGLE, the block is an indirect block
2717 * and recursive calls to indirtrunc must be used to cleanse other indirect
2718 * blocks.
2719 */
2720static int
2721indir_trunc(freeblks, dbn, level, lbn, countp)
2722	struct freeblks *freeblks;
2723	ufs2_daddr_t dbn;
2724	int level;
2725	ufs_lbn_t lbn;
2726	ufs2_daddr_t *countp;
2727{
2728	struct buf *bp;
2729	struct fs *fs;
2730	struct worklist *wk;
2731	struct indirdep *indirdep;
2732	struct ufsmount *ump;
2733	ufs1_daddr_t *bap1 = 0;
2734	ufs2_daddr_t nb, *bap2 = 0;
2735	ufs_lbn_t lbnadd;
2736	int i, nblocks, ufs1fmt;
2737	int error, allerror = 0;
2738	int fs_pendingblocks;
2739
2740	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
2741	fs = ump->um_fs;
2742	fs_pendingblocks = 0;
2743	lbnadd = 1;
2744	for (i = level; i > 0; i--)
2745		lbnadd *= NINDIR(fs);
2746	/*
2747	 * Get buffer of block pointers to be freed. This routine is not
2748	 * called until the zero'ed inode has been written, so it is safe
2749	 * to free blocks as they are encountered. Because the inode has
2750	 * been zero'ed, calls to bmap on these blocks will fail. So, we
2751	 * have to use the on-disk address and the block device for the
2752	 * filesystem to look them up. If the file was deleted before its
2753	 * indirect blocks were all written to disk, the routine that set
2754	 * us up (deallocate_dependencies) will have arranged to leave
2755	 * a complete copy of the indirect block in memory for our use.
2756	 * Otherwise we have to read the blocks in from the disk.
2757	 */
2758#ifdef notyet
2759	bp = getblk(freeblks->fb_devvp, dbn, (int)fs->fs_bsize, 0, 0,
2760	    GB_NOCREAT);
2761#else
2762	bp = incore(&freeblks->fb_devvp->v_bufobj, dbn);
2763#endif
2764	ACQUIRE_LOCK(&lk);
2765	if (bp != NULL && (wk = LIST_FIRST(&bp->b_dep)) != NULL) {
2766		if (wk->wk_type != D_INDIRDEP ||
2767		    (indirdep = WK_INDIRDEP(wk))->ir_savebp != bp ||
2768		    (indirdep->ir_state & GOINGAWAY) == 0)
2769			panic("indir_trunc: lost indirdep");
2770		WORKLIST_REMOVE(wk);
2771		WORKITEM_FREE(indirdep, D_INDIRDEP);
2772		if (LIST_FIRST(&bp->b_dep) != NULL)
2773			panic("indir_trunc: dangling dep");
2774		ump->um_numindirdeps -= 1;
2775		FREE_LOCK(&lk);
2776	} else {
2777#ifdef notyet
2778		if (bp)
2779			brelse(bp);
2780#endif
2781		FREE_LOCK(&lk);
2782		error = bread(freeblks->fb_devvp, dbn, (int)fs->fs_bsize,
2783		    NOCRED, &bp);
2784		if (error) {
2785			brelse(bp);
2786			return (error);
2787		}
2788	}
2789	/*
2790	 * Recursively free indirect blocks.
2791	 */
2792	if (ump->um_fstype == UFS1) {
2793		ufs1fmt = 1;
2794		bap1 = (ufs1_daddr_t *)bp->b_data;
2795	} else {
2796		ufs1fmt = 0;
2797		bap2 = (ufs2_daddr_t *)bp->b_data;
2798	}
2799	nblocks = btodb(fs->fs_bsize);
2800	for (i = NINDIR(fs) - 1; i >= 0; i--) {
2801		if (ufs1fmt)
2802			nb = bap1[i];
2803		else
2804			nb = bap2[i];
2805		if (nb == 0)
2806			continue;
2807		if (level != 0) {
2808			if ((error = indir_trunc(freeblks, fsbtodb(fs, nb),
2809			     level - 1, lbn + (i * lbnadd), countp)) != 0)
2810				allerror = error;
2811		}
2812		ffs_blkfree(ump, fs, freeblks->fb_devvp, nb, fs->fs_bsize,
2813		    freeblks->fb_previousinum);
2814		fs_pendingblocks += nblocks;
2815		*countp += nblocks;
2816	}
2817	UFS_LOCK(ump);
2818	fs->fs_pendingblocks -= fs_pendingblocks;
2819	UFS_UNLOCK(ump);
2820	bp->b_flags |= B_INVAL | B_NOCACHE;
2821	brelse(bp);
2822	return (allerror);
2823}
2824
2825/*
2826 * Free an allocindir.
2827 * This routine must be called with splbio interrupts blocked.
2828 */
2829static void
2830free_allocindir(aip, inodedep)
2831	struct allocindir *aip;
2832	struct inodedep *inodedep;
2833{
2834	struct freefrag *freefrag;
2835
2836	mtx_assert(&lk, MA_OWNED);
2837	if ((aip->ai_state & DEPCOMPLETE) == 0)
2838		LIST_REMOVE(aip, ai_deps);
2839	if (aip->ai_state & ONWORKLIST)
2840		WORKLIST_REMOVE(&aip->ai_list);
2841	LIST_REMOVE(aip, ai_next);
2842	if ((freefrag = aip->ai_freefrag) != NULL) {
2843		if (inodedep == NULL)
2844			add_to_worklist(&freefrag->ff_list);
2845		else
2846			WORKLIST_INSERT(&inodedep->id_bufwait,
2847			    &freefrag->ff_list);
2848	}
2849	WORKITEM_FREE(aip, D_ALLOCINDIR);
2850}
2851
2852/*
2853 * Directory entry addition dependencies.
2854 *
2855 * When adding a new directory entry, the inode (with its incremented link
2856 * count) must be written to disk before the directory entry's pointer to it.
2857 * Also, if the inode is newly allocated, the corresponding freemap must be
2858 * updated (on disk) before the directory entry's pointer. These requirements
2859 * are met via undo/redo on the directory entry's pointer, which consists
2860 * simply of the inode number.
2861 *
2862 * As directory entries are added and deleted, the free space within a
2863 * directory block can become fragmented.  The ufs filesystem will compact
2864 * a fragmented directory block to make space for a new entry. When this
2865 * occurs, the offsets of previously added entries change. Any "diradd"
2866 * dependency structures corresponding to these entries must be updated with
2867 * the new offsets.
2868 */
2869
2870/*
2871 * This routine is called after the in-memory inode's link
2872 * count has been incremented, but before the directory entry's
2873 * pointer to the inode has been set.
2874 */
2875int
2876softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
2877	struct buf *bp;		/* buffer containing directory block */
2878	struct inode *dp;	/* inode for directory */
2879	off_t diroffset;	/* offset of new entry in directory */
2880	ino_t newinum;		/* inode referenced by new directory entry */
2881	struct buf *newdirbp;	/* non-NULL => contents of new mkdir */
2882	int isnewblk;		/* entry is in a newly allocated block */
2883{
2884	int offset;		/* offset of new entry within directory block */
2885	ufs_lbn_t lbn;		/* block in directory containing new entry */
2886	struct fs *fs;
2887	struct diradd *dap;
2888	struct allocdirect *adp;
2889	struct pagedep *pagedep;
2890	struct inodedep *inodedep;
2891	struct newdirblk *newdirblk = 0;
2892	struct mkdir *mkdir1, *mkdir2;
2893	struct mount *mp;
2894
2895	/*
2896	 * Whiteouts have no dependencies.
2897	 */
2898	if (newinum == WINO) {
2899		if (newdirbp != NULL)
2900			bdwrite(newdirbp);
2901		return (0);
2902	}
2903	mp = UFSTOVFS(dp->i_ump);
2904	fs = dp->i_fs;
2905	lbn = lblkno(fs, diroffset);
2906	offset = blkoff(fs, diroffset);
2907	MALLOC(dap, struct diradd *, sizeof(struct diradd), M_DIRADD,
2908		M_SOFTDEP_FLAGS|M_ZERO);
2909	workitem_alloc(&dap->da_list, D_DIRADD, mp);
2910	dap->da_offset = offset;
2911	dap->da_newinum = newinum;
2912	dap->da_state = ATTACHED;
2913	if (isnewblk && lbn < NDADDR && fragoff(fs, diroffset) == 0) {
2914		MALLOC(newdirblk, struct newdirblk *, sizeof(struct newdirblk),
2915		    M_NEWDIRBLK, M_SOFTDEP_FLAGS);
2916		workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
2917	}
2918	if (newdirbp == NULL) {
2919		dap->da_state |= DEPCOMPLETE;
2920		ACQUIRE_LOCK(&lk);
2921	} else {
2922		dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
2923		MALLOC(mkdir1, struct mkdir *, sizeof(struct mkdir), M_MKDIR,
2924		    M_SOFTDEP_FLAGS);
2925		workitem_alloc(&mkdir1->md_list, D_MKDIR, mp);
2926		mkdir1->md_state = MKDIR_BODY;
2927		mkdir1->md_diradd = dap;
2928		MALLOC(mkdir2, struct mkdir *, sizeof(struct mkdir), M_MKDIR,
2929		    M_SOFTDEP_FLAGS);
2930		workitem_alloc(&mkdir2->md_list, D_MKDIR, mp);
2931		mkdir2->md_state = MKDIR_PARENT;
2932		mkdir2->md_diradd = dap;
2933		/*
2934		 * Dependency on "." and ".." being written to disk.
2935		 */
2936		mkdir1->md_buf = newdirbp;
2937		ACQUIRE_LOCK(&lk);
2938		LIST_INSERT_HEAD(&mkdirlisthd, mkdir1, md_mkdirs);
2939		WORKLIST_INSERT(&newdirbp->b_dep, &mkdir1->md_list);
2940		FREE_LOCK(&lk);
2941		bdwrite(newdirbp);
2942		/*
2943		 * Dependency on link count increase for parent directory
2944		 */
2945		ACQUIRE_LOCK(&lk);
2946		if (inodedep_lookup(mp, dp->i_number, 0, &inodedep) == 0
2947		    || (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
2948			dap->da_state &= ~MKDIR_PARENT;
2949			WORKITEM_FREE(mkdir2, D_MKDIR);
2950		} else {
2951			LIST_INSERT_HEAD(&mkdirlisthd, mkdir2, md_mkdirs);
2952			WORKLIST_INSERT(&inodedep->id_bufwait,&mkdir2->md_list);
2953		}
2954	}
2955	/*
2956	 * Link into parent directory pagedep to await its being written.
2957	 */
2958	if (pagedep_lookup(dp, lbn, DEPALLOC, &pagedep) == 0)
2959		WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
2960	dap->da_pagedep = pagedep;
2961	LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
2962	    da_pdlist);
2963	/*
2964	 * Link into its inodedep. Put it on the id_bufwait list if the inode
2965	 * is not yet written. If it is written, do the post-inode write
2966	 * processing to put it on the id_pendinghd list.
2967	 */
2968	(void) inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
2969	if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
2970		diradd_inode_written(dap, inodedep);
2971	else
2972		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
2973	if (isnewblk) {
2974		/*
2975		 * Directories growing into indirect blocks are rare
2976		 * enough and the frequency of new block allocation
2977		 * in those cases even more rare, that we choose not
2978		 * to bother tracking them. Rather we simply force the
2979		 * new directory entry to disk.
2980		 */
2981		if (lbn >= NDADDR) {
2982			FREE_LOCK(&lk);
2983			/*
2984			 * We only have a new allocation when at the
2985			 * beginning of a new block, not when we are
2986			 * expanding into an existing block.
2987			 */
2988			if (blkoff(fs, diroffset) == 0)
2989				return (1);
2990			return (0);
2991		}
2992		/*
2993		 * We only have a new allocation when at the beginning
2994		 * of a new fragment, not when we are expanding into an
2995		 * existing fragment. Also, there is nothing to do if we
2996		 * are already tracking this block.
2997		 */
2998		if (fragoff(fs, diroffset) != 0) {
2999			FREE_LOCK(&lk);
3000			return (0);
3001		}
3002		if ((pagedep->pd_state & NEWBLOCK) != 0) {
3003			WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
3004			FREE_LOCK(&lk);
3005			return (0);
3006		}
3007		/*
3008		 * Find our associated allocdirect and have it track us.
3009		 */
3010		if (inodedep_lookup(mp, dp->i_number, 0, &inodedep) == 0)
3011			panic("softdep_setup_directory_add: lost inodedep");
3012		adp = TAILQ_LAST(&inodedep->id_newinoupdt, allocdirectlst);
3013		if (adp == NULL || adp->ad_lbn != lbn)
3014			panic("softdep_setup_directory_add: lost entry");
3015		pagedep->pd_state |= NEWBLOCK;
3016		newdirblk->db_pagedep = pagedep;
3017		WORKLIST_INSERT(&adp->ad_newdirblk, &newdirblk->db_list);
3018	}
3019	FREE_LOCK(&lk);
3020	return (0);
3021}
3022
3023/*
3024 * This procedure is called to change the offset of a directory
3025 * entry when compacting a directory block which must be owned
3026 * exclusively by the caller. Note that the actual entry movement
3027 * must be done in this procedure to ensure that no I/O completions
3028 * occur while the move is in progress.
3029 */
3030void
3031softdep_change_directoryentry_offset(dp, base, oldloc, newloc, entrysize)
3032	struct inode *dp;	/* inode for directory */
3033	caddr_t base;		/* address of dp->i_offset */
3034	caddr_t oldloc;		/* address of old directory location */
3035	caddr_t newloc;		/* address of new directory location */
3036	int entrysize;		/* size of directory entry */
3037{
3038	int offset, oldoffset, newoffset;
3039	struct pagedep *pagedep;
3040	struct diradd *dap;
3041	ufs_lbn_t lbn;
3042
3043	ACQUIRE_LOCK(&lk);
3044	lbn = lblkno(dp->i_fs, dp->i_offset);
3045	offset = blkoff(dp->i_fs, dp->i_offset);
3046	if (pagedep_lookup(dp, lbn, 0, &pagedep) == 0)
3047		goto done;
3048	oldoffset = offset + (oldloc - base);
3049	newoffset = offset + (newloc - base);
3050
3051	LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(oldoffset)], da_pdlist) {
3052		if (dap->da_offset != oldoffset)
3053			continue;
3054		dap->da_offset = newoffset;
3055		if (DIRADDHASH(newoffset) == DIRADDHASH(oldoffset))
3056			break;
3057		LIST_REMOVE(dap, da_pdlist);
3058		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(newoffset)],
3059		    dap, da_pdlist);
3060		break;
3061	}
3062	if (dap == NULL) {
3063
3064		LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist) {
3065			if (dap->da_offset == oldoffset) {
3066				dap->da_offset = newoffset;
3067				break;
3068			}
3069		}
3070	}
3071done:
3072	bcopy(oldloc, newloc, entrysize);
3073	FREE_LOCK(&lk);
3074}
3075
3076/*
3077 * Free a diradd dependency structure. This routine must be called
3078 * with splbio interrupts blocked.
3079 */
3080static void
3081free_diradd(dap)
3082	struct diradd *dap;
3083{
3084	struct dirrem *dirrem;
3085	struct pagedep *pagedep;
3086	struct inodedep *inodedep;
3087	struct mkdir *mkdir, *nextmd;
3088
3089	mtx_assert(&lk, MA_OWNED);
3090	WORKLIST_REMOVE(&dap->da_list);
3091	LIST_REMOVE(dap, da_pdlist);
3092	if ((dap->da_state & DIRCHG) == 0) {
3093		pagedep = dap->da_pagedep;
3094	} else {
3095		dirrem = dap->da_previous;
3096		pagedep = dirrem->dm_pagedep;
3097		dirrem->dm_dirinum = pagedep->pd_ino;
3098		add_to_worklist(&dirrem->dm_list);
3099	}
3100	if (inodedep_lookup(pagedep->pd_list.wk_mp, dap->da_newinum,
3101	    0, &inodedep) != 0)
3102		(void) free_inodedep(inodedep);
3103	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
3104		for (mkdir = LIST_FIRST(&mkdirlisthd); mkdir; mkdir = nextmd) {
3105			nextmd = LIST_NEXT(mkdir, md_mkdirs);
3106			if (mkdir->md_diradd != dap)
3107				continue;
3108			dap->da_state &= ~mkdir->md_state;
3109			WORKLIST_REMOVE(&mkdir->md_list);
3110			LIST_REMOVE(mkdir, md_mkdirs);
3111			WORKITEM_FREE(mkdir, D_MKDIR);
3112		}
3113		if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
3114			panic("free_diradd: unfound ref");
3115	}
3116	WORKITEM_FREE(dap, D_DIRADD);
3117}
3118
3119/*
3120 * Directory entry removal dependencies.
3121 *
3122 * When removing a directory entry, the entry's inode pointer must be
3123 * zero'ed on disk before the corresponding inode's link count is decremented
3124 * (possibly freeing the inode for re-use). This dependency is handled by
3125 * updating the directory entry but delaying the inode count reduction until
3126 * after the directory block has been written to disk. After this point, the
3127 * inode count can be decremented whenever it is convenient.
3128 */
3129
3130/*
3131 * This routine should be called immediately after removing
3132 * a directory entry.  The inode's link count should not be
3133 * decremented by the calling procedure -- the soft updates
3134 * code will do this task when it is safe.
3135 */
3136void
3137softdep_setup_remove(bp, dp, ip, isrmdir)
3138	struct buf *bp;		/* buffer containing directory block */
3139	struct inode *dp;	/* inode for the directory being modified */
3140	struct inode *ip;	/* inode for directory entry being removed */
3141	int isrmdir;		/* indicates if doing RMDIR */
3142{
3143	struct dirrem *dirrem, *prevdirrem;
3144
3145	/*
3146	 * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.
3147	 */
3148	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
3149
3150	/*
3151	 * If the COMPLETE flag is clear, then there were no active
3152	 * entries and we want to roll back to a zeroed entry until
3153	 * the new inode is committed to disk. If the COMPLETE flag is
3154	 * set then we have deleted an entry that never made it to
3155	 * disk. If the entry we deleted resulted from a name change,
3156	 * then the old name still resides on disk. We cannot delete
3157	 * its inode (returned to us in prevdirrem) until the zeroed
3158	 * directory entry gets to disk. The new inode has never been
3159	 * referenced on the disk, so can be deleted immediately.
3160	 */
3161	if ((dirrem->dm_state & COMPLETE) == 0) {
3162		LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
3163		    dm_next);
3164		FREE_LOCK(&lk);
3165	} else {
3166		if (prevdirrem != NULL)
3167			LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
3168			    prevdirrem, dm_next);
3169		dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
3170		FREE_LOCK(&lk);
3171		handle_workitem_remove(dirrem, NULL);
3172	}
3173}
3174
3175/*
3176 * Allocate a new dirrem if appropriate and return it along with
3177 * its associated pagedep. Called without a lock, returns with lock.
3178 */
3179static long num_dirrem;		/* number of dirrem allocated */
3180static struct dirrem *
3181newdirrem(bp, dp, ip, isrmdir, prevdirremp)
3182	struct buf *bp;		/* buffer containing directory block */
3183	struct inode *dp;	/* inode for the directory being modified */
3184	struct inode *ip;	/* inode for directory entry being removed */
3185	int isrmdir;		/* indicates if doing RMDIR */
3186	struct dirrem **prevdirremp; /* previously referenced inode, if any */
3187{
3188	int offset;
3189	ufs_lbn_t lbn;
3190	struct diradd *dap;
3191	struct dirrem *dirrem;
3192	struct pagedep *pagedep;
3193
3194	/*
3195	 * Whiteouts have no deletion dependencies.
3196	 */
3197	if (ip == NULL)
3198		panic("newdirrem: whiteout");
3199	/*
3200	 * If we are over our limit, try to improve the situation.
3201	 * Limiting the number of dirrem structures will also limit
3202	 * the number of freefile and freeblks structures.
3203	 */
3204	ACQUIRE_LOCK(&lk);
3205	if (num_dirrem > max_softdeps / 2)
3206		(void) request_cleanup(ITOV(dp)->v_mount, FLUSH_REMOVE);
3207	num_dirrem += 1;
3208	FREE_LOCK(&lk);
3209	MALLOC(dirrem, struct dirrem *, sizeof(struct dirrem),
3210		M_DIRREM, M_SOFTDEP_FLAGS|M_ZERO);
3211	workitem_alloc(&dirrem->dm_list, D_DIRREM, ITOV(dp)->v_mount);
3212	dirrem->dm_state = isrmdir ? RMDIR : 0;
3213	dirrem->dm_oldinum = ip->i_number;
3214	*prevdirremp = NULL;
3215
3216	ACQUIRE_LOCK(&lk);
3217	lbn = lblkno(dp->i_fs, dp->i_offset);
3218	offset = blkoff(dp->i_fs, dp->i_offset);
3219	if (pagedep_lookup(dp, lbn, DEPALLOC, &pagedep) == 0)
3220		WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
3221	dirrem->dm_pagedep = pagedep;
3222	/*
3223	 * Check for a diradd dependency for the same directory entry.
3224	 * If present, then both dependencies become obsolete and can
3225	 * be de-allocated. Check for an entry on both the pd_dirraddhd
3226	 * list and the pd_pendinghd list.
3227	 */
3228
3229	LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
3230		if (dap->da_offset == offset)
3231			break;
3232	if (dap == NULL) {
3233
3234		LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
3235			if (dap->da_offset == offset)
3236				break;
3237		if (dap == NULL)
3238			return (dirrem);
3239	}
3240	/*
3241	 * Must be ATTACHED at this point.
3242	 */
3243	if ((dap->da_state & ATTACHED) == 0)
3244		panic("newdirrem: not ATTACHED");
3245	if (dap->da_newinum != ip->i_number)
3246		panic("newdirrem: inum %d should be %d",
3247		    ip->i_number, dap->da_newinum);
3248	/*
3249	 * If we are deleting a changed name that never made it to disk,
3250	 * then return the dirrem describing the previous inode (which
3251	 * represents the inode currently referenced from this entry on disk).
3252	 */
3253	if ((dap->da_state & DIRCHG) != 0) {
3254		*prevdirremp = dap->da_previous;
3255		dap->da_state &= ~DIRCHG;
3256		dap->da_pagedep = pagedep;
3257	}
3258	/*
3259	 * We are deleting an entry that never made it to disk.
3260	 * Mark it COMPLETE so we can delete its inode immediately.
3261	 */
3262	dirrem->dm_state |= COMPLETE;
3263	free_diradd(dap);
3264	return (dirrem);
3265}
3266
3267/*
3268 * Directory entry change dependencies.
3269 *
3270 * Changing an existing directory entry requires that an add operation
3271 * be completed first followed by a deletion. The semantics for the addition
3272 * are identical to the description of adding a new entry above except
3273 * that the rollback is to the old inode number rather than zero. Once
3274 * the addition dependency is completed, the removal is done as described
3275 * in the removal routine above.
3276 */
3277
3278/*
3279 * This routine should be called immediately after changing
3280 * a directory entry.  The inode's link count should not be
3281 * decremented by the calling procedure -- the soft updates
3282 * code will perform this task when it is safe.
3283 */
3284void
3285softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
3286	struct buf *bp;		/* buffer containing directory block */
3287	struct inode *dp;	/* inode for the directory being modified */
3288	struct inode *ip;	/* inode for directory entry being removed */
3289	ino_t newinum;		/* new inode number for changed entry */
3290	int isrmdir;		/* indicates if doing RMDIR */
3291{
3292	int offset;
3293	struct diradd *dap = NULL;
3294	struct dirrem *dirrem, *prevdirrem;
3295	struct pagedep *pagedep;
3296	struct inodedep *inodedep;
3297	struct mount *mp;
3298
3299	offset = blkoff(dp->i_fs, dp->i_offset);
3300	mp = UFSTOVFS(dp->i_ump);
3301
3302	/*
3303	 * Whiteouts do not need diradd dependencies.
3304	 */
3305	if (newinum != WINO) {
3306		MALLOC(dap, struct diradd *, sizeof(struct diradd),
3307		    M_DIRADD, M_SOFTDEP_FLAGS|M_ZERO);
3308		workitem_alloc(&dap->da_list, D_DIRADD, mp);
3309		dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
3310		dap->da_offset = offset;
3311		dap->da_newinum = newinum;
3312	}
3313
3314	/*
3315	 * Allocate a new dirrem and ACQUIRE_LOCK.
3316	 */
3317	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
3318	pagedep = dirrem->dm_pagedep;
3319	/*
3320	 * The possible values for isrmdir:
3321	 *	0 - non-directory file rename
3322	 *	1 - directory rename within same directory
3323	 *   inum - directory rename to new directory of given inode number
3324	 * When renaming to a new directory, we are both deleting and
3325	 * creating a new directory entry, so the link count on the new
3326	 * directory should not change. Thus we do not need the followup
3327	 * dirrem which is usually done in handle_workitem_remove. We set
3328	 * the DIRCHG flag to tell handle_workitem_remove to skip the
3329	 * followup dirrem.
3330	 */
3331	if (isrmdir > 1)
3332		dirrem->dm_state |= DIRCHG;
3333
3334	/*
3335	 * Whiteouts have no additional dependencies,
3336	 * so just put the dirrem on the correct list.
3337	 */
3338	if (newinum == WINO) {
3339		if ((dirrem->dm_state & COMPLETE) == 0) {
3340			LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
3341			    dm_next);
3342		} else {
3343			dirrem->dm_dirinum = pagedep->pd_ino;
3344			add_to_worklist(&dirrem->dm_list);
3345		}
3346		FREE_LOCK(&lk);
3347		return;
3348	}
3349
3350	/*
3351	 * If the COMPLETE flag is clear, then there were no active
3352	 * entries and we want to roll back to the previous inode until
3353	 * the new inode is committed to disk. If the COMPLETE flag is
3354	 * set, then we have deleted an entry that never made it to disk.
3355	 * If the entry we deleted resulted from a name change, then the old
3356	 * inode reference still resides on disk. Any rollback that we do
3357	 * needs to be to that old inode (returned to us in prevdirrem). If
3358	 * the entry we deleted resulted from a create, then there is
3359	 * no entry on the disk, so we want to roll back to zero rather
3360	 * than the uncommitted inode. In either of the COMPLETE cases we
3361	 * want to immediately free the unwritten and unreferenced inode.
3362	 */
3363	if ((dirrem->dm_state & COMPLETE) == 0) {
3364		dap->da_previous = dirrem;
3365	} else {
3366		if (prevdirrem != NULL) {
3367			dap->da_previous = prevdirrem;
3368		} else {
3369			dap->da_state &= ~DIRCHG;
3370			dap->da_pagedep = pagedep;
3371		}
3372		dirrem->dm_dirinum = pagedep->pd_ino;
3373		add_to_worklist(&dirrem->dm_list);
3374	}
3375	/*
3376	 * Link into its inodedep. Put it on the id_bufwait list if the inode
3377	 * is not yet written. If it is written, do the post-inode write
3378	 * processing to put it on the id_pendinghd list.
3379	 */
3380	if (inodedep_lookup(mp, newinum, DEPALLOC, &inodedep) == 0 ||
3381	    (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
3382		dap->da_state |= COMPLETE;
3383		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
3384		WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
3385	} else {
3386		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
3387		    dap, da_pdlist);
3388		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
3389	}
3390	FREE_LOCK(&lk);
3391}
3392
3393/*
3394 * Called whenever the link count on an inode is changed.
3395 * It creates an inode dependency so that the new reference(s)
3396 * to the inode cannot be committed to disk until the updated
3397 * inode has been written.
3398 */
3399void
3400softdep_change_linkcnt(ip)
3401	struct inode *ip;	/* the inode with the increased link count */
3402{
3403	struct inodedep *inodedep;
3404
3405	ACQUIRE_LOCK(&lk);
3406	(void) inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number,
3407	    DEPALLOC, &inodedep);
3408	if (ip->i_nlink < ip->i_effnlink)
3409		panic("softdep_change_linkcnt: bad delta");
3410	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
3411	FREE_LOCK(&lk);
3412}
3413
3414/*
3415 * Called when the effective link count and the reference count
3416 * on an inode drops to zero. At this point there are no names
3417 * referencing the file in the filesystem and no active file
3418 * references. The space associated with the file will be freed
3419 * as soon as the necessary soft dependencies are cleared.
3420 */
3421void
3422softdep_releasefile(ip)
3423	struct inode *ip;	/* inode with the zero effective link count */
3424{
3425	struct inodedep *inodedep;
3426	struct fs *fs;
3427	int extblocks;
3428
3429	if (ip->i_effnlink > 0)
3430		panic("softdep_filerelease: file still referenced");
3431	/*
3432	 * We may be called several times as the real reference count
3433	 * drops to zero. We only want to account for the space once.
3434	 */
3435	if (ip->i_flag & IN_SPACECOUNTED)
3436		return;
3437	/*
3438	 * We have to deactivate a snapshot otherwise copyonwrites may
3439	 * add blocks and the cleanup may remove blocks after we have
3440	 * tried to account for them.
3441	 */
3442	if ((ip->i_flags & SF_SNAPSHOT) != 0)
3443		ffs_snapremove(ITOV(ip));
3444	/*
3445	 * If we are tracking an nlinkdelta, we have to also remember
3446	 * whether we accounted for the freed space yet.
3447	 */
3448	ACQUIRE_LOCK(&lk);
3449	if ((inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, 0, &inodedep)))
3450		inodedep->id_state |= SPACECOUNTED;
3451	FREE_LOCK(&lk);
3452	fs = ip->i_fs;
3453	extblocks = 0;
3454	if (fs->fs_magic == FS_UFS2_MAGIC)
3455		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
3456	UFS_LOCK(ip->i_ump);
3457	ip->i_fs->fs_pendingblocks += DIP(ip, i_blocks) - extblocks;
3458	ip->i_fs->fs_pendinginodes += 1;
3459	UFS_UNLOCK(ip->i_ump);
3460	ip->i_flag |= IN_SPACECOUNTED;
3461}
3462
3463/*
3464 * This workitem decrements the inode's link count.
3465 * If the link count reaches zero, the file is removed.
3466 */
3467static void
3468handle_workitem_remove(dirrem, xp)
3469	struct dirrem *dirrem;
3470	struct vnode *xp;
3471{
3472	struct thread *td = curthread;
3473	struct inodedep *inodedep;
3474	struct vnode *vp;
3475	struct inode *ip;
3476	ino_t oldinum;
3477	int error;
3478
3479	if ((vp = xp) == NULL &&
3480	    (error = ffs_vget(dirrem->dm_list.wk_mp,
3481	    dirrem->dm_oldinum, LK_EXCLUSIVE, &vp)) != 0) {
3482		softdep_error("handle_workitem_remove: vget", error);
3483		return;
3484	}
3485	ip = VTOI(vp);
3486	ACQUIRE_LOCK(&lk);
3487	if ((inodedep_lookup(dirrem->dm_list.wk_mp,
3488	    dirrem->dm_oldinum, 0, &inodedep)) == 0)
3489		panic("handle_workitem_remove: lost inodedep");
3490	/*
3491	 * Normal file deletion.
3492	 */
3493	if ((dirrem->dm_state & RMDIR) == 0) {
3494		ip->i_nlink--;
3495		DIP_SET(ip, i_nlink, ip->i_nlink);
3496		ip->i_flag |= IN_CHANGE;
3497		if (ip->i_nlink < ip->i_effnlink)
3498			panic("handle_workitem_remove: bad file delta");
3499		inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
3500		num_dirrem -= 1;
3501		WORKITEM_FREE(dirrem, D_DIRREM);
3502		FREE_LOCK(&lk);
3503		vput(vp);
3504		return;
3505	}
3506	/*
3507	 * Directory deletion. Decrement reference count for both the
3508	 * just deleted parent directory entry and the reference for ".".
3509	 * Next truncate the directory to length zero. When the
3510	 * truncation completes, arrange to have the reference count on
3511	 * the parent decremented to account for the loss of "..".
3512	 */
3513	ip->i_nlink -= 2;
3514	DIP_SET(ip, i_nlink, ip->i_nlink);
3515	ip->i_flag |= IN_CHANGE;
3516	if (ip->i_nlink < ip->i_effnlink)
3517		panic("handle_workitem_remove: bad dir delta");
3518	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
3519	FREE_LOCK(&lk);
3520	if ((error = ffs_truncate(vp, (off_t)0, 0, td->td_ucred, td)) != 0)
3521		softdep_error("handle_workitem_remove: truncate", error);
3522	ACQUIRE_LOCK(&lk);
3523	/*
3524	 * Rename a directory to a new parent. Since, we are both deleting
3525	 * and creating a new directory entry, the link count on the new
3526	 * directory should not change. Thus we skip the followup dirrem.
3527	 */
3528	if (dirrem->dm_state & DIRCHG) {
3529		num_dirrem -= 1;
3530		WORKITEM_FREE(dirrem, D_DIRREM);
3531		FREE_LOCK(&lk);
3532		vput(vp);
3533		return;
3534	}
3535	/*
3536	 * If the inodedep does not exist, then the zero'ed inode has
3537	 * been written to disk. If the allocated inode has never been
3538	 * written to disk, then the on-disk inode is zero'ed. In either
3539	 * case we can remove the file immediately.
3540	 */
3541	dirrem->dm_state = 0;
3542	oldinum = dirrem->dm_oldinum;
3543	dirrem->dm_oldinum = dirrem->dm_dirinum;
3544	if (inodedep_lookup(dirrem->dm_list.wk_mp, oldinum,
3545	    0, &inodedep) == 0 || check_inode_unwritten(inodedep)) {
3546		FREE_LOCK(&lk);
3547		vput(vp);
3548		handle_workitem_remove(dirrem, NULL);
3549		return;
3550	}
3551	WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
3552	FREE_LOCK(&lk);
3553	ip->i_flag |= IN_CHANGE;
3554	ffs_update(vp, 0);
3555	vput(vp);
3556}
3557
3558/*
3559 * Inode de-allocation dependencies.
3560 *
3561 * When an inode's link count is reduced to zero, it can be de-allocated. We
3562 * found it convenient to postpone de-allocation until after the inode is
3563 * written to disk with its new link count (zero).  At this point, all of the
3564 * on-disk inode's block pointers are nullified and, with careful dependency
3565 * list ordering, all dependencies related to the inode will be satisfied and
3566 * the corresponding dependency structures de-allocated.  So, if/when the
3567 * inode is reused, there will be no mixing of old dependencies with new
3568 * ones.  This artificial dependency is set up by the block de-allocation
3569 * procedure above (softdep_setup_freeblocks) and completed by the
3570 * following procedure.
3571 */
3572static void
3573handle_workitem_freefile(freefile)
3574	struct freefile *freefile;
3575{
3576	struct fs *fs;
3577	struct inodedep *idp;
3578	struct ufsmount *ump;
3579	int error;
3580
3581	ump = VFSTOUFS(freefile->fx_list.wk_mp);
3582	fs = ump->um_fs;
3583#ifdef DEBUG
3584	ACQUIRE_LOCK(&lk);
3585	error = inodedep_lookup(UFSTOVFS(ump), freefile->fx_oldinum, 0, &idp);
3586	FREE_LOCK(&lk);
3587	if (error)
3588		panic("handle_workitem_freefile: inodedep survived");
3589#endif
3590	UFS_LOCK(ump);
3591	fs->fs_pendinginodes -= 1;
3592	UFS_UNLOCK(ump);
3593	if ((error = ffs_freefile(ump, fs, freefile->fx_devvp,
3594	    freefile->fx_oldinum, freefile->fx_mode)) != 0)
3595		softdep_error("handle_workitem_freefile", error);
3596	ACQUIRE_LOCK(&lk);
3597	WORKITEM_FREE(freefile, D_FREEFILE);
3598	FREE_LOCK(&lk);
3599}
3600
3601
3602/*
3603 * Helper function which unlinks marker element from work list and returns
3604 * the next element on the list.
3605 */
3606static __inline struct worklist *
3607markernext(struct worklist *marker)
3608{
3609	struct worklist *next;
3610
3611	next = LIST_NEXT(marker, wk_list);
3612	LIST_REMOVE(marker, wk_list);
3613	return next;
3614}
3615
3616/*
3617 * Disk writes.
3618 *
3619 * The dependency structures constructed above are most actively used when file
3620 * system blocks are written to disk.  No constraints are placed on when a
3621 * block can be written, but unsatisfied update dependencies are made safe by
3622 * modifying (or replacing) the source memory for the duration of the disk
3623 * write.  When the disk write completes, the memory block is again brought
3624 * up-to-date.
3625 *
3626 * In-core inode structure reclamation.
3627 *
3628 * Because there are a finite number of "in-core" inode structures, they are
3629 * reused regularly.  By transferring all inode-related dependencies to the
3630 * in-memory inode block and indexing them separately (via "inodedep"s), we
3631 * can allow "in-core" inode structures to be reused at any time and avoid
3632 * any increase in contention.
3633 *
3634 * Called just before entering the device driver to initiate a new disk I/O.
3635 * The buffer must be locked, thus, no I/O completion operations can occur
3636 * while we are manipulating its associated dependencies.
3637 */
3638static void
3639softdep_disk_io_initiation(bp)
3640	struct buf *bp;		/* structure describing disk write to occur */
3641{
3642	struct worklist *wk;
3643	struct worklist marker;
3644	struct indirdep *indirdep;
3645	struct inodedep *inodedep;
3646
3647	/*
3648	 * We only care about write operations. There should never
3649	 * be dependencies for reads.
3650	 */
3651	if (bp->b_iocmd != BIO_WRITE)
3652		panic("softdep_disk_io_initiation: not write");
3653
3654	marker.wk_type = D_LAST + 1;	/* Not a normal workitem */
3655	PHOLD(curproc);			/* Don't swap out kernel stack */
3656
3657	ACQUIRE_LOCK(&lk);
3658	/*
3659	 * Do any necessary pre-I/O processing.
3660	 */
3661	for (wk = LIST_FIRST(&bp->b_dep); wk != NULL;
3662	     wk = markernext(&marker)) {
3663		LIST_INSERT_AFTER(wk, &marker, wk_list);
3664		switch (wk->wk_type) {
3665
3666		case D_PAGEDEP:
3667			initiate_write_filepage(WK_PAGEDEP(wk), bp);
3668			continue;
3669
3670		case D_INODEDEP:
3671			inodedep = WK_INODEDEP(wk);
3672			if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC)
3673				initiate_write_inodeblock_ufs1(inodedep, bp);
3674			else
3675				initiate_write_inodeblock_ufs2(inodedep, bp);
3676			continue;
3677
3678		case D_INDIRDEP:
3679			indirdep = WK_INDIRDEP(wk);
3680			if (indirdep->ir_state & GOINGAWAY)
3681				panic("disk_io_initiation: indirdep gone");
3682			/*
3683			 * If there are no remaining dependencies, this
3684			 * will be writing the real pointers, so the
3685			 * dependency can be freed.
3686			 */
3687			if (LIST_FIRST(&indirdep->ir_deplisthd) == NULL) {
3688				struct buf *bp;
3689
3690				bp = indirdep->ir_savebp;
3691				bp->b_flags |= B_INVAL | B_NOCACHE;
3692				/* inline expand WORKLIST_REMOVE(wk); */
3693				wk->wk_state &= ~ONWORKLIST;
3694				LIST_REMOVE(wk, wk_list);
3695				WORKITEM_FREE(indirdep, D_INDIRDEP);
3696				FREE_LOCK(&lk);
3697				brelse(bp);
3698				ACQUIRE_LOCK(&lk);
3699				continue;
3700			}
3701			/*
3702			 * Replace up-to-date version with safe version.
3703			 */
3704			FREE_LOCK(&lk);
3705			MALLOC(indirdep->ir_saveddata, caddr_t, bp->b_bcount,
3706			    M_INDIRDEP, M_SOFTDEP_FLAGS);
3707			ACQUIRE_LOCK(&lk);
3708			indirdep->ir_state &= ~ATTACHED;
3709			indirdep->ir_state |= UNDONE;
3710			bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
3711			bcopy(indirdep->ir_savebp->b_data, bp->b_data,
3712			    bp->b_bcount);
3713			continue;
3714
3715		case D_MKDIR:
3716		case D_BMSAFEMAP:
3717		case D_ALLOCDIRECT:
3718		case D_ALLOCINDIR:
3719			continue;
3720
3721		default:
3722			panic("handle_disk_io_initiation: Unexpected type %s",
3723			    TYPENAME(wk->wk_type));
3724			/* NOTREACHED */
3725		}
3726	}
3727	FREE_LOCK(&lk);
3728	PRELE(curproc);			/* Allow swapout of kernel stack */
3729}
3730
3731/*
3732 * Called from within the procedure above to deal with unsatisfied
3733 * allocation dependencies in a directory. The buffer must be locked,
3734 * thus, no I/O completion operations can occur while we are
3735 * manipulating its associated dependencies.
3736 */
3737static void
3738initiate_write_filepage(pagedep, bp)
3739	struct pagedep *pagedep;
3740	struct buf *bp;
3741{
3742	struct diradd *dap;
3743	struct direct *ep;
3744	int i;
3745
3746	if (pagedep->pd_state & IOSTARTED) {
3747		/*
3748		 * This can only happen if there is a driver that does not
3749		 * understand chaining. Here biodone will reissue the call
3750		 * to strategy for the incomplete buffers.
3751		 */
3752		printf("initiate_write_filepage: already started\n");
3753		return;
3754	}
3755	pagedep->pd_state |= IOSTARTED;
3756	for (i = 0; i < DAHASHSZ; i++) {
3757		LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
3758			ep = (struct direct *)
3759			    ((char *)bp->b_data + dap->da_offset);
3760			if (ep->d_ino != dap->da_newinum)
3761				panic("%s: dir inum %d != new %d",
3762				    "initiate_write_filepage",
3763				    ep->d_ino, dap->da_newinum);
3764			if (dap->da_state & DIRCHG)
3765				ep->d_ino = dap->da_previous->dm_oldinum;
3766			else
3767				ep->d_ino = 0;
3768			dap->da_state &= ~ATTACHED;
3769			dap->da_state |= UNDONE;
3770		}
3771	}
3772}
3773
3774/*
3775 * Version of initiate_write_inodeblock that handles UFS1 dinodes.
3776 * Note that any bug fixes made to this routine must be done in the
3777 * version found below.
3778 *
3779 * Called from within the procedure above to deal with unsatisfied
3780 * allocation dependencies in an inodeblock. The buffer must be
3781 * locked, thus, no I/O completion operations can occur while we
3782 * are manipulating its associated dependencies.
3783 */
3784static void
3785initiate_write_inodeblock_ufs1(inodedep, bp)
3786	struct inodedep *inodedep;
3787	struct buf *bp;			/* The inode block */
3788{
3789	struct allocdirect *adp, *lastadp;
3790	struct ufs1_dinode *dp;
3791	struct ufs1_dinode *sip;
3792	struct fs *fs;
3793	ufs_lbn_t i, prevlbn = 0;
3794	int deplist;
3795
3796	if (inodedep->id_state & IOSTARTED)
3797		panic("initiate_write_inodeblock_ufs1: already started");
3798	inodedep->id_state |= IOSTARTED;
3799	fs = inodedep->id_fs;
3800	dp = (struct ufs1_dinode *)bp->b_data +
3801	    ino_to_fsbo(fs, inodedep->id_ino);
3802	/*
3803	 * If the bitmap is not yet written, then the allocated
3804	 * inode cannot be written to disk.
3805	 */
3806	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
3807		if (inodedep->id_savedino1 != NULL)
3808			panic("initiate_write_inodeblock_ufs1: I/O underway");
3809		FREE_LOCK(&lk);
3810		MALLOC(sip, struct ufs1_dinode *,
3811		    sizeof(struct ufs1_dinode), M_SAVEDINO, M_SOFTDEP_FLAGS);
3812		ACQUIRE_LOCK(&lk);
3813		inodedep->id_savedino1 = sip;
3814		*inodedep->id_savedino1 = *dp;
3815		bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
3816		dp->di_gen = inodedep->id_savedino1->di_gen;
3817		return;
3818	}
3819	/*
3820	 * If no dependencies, then there is nothing to roll back.
3821	 */
3822	inodedep->id_savedsize = dp->di_size;
3823	inodedep->id_savedextsize = 0;
3824	if (TAILQ_FIRST(&inodedep->id_inoupdt) == NULL)
3825		return;
3826	/*
3827	 * Set the dependencies to busy.
3828	 */
3829	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
3830	     adp = TAILQ_NEXT(adp, ad_next)) {
3831#ifdef DIAGNOSTIC
3832		if (deplist != 0 && prevlbn >= adp->ad_lbn)
3833			panic("softdep_write_inodeblock: lbn order");
3834		prevlbn = adp->ad_lbn;
3835		if (adp->ad_lbn < NDADDR &&
3836		    dp->di_db[adp->ad_lbn] != adp->ad_newblkno)
3837			panic("%s: direct pointer #%jd mismatch %d != %jd",
3838			    "softdep_write_inodeblock",
3839			    (intmax_t)adp->ad_lbn,
3840			    dp->di_db[adp->ad_lbn],
3841			    (intmax_t)adp->ad_newblkno);
3842		if (adp->ad_lbn >= NDADDR &&
3843		    dp->di_ib[adp->ad_lbn - NDADDR] != adp->ad_newblkno)
3844			panic("%s: indirect pointer #%jd mismatch %d != %jd",
3845			    "softdep_write_inodeblock",
3846			    (intmax_t)adp->ad_lbn - NDADDR,
3847			    dp->di_ib[adp->ad_lbn - NDADDR],
3848			    (intmax_t)adp->ad_newblkno);
3849		deplist |= 1 << adp->ad_lbn;
3850		if ((adp->ad_state & ATTACHED) == 0)
3851			panic("softdep_write_inodeblock: Unknown state 0x%x",
3852			    adp->ad_state);
3853#endif /* DIAGNOSTIC */
3854		adp->ad_state &= ~ATTACHED;
3855		adp->ad_state |= UNDONE;
3856	}
3857	/*
3858	 * The on-disk inode cannot claim to be any larger than the last
3859	 * fragment that has been written. Otherwise, the on-disk inode
3860	 * might have fragments that were not the last block in the file
3861	 * which would corrupt the filesystem.
3862	 */
3863	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
3864	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
3865		if (adp->ad_lbn >= NDADDR)
3866			break;
3867		dp->di_db[adp->ad_lbn] = adp->ad_oldblkno;
3868		/* keep going until hitting a rollback to a frag */
3869		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
3870			continue;
3871		dp->di_size = fs->fs_bsize * adp->ad_lbn + adp->ad_oldsize;
3872		for (i = adp->ad_lbn + 1; i < NDADDR; i++) {
3873#ifdef DIAGNOSTIC
3874			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
3875				panic("softdep_write_inodeblock: lost dep1");
3876#endif /* DIAGNOSTIC */
3877			dp->di_db[i] = 0;
3878		}
3879		for (i = 0; i < NIADDR; i++) {
3880#ifdef DIAGNOSTIC
3881			if (dp->di_ib[i] != 0 &&
3882			    (deplist & ((1 << NDADDR) << i)) == 0)
3883				panic("softdep_write_inodeblock: lost dep2");
3884#endif /* DIAGNOSTIC */
3885			dp->di_ib[i] = 0;
3886		}
3887		return;
3888	}
3889	/*
3890	 * If we have zero'ed out the last allocated block of the file,
3891	 * roll back the size to the last currently allocated block.
3892	 * We know that this last allocated block is a full-sized as
3893	 * we already checked for fragments in the loop above.
3894	 */
3895	if (lastadp != NULL &&
3896	    dp->di_size <= (lastadp->ad_lbn + 1) * fs->fs_bsize) {
3897		for (i = lastadp->ad_lbn; i >= 0; i--)
3898			if (dp->di_db[i] != 0)
3899				break;
3900		dp->di_size = (i + 1) * fs->fs_bsize;
3901	}
3902	/*
3903	 * The only dependencies are for indirect blocks.
3904	 *
3905	 * The file size for indirect block additions is not guaranteed.
3906	 * Such a guarantee would be non-trivial to achieve. The conventional
3907	 * synchronous write implementation also does not make this guarantee.
3908	 * Fsck should catch and fix discrepancies. Arguably, the file size
3909	 * can be over-estimated without destroying integrity when the file
3910	 * moves into the indirect blocks (i.e., is large). If we want to
3911	 * postpone fsck, we are stuck with this argument.
3912	 */
3913	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
3914		dp->di_ib[adp->ad_lbn - NDADDR] = 0;
3915}
3916
3917/*
3918 * Version of initiate_write_inodeblock that handles UFS2 dinodes.
3919 * Note that any bug fixes made to this routine must be done in the
3920 * version found above.
3921 *
3922 * Called from within the procedure above to deal with unsatisfied
3923 * allocation dependencies in an inodeblock. The buffer must be
3924 * locked, thus, no I/O completion operations can occur while we
3925 * are manipulating its associated dependencies.
3926 */
3927static void
3928initiate_write_inodeblock_ufs2(inodedep, bp)
3929	struct inodedep *inodedep;
3930	struct buf *bp;			/* The inode block */
3931{
3932	struct allocdirect *adp, *lastadp;
3933	struct ufs2_dinode *dp;
3934	struct ufs2_dinode *sip;
3935	struct fs *fs;
3936	ufs_lbn_t i, prevlbn = 0;
3937	int deplist;
3938
3939	if (inodedep->id_state & IOSTARTED)
3940		panic("initiate_write_inodeblock_ufs2: already started");
3941	inodedep->id_state |= IOSTARTED;
3942	fs = inodedep->id_fs;
3943	dp = (struct ufs2_dinode *)bp->b_data +
3944	    ino_to_fsbo(fs, inodedep->id_ino);
3945	/*
3946	 * If the bitmap is not yet written, then the allocated
3947	 * inode cannot be written to disk.
3948	 */
3949	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
3950		if (inodedep->id_savedino2 != NULL)
3951			panic("initiate_write_inodeblock_ufs2: I/O underway");
3952		FREE_LOCK(&lk);
3953		MALLOC(sip, struct ufs2_dinode *,
3954		    sizeof(struct ufs2_dinode), M_SAVEDINO, M_SOFTDEP_FLAGS);
3955		ACQUIRE_LOCK(&lk);
3956		inodedep->id_savedino2 = sip;
3957		*inodedep->id_savedino2 = *dp;
3958		bzero((caddr_t)dp, sizeof(struct ufs2_dinode));
3959		dp->di_gen = inodedep->id_savedino2->di_gen;
3960		return;
3961	}
3962	/*
3963	 * If no dependencies, then there is nothing to roll back.
3964	 */
3965	inodedep->id_savedsize = dp->di_size;
3966	inodedep->id_savedextsize = dp->di_extsize;
3967	if (TAILQ_FIRST(&inodedep->id_inoupdt) == NULL &&
3968	    TAILQ_FIRST(&inodedep->id_extupdt) == NULL)
3969		return;
3970	/*
3971	 * Set the ext data dependencies to busy.
3972	 */
3973	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
3974	     adp = TAILQ_NEXT(adp, ad_next)) {
3975#ifdef DIAGNOSTIC
3976		if (deplist != 0 && prevlbn >= adp->ad_lbn)
3977			panic("softdep_write_inodeblock: lbn order");
3978		prevlbn = adp->ad_lbn;
3979		if (dp->di_extb[adp->ad_lbn] != adp->ad_newblkno)
3980			panic("%s: direct pointer #%jd mismatch %jd != %jd",
3981			    "softdep_write_inodeblock",
3982			    (intmax_t)adp->ad_lbn,
3983			    (intmax_t)dp->di_extb[adp->ad_lbn],
3984			    (intmax_t)adp->ad_newblkno);
3985		deplist |= 1 << adp->ad_lbn;
3986		if ((adp->ad_state & ATTACHED) == 0)
3987			panic("softdep_write_inodeblock: Unknown state 0x%x",
3988			    adp->ad_state);
3989#endif /* DIAGNOSTIC */
3990		adp->ad_state &= ~ATTACHED;
3991		adp->ad_state |= UNDONE;
3992	}
3993	/*
3994	 * The on-disk inode cannot claim to be any larger than the last
3995	 * fragment that has been written. Otherwise, the on-disk inode
3996	 * might have fragments that were not the last block in the ext
3997	 * data which would corrupt the filesystem.
3998	 */
3999	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
4000	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
4001		dp->di_extb[adp->ad_lbn] = adp->ad_oldblkno;
4002		/* keep going until hitting a rollback to a frag */
4003		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
4004			continue;
4005		dp->di_extsize = fs->fs_bsize * adp->ad_lbn + adp->ad_oldsize;
4006		for (i = adp->ad_lbn + 1; i < NXADDR; i++) {
4007#ifdef DIAGNOSTIC
4008			if (dp->di_extb[i] != 0 && (deplist & (1 << i)) == 0)
4009				panic("softdep_write_inodeblock: lost dep1");
4010#endif /* DIAGNOSTIC */
4011			dp->di_extb[i] = 0;
4012		}
4013		lastadp = NULL;
4014		break;
4015	}
4016	/*
4017	 * If we have zero'ed out the last allocated block of the ext
4018	 * data, roll back the size to the last currently allocated block.
4019	 * We know that this last allocated block is a full-sized as
4020	 * we already checked for fragments in the loop above.
4021	 */
4022	if (lastadp != NULL &&
4023	    dp->di_extsize <= (lastadp->ad_lbn + 1) * fs->fs_bsize) {
4024		for (i = lastadp->ad_lbn; i >= 0; i--)
4025			if (dp->di_extb[i] != 0)
4026				break;
4027		dp->di_extsize = (i + 1) * fs->fs_bsize;
4028	}
4029	/*
4030	 * Set the file data dependencies to busy.
4031	 */
4032	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
4033	     adp = TAILQ_NEXT(adp, ad_next)) {
4034#ifdef DIAGNOSTIC
4035		if (deplist != 0 && prevlbn >= adp->ad_lbn)
4036			panic("softdep_write_inodeblock: lbn order");
4037		prevlbn = adp->ad_lbn;
4038		if (adp->ad_lbn < NDADDR &&
4039		    dp->di_db[adp->ad_lbn] != adp->ad_newblkno)
4040			panic("%s: direct pointer #%jd mismatch %jd != %jd",
4041			    "softdep_write_inodeblock",
4042			    (intmax_t)adp->ad_lbn,
4043			    (intmax_t)dp->di_db[adp->ad_lbn],
4044			    (intmax_t)adp->ad_newblkno);
4045		if (adp->ad_lbn >= NDADDR &&
4046		    dp->di_ib[adp->ad_lbn - NDADDR] != adp->ad_newblkno)
4047			panic("%s indirect pointer #%jd mismatch %jd != %jd",
4048			    "softdep_write_inodeblock:",
4049			    (intmax_t)adp->ad_lbn - NDADDR,
4050			    (intmax_t)dp->di_ib[adp->ad_lbn - NDADDR],
4051			    (intmax_t)adp->ad_newblkno);
4052		deplist |= 1 << adp->ad_lbn;
4053		if ((adp->ad_state & ATTACHED) == 0)
4054			panic("softdep_write_inodeblock: Unknown state 0x%x",
4055			    adp->ad_state);
4056#endif /* DIAGNOSTIC */
4057		adp->ad_state &= ~ATTACHED;
4058		adp->ad_state |= UNDONE;
4059	}
4060	/*
4061	 * The on-disk inode cannot claim to be any larger than the last
4062	 * fragment that has been written. Otherwise, the on-disk inode
4063	 * might have fragments that were not the last block in the file
4064	 * which would corrupt the filesystem.
4065	 */
4066	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
4067	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
4068		if (adp->ad_lbn >= NDADDR)
4069			break;
4070		dp->di_db[adp->ad_lbn] = adp->ad_oldblkno;
4071		/* keep going until hitting a rollback to a frag */
4072		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
4073			continue;
4074		dp->di_size = fs->fs_bsize * adp->ad_lbn + adp->ad_oldsize;
4075		for (i = adp->ad_lbn + 1; i < NDADDR; i++) {
4076#ifdef DIAGNOSTIC
4077			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
4078				panic("softdep_write_inodeblock: lost dep2");
4079#endif /* DIAGNOSTIC */
4080			dp->di_db[i] = 0;
4081		}
4082		for (i = 0; i < NIADDR; i++) {
4083#ifdef DIAGNOSTIC
4084			if (dp->di_ib[i] != 0 &&
4085			    (deplist & ((1 << NDADDR) << i)) == 0)
4086				panic("softdep_write_inodeblock: lost dep3");
4087#endif /* DIAGNOSTIC */
4088			dp->di_ib[i] = 0;
4089		}
4090		return;
4091	}
4092	/*
4093	 * If we have zero'ed out the last allocated block of the file,
4094	 * roll back the size to the last currently allocated block.
4095	 * We know that this last allocated block is a full-sized as
4096	 * we already checked for fragments in the loop above.
4097	 */
4098	if (lastadp != NULL &&
4099	    dp->di_size <= (lastadp->ad_lbn + 1) * fs->fs_bsize) {
4100		for (i = lastadp->ad_lbn; i >= 0; i--)
4101			if (dp->di_db[i] != 0)
4102				break;
4103		dp->di_size = (i + 1) * fs->fs_bsize;
4104	}
4105	/*
4106	 * The only dependencies are for indirect blocks.
4107	 *
4108	 * The file size for indirect block additions is not guaranteed.
4109	 * Such a guarantee would be non-trivial to achieve. The conventional
4110	 * synchronous write implementation also does not make this guarantee.
4111	 * Fsck should catch and fix discrepancies. Arguably, the file size
4112	 * can be over-estimated without destroying integrity when the file
4113	 * moves into the indirect blocks (i.e., is large). If we want to
4114	 * postpone fsck, we are stuck with this argument.
4115	 */
4116	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
4117		dp->di_ib[adp->ad_lbn - NDADDR] = 0;
4118}
4119
4120/*
4121 * This routine is called during the completion interrupt
4122 * service routine for a disk write (from the procedure called
4123 * by the device driver to inform the filesystem caches of
4124 * a request completion).  It should be called early in this
4125 * procedure, before the block is made available to other
4126 * processes or other routines are called.
4127 */
4128static void
4129softdep_disk_write_complete(bp)
4130	struct buf *bp;		/* describes the completed disk write */
4131{
4132	struct worklist *wk;
4133	struct worklist *owk;
4134	struct workhead reattach;
4135	struct newblk *newblk;
4136	struct allocindir *aip;
4137	struct allocdirect *adp;
4138	struct indirdep *indirdep;
4139	struct inodedep *inodedep;
4140	struct bmsafemap *bmsafemap;
4141
4142	/*
4143	 * If an error occurred while doing the write, then the data
4144	 * has not hit the disk and the dependencies cannot be unrolled.
4145	 */
4146	if ((bp->b_ioflags & BIO_ERROR) != 0 && (bp->b_flags & B_INVAL) == 0)
4147		return;
4148	LIST_INIT(&reattach);
4149	/*
4150	 * This lock must not be released anywhere in this code segment.
4151	 */
4152	ACQUIRE_LOCK(&lk);
4153	owk = NULL;
4154	while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
4155		WORKLIST_REMOVE(wk);
4156		if (wk == owk)
4157			panic("duplicate worklist: %p\n", wk);
4158		owk = wk;
4159		switch (wk->wk_type) {
4160
4161		case D_PAGEDEP:
4162			if (handle_written_filepage(WK_PAGEDEP(wk), bp))
4163				WORKLIST_INSERT(&reattach, wk);
4164			continue;
4165
4166		case D_INODEDEP:
4167			if (handle_written_inodeblock(WK_INODEDEP(wk), bp))
4168				WORKLIST_INSERT(&reattach, wk);
4169			continue;
4170
4171		case D_BMSAFEMAP:
4172			bmsafemap = WK_BMSAFEMAP(wk);
4173			while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkhd))) {
4174				newblk->nb_state |= DEPCOMPLETE;
4175				newblk->nb_bmsafemap = NULL;
4176				LIST_REMOVE(newblk, nb_deps);
4177			}
4178			while ((adp =
4179			   LIST_FIRST(&bmsafemap->sm_allocdirecthd))) {
4180				adp->ad_state |= DEPCOMPLETE;
4181				adp->ad_buf = NULL;
4182				LIST_REMOVE(adp, ad_deps);
4183				handle_allocdirect_partdone(adp);
4184			}
4185			while ((aip =
4186			    LIST_FIRST(&bmsafemap->sm_allocindirhd))) {
4187				aip->ai_state |= DEPCOMPLETE;
4188				aip->ai_buf = NULL;
4189				LIST_REMOVE(aip, ai_deps);
4190				handle_allocindir_partdone(aip);
4191			}
4192			while ((inodedep =
4193			     LIST_FIRST(&bmsafemap->sm_inodedephd)) != NULL) {
4194				inodedep->id_state |= DEPCOMPLETE;
4195				LIST_REMOVE(inodedep, id_deps);
4196				inodedep->id_buf = NULL;
4197			}
4198			WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
4199			continue;
4200
4201		case D_MKDIR:
4202			handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
4203			continue;
4204
4205		case D_ALLOCDIRECT:
4206			adp = WK_ALLOCDIRECT(wk);
4207			adp->ad_state |= COMPLETE;
4208			handle_allocdirect_partdone(adp);
4209			continue;
4210
4211		case D_ALLOCINDIR:
4212			aip = WK_ALLOCINDIR(wk);
4213			aip->ai_state |= COMPLETE;
4214			handle_allocindir_partdone(aip);
4215			continue;
4216
4217		case D_INDIRDEP:
4218			indirdep = WK_INDIRDEP(wk);
4219			if (indirdep->ir_state & GOINGAWAY)
4220				panic("disk_write_complete: indirdep gone");
4221			bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
4222			FREE(indirdep->ir_saveddata, M_INDIRDEP);
4223			indirdep->ir_saveddata = 0;
4224			indirdep->ir_state &= ~UNDONE;
4225			indirdep->ir_state |= ATTACHED;
4226			while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != 0) {
4227				handle_allocindir_partdone(aip);
4228				if (aip == LIST_FIRST(&indirdep->ir_donehd))
4229					panic("disk_write_complete: not gone");
4230			}
4231			WORKLIST_INSERT(&reattach, wk);
4232			if ((bp->b_flags & B_DELWRI) == 0)
4233				stat_indir_blk_ptrs++;
4234			bdirty(bp);
4235			continue;
4236
4237		default:
4238			panic("handle_disk_write_complete: Unknown type %s",
4239			    TYPENAME(wk->wk_type));
4240			/* NOTREACHED */
4241		}
4242	}
4243	/*
4244	 * Reattach any requests that must be redone.
4245	 */
4246	while ((wk = LIST_FIRST(&reattach)) != NULL) {
4247		WORKLIST_REMOVE(wk);
4248		WORKLIST_INSERT(&bp->b_dep, wk);
4249	}
4250	FREE_LOCK(&lk);
4251}
4252
4253/*
4254 * Called from within softdep_disk_write_complete above. Note that
4255 * this routine is always called from interrupt level with further
4256 * splbio interrupts blocked.
4257 */
4258static void
4259handle_allocdirect_partdone(adp)
4260	struct allocdirect *adp;	/* the completed allocdirect */
4261{
4262	struct allocdirectlst *listhead;
4263	struct allocdirect *listadp;
4264	struct inodedep *inodedep;
4265	long bsize, delay;
4266
4267	if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
4268		return;
4269	if (adp->ad_buf != NULL)
4270		panic("handle_allocdirect_partdone: dangling dep");
4271	/*
4272	 * The on-disk inode cannot claim to be any larger than the last
4273	 * fragment that has been written. Otherwise, the on-disk inode
4274	 * might have fragments that were not the last block in the file
4275	 * which would corrupt the filesystem. Thus, we cannot free any
4276	 * allocdirects after one whose ad_oldblkno claims a fragment as
4277	 * these blocks must be rolled back to zero before writing the inode.
4278	 * We check the currently active set of allocdirects in id_inoupdt
4279	 * or id_extupdt as appropriate.
4280	 */
4281	inodedep = adp->ad_inodedep;
4282	bsize = inodedep->id_fs->fs_bsize;
4283	if (adp->ad_state & EXTDATA)
4284		listhead = &inodedep->id_extupdt;
4285	else
4286		listhead = &inodedep->id_inoupdt;
4287	TAILQ_FOREACH(listadp, listhead, ad_next) {
4288		/* found our block */
4289		if (listadp == adp)
4290			break;
4291		/* continue if ad_oldlbn is not a fragment */
4292		if (listadp->ad_oldsize == 0 ||
4293		    listadp->ad_oldsize == bsize)
4294			continue;
4295		/* hit a fragment */
4296		return;
4297	}
4298	/*
4299	 * If we have reached the end of the current list without
4300	 * finding the just finished dependency, then it must be
4301	 * on the future dependency list. Future dependencies cannot
4302	 * be freed until they are moved to the current list.
4303	 */
4304	if (listadp == NULL) {
4305#ifdef DEBUG
4306		if (adp->ad_state & EXTDATA)
4307			listhead = &inodedep->id_newextupdt;
4308		else
4309			listhead = &inodedep->id_newinoupdt;
4310		TAILQ_FOREACH(listadp, listhead, ad_next)
4311			/* found our block */
4312			if (listadp == adp)
4313				break;
4314		if (listadp == NULL)
4315			panic("handle_allocdirect_partdone: lost dep");
4316#endif /* DEBUG */
4317		return;
4318	}
4319	/*
4320	 * If we have found the just finished dependency, then free
4321	 * it along with anything that follows it that is complete.
4322	 * If the inode still has a bitmap dependency, then it has
4323	 * never been written to disk, hence the on-disk inode cannot
4324	 * reference the old fragment so we can free it without delay.
4325	 */
4326	delay = (inodedep->id_state & DEPCOMPLETE);
4327	for (; adp; adp = listadp) {
4328		listadp = TAILQ_NEXT(adp, ad_next);
4329		if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
4330			return;
4331		free_allocdirect(listhead, adp, delay);
4332	}
4333}
4334
4335/*
4336 * Called from within softdep_disk_write_complete above. Note that
4337 * this routine is always called from interrupt level with further
4338 * splbio interrupts blocked.
4339 */
4340static void
4341handle_allocindir_partdone(aip)
4342	struct allocindir *aip;		/* the completed allocindir */
4343{
4344	struct indirdep *indirdep;
4345
4346	if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
4347		return;
4348	if (aip->ai_buf != NULL)
4349		panic("handle_allocindir_partdone: dangling dependency");
4350	indirdep = aip->ai_indirdep;
4351	if (indirdep->ir_state & UNDONE) {
4352		LIST_REMOVE(aip, ai_next);
4353		LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
4354		return;
4355	}
4356	if (indirdep->ir_state & UFS1FMT)
4357		((ufs1_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
4358		    aip->ai_newblkno;
4359	else
4360		((ufs2_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
4361		    aip->ai_newblkno;
4362	LIST_REMOVE(aip, ai_next);
4363	if (aip->ai_freefrag != NULL)
4364		add_to_worklist(&aip->ai_freefrag->ff_list);
4365	WORKITEM_FREE(aip, D_ALLOCINDIR);
4366}
4367
4368/*
4369 * Called from within softdep_disk_write_complete above to restore
4370 * in-memory inode block contents to their most up-to-date state. Note
4371 * that this routine is always called from interrupt level with further
4372 * splbio interrupts blocked.
4373 */
4374static int
4375handle_written_inodeblock(inodedep, bp)
4376	struct inodedep *inodedep;
4377	struct buf *bp;		/* buffer containing the inode block */
4378{
4379	struct worklist *wk, *filefree;
4380	struct allocdirect *adp, *nextadp;
4381	struct ufs1_dinode *dp1 = NULL;
4382	struct ufs2_dinode *dp2 = NULL;
4383	int hadchanges, fstype;
4384
4385	if ((inodedep->id_state & IOSTARTED) == 0)
4386		panic("handle_written_inodeblock: not started");
4387	inodedep->id_state &= ~IOSTARTED;
4388	if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC) {
4389		fstype = UFS1;
4390		dp1 = (struct ufs1_dinode *)bp->b_data +
4391		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
4392	} else {
4393		fstype = UFS2;
4394		dp2 = (struct ufs2_dinode *)bp->b_data +
4395		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
4396	}
4397	/*
4398	 * If we had to rollback the inode allocation because of
4399	 * bitmaps being incomplete, then simply restore it.
4400	 * Keep the block dirty so that it will not be reclaimed until
4401	 * all associated dependencies have been cleared and the
4402	 * corresponding updates written to disk.
4403	 */
4404	if (inodedep->id_savedino1 != NULL) {
4405		if (fstype == UFS1)
4406			*dp1 = *inodedep->id_savedino1;
4407		else
4408			*dp2 = *inodedep->id_savedino2;
4409		FREE(inodedep->id_savedino1, M_SAVEDINO);
4410		inodedep->id_savedino1 = NULL;
4411		if ((bp->b_flags & B_DELWRI) == 0)
4412			stat_inode_bitmap++;
4413		bdirty(bp);
4414		return (1);
4415	}
4416	inodedep->id_state |= COMPLETE;
4417	/*
4418	 * Roll forward anything that had to be rolled back before
4419	 * the inode could be updated.
4420	 */
4421	hadchanges = 0;
4422	for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
4423		nextadp = TAILQ_NEXT(adp, ad_next);
4424		if (adp->ad_state & ATTACHED)
4425			panic("handle_written_inodeblock: new entry");
4426		if (fstype == UFS1) {
4427			if (adp->ad_lbn < NDADDR) {
4428				if (dp1->di_db[adp->ad_lbn]!=adp->ad_oldblkno)
4429					panic("%s %s #%jd mismatch %d != %jd",
4430					    "handle_written_inodeblock:",
4431					    "direct pointer",
4432					    (intmax_t)adp->ad_lbn,
4433					    dp1->di_db[adp->ad_lbn],
4434					    (intmax_t)adp->ad_oldblkno);
4435				dp1->di_db[adp->ad_lbn] = adp->ad_newblkno;
4436			} else {
4437				if (dp1->di_ib[adp->ad_lbn - NDADDR] != 0)
4438					panic("%s: %s #%jd allocated as %d",
4439					    "handle_written_inodeblock",
4440					    "indirect pointer",
4441					    (intmax_t)adp->ad_lbn - NDADDR,
4442					    dp1->di_ib[adp->ad_lbn - NDADDR]);
4443				dp1->di_ib[adp->ad_lbn - NDADDR] =
4444				    adp->ad_newblkno;
4445			}
4446		} else {
4447			if (adp->ad_lbn < NDADDR) {
4448				if (dp2->di_db[adp->ad_lbn]!=adp->ad_oldblkno)
4449					panic("%s: %s #%jd %s %jd != %jd",
4450					    "handle_written_inodeblock",
4451					    "direct pointer",
4452					    (intmax_t)adp->ad_lbn, "mismatch",
4453					    (intmax_t)dp2->di_db[adp->ad_lbn],
4454					    (intmax_t)adp->ad_oldblkno);
4455				dp2->di_db[adp->ad_lbn] = adp->ad_newblkno;
4456			} else {
4457				if (dp2->di_ib[adp->ad_lbn - NDADDR] != 0)
4458					panic("%s: %s #%jd allocated as %jd",
4459					    "handle_written_inodeblock",
4460					    "indirect pointer",
4461					    (intmax_t)adp->ad_lbn - NDADDR,
4462					    (intmax_t)
4463					    dp2->di_ib[adp->ad_lbn - NDADDR]);
4464				dp2->di_ib[adp->ad_lbn - NDADDR] =
4465				    adp->ad_newblkno;
4466			}
4467		}
4468		adp->ad_state &= ~UNDONE;
4469		adp->ad_state |= ATTACHED;
4470		hadchanges = 1;
4471	}
4472	for (adp = TAILQ_FIRST(&inodedep->id_extupdt); adp; adp = nextadp) {
4473		nextadp = TAILQ_NEXT(adp, ad_next);
4474		if (adp->ad_state & ATTACHED)
4475			panic("handle_written_inodeblock: new entry");
4476		if (dp2->di_extb[adp->ad_lbn] != adp->ad_oldblkno)
4477			panic("%s: direct pointers #%jd %s %jd != %jd",
4478			    "handle_written_inodeblock",
4479			    (intmax_t)adp->ad_lbn, "mismatch",
4480			    (intmax_t)dp2->di_extb[adp->ad_lbn],
4481			    (intmax_t)adp->ad_oldblkno);
4482		dp2->di_extb[adp->ad_lbn] = adp->ad_newblkno;
4483		adp->ad_state &= ~UNDONE;
4484		adp->ad_state |= ATTACHED;
4485		hadchanges = 1;
4486	}
4487	if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
4488		stat_direct_blk_ptrs++;
4489	/*
4490	 * Reset the file size to its most up-to-date value.
4491	 */
4492	if (inodedep->id_savedsize == -1 || inodedep->id_savedextsize == -1)
4493		panic("handle_written_inodeblock: bad size");
4494	if (fstype == UFS1) {
4495		if (dp1->di_size != inodedep->id_savedsize) {
4496			dp1->di_size = inodedep->id_savedsize;
4497			hadchanges = 1;
4498		}
4499	} else {
4500		if (dp2->di_size != inodedep->id_savedsize) {
4501			dp2->di_size = inodedep->id_savedsize;
4502			hadchanges = 1;
4503		}
4504		if (dp2->di_extsize != inodedep->id_savedextsize) {
4505			dp2->di_extsize = inodedep->id_savedextsize;
4506			hadchanges = 1;
4507		}
4508	}
4509	inodedep->id_savedsize = -1;
4510	inodedep->id_savedextsize = -1;
4511	/*
4512	 * If there were any rollbacks in the inode block, then it must be
4513	 * marked dirty so that its will eventually get written back in
4514	 * its correct form.
4515	 */
4516	if (hadchanges)
4517		bdirty(bp);
4518	/*
4519	 * Process any allocdirects that completed during the update.
4520	 */
4521	if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
4522		handle_allocdirect_partdone(adp);
4523	if ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
4524		handle_allocdirect_partdone(adp);
4525	/*
4526	 * Process deallocations that were held pending until the
4527	 * inode had been written to disk. Freeing of the inode
4528	 * is delayed until after all blocks have been freed to
4529	 * avoid creation of new <vfsid, inum, lbn> triples
4530	 * before the old ones have been deleted.
4531	 */
4532	filefree = NULL;
4533	while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
4534		WORKLIST_REMOVE(wk);
4535		switch (wk->wk_type) {
4536
4537		case D_FREEFILE:
4538			/*
4539			 * We defer adding filefree to the worklist until
4540			 * all other additions have been made to ensure
4541			 * that it will be done after all the old blocks
4542			 * have been freed.
4543			 */
4544			if (filefree != NULL)
4545				panic("handle_written_inodeblock: filefree");
4546			filefree = wk;
4547			continue;
4548
4549		case D_MKDIR:
4550			handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
4551			continue;
4552
4553		case D_DIRADD:
4554			diradd_inode_written(WK_DIRADD(wk), inodedep);
4555			continue;
4556
4557		case D_FREEBLKS:
4558			wk->wk_state |= COMPLETE;
4559			if ((wk->wk_state  & ALLCOMPLETE) != ALLCOMPLETE)
4560				continue;
4561			 /* -- fall through -- */
4562		case D_FREEFRAG:
4563		case D_DIRREM:
4564			add_to_worklist(wk);
4565			continue;
4566
4567		case D_NEWDIRBLK:
4568			free_newdirblk(WK_NEWDIRBLK(wk));
4569			continue;
4570
4571		default:
4572			panic("handle_written_inodeblock: Unknown type %s",
4573			    TYPENAME(wk->wk_type));
4574			/* NOTREACHED */
4575		}
4576	}
4577	if (filefree != NULL) {
4578		if (free_inodedep(inodedep) == 0)
4579			panic("handle_written_inodeblock: live inodedep");
4580		add_to_worklist(filefree);
4581		return (0);
4582	}
4583
4584	/*
4585	 * If no outstanding dependencies, free it.
4586	 */
4587	if (free_inodedep(inodedep) ||
4588	    (TAILQ_FIRST(&inodedep->id_inoupdt) == 0 &&
4589	     TAILQ_FIRST(&inodedep->id_extupdt) == 0))
4590		return (0);
4591	return (hadchanges);
4592}
4593
4594/*
4595 * Process a diradd entry after its dependent inode has been written.
4596 * This routine must be called with splbio interrupts blocked.
4597 */
4598static void
4599diradd_inode_written(dap, inodedep)
4600	struct diradd *dap;
4601	struct inodedep *inodedep;
4602{
4603	struct pagedep *pagedep;
4604
4605	dap->da_state |= COMPLETE;
4606	if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
4607		if (dap->da_state & DIRCHG)
4608			pagedep = dap->da_previous->dm_pagedep;
4609		else
4610			pagedep = dap->da_pagedep;
4611		LIST_REMOVE(dap, da_pdlist);
4612		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
4613	}
4614	WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
4615}
4616
4617/*
4618 * Handle the completion of a mkdir dependency.
4619 */
4620static void
4621handle_written_mkdir(mkdir, type)
4622	struct mkdir *mkdir;
4623	int type;
4624{
4625	struct diradd *dap;
4626	struct pagedep *pagedep;
4627
4628	if (mkdir->md_state != type)
4629		panic("handle_written_mkdir: bad type");
4630	dap = mkdir->md_diradd;
4631	dap->da_state &= ~type;
4632	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
4633		dap->da_state |= DEPCOMPLETE;
4634	if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
4635		if (dap->da_state & DIRCHG)
4636			pagedep = dap->da_previous->dm_pagedep;
4637		else
4638			pagedep = dap->da_pagedep;
4639		LIST_REMOVE(dap, da_pdlist);
4640		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
4641	}
4642	LIST_REMOVE(mkdir, md_mkdirs);
4643	WORKITEM_FREE(mkdir, D_MKDIR);
4644}
4645
4646/*
4647 * Called from within softdep_disk_write_complete above.
4648 * A write operation was just completed. Removed inodes can
4649 * now be freed and associated block pointers may be committed.
4650 * Note that this routine is always called from interrupt level
4651 * with further splbio interrupts blocked.
4652 */
4653static int
4654handle_written_filepage(pagedep, bp)
4655	struct pagedep *pagedep;
4656	struct buf *bp;		/* buffer containing the written page */
4657{
4658	struct dirrem *dirrem;
4659	struct diradd *dap, *nextdap;
4660	struct direct *ep;
4661	int i, chgs;
4662
4663	if ((pagedep->pd_state & IOSTARTED) == 0)
4664		panic("handle_written_filepage: not started");
4665	pagedep->pd_state &= ~IOSTARTED;
4666	/*
4667	 * Process any directory removals that have been committed.
4668	 */
4669	while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
4670		LIST_REMOVE(dirrem, dm_next);
4671		dirrem->dm_dirinum = pagedep->pd_ino;
4672		add_to_worklist(&dirrem->dm_list);
4673	}
4674	/*
4675	 * Free any directory additions that have been committed.
4676	 * If it is a newly allocated block, we have to wait until
4677	 * the on-disk directory inode claims the new block.
4678	 */
4679	if ((pagedep->pd_state & NEWBLOCK) == 0)
4680		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
4681			free_diradd(dap);
4682	/*
4683	 * Uncommitted directory entries must be restored.
4684	 */
4685	for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
4686		for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
4687		     dap = nextdap) {
4688			nextdap = LIST_NEXT(dap, da_pdlist);
4689			if (dap->da_state & ATTACHED)
4690				panic("handle_written_filepage: attached");
4691			ep = (struct direct *)
4692			    ((char *)bp->b_data + dap->da_offset);
4693			ep->d_ino = dap->da_newinum;
4694			dap->da_state &= ~UNDONE;
4695			dap->da_state |= ATTACHED;
4696			chgs = 1;
4697			/*
4698			 * If the inode referenced by the directory has
4699			 * been written out, then the dependency can be
4700			 * moved to the pending list.
4701			 */
4702			if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
4703				LIST_REMOVE(dap, da_pdlist);
4704				LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
4705				    da_pdlist);
4706			}
4707		}
4708	}
4709	/*
4710	 * If there were any rollbacks in the directory, then it must be
4711	 * marked dirty so that its will eventually get written back in
4712	 * its correct form.
4713	 */
4714	if (chgs) {
4715		if ((bp->b_flags & B_DELWRI) == 0)
4716			stat_dir_entry++;
4717		bdirty(bp);
4718		return (1);
4719	}
4720	/*
4721	 * If we are not waiting for a new directory block to be
4722	 * claimed by its inode, then the pagedep will be freed.
4723	 * Otherwise it will remain to track any new entries on
4724	 * the page in case they are fsync'ed.
4725	 */
4726	if ((pagedep->pd_state & NEWBLOCK) == 0) {
4727		LIST_REMOVE(pagedep, pd_hash);
4728		WORKITEM_FREE(pagedep, D_PAGEDEP);
4729	}
4730	return (0);
4731}
4732
4733/*
4734 * Writing back in-core inode structures.
4735 *
4736 * The filesystem only accesses an inode's contents when it occupies an
4737 * "in-core" inode structure.  These "in-core" structures are separate from
4738 * the page frames used to cache inode blocks.  Only the latter are
4739 * transferred to/from the disk.  So, when the updated contents of the
4740 * "in-core" inode structure are copied to the corresponding in-memory inode
4741 * block, the dependencies are also transferred.  The following procedure is
4742 * called when copying a dirty "in-core" inode to a cached inode block.
4743 */
4744
4745/*
4746 * Called when an inode is loaded from disk. If the effective link count
4747 * differed from the actual link count when it was last flushed, then we
4748 * need to ensure that the correct effective link count is put back.
4749 */
4750void
4751softdep_load_inodeblock(ip)
4752	struct inode *ip;	/* the "in_core" copy of the inode */
4753{
4754	struct inodedep *inodedep;
4755
4756	/*
4757	 * Check for alternate nlink count.
4758	 */
4759	ip->i_effnlink = ip->i_nlink;
4760	ACQUIRE_LOCK(&lk);
4761	if (inodedep_lookup(UFSTOVFS(ip->i_ump),
4762	    ip->i_number, 0, &inodedep) == 0) {
4763		FREE_LOCK(&lk);
4764		return;
4765	}
4766	ip->i_effnlink -= inodedep->id_nlinkdelta;
4767	if (inodedep->id_state & SPACECOUNTED)
4768		ip->i_flag |= IN_SPACECOUNTED;
4769	FREE_LOCK(&lk);
4770}
4771
4772/*
4773 * This routine is called just before the "in-core" inode
4774 * information is to be copied to the in-memory inode block.
4775 * Recall that an inode block contains several inodes. If
4776 * the force flag is set, then the dependencies will be
4777 * cleared so that the update can always be made. Note that
4778 * the buffer is locked when this routine is called, so we
4779 * will never be in the middle of writing the inode block
4780 * to disk.
4781 */
4782void
4783softdep_update_inodeblock(ip, bp, waitfor)
4784	struct inode *ip;	/* the "in_core" copy of the inode */
4785	struct buf *bp;		/* the buffer containing the inode block */
4786	int waitfor;		/* nonzero => update must be allowed */
4787{
4788	struct inodedep *inodedep;
4789	struct worklist *wk;
4790	struct mount *mp;
4791	struct buf *ibp;
4792	int error;
4793
4794	/*
4795	 * If the effective link count is not equal to the actual link
4796	 * count, then we must track the difference in an inodedep while
4797	 * the inode is (potentially) tossed out of the cache. Otherwise,
4798	 * if there is no existing inodedep, then there are no dependencies
4799	 * to track.
4800	 */
4801	mp = UFSTOVFS(ip->i_ump);
4802	ACQUIRE_LOCK(&lk);
4803	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
4804		FREE_LOCK(&lk);
4805		if (ip->i_effnlink != ip->i_nlink)
4806			panic("softdep_update_inodeblock: bad link count");
4807		return;
4808	}
4809	if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink)
4810		panic("softdep_update_inodeblock: bad delta");
4811	/*
4812	 * Changes have been initiated. Anything depending on these
4813	 * changes cannot occur until this inode has been written.
4814	 */
4815	inodedep->id_state &= ~COMPLETE;
4816	if ((inodedep->id_state & ONWORKLIST) == 0)
4817		WORKLIST_INSERT(&bp->b_dep, &inodedep->id_list);
4818	/*
4819	 * Any new dependencies associated with the incore inode must
4820	 * now be moved to the list associated with the buffer holding
4821	 * the in-memory copy of the inode. Once merged process any
4822	 * allocdirects that are completed by the merger.
4823	 */
4824	merge_inode_lists(&inodedep->id_newinoupdt, &inodedep->id_inoupdt);
4825	if (TAILQ_FIRST(&inodedep->id_inoupdt) != NULL)
4826		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt));
4827	merge_inode_lists(&inodedep->id_newextupdt, &inodedep->id_extupdt);
4828	if (TAILQ_FIRST(&inodedep->id_extupdt) != NULL)
4829		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_extupdt));
4830	/*
4831	 * Now that the inode has been pushed into the buffer, the
4832	 * operations dependent on the inode being written to disk
4833	 * can be moved to the id_bufwait so that they will be
4834	 * processed when the buffer I/O completes.
4835	 */
4836	while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
4837		WORKLIST_REMOVE(wk);
4838		WORKLIST_INSERT(&inodedep->id_bufwait, wk);
4839	}
4840	/*
4841	 * Newly allocated inodes cannot be written until the bitmap
4842	 * that allocates them have been written (indicated by
4843	 * DEPCOMPLETE being set in id_state). If we are doing a
4844	 * forced sync (e.g., an fsync on a file), we force the bitmap
4845	 * to be written so that the update can be done.
4846	 */
4847	if (waitfor == 0) {
4848		FREE_LOCK(&lk);
4849		return;
4850	}
4851retry:
4852	if ((inodedep->id_state & DEPCOMPLETE) != 0) {
4853		FREE_LOCK(&lk);
4854		return;
4855	}
4856	ibp = inodedep->id_buf;
4857	ibp = getdirtybuf(ibp, &lk, MNT_WAIT);
4858	if (ibp == NULL) {
4859		/*
4860		 * If ibp came back as NULL, the dependency could have been
4861		 * freed while we slept.  Look it up again, and check to see
4862		 * that it has completed.
4863		 */
4864		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
4865			goto retry;
4866		FREE_LOCK(&lk);
4867		return;
4868	}
4869	FREE_LOCK(&lk);
4870	if ((error = bwrite(ibp)) != 0)
4871		softdep_error("softdep_update_inodeblock: bwrite", error);
4872}
4873
4874/*
4875 * Merge the a new inode dependency list (such as id_newinoupdt) into an
4876 * old inode dependency list (such as id_inoupdt). This routine must be
4877 * called with splbio interrupts blocked.
4878 */
4879static void
4880merge_inode_lists(newlisthead, oldlisthead)
4881	struct allocdirectlst *newlisthead;
4882	struct allocdirectlst *oldlisthead;
4883{
4884	struct allocdirect *listadp, *newadp;
4885
4886	newadp = TAILQ_FIRST(newlisthead);
4887	for (listadp = TAILQ_FIRST(oldlisthead); listadp && newadp;) {
4888		if (listadp->ad_lbn < newadp->ad_lbn) {
4889			listadp = TAILQ_NEXT(listadp, ad_next);
4890			continue;
4891		}
4892		TAILQ_REMOVE(newlisthead, newadp, ad_next);
4893		TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
4894		if (listadp->ad_lbn == newadp->ad_lbn) {
4895			allocdirect_merge(oldlisthead, newadp,
4896			    listadp);
4897			listadp = newadp;
4898		}
4899		newadp = TAILQ_FIRST(newlisthead);
4900	}
4901	while ((newadp = TAILQ_FIRST(newlisthead)) != NULL) {
4902		TAILQ_REMOVE(newlisthead, newadp, ad_next);
4903		TAILQ_INSERT_TAIL(oldlisthead, newadp, ad_next);
4904	}
4905}
4906
4907/*
4908 * If we are doing an fsync, then we must ensure that any directory
4909 * entries for the inode have been written after the inode gets to disk.
4910 */
4911int
4912softdep_fsync(vp)
4913	struct vnode *vp;	/* the "in_core" copy of the inode */
4914{
4915	struct inodedep *inodedep;
4916	struct pagedep *pagedep;
4917	struct worklist *wk;
4918	struct diradd *dap;
4919	struct mount *mp;
4920	struct vnode *pvp;
4921	struct inode *ip;
4922	struct buf *bp;
4923	struct fs *fs;
4924	struct thread *td = curthread;
4925	int error, flushparent;
4926	ino_t parentino;
4927	ufs_lbn_t lbn;
4928
4929	ip = VTOI(vp);
4930	fs = ip->i_fs;
4931	mp = vp->v_mount;
4932	ACQUIRE_LOCK(&lk);
4933	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
4934		FREE_LOCK(&lk);
4935		return (0);
4936	}
4937	if (LIST_FIRST(&inodedep->id_inowait) != NULL ||
4938	    LIST_FIRST(&inodedep->id_bufwait) != NULL ||
4939	    TAILQ_FIRST(&inodedep->id_extupdt) != NULL ||
4940	    TAILQ_FIRST(&inodedep->id_newextupdt) != NULL ||
4941	    TAILQ_FIRST(&inodedep->id_inoupdt) != NULL ||
4942	    TAILQ_FIRST(&inodedep->id_newinoupdt) != NULL)
4943		panic("softdep_fsync: pending ops");
4944	for (error = 0, flushparent = 0; ; ) {
4945		if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
4946			break;
4947		if (wk->wk_type != D_DIRADD)
4948			panic("softdep_fsync: Unexpected type %s",
4949			    TYPENAME(wk->wk_type));
4950		dap = WK_DIRADD(wk);
4951		/*
4952		 * Flush our parent if this directory entry has a MKDIR_PARENT
4953		 * dependency or is contained in a newly allocated block.
4954		 */
4955		if (dap->da_state & DIRCHG)
4956			pagedep = dap->da_previous->dm_pagedep;
4957		else
4958			pagedep = dap->da_pagedep;
4959		parentino = pagedep->pd_ino;
4960		lbn = pagedep->pd_lbn;
4961		if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE)
4962			panic("softdep_fsync: dirty");
4963		if ((dap->da_state & MKDIR_PARENT) ||
4964		    (pagedep->pd_state & NEWBLOCK))
4965			flushparent = 1;
4966		else
4967			flushparent = 0;
4968		/*
4969		 * If we are being fsync'ed as part of vgone'ing this vnode,
4970		 * then we will not be able to release and recover the
4971		 * vnode below, so we just have to give up on writing its
4972		 * directory entry out. It will eventually be written, just
4973		 * not now, but then the user was not asking to have it
4974		 * written, so we are not breaking any promises.
4975		 */
4976		if (vp->v_iflag & VI_DOOMED)
4977			break;
4978		/*
4979		 * We prevent deadlock by always fetching inodes from the
4980		 * root, moving down the directory tree. Thus, when fetching
4981		 * our parent directory, we first try to get the lock. If
4982		 * that fails, we must unlock ourselves before requesting
4983		 * the lock on our parent. See the comment in ufs_lookup
4984		 * for details on possible races.
4985		 */
4986		FREE_LOCK(&lk);
4987		if (ffs_vget(mp, parentino, LK_NOWAIT | LK_EXCLUSIVE, &pvp)) {
4988			VOP_UNLOCK(vp, 0, td);
4989			error = ffs_vget(mp, parentino, LK_EXCLUSIVE, &pvp);
4990			vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, td);
4991			if (error != 0)
4992				return (error);
4993		}
4994		/*
4995		 * All MKDIR_PARENT dependencies and all the NEWBLOCK pagedeps
4996		 * that are contained in direct blocks will be resolved by
4997		 * doing a ffs_update. Pagedeps contained in indirect blocks
4998		 * may require a complete sync'ing of the directory. So, we
4999		 * try the cheap and fast ffs_update first, and if that fails,
5000		 * then we do the slower ffs_syncvnode of the directory.
5001		 */
5002		if (flushparent) {
5003			if ((error = ffs_update(pvp, 1)) != 0) {
5004				vput(pvp);
5005				return (error);
5006			}
5007			if ((pagedep->pd_state & NEWBLOCK) &&
5008			    (error = ffs_syncvnode(pvp, MNT_WAIT))) {
5009				vput(pvp);
5010				return (error);
5011			}
5012		}
5013		/*
5014		 * Flush directory page containing the inode's name.
5015		 */
5016		error = bread(pvp, lbn, blksize(fs, VTOI(pvp), lbn), td->td_ucred,
5017		    &bp);
5018		if (error == 0)
5019			error = bwrite(bp);
5020		else
5021			brelse(bp);
5022		vput(pvp);
5023		if (error != 0)
5024			return (error);
5025		ACQUIRE_LOCK(&lk);
5026		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
5027			break;
5028	}
5029	FREE_LOCK(&lk);
5030	return (0);
5031}
5032
5033/*
5034 * Flush all the dirty bitmaps associated with the block device
5035 * before flushing the rest of the dirty blocks so as to reduce
5036 * the number of dependencies that will have to be rolled back.
5037 */
5038void
5039softdep_fsync_mountdev(vp)
5040	struct vnode *vp;
5041{
5042	struct buf *bp, *nbp;
5043	struct worklist *wk;
5044
5045	if (!vn_isdisk(vp, NULL))
5046		panic("softdep_fsync_mountdev: vnode not a disk");
5047restart:
5048	ACQUIRE_LOCK(&lk);
5049	VI_LOCK(vp);
5050	TAILQ_FOREACH_SAFE(bp, &vp->v_bufobj.bo_dirty.bv_hd, b_bobufs, nbp) {
5051		/*
5052		 * If it is already scheduled, skip to the next buffer.
5053		 */
5054		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL))
5055			continue;
5056
5057		if ((bp->b_flags & B_DELWRI) == 0)
5058			panic("softdep_fsync_mountdev: not dirty");
5059		/*
5060		 * We are only interested in bitmaps with outstanding
5061		 * dependencies.
5062		 */
5063		if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
5064		    wk->wk_type != D_BMSAFEMAP ||
5065		    (bp->b_vflags & BV_BKGRDINPROG)) {
5066			BUF_UNLOCK(bp);
5067			continue;
5068		}
5069		VI_UNLOCK(vp);
5070		FREE_LOCK(&lk);
5071		bremfree(bp);
5072		(void) bawrite(bp);
5073		goto restart;
5074	}
5075	FREE_LOCK(&lk);
5076	drain_output(vp);
5077	VI_UNLOCK(vp);
5078}
5079
5080/*
5081 * This routine is called when we are trying to synchronously flush a
5082 * file. This routine must eliminate any filesystem metadata dependencies
5083 * so that the syncing routine can succeed by pushing the dirty blocks
5084 * associated with the file. If any I/O errors occur, they are returned.
5085 */
5086int
5087softdep_sync_metadata(struct vnode *vp)
5088{
5089	struct pagedep *pagedep;
5090	struct allocdirect *adp;
5091	struct allocindir *aip;
5092	struct buf *bp, *nbp;
5093	struct worklist *wk;
5094	int i, error, waitfor;
5095
5096	if (!DOINGSOFTDEP(vp))
5097		return (0);
5098	/*
5099	 * Ensure that any direct block dependencies have been cleared.
5100	 */
5101	ACQUIRE_LOCK(&lk);
5102	if ((error = flush_inodedep_deps(vp->v_mount, VTOI(vp)->i_number))) {
5103		FREE_LOCK(&lk);
5104		return (error);
5105	}
5106	FREE_LOCK(&lk);
5107	/*
5108	 * For most files, the only metadata dependencies are the
5109	 * cylinder group maps that allocate their inode or blocks.
5110	 * The block allocation dependencies can be found by traversing
5111	 * the dependency lists for any buffers that remain on their
5112	 * dirty buffer list. The inode allocation dependency will
5113	 * be resolved when the inode is updated with MNT_WAIT.
5114	 * This work is done in two passes. The first pass grabs most
5115	 * of the buffers and begins asynchronously writing them. The
5116	 * only way to wait for these asynchronous writes is to sleep
5117	 * on the filesystem vnode which may stay busy for a long time
5118	 * if the filesystem is active. So, instead, we make a second
5119	 * pass over the dependencies blocking on each write. In the
5120	 * usual case we will be blocking against a write that we
5121	 * initiated, so when it is done the dependency will have been
5122	 * resolved. Thus the second pass is expected to end quickly.
5123	 */
5124	waitfor = MNT_NOWAIT;
5125
5126top:
5127	/*
5128	 * We must wait for any I/O in progress to finish so that
5129	 * all potential buffers on the dirty list will be visible.
5130	 */
5131	VI_LOCK(vp);
5132	drain_output(vp);
5133	while ((bp = TAILQ_FIRST(&vp->v_bufobj.bo_dirty.bv_hd)) != NULL) {
5134		bp = getdirtybuf(bp, VI_MTX(vp), MNT_WAIT);
5135		if (bp)
5136			break;
5137	}
5138	VI_UNLOCK(vp);
5139	if (bp == NULL)
5140		return (0);
5141loop:
5142	/* While syncing snapshots, we must allow recursive lookups */
5143	bp->b_lock.lk_flags |= LK_CANRECURSE;
5144	ACQUIRE_LOCK(&lk);
5145	/*
5146	 * As we hold the buffer locked, none of its dependencies
5147	 * will disappear.
5148	 */
5149	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5150		switch (wk->wk_type) {
5151
5152		case D_ALLOCDIRECT:
5153			adp = WK_ALLOCDIRECT(wk);
5154			if (adp->ad_state & DEPCOMPLETE)
5155				continue;
5156			nbp = adp->ad_buf;
5157			nbp = getdirtybuf(nbp, &lk, waitfor);
5158			if (nbp == NULL)
5159				continue;
5160			FREE_LOCK(&lk);
5161			if (waitfor == MNT_NOWAIT) {
5162				bawrite(nbp);
5163			} else if ((error = bwrite(nbp)) != 0) {
5164				break;
5165			}
5166			ACQUIRE_LOCK(&lk);
5167			continue;
5168
5169		case D_ALLOCINDIR:
5170			aip = WK_ALLOCINDIR(wk);
5171			if (aip->ai_state & DEPCOMPLETE)
5172				continue;
5173			nbp = aip->ai_buf;
5174			nbp = getdirtybuf(nbp, &lk, waitfor);
5175			if (nbp == NULL)
5176				continue;
5177			FREE_LOCK(&lk);
5178			if (waitfor == MNT_NOWAIT) {
5179				bawrite(nbp);
5180			} else if ((error = bwrite(nbp)) != 0) {
5181				break;
5182			}
5183			ACQUIRE_LOCK(&lk);
5184			continue;
5185
5186		case D_INDIRDEP:
5187		restart:
5188
5189			LIST_FOREACH(aip, &WK_INDIRDEP(wk)->ir_deplisthd, ai_next) {
5190				if (aip->ai_state & DEPCOMPLETE)
5191					continue;
5192				nbp = aip->ai_buf;
5193				nbp = getdirtybuf(nbp, &lk, MNT_WAIT);
5194				if (nbp == NULL)
5195					goto restart;
5196				FREE_LOCK(&lk);
5197				if ((error = bwrite(nbp)) != 0) {
5198					break;
5199				}
5200				ACQUIRE_LOCK(&lk);
5201				goto restart;
5202			}
5203			continue;
5204
5205		case D_INODEDEP:
5206			if ((error = flush_inodedep_deps(wk->wk_mp,
5207			    WK_INODEDEP(wk)->id_ino)) != 0) {
5208				FREE_LOCK(&lk);
5209				break;
5210			}
5211			continue;
5212
5213		case D_PAGEDEP:
5214			/*
5215			 * We are trying to sync a directory that may
5216			 * have dependencies on both its own metadata
5217			 * and/or dependencies on the inodes of any
5218			 * recently allocated files. We walk its diradd
5219			 * lists pushing out the associated inode.
5220			 */
5221			pagedep = WK_PAGEDEP(wk);
5222			for (i = 0; i < DAHASHSZ; i++) {
5223				if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
5224					continue;
5225				if ((error =
5226				    flush_pagedep_deps(vp, wk->wk_mp,
5227						&pagedep->pd_diraddhd[i]))) {
5228					FREE_LOCK(&lk);
5229					break;
5230				}
5231			}
5232			continue;
5233
5234		case D_MKDIR:
5235			/*
5236			 * This case should never happen if the vnode has
5237			 * been properly sync'ed. However, if this function
5238			 * is used at a place where the vnode has not yet
5239			 * been sync'ed, this dependency can show up. So,
5240			 * rather than panic, just flush it.
5241			 */
5242			nbp = WK_MKDIR(wk)->md_buf;
5243			nbp = getdirtybuf(nbp, &lk, waitfor);
5244			if (nbp == NULL)
5245				continue;
5246			FREE_LOCK(&lk);
5247			if (waitfor == MNT_NOWAIT) {
5248				bawrite(nbp);
5249			} else if ((error = bwrite(nbp)) != 0) {
5250				break;
5251			}
5252			ACQUIRE_LOCK(&lk);
5253			continue;
5254
5255		case D_BMSAFEMAP:
5256			/*
5257			 * This case should never happen if the vnode has
5258			 * been properly sync'ed. However, if this function
5259			 * is used at a place where the vnode has not yet
5260			 * been sync'ed, this dependency can show up. So,
5261			 * rather than panic, just flush it.
5262			 */
5263			nbp = WK_BMSAFEMAP(wk)->sm_buf;
5264			nbp = getdirtybuf(nbp, &lk, waitfor);
5265			if (nbp == NULL)
5266				continue;
5267			FREE_LOCK(&lk);
5268			if (waitfor == MNT_NOWAIT) {
5269				bawrite(nbp);
5270			} else if ((error = bwrite(nbp)) != 0) {
5271				break;
5272			}
5273			ACQUIRE_LOCK(&lk);
5274			continue;
5275
5276		default:
5277			panic("softdep_sync_metadata: Unknown type %s",
5278			    TYPENAME(wk->wk_type));
5279			/* NOTREACHED */
5280		}
5281		/* We reach here only in error and unlocked */
5282		if (error == 0)
5283			panic("softdep_sync_metadata: zero error");
5284		bp->b_lock.lk_flags &= ~LK_CANRECURSE;
5285		bawrite(bp);
5286		return (error);
5287	}
5288	FREE_LOCK(&lk);
5289	VI_LOCK(vp);
5290	while ((nbp = TAILQ_NEXT(bp, b_bobufs)) != NULL) {
5291		nbp = getdirtybuf(nbp, VI_MTX(vp), MNT_WAIT);
5292		if (nbp)
5293			break;
5294	}
5295	VI_UNLOCK(vp);
5296	bp->b_lock.lk_flags &= ~LK_CANRECURSE;
5297	bawrite(bp);
5298	if (nbp != NULL) {
5299		bp = nbp;
5300		goto loop;
5301	}
5302	/*
5303	 * The brief unlock is to allow any pent up dependency
5304	 * processing to be done. Then proceed with the second pass.
5305	 */
5306	if (waitfor == MNT_NOWAIT) {
5307		waitfor = MNT_WAIT;
5308		goto top;
5309	}
5310
5311	/*
5312	 * If we have managed to get rid of all the dirty buffers,
5313	 * then we are done. For certain directories and block
5314	 * devices, we may need to do further work.
5315	 *
5316	 * We must wait for any I/O in progress to finish so that
5317	 * all potential buffers on the dirty list will be visible.
5318	 */
5319	VI_LOCK(vp);
5320	drain_output(vp);
5321	VI_UNLOCK(vp);
5322	return (0);
5323}
5324
5325/*
5326 * Flush the dependencies associated with an inodedep.
5327 * Called with splbio blocked.
5328 */
5329static int
5330flush_inodedep_deps(mp, ino)
5331	struct mount *mp;
5332	ino_t ino;
5333{
5334	struct inodedep *inodedep;
5335	int error, waitfor;
5336
5337	/*
5338	 * This work is done in two passes. The first pass grabs most
5339	 * of the buffers and begins asynchronously writing them. The
5340	 * only way to wait for these asynchronous writes is to sleep
5341	 * on the filesystem vnode which may stay busy for a long time
5342	 * if the filesystem is active. So, instead, we make a second
5343	 * pass over the dependencies blocking on each write. In the
5344	 * usual case we will be blocking against a write that we
5345	 * initiated, so when it is done the dependency will have been
5346	 * resolved. Thus the second pass is expected to end quickly.
5347	 * We give a brief window at the top of the loop to allow
5348	 * any pending I/O to complete.
5349	 */
5350	for (error = 0, waitfor = MNT_NOWAIT; ; ) {
5351		if (error)
5352			return (error);
5353		FREE_LOCK(&lk);
5354		ACQUIRE_LOCK(&lk);
5355		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
5356			return (0);
5357		if (flush_deplist(&inodedep->id_inoupdt, waitfor, &error) ||
5358		    flush_deplist(&inodedep->id_newinoupdt, waitfor, &error) ||
5359		    flush_deplist(&inodedep->id_extupdt, waitfor, &error) ||
5360		    flush_deplist(&inodedep->id_newextupdt, waitfor, &error))
5361			continue;
5362		/*
5363		 * If pass2, we are done, otherwise do pass 2.
5364		 */
5365		if (waitfor == MNT_WAIT)
5366			break;
5367		waitfor = MNT_WAIT;
5368	}
5369	/*
5370	 * Try freeing inodedep in case all dependencies have been removed.
5371	 */
5372	if (inodedep_lookup(mp, ino, 0, &inodedep) != 0)
5373		(void) free_inodedep(inodedep);
5374	return (0);
5375}
5376
5377/*
5378 * Flush an inode dependency list.
5379 * Called with splbio blocked.
5380 */
5381static int
5382flush_deplist(listhead, waitfor, errorp)
5383	struct allocdirectlst *listhead;
5384	int waitfor;
5385	int *errorp;
5386{
5387	struct allocdirect *adp;
5388	struct buf *bp;
5389
5390	mtx_assert(&lk, MA_OWNED);
5391	TAILQ_FOREACH(adp, listhead, ad_next) {
5392		if (adp->ad_state & DEPCOMPLETE)
5393			continue;
5394		bp = adp->ad_buf;
5395		bp = getdirtybuf(bp, &lk, waitfor);
5396		if (bp == NULL) {
5397			if (waitfor == MNT_NOWAIT)
5398				continue;
5399			return (1);
5400		}
5401		FREE_LOCK(&lk);
5402		if (waitfor == MNT_NOWAIT) {
5403			bawrite(bp);
5404		} else if ((*errorp = bwrite(bp)) != 0) {
5405			ACQUIRE_LOCK(&lk);
5406			return (1);
5407		}
5408		ACQUIRE_LOCK(&lk);
5409		return (1);
5410	}
5411	return (0);
5412}
5413
5414/*
5415 * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
5416 * Called with splbio blocked.
5417 */
5418static int
5419flush_pagedep_deps(pvp, mp, diraddhdp)
5420	struct vnode *pvp;
5421	struct mount *mp;
5422	struct diraddhd *diraddhdp;
5423{
5424	struct inodedep *inodedep;
5425	struct ufsmount *ump;
5426	struct diradd *dap;
5427	struct vnode *vp;
5428	int error = 0;
5429	struct buf *bp;
5430	ino_t inum;
5431
5432	ump = VFSTOUFS(mp);
5433	while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
5434		/*
5435		 * Flush ourselves if this directory entry
5436		 * has a MKDIR_PARENT dependency.
5437		 */
5438		if (dap->da_state & MKDIR_PARENT) {
5439			FREE_LOCK(&lk);
5440			if ((error = ffs_update(pvp, 1)) != 0)
5441				break;
5442			ACQUIRE_LOCK(&lk);
5443			/*
5444			 * If that cleared dependencies, go on to next.
5445			 */
5446			if (dap != LIST_FIRST(diraddhdp))
5447				continue;
5448			if (dap->da_state & MKDIR_PARENT)
5449				panic("flush_pagedep_deps: MKDIR_PARENT");
5450		}
5451		/*
5452		 * A newly allocated directory must have its "." and
5453		 * ".." entries written out before its name can be
5454		 * committed in its parent. We do not want or need
5455		 * the full semantics of a synchronous ffs_syncvnode as
5456		 * that may end up here again, once for each directory
5457		 * level in the filesystem. Instead, we push the blocks
5458		 * and wait for them to clear. We have to fsync twice
5459		 * because the first call may choose to defer blocks
5460		 * that still have dependencies, but deferral will
5461		 * happen at most once.
5462		 */
5463		inum = dap->da_newinum;
5464		if (dap->da_state & MKDIR_BODY) {
5465			FREE_LOCK(&lk);
5466			if ((error = ffs_vget(mp, inum, LK_EXCLUSIVE, &vp)))
5467				break;
5468			if ((error=ffs_syncvnode(vp, MNT_NOWAIT)) ||
5469			    (error=ffs_syncvnode(vp, MNT_NOWAIT))) {
5470				vput(vp);
5471				break;
5472			}
5473			VI_LOCK(vp);
5474			drain_output(vp);
5475			VI_UNLOCK(vp);
5476			vput(vp);
5477			ACQUIRE_LOCK(&lk);
5478			/*
5479			 * If that cleared dependencies, go on to next.
5480			 */
5481			if (dap != LIST_FIRST(diraddhdp))
5482				continue;
5483			if (dap->da_state & MKDIR_BODY)
5484				panic("flush_pagedep_deps: MKDIR_BODY");
5485		}
5486		/*
5487		 * Flush the inode on which the directory entry depends.
5488		 * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
5489		 * the only remaining dependency is that the updated inode
5490		 * count must get pushed to disk. The inode has already
5491		 * been pushed into its inode buffer (via VOP_UPDATE) at
5492		 * the time of the reference count change. So we need only
5493		 * locate that buffer, ensure that there will be no rollback
5494		 * caused by a bitmap dependency, then write the inode buffer.
5495		 */
5496retry:
5497		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
5498			panic("flush_pagedep_deps: lost inode");
5499		/*
5500		 * If the inode still has bitmap dependencies,
5501		 * push them to disk.
5502		 */
5503		if ((inodedep->id_state & DEPCOMPLETE) == 0) {
5504			bp = inodedep->id_buf;
5505			bp = getdirtybuf(bp, &lk, MNT_WAIT);
5506			if (bp == NULL)
5507				goto retry;
5508			FREE_LOCK(&lk);
5509			if ((error = bwrite(bp)) != 0)
5510				break;
5511			ACQUIRE_LOCK(&lk);
5512			if (dap != LIST_FIRST(diraddhdp))
5513				continue;
5514		}
5515		/*
5516		 * If the inode is still sitting in a buffer waiting
5517		 * to be written, push it to disk.
5518		 */
5519		FREE_LOCK(&lk);
5520		if ((error = bread(ump->um_devvp,
5521		    fsbtodb(ump->um_fs, ino_to_fsba(ump->um_fs, inum)),
5522		    (int)ump->um_fs->fs_bsize, NOCRED, &bp)) != 0) {
5523			brelse(bp);
5524			break;
5525		}
5526		if ((error = bwrite(bp)) != 0)
5527			break;
5528		ACQUIRE_LOCK(&lk);
5529		/*
5530		 * If we have failed to get rid of all the dependencies
5531		 * then something is seriously wrong.
5532		 */
5533		if (dap == LIST_FIRST(diraddhdp))
5534			panic("flush_pagedep_deps: flush failed");
5535	}
5536	if (error)
5537		ACQUIRE_LOCK(&lk);
5538	return (error);
5539}
5540
5541/*
5542 * A large burst of file addition or deletion activity can drive the
5543 * memory load excessively high. First attempt to slow things down
5544 * using the techniques below. If that fails, this routine requests
5545 * the offending operations to fall back to running synchronously
5546 * until the memory load returns to a reasonable level.
5547 */
5548int
5549softdep_slowdown(vp)
5550	struct vnode *vp;
5551{
5552	int max_softdeps_hard;
5553
5554	max_softdeps_hard = max_softdeps * 11 / 10;
5555	if (num_dirrem < max_softdeps_hard / 2 &&
5556	    num_inodedep < max_softdeps_hard &&
5557	    VFSTOUFS(vp->v_mount)->um_numindirdeps < maxindirdeps)
5558  		return (0);
5559	if (VFSTOUFS(vp->v_mount)->um_numindirdeps >= maxindirdeps)
5560		softdep_speedup();
5561	stat_sync_limit_hit += 1;
5562	return (1);
5563}
5564
5565/*
5566 * Called by the allocation routines when they are about to fail
5567 * in the hope that we can free up some disk space.
5568 *
5569 * First check to see if the work list has anything on it. If it has,
5570 * clean up entries until we successfully free some space. Because this
5571 * process holds inodes locked, we cannot handle any remove requests
5572 * that might block on a locked inode as that could lead to deadlock.
5573 * If the worklist yields no free space, encourage the syncer daemon
5574 * to help us. In no event will we try for longer than tickdelay seconds.
5575 */
5576int
5577softdep_request_cleanup(fs, vp)
5578	struct fs *fs;
5579	struct vnode *vp;
5580{
5581	struct ufsmount *ump;
5582	long starttime;
5583	ufs2_daddr_t needed;
5584	int error;
5585
5586	ump = VTOI(vp)->i_ump;
5587	mtx_assert(UFS_MTX(ump), MA_OWNED);
5588	needed = fs->fs_cstotal.cs_nbfree + fs->fs_contigsumsize;
5589	starttime = time_second + tickdelay;
5590	/*
5591	 * If we are being called because of a process doing a
5592	 * copy-on-write, then it is not safe to update the vnode
5593	 * as we may recurse into the copy-on-write routine.
5594	 */
5595	if (!(curthread->td_pflags & TDP_COWINPROGRESS)) {
5596		UFS_UNLOCK(ump);
5597		error = ffs_update(vp, 1);
5598		UFS_LOCK(ump);
5599		if (error != 0)
5600			return (0);
5601	}
5602	while (fs->fs_pendingblocks > 0 && fs->fs_cstotal.cs_nbfree <= needed) {
5603		if (time_second > starttime)
5604			return (0);
5605		UFS_UNLOCK(ump);
5606		ACQUIRE_LOCK(&lk);
5607		if (ump->softdep_on_worklist > 0 &&
5608		    process_worklist_item(UFSTOVFS(ump), LK_NOWAIT) != -1) {
5609			stat_worklist_push += 1;
5610			FREE_LOCK(&lk);
5611			UFS_LOCK(ump);
5612			continue;
5613		}
5614		request_cleanup(UFSTOVFS(ump), FLUSH_REMOVE_WAIT);
5615		FREE_LOCK(&lk);
5616		UFS_LOCK(ump);
5617	}
5618	return (1);
5619}
5620
5621/*
5622 * If memory utilization has gotten too high, deliberately slow things
5623 * down and speed up the I/O processing.
5624 */
5625extern struct thread *syncertd;
5626static int
5627request_cleanup(mp, resource)
5628	struct mount *mp;
5629	int resource;
5630{
5631	struct thread *td = curthread;
5632	struct ufsmount *ump;
5633
5634	mtx_assert(&lk, MA_OWNED);
5635	/*
5636	 * We never hold up the filesystem syncer or buf daemon.
5637	 */
5638	if (td->td_pflags & (TDP_SOFTDEP|TDP_NORUNNINGBUF))
5639		return (0);
5640	ump = VFSTOUFS(mp);
5641	/*
5642	 * First check to see if the work list has gotten backlogged.
5643	 * If it has, co-opt this process to help clean up two entries.
5644	 * Because this process may hold inodes locked, we cannot
5645	 * handle any remove requests that might block on a locked
5646	 * inode as that could lead to deadlock.  We set TDP_SOFTDEP
5647	 * to avoid recursively processing the worklist.
5648	 */
5649	if (ump->softdep_on_worklist > max_softdeps / 10) {
5650		td->td_pflags |= TDP_SOFTDEP;
5651		process_worklist_item(mp, LK_NOWAIT);
5652		process_worklist_item(mp, LK_NOWAIT);
5653		td->td_pflags &= ~TDP_SOFTDEP;
5654		stat_worklist_push += 2;
5655		return(1);
5656	}
5657	/*
5658	 * Next, we attempt to speed up the syncer process. If that
5659	 * is successful, then we allow the process to continue.
5660	 */
5661	if (softdep_speedup() && resource != FLUSH_REMOVE_WAIT)
5662		return(0);
5663	/*
5664	 * If we are resource constrained on inode dependencies, try
5665	 * flushing some dirty inodes. Otherwise, we are constrained
5666	 * by file deletions, so try accelerating flushes of directories
5667	 * with removal dependencies. We would like to do the cleanup
5668	 * here, but we probably hold an inode locked at this point and
5669	 * that might deadlock against one that we try to clean. So,
5670	 * the best that we can do is request the syncer daemon to do
5671	 * the cleanup for us.
5672	 */
5673	switch (resource) {
5674
5675	case FLUSH_INODES:
5676		stat_ino_limit_push += 1;
5677		req_clear_inodedeps += 1;
5678		stat_countp = &stat_ino_limit_hit;
5679		break;
5680
5681	case FLUSH_REMOVE:
5682	case FLUSH_REMOVE_WAIT:
5683		stat_blk_limit_push += 1;
5684		req_clear_remove += 1;
5685		stat_countp = &stat_blk_limit_hit;
5686		break;
5687
5688	default:
5689		panic("request_cleanup: unknown type");
5690	}
5691	/*
5692	 * Hopefully the syncer daemon will catch up and awaken us.
5693	 * We wait at most tickdelay before proceeding in any case.
5694	 */
5695	proc_waiting += 1;
5696	if (handle.callout == NULL)
5697		handle = timeout(pause_timer, 0, tickdelay > 2 ? tickdelay : 2);
5698	msleep((caddr_t)&proc_waiting, &lk, PPAUSE, "softupdate", 0);
5699	proc_waiting -= 1;
5700	return (1);
5701}
5702
5703/*
5704 * Awaken processes pausing in request_cleanup and clear proc_waiting
5705 * to indicate that there is no longer a timer running.
5706 */
5707static void
5708pause_timer(arg)
5709	void *arg;
5710{
5711
5712	ACQUIRE_LOCK(&lk);
5713	*stat_countp += 1;
5714	wakeup_one(&proc_waiting);
5715	if (proc_waiting > 0)
5716		handle = timeout(pause_timer, 0, tickdelay > 2 ? tickdelay : 2);
5717	else
5718		handle.callout = NULL;
5719	FREE_LOCK(&lk);
5720}
5721
5722/*
5723 * Flush out a directory with at least one removal dependency in an effort to
5724 * reduce the number of dirrem, freefile, and freeblks dependency structures.
5725 */
5726static void
5727clear_remove(td)
5728	struct thread *td;
5729{
5730	struct pagedep_hashhead *pagedephd;
5731	struct pagedep *pagedep;
5732	static int next = 0;
5733	struct mount *mp;
5734	struct vnode *vp;
5735	int error, cnt;
5736	ino_t ino;
5737
5738	mtx_assert(&lk, MA_OWNED);
5739
5740	for (cnt = 0; cnt < pagedep_hash; cnt++) {
5741		pagedephd = &pagedep_hashtbl[next++];
5742		if (next >= pagedep_hash)
5743			next = 0;
5744		LIST_FOREACH(pagedep, pagedephd, pd_hash) {
5745			if (LIST_FIRST(&pagedep->pd_dirremhd) == NULL)
5746				continue;
5747			mp = pagedep->pd_list.wk_mp;
5748			ino = pagedep->pd_ino;
5749			if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
5750				continue;
5751			FREE_LOCK(&lk);
5752			if ((error = ffs_vget(mp, ino, LK_EXCLUSIVE, &vp))) {
5753				softdep_error("clear_remove: vget", error);
5754				vn_finished_write(mp);
5755				ACQUIRE_LOCK(&lk);
5756				return;
5757			}
5758			if ((error = ffs_syncvnode(vp, MNT_NOWAIT)))
5759				softdep_error("clear_remove: fsync", error);
5760			VI_LOCK(vp);
5761			drain_output(vp);
5762			VI_UNLOCK(vp);
5763			vput(vp);
5764			vn_finished_write(mp);
5765			ACQUIRE_LOCK(&lk);
5766			return;
5767		}
5768	}
5769}
5770
5771/*
5772 * Clear out a block of dirty inodes in an effort to reduce
5773 * the number of inodedep dependency structures.
5774 */
5775static void
5776clear_inodedeps(td)
5777	struct thread *td;
5778{
5779	struct inodedep_hashhead *inodedephd;
5780	struct inodedep *inodedep;
5781	static int next = 0;
5782	struct mount *mp;
5783	struct vnode *vp;
5784	struct fs *fs;
5785	int error, cnt;
5786	ino_t firstino, lastino, ino;
5787
5788	mtx_assert(&lk, MA_OWNED);
5789	/*
5790	 * Pick a random inode dependency to be cleared.
5791	 * We will then gather up all the inodes in its block
5792	 * that have dependencies and flush them out.
5793	 */
5794	for (cnt = 0; cnt < inodedep_hash; cnt++) {
5795		inodedephd = &inodedep_hashtbl[next++];
5796		if (next >= inodedep_hash)
5797			next = 0;
5798		if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
5799			break;
5800	}
5801	if (inodedep == NULL)
5802		return;
5803	fs = inodedep->id_fs;
5804	mp = inodedep->id_list.wk_mp;
5805	/*
5806	 * Find the last inode in the block with dependencies.
5807	 */
5808	firstino = inodedep->id_ino & ~(INOPB(fs) - 1);
5809	for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
5810		if (inodedep_lookup(mp, lastino, 0, &inodedep) != 0)
5811			break;
5812	/*
5813	 * Asynchronously push all but the last inode with dependencies.
5814	 * Synchronously push the last inode with dependencies to ensure
5815	 * that the inode block gets written to free up the inodedeps.
5816	 */
5817	for (ino = firstino; ino <= lastino; ino++) {
5818		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
5819			continue;
5820		if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
5821			continue;
5822		FREE_LOCK(&lk);
5823		if ((error = ffs_vget(mp, ino, LK_EXCLUSIVE, &vp)) != 0) {
5824			softdep_error("clear_inodedeps: vget", error);
5825			vn_finished_write(mp);
5826			ACQUIRE_LOCK(&lk);
5827			return;
5828		}
5829		if (ino == lastino) {
5830			if ((error = ffs_syncvnode(vp, MNT_WAIT)))
5831				softdep_error("clear_inodedeps: fsync1", error);
5832		} else {
5833			if ((error = ffs_syncvnode(vp, MNT_NOWAIT)))
5834				softdep_error("clear_inodedeps: fsync2", error);
5835			VI_LOCK(vp);
5836			drain_output(vp);
5837			VI_UNLOCK(vp);
5838		}
5839		vput(vp);
5840		vn_finished_write(mp);
5841		ACQUIRE_LOCK(&lk);
5842	}
5843}
5844
5845/*
5846 * Function to determine if the buffer has outstanding dependencies
5847 * that will cause a roll-back if the buffer is written. If wantcount
5848 * is set, return number of dependencies, otherwise just yes or no.
5849 */
5850static int
5851softdep_count_dependencies(bp, wantcount)
5852	struct buf *bp;
5853	int wantcount;
5854{
5855	struct worklist *wk;
5856	struct inodedep *inodedep;
5857	struct indirdep *indirdep;
5858	struct allocindir *aip;
5859	struct pagedep *pagedep;
5860	struct diradd *dap;
5861	int i, retval;
5862
5863	retval = 0;
5864	ACQUIRE_LOCK(&lk);
5865	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5866		switch (wk->wk_type) {
5867
5868		case D_INODEDEP:
5869			inodedep = WK_INODEDEP(wk);
5870			if ((inodedep->id_state & DEPCOMPLETE) == 0) {
5871				/* bitmap allocation dependency */
5872				retval += 1;
5873				if (!wantcount)
5874					goto out;
5875			}
5876			if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
5877				/* direct block pointer dependency */
5878				retval += 1;
5879				if (!wantcount)
5880					goto out;
5881			}
5882			if (TAILQ_FIRST(&inodedep->id_extupdt)) {
5883				/* direct block pointer dependency */
5884				retval += 1;
5885				if (!wantcount)
5886					goto out;
5887			}
5888			continue;
5889
5890		case D_INDIRDEP:
5891			indirdep = WK_INDIRDEP(wk);
5892
5893			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
5894				/* indirect block pointer dependency */
5895				retval += 1;
5896				if (!wantcount)
5897					goto out;
5898			}
5899			continue;
5900
5901		case D_PAGEDEP:
5902			pagedep = WK_PAGEDEP(wk);
5903			for (i = 0; i < DAHASHSZ; i++) {
5904
5905				LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
5906					/* directory entry dependency */
5907					retval += 1;
5908					if (!wantcount)
5909						goto out;
5910				}
5911			}
5912			continue;
5913
5914		case D_BMSAFEMAP:
5915		case D_ALLOCDIRECT:
5916		case D_ALLOCINDIR:
5917		case D_MKDIR:
5918			/* never a dependency on these blocks */
5919			continue;
5920
5921		default:
5922			panic("softdep_check_for_rollback: Unexpected type %s",
5923			    TYPENAME(wk->wk_type));
5924			/* NOTREACHED */
5925		}
5926	}
5927out:
5928	FREE_LOCK(&lk);
5929	return retval;
5930}
5931
5932/*
5933 * Acquire exclusive access to a buffer.
5934 * Must be called with a locked mtx parameter.
5935 * Return acquired buffer or NULL on failure.
5936 */
5937static struct buf *
5938getdirtybuf(bp, mtx, waitfor)
5939	struct buf *bp;
5940	struct mtx *mtx;
5941	int waitfor;
5942{
5943	int error;
5944
5945	mtx_assert(mtx, MA_OWNED);
5946	if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0) {
5947		if (waitfor != MNT_WAIT)
5948			return (NULL);
5949		error = BUF_LOCK(bp,
5950		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, mtx);
5951		/*
5952		 * Even if we sucessfully acquire bp here, we have dropped
5953		 * mtx, which may violates our guarantee.
5954		 */
5955		if (error == 0)
5956			BUF_UNLOCK(bp);
5957		else if (error != ENOLCK)
5958			panic("getdirtybuf: inconsistent lock: %d", error);
5959		mtx_lock(mtx);
5960		return (NULL);
5961	}
5962	if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
5963		if (mtx == &lk && waitfor == MNT_WAIT) {
5964			mtx_unlock(mtx);
5965			BO_LOCK(bp->b_bufobj);
5966			BUF_UNLOCK(bp);
5967			if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
5968				bp->b_vflags |= BV_BKGRDWAIT;
5969				msleep(&bp->b_xflags, BO_MTX(bp->b_bufobj),
5970				       PRIBIO | PDROP, "getbuf", 0);
5971			} else
5972				BO_UNLOCK(bp->b_bufobj);
5973			mtx_lock(mtx);
5974			return (NULL);
5975		}
5976		BUF_UNLOCK(bp);
5977		if (waitfor != MNT_WAIT)
5978			return (NULL);
5979		/*
5980		 * The mtx argument must be bp->b_vp's mutex in
5981		 * this case.
5982		 */
5983#ifdef	DEBUG_VFS_LOCKS
5984		if (bp->b_vp->v_type != VCHR)
5985			ASSERT_VI_LOCKED(bp->b_vp, "getdirtybuf");
5986#endif
5987		bp->b_vflags |= BV_BKGRDWAIT;
5988		msleep(&bp->b_xflags, mtx, PRIBIO, "getbuf", 0);
5989		return (NULL);
5990	}
5991	if ((bp->b_flags & B_DELWRI) == 0) {
5992		BUF_UNLOCK(bp);
5993		return (NULL);
5994	}
5995	bremfree(bp);
5996	return (bp);
5997}
5998
5999/*
6000 * Wait for pending output on a vnode to complete.
6001 * Must be called with vnode lock and interlock locked.
6002 *
6003 * XXX: Should just be a call to bufobj_wwait().
6004 */
6005static void
6006drain_output(vp)
6007	struct vnode *vp;
6008{
6009	ASSERT_VOP_LOCKED(vp, "drain_output");
6010	ASSERT_VI_LOCKED(vp, "drain_output");
6011
6012	while (vp->v_bufobj.bo_numoutput) {
6013		vp->v_bufobj.bo_flag |= BO_WWAIT;
6014		msleep((caddr_t)&vp->v_bufobj.bo_numoutput,
6015		    VI_MTX(vp), PRIBIO + 1, "drainvp", 0);
6016	}
6017}
6018
6019/*
6020 * Called whenever a buffer that is being invalidated or reallocated
6021 * contains dependencies. This should only happen if an I/O error has
6022 * occurred. The routine is called with the buffer locked.
6023 */
6024static void
6025softdep_deallocate_dependencies(bp)
6026	struct buf *bp;
6027{
6028
6029	if ((bp->b_ioflags & BIO_ERROR) == 0)
6030		panic("softdep_deallocate_dependencies: dangling deps");
6031	softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntonname, bp->b_error);
6032	panic("softdep_deallocate_dependencies: unrecovered I/O error");
6033}
6034
6035/*
6036 * Function to handle asynchronous write errors in the filesystem.
6037 */
6038static void
6039softdep_error(func, error)
6040	char *func;
6041	int error;
6042{
6043
6044	/* XXX should do something better! */
6045	printf("%s: got error %d while accessing filesystem\n", func, error);
6046}
6047
6048#endif /* SOFTUPDATES */
6049