ffs_softdep.c revision 48225
195643Smarkm/*
295643Smarkm * Copyright 1998 Marshall Kirk McKusick. All Rights Reserved.
395643Smarkm *
495643Smarkm * The soft updates code is derived from the appendix of a University
595643Smarkm * of Michigan technical report (Gregory R. Ganger and Yale N. Patt,
695643Smarkm * "Soft Updates: A Solution to the Metadata Update Problem in File
795643Smarkm * Systems", CSE-TR-254-95, August 1995).
895643Smarkm *
995643Smarkm * The following are the copyrights and redistribution conditions that
1095643Smarkm * apply to this copy of the soft update software. For a license
1195643Smarkm * to use, redistribute or sell the soft update software under
1295643Smarkm * conditions other than those described here, please contact the
1395643Smarkm * author at one of the following addresses:
1495643Smarkm *
1595643Smarkm *	Marshall Kirk McKusick		mckusick@mckusick.com
1695643Smarkm *	1614 Oxford Street		+1-510-843-9542
1795643Smarkm *	Berkeley, CA 94709-1608
1895643Smarkm *	USA
1995643Smarkm *
2095643Smarkm * Redistribution and use in source and binary forms, with or without
2195643Smarkm * modification, are permitted provided that the following conditions
2295643Smarkm * are met:
2395643Smarkm *
2495643Smarkm * 1. Redistributions of source code must retain the above copyright
2595643Smarkm *    notice, this list of conditions and the following disclaimer.
2695643Smarkm * 2. Redistributions in binary form must reproduce the above copyright
2795643Smarkm *    notice, this list of conditions and the following disclaimer in the
2895643Smarkm *    documentation and/or other materials provided with the distribution.
2995643Smarkm * 3. None of the names of McKusick, Ganger, Patt, or the University of
3095643Smarkm *    Michigan may be used to endorse or promote products derived from
3195643Smarkm *    this software without specific prior written permission.
3295643Smarkm * 4. Redistributions in any form must be accompanied by information on
3395643Smarkm *    how to obtain complete source code for any accompanying software
3495643Smarkm *    that uses this software. This source code must either be included
3595643Smarkm *    in the distribution or be available for no more than the cost of
3695643Smarkm *    distribution plus a nominal fee, and must be freely redistributable
37 *    under reasonable conditions. For an executable file, complete
38 *    source code means the source code for all modules it contains.
39 *    It does not mean source code for modules or files that typically
40 *    accompany the operating system on which the executable file runs,
41 *    e.g., standard library modules or system header files.
42 *
43 * THIS SOFTWARE IS PROVIDED BY MARSHALL KIRK MCKUSICK ``AS IS'' AND ANY
44 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
45 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
46 * DISCLAIMED.  IN NO EVENT SHALL MARSHALL KIRK MCKUSICK BE LIABLE FOR
47 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
48 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
49 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
50 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
51 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
52 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
53 * SUCH DAMAGE.
54 *
55 *	from: @(#)ffs_softdep.c	9.40 (McKusick) 6/15/99
56 *	$Id: ffs_softdep.c,v 1.31 1999/06/16 23:27:55 mckusick Exp $
57 */
58
59/*
60 * For now we want the safety net that the DIAGNOSTIC and DEBUG flags provide.
61 */
62#ifndef DIAGNOSTIC
63#define DIAGNOSTIC
64#endif
65#ifndef DEBUG
66#define DEBUG
67#endif
68
69#include <sys/param.h>
70#include <sys/buf.h>
71#include <sys/kernel.h>
72#include <sys/malloc.h>
73#include <sys/mount.h>
74#include <sys/proc.h>
75#include <sys/syslog.h>
76#include <sys/systm.h>
77#include <sys/vnode.h>
78#include <miscfs/specfs/specdev.h>
79#include <ufs/ufs/dir.h>
80#include <ufs/ufs/quota.h>
81#include <ufs/ufs/inode.h>
82#include <ufs/ufs/ufsmount.h>
83#include <ufs/ffs/fs.h>
84#include <ufs/ffs/softdep.h>
85#include <ufs/ffs/ffs_extern.h>
86#include <ufs/ufs/ufs_extern.h>
87
88/*
89 * These definitions need to be adapted to the system to which
90 * this file is being ported.
91 */
92/*
93 * malloc types defined for the softdep system.
94 */
95MALLOC_DEFINE(M_PAGEDEP, "pagedep","File page dependencies");
96MALLOC_DEFINE(M_INODEDEP, "inodedep","Inode dependencies");
97MALLOC_DEFINE(M_NEWBLK, "newblk","New block allocation");
98MALLOC_DEFINE(M_BMSAFEMAP, "bmsafemap","Block or frag allocated from cyl group map");
99MALLOC_DEFINE(M_ALLOCDIRECT, "allocdirect","Block or frag dependency for an inode");
100MALLOC_DEFINE(M_INDIRDEP, "indirdep","Indirect block dependencies");
101MALLOC_DEFINE(M_ALLOCINDIR, "allocindir","Block dependency for an indirect block");
102MALLOC_DEFINE(M_FREEFRAG, "freefrag","Previously used frag for an inode");
103MALLOC_DEFINE(M_FREEBLKS, "freeblks","Blocks freed from an inode");
104MALLOC_DEFINE(M_FREEFILE, "freefile","Inode deallocated");
105MALLOC_DEFINE(M_DIRADD, "diradd","New directory entry");
106MALLOC_DEFINE(M_MKDIR, "mkdir","New directory");
107MALLOC_DEFINE(M_DIRREM, "dirrem","Directory entry deleted");
108
109#define	D_PAGEDEP	0
110#define	D_INODEDEP	1
111#define	D_NEWBLK	2
112#define	D_BMSAFEMAP	3
113#define	D_ALLOCDIRECT	4
114#define	D_INDIRDEP	5
115#define	D_ALLOCINDIR	6
116#define	D_FREEFRAG	7
117#define	D_FREEBLKS	8
118#define	D_FREEFILE	9
119#define	D_DIRADD	10
120#define	D_MKDIR		11
121#define	D_DIRREM	12
122#define D_LAST		D_DIRREM
123
124/*
125 * translate from workitem type to memory type
126 * MUST match the defines above, such that memtype[D_XXX] == M_XXX
127 */
128static struct malloc_type *memtype[] = {
129	M_PAGEDEP,
130	M_INODEDEP,
131	M_NEWBLK,
132	M_BMSAFEMAP,
133	M_ALLOCDIRECT,
134	M_INDIRDEP,
135	M_ALLOCINDIR,
136	M_FREEFRAG,
137	M_FREEBLKS,
138	M_FREEFILE,
139	M_DIRADD,
140	M_MKDIR,
141	M_DIRREM
142};
143
144#define DtoM(type) (memtype[type])
145
146/*
147 * Names of malloc types.
148 */
149#define TYPENAME(type)  \
150	((unsigned)(type) < D_LAST ? memtype[type]->ks_shortdesc : "???")
151#define CURPROC curproc
152/*
153 * End system adaptaion definitions.
154 */
155
156/*
157 * Internal function prototypes.
158 */
159static	void softdep_error __P((char *, int));
160static	void drain_output __P((struct vnode *, int));
161static	int getdirtybuf __P((struct buf **, int));
162static	void clear_remove __P((struct proc *));
163static	void clear_inodedeps __P((struct proc *));
164static	int flush_pagedep_deps __P((struct vnode *, struct mount *,
165	    struct diraddhd *));
166static	int flush_inodedep_deps __P((struct fs *, ino_t));
167static	int handle_written_filepage __P((struct pagedep *, struct buf *));
168static  void diradd_inode_written __P((struct diradd *, struct inodedep *));
169static	int handle_written_inodeblock __P((struct inodedep *, struct buf *));
170static	void handle_allocdirect_partdone __P((struct allocdirect *));
171static	void handle_allocindir_partdone __P((struct allocindir *));
172static	void initiate_write_filepage __P((struct pagedep *, struct buf *));
173static	void handle_written_mkdir __P((struct mkdir *, int));
174static	void initiate_write_inodeblock __P((struct inodedep *, struct buf *));
175static	void handle_workitem_freefile __P((struct freefile *));
176static	void handle_workitem_remove __P((struct dirrem *));
177static	struct dirrem *newdirrem __P((struct buf *, struct inode *,
178	    struct inode *, int));
179static	void free_diradd __P((struct diradd *));
180static	void free_allocindir __P((struct allocindir *, struct inodedep *));
181static	int indir_trunc __P((struct inode *, ufs_daddr_t, int, ufs_lbn_t,
182	    long *));
183static	void deallocate_dependencies __P((struct buf *, struct inodedep *));
184static	void free_allocdirect __P((struct allocdirectlst *,
185	    struct allocdirect *, int));
186static	int free_inodedep __P((struct inodedep *));
187static	void handle_workitem_freeblocks __P((struct freeblks *));
188static	void merge_inode_lists __P((struct inodedep *));
189static	void setup_allocindir_phase2 __P((struct buf *, struct inode *,
190	    struct allocindir *));
191static	struct allocindir *newallocindir __P((struct inode *, int, ufs_daddr_t,
192	    ufs_daddr_t));
193static	void handle_workitem_freefrag __P((struct freefrag *));
194static	struct freefrag *newfreefrag __P((struct inode *, ufs_daddr_t, long));
195static	void allocdirect_merge __P((struct allocdirectlst *,
196	    struct allocdirect *, struct allocdirect *));
197static	struct bmsafemap *bmsafemap_lookup __P((struct buf *));
198static	int newblk_lookup __P((struct fs *, ufs_daddr_t, int,
199	    struct newblk **));
200static	int inodedep_lookup __P((struct fs *, ino_t, int, struct inodedep **));
201static	int pagedep_lookup __P((struct inode *, ufs_lbn_t, int,
202	    struct pagedep **));
203static	void pause_timer __P((void *));
204static	int request_cleanup __P((int, int));
205static	void add_to_worklist __P((struct worklist *));
206
207/*
208 * Exported softdep operations.
209 */
210struct bio_ops bioops = {
211	softdep_disk_io_initiation,		/* io_start */
212	softdep_disk_write_complete,		/* io_complete */
213	softdep_deallocate_dependencies,	/* io_deallocate */
214	softdep_fsync,				/* io_fsync */
215	softdep_process_worklist,		/* io_sync */
216};
217
218/*
219 * Locking primitives.
220 *
221 * For a uniprocessor, all we need to do is protect against disk
222 * interrupts. For a multiprocessor, this lock would have to be
223 * a mutex. A single mutex is used throughout this file, though
224 * finer grain locking could be used if contention warranted it.
225 *
226 * For a multiprocessor, the sleep call would accept a lock and
227 * release it after the sleep processing was complete. In a uniprocessor
228 * implementation there is no such interlock, so we simple mark
229 * the places where it needs to be done with the `interlocked' form
230 * of the lock calls. Since the uniprocessor sleep already interlocks
231 * the spl, there is nothing that really needs to be done.
232 */
233#ifndef /* NOT */ DEBUG
234static struct lockit {
235	int	lkt_spl;
236} lk = { 0 };
237#define ACQUIRE_LOCK(lk)		(lk)->lkt_spl = splbio()
238#define FREE_LOCK(lk)			splx((lk)->lkt_spl)
239#define ACQUIRE_LOCK_INTERLOCKED(lk)
240#define FREE_LOCK_INTERLOCKED(lk)
241
242#else /* DEBUG */
243static struct lockit {
244	int	lkt_spl;
245	pid_t	lkt_held;
246} lk = { 0, -1 };
247static int lockcnt;
248
249static	void acquire_lock __P((struct lockit *));
250static	void free_lock __P((struct lockit *));
251static	void acquire_lock_interlocked __P((struct lockit *));
252static	void free_lock_interlocked __P((struct lockit *));
253
254#define ACQUIRE_LOCK(lk)		acquire_lock(lk)
255#define FREE_LOCK(lk)			free_lock(lk)
256#define ACQUIRE_LOCK_INTERLOCKED(lk)	acquire_lock_interlocked(lk)
257#define FREE_LOCK_INTERLOCKED(lk)	free_lock_interlocked(lk)
258
259static void
260acquire_lock(lk)
261	struct lockit *lk;
262{
263
264	if (lk->lkt_held != -1) {
265		if (lk->lkt_held == CURPROC->p_pid)
266			panic("softdep_lock: locking against myself");
267		else
268			panic("softdep_lock: lock held by %d", lk->lkt_held);
269	}
270	lk->lkt_spl = splbio();
271	lk->lkt_held = CURPROC->p_pid;
272	lockcnt++;
273}
274
275static void
276free_lock(lk)
277	struct lockit *lk;
278{
279
280	if (lk->lkt_held == -1)
281		panic("softdep_unlock: lock not held");
282	lk->lkt_held = -1;
283	splx(lk->lkt_spl);
284}
285
286static void
287acquire_lock_interlocked(lk)
288	struct lockit *lk;
289{
290
291	if (lk->lkt_held != -1) {
292		if (lk->lkt_held == CURPROC->p_pid)
293			panic("softdep_lock_interlocked: locking against self");
294		else
295			panic("softdep_lock_interlocked: lock held by %d",
296			    lk->lkt_held);
297	}
298	lk->lkt_held = CURPROC->p_pid;
299	lockcnt++;
300}
301
302static void
303free_lock_interlocked(lk)
304	struct lockit *lk;
305{
306
307	if (lk->lkt_held == -1)
308		panic("softdep_unlock_interlocked: lock not held");
309	lk->lkt_held = -1;
310}
311#endif /* DEBUG */
312
313/*
314 * Place holder for real semaphores.
315 */
316struct sema {
317	int	value;
318	pid_t	holder;
319	char	*name;
320	int	prio;
321	int	timo;
322};
323static	void sema_init __P((struct sema *, char *, int, int));
324static	int sema_get __P((struct sema *, struct lockit *));
325static	void sema_release __P((struct sema *));
326
327static void
328sema_init(semap, name, prio, timo)
329	struct sema *semap;
330	char *name;
331	int prio, timo;
332{
333
334	semap->holder = -1;
335	semap->value = 0;
336	semap->name = name;
337	semap->prio = prio;
338	semap->timo = timo;
339}
340
341static int
342sema_get(semap, interlock)
343	struct sema *semap;
344	struct lockit *interlock;
345{
346
347	if (semap->value++ > 0) {
348		if (interlock != NULL)
349			FREE_LOCK_INTERLOCKED(interlock);
350		tsleep((caddr_t)semap, semap->prio, semap->name, semap->timo);
351		if (interlock != NULL) {
352			ACQUIRE_LOCK_INTERLOCKED(interlock);
353			FREE_LOCK(interlock);
354		}
355		return (0);
356	}
357	semap->holder = CURPROC->p_pid;
358	if (interlock != NULL)
359		FREE_LOCK(interlock);
360	return (1);
361}
362
363static void
364sema_release(semap)
365	struct sema *semap;
366{
367
368	if (semap->value <= 0 || semap->holder != CURPROC->p_pid)
369		panic("sema_release: not held");
370	if (--semap->value > 0) {
371		semap->value = 0;
372		wakeup(semap);
373	}
374	semap->holder = -1;
375}
376
377/*
378 * Worklist queue management.
379 * These routines require that the lock be held.
380 */
381#ifndef /* NOT */ DEBUG
382#define WORKLIST_INSERT(head, item) do {	\
383	(item)->wk_state |= ONWORKLIST;		\
384	LIST_INSERT_HEAD(head, item, wk_list);	\
385} while (0)
386#define WORKLIST_REMOVE(item) do {		\
387	(item)->wk_state &= ~ONWORKLIST;	\
388	LIST_REMOVE(item, wk_list);		\
389} while (0)
390#define WORKITEM_FREE(item, type) FREE(item, DtoM(type))
391
392#else /* DEBUG */
393static	void worklist_insert __P((struct workhead *, struct worklist *));
394static	void worklist_remove __P((struct worklist *));
395static	void workitem_free __P((struct worklist *, int));
396
397#define WORKLIST_INSERT(head, item) worklist_insert(head, item)
398#define WORKLIST_REMOVE(item) worklist_remove(item)
399#define WORKITEM_FREE(item, type) workitem_free((struct worklist *)item, type)
400
401static void
402worklist_insert(head, item)
403	struct workhead *head;
404	struct worklist *item;
405{
406
407	if (lk.lkt_held == -1)
408		panic("worklist_insert: lock not held");
409	if (item->wk_state & ONWORKLIST)
410		panic("worklist_insert: already on list");
411	item->wk_state |= ONWORKLIST;
412	LIST_INSERT_HEAD(head, item, wk_list);
413}
414
415static void
416worklist_remove(item)
417	struct worklist *item;
418{
419
420	if (lk.lkt_held == -1)
421		panic("worklist_remove: lock not held");
422	if ((item->wk_state & ONWORKLIST) == 0)
423		panic("worklist_remove: not on list");
424	item->wk_state &= ~ONWORKLIST;
425	LIST_REMOVE(item, wk_list);
426}
427
428static void
429workitem_free(item, type)
430	struct worklist *item;
431	int type;
432{
433
434	if (item->wk_state & ONWORKLIST)
435		panic("workitem_free: still on list");
436	if (item->wk_type != type)
437		panic("workitem_free: type mismatch");
438	FREE(item, DtoM(type));
439}
440#endif /* DEBUG */
441
442/*
443 * Workitem queue management
444 */
445static struct workhead softdep_workitem_pending;
446static int softdep_worklist_busy;
447static int max_softdeps;	/* maximum number of structs before slowdown */
448static int tickdelay = 2;	/* number of ticks to pause during slowdown */
449static int proc_waiting;	/* tracks whether we have a timeout posted */
450static struct proc *filesys_syncer; /* proc of filesystem syncer process */
451static int req_clear_inodedeps;	/* syncer process flush some inodedeps */
452#define FLUSH_INODES	1
453static int req_clear_remove;	/* syncer process flush some freeblks */
454#define FLUSH_REMOVE	2
455/*
456 * runtime statistics
457 */
458static int stat_blk_limit_push;	/* number of times block limit neared */
459static int stat_ino_limit_push;	/* number of times inode limit neared */
460static int stat_blk_limit_hit;	/* number of times block slowdown imposed */
461static int stat_ino_limit_hit;	/* number of times inode slowdown imposed */
462static int stat_indir_blk_ptrs;	/* bufs redirtied as indir ptrs not written */
463static int stat_inode_bitmap;	/* bufs redirtied as inode bitmap not written */
464static int stat_direct_blk_ptrs;/* bufs redirtied as direct ptrs not written */
465static int stat_dir_entry;	/* bufs redirtied as dir entry cannot write */
466#ifdef DEBUG
467#include <vm/vm.h>
468#include <sys/sysctl.h>
469#if defined(__FreeBSD__)
470SYSCTL_INT(_debug, OID_AUTO, max_softdeps, CTLFLAG_RW, &max_softdeps, 0, "");
471SYSCTL_INT(_debug, OID_AUTO, tickdelay, CTLFLAG_RW, &tickdelay, 0, "");
472SYSCTL_INT(_debug, OID_AUTO, blk_limit_push, CTLFLAG_RW, &stat_blk_limit_push, 0,"");
473SYSCTL_INT(_debug, OID_AUTO, ino_limit_push, CTLFLAG_RW, &stat_ino_limit_push, 0,"");
474SYSCTL_INT(_debug, OID_AUTO, blk_limit_hit, CTLFLAG_RW, &stat_blk_limit_hit, 0, "");
475SYSCTL_INT(_debug, OID_AUTO, ino_limit_hit, CTLFLAG_RW, &stat_ino_limit_hit, 0, "");
476SYSCTL_INT(_debug, OID_AUTO, indir_blk_ptrs, CTLFLAG_RW, &stat_indir_blk_ptrs, 0, "");
477SYSCTL_INT(_debug, OID_AUTO, inode_bitmap, CTLFLAG_RW, &stat_inode_bitmap, 0, "");
478SYSCTL_INT(_debug, OID_AUTO, direct_blk_ptrs, CTLFLAG_RW, &stat_direct_blk_ptrs, 0, "");
479SYSCTL_INT(_debug, OID_AUTO, dir_entry, CTLFLAG_RW, &stat_dir_entry, 0, "");
480#else /* !__FreeBSD__ */
481struct ctldebug debug20 = { "max_softdeps", &max_softdeps };
482struct ctldebug debug21 = { "tickdelay", &tickdelay };
483struct ctldebug debug23 = { "blk_limit_push", &stat_blk_limit_push };
484struct ctldebug debug24 = { "ino_limit_push", &stat_ino_limit_push };
485struct ctldebug debug25 = { "blk_limit_hit", &stat_blk_limit_hit };
486struct ctldebug debug26 = { "ino_limit_hit", &stat_ino_limit_hit };
487struct ctldebug debug27 = { "indir_blk_ptrs", &stat_indir_blk_ptrs };
488struct ctldebug debug28 = { "inode_bitmap", &stat_inode_bitmap };
489struct ctldebug debug29 = { "direct_blk_ptrs", &stat_direct_blk_ptrs };
490struct ctldebug debug30 = { "dir_entry", &stat_dir_entry };
491#endif	/* !__FreeBSD__ */
492
493#endif /* DEBUG */
494
495/*
496 * Add an item to the end of the work queue.
497 * This routine requires that the lock be held.
498 * This is the only routine that adds items to the list.
499 * The following routine is the only one that removes items
500 * and does so in order from first to last.
501 */
502static void
503add_to_worklist(wk)
504	struct worklist *wk;
505{
506	static struct worklist *worklist_tail;
507
508	if (wk->wk_state & ONWORKLIST)
509		panic("add_to_worklist: already on list");
510	wk->wk_state |= ONWORKLIST;
511	if (LIST_FIRST(&softdep_workitem_pending) == NULL)
512		LIST_INSERT_HEAD(&softdep_workitem_pending, wk, wk_list);
513	else
514		LIST_INSERT_AFTER(worklist_tail, wk, wk_list);
515	worklist_tail = wk;
516}
517
518/*
519 * Process that runs once per second to handle items in the background queue.
520 *
521 * Note that we ensure that everything is done in the order in which they
522 * appear in the queue. The code below depends on this property to ensure
523 * that blocks of a file are freed before the inode itself is freed. This
524 * ordering ensures that no new <vfsid, inum, lbn> triples will be generated
525 * until all the old ones have been purged from the dependency lists.
526 */
527int
528softdep_process_worklist(matchmnt)
529	struct mount *matchmnt;
530{
531	struct proc *p = CURPROC;
532	struct worklist *wk;
533	struct fs *matchfs;
534	int matchcnt;
535
536	/*
537	 * Record the process identifier of our caller so that we can give
538	 * this process preferential treatment in request_cleanup below.
539	 */
540	filesys_syncer = p;
541	matchcnt = 0;
542	matchfs = NULL;
543	if (matchmnt != NULL)
544		matchfs = VFSTOUFS(matchmnt)->um_fs;
545	/*
546	 * There is no danger of having multiple processes run this
547	 * code. It is single threaded solely so that softdep_flushfiles
548	 * (below) can get an accurate count of the number of items
549	 * related to its mount point that are in the list.
550	 */
551	if (softdep_worklist_busy && matchmnt == NULL)
552		return (-1);
553	/*
554	 * If requested, try removing inode or removal dependencies.
555	 */
556	if (req_clear_inodedeps) {
557		clear_inodedeps(p);
558		req_clear_inodedeps = 0;
559		wakeup(&proc_waiting);
560	}
561	if (req_clear_remove) {
562		clear_remove(p);
563		req_clear_remove = 0;
564		wakeup(&proc_waiting);
565	}
566	ACQUIRE_LOCK(&lk);
567	while ((wk = LIST_FIRST(&softdep_workitem_pending)) != 0) {
568		WORKLIST_REMOVE(wk);
569		FREE_LOCK(&lk);
570		switch (wk->wk_type) {
571
572		case D_DIRREM:
573			/* removal of a directory entry */
574			if (WK_DIRREM(wk)->dm_mnt == matchmnt)
575				matchcnt += 1;
576			handle_workitem_remove(WK_DIRREM(wk));
577			break;
578
579		case D_FREEBLKS:
580			/* releasing blocks and/or fragments from a file */
581			if (WK_FREEBLKS(wk)->fb_fs == matchfs)
582				matchcnt += 1;
583			handle_workitem_freeblocks(WK_FREEBLKS(wk));
584			break;
585
586		case D_FREEFRAG:
587			/* releasing a fragment when replaced as a file grows */
588			if (WK_FREEFRAG(wk)->ff_fs == matchfs)
589				matchcnt += 1;
590			handle_workitem_freefrag(WK_FREEFRAG(wk));
591			break;
592
593		case D_FREEFILE:
594			/* releasing an inode when its link count drops to 0 */
595			if (WK_FREEFILE(wk)->fx_fs == matchfs)
596				matchcnt += 1;
597			handle_workitem_freefile(WK_FREEFILE(wk));
598			break;
599
600		default:
601			panic("%s_process_worklist: Unknown type %s",
602			    "softdep", TYPENAME(wk->wk_type));
603			/* NOTREACHED */
604		}
605		if (softdep_worklist_busy && matchmnt == NULL)
606			return (-1);
607		/*
608		 * If requested, try removing inode or removal dependencies.
609		 */
610		if (req_clear_inodedeps) {
611			clear_inodedeps(p);
612			req_clear_inodedeps = 0;
613			wakeup(&proc_waiting);
614		}
615		if (req_clear_remove) {
616			clear_remove(p);
617			req_clear_remove = 0;
618			wakeup(&proc_waiting);
619		}
620		ACQUIRE_LOCK(&lk);
621	}
622	FREE_LOCK(&lk);
623	return (matchcnt);
624}
625
626/*
627 * Purge the work list of all items associated with a particular mount point.
628 */
629int
630softdep_flushfiles(oldmnt, flags, p)
631	struct mount *oldmnt;
632	int flags;
633	struct proc *p;
634{
635	struct vnode *devvp;
636	int error, loopcnt;
637
638	/*
639	 * Await our turn to clear out the queue.
640	 */
641	while (softdep_worklist_busy)
642		tsleep(&lbolt, PRIBIO, "softflush", 0);
643	softdep_worklist_busy = 1;
644	if ((error = ffs_flushfiles(oldmnt, flags, p)) != 0) {
645		softdep_worklist_busy = 0;
646		return (error);
647	}
648	/*
649	 * Alternately flush the block device associated with the mount
650	 * point and process any dependencies that the flushing
651	 * creates. In theory, this loop can happen at most twice,
652	 * but we give it a few extra just to be sure.
653	 */
654	devvp = VFSTOUFS(oldmnt)->um_devvp;
655	for (loopcnt = 10; loopcnt > 0; loopcnt--) {
656		if (softdep_process_worklist(oldmnt) == 0) {
657			/*
658			 * Do another flush in case any vnodes were brought in
659			 * as part of the cleanup operations.
660			 */
661			if ((error = ffs_flushfiles(oldmnt, flags, p)) != 0)
662				break;
663			/*
664			 * If we still found nothing to do, we are really done.
665			 */
666			if (softdep_process_worklist(oldmnt) == 0)
667				break;
668		}
669		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY, p);
670		error = VOP_FSYNC(devvp, p->p_ucred, MNT_WAIT, p);
671		VOP_UNLOCK(devvp, 0, p);
672		if (error)
673			break;
674	}
675	softdep_worklist_busy = 0;
676	/*
677	 * If we are unmounting then it is an error to fail. If we
678	 * are simply trying to downgrade to read-only, then filesystem
679	 * activity can keep us busy forever, so we just fail with EBUSY.
680	 */
681	if (loopcnt == 0) {
682		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT)
683			panic("softdep_flushfiles: looping");
684		error = EBUSY;
685	}
686	return (error);
687}
688
689/*
690 * Structure hashing.
691 *
692 * There are three types of structures that can be looked up:
693 *	1) pagedep structures identified by mount point, inode number,
694 *	   and logical block.
695 *	2) inodedep structures identified by mount point and inode number.
696 *	3) newblk structures identified by mount point and
697 *	   physical block number.
698 *
699 * The "pagedep" and "inodedep" dependency structures are hashed
700 * separately from the file blocks and inodes to which they correspond.
701 * This separation helps when the in-memory copy of an inode or
702 * file block must be replaced. It also obviates the need to access
703 * an inode or file page when simply updating (or de-allocating)
704 * dependency structures. Lookup of newblk structures is needed to
705 * find newly allocated blocks when trying to associate them with
706 * their allocdirect or allocindir structure.
707 *
708 * The lookup routines optionally create and hash a new instance when
709 * an existing entry is not found.
710 */
711#define DEPALLOC	0x0001	/* allocate structure if lookup fails */
712
713/*
714 * Structures and routines associated with pagedep caching.
715 */
716LIST_HEAD(pagedep_hashhead, pagedep) *pagedep_hashtbl;
717u_long	pagedep_hash;		/* size of hash table - 1 */
718#define	PAGEDEP_HASH(mp, inum, lbn) \
719	(&pagedep_hashtbl[((((register_t)(mp)) >> 13) + (inum) + (lbn)) & \
720	    pagedep_hash])
721static struct sema pagedep_in_progress;
722
723/*
724 * Look up a pagedep. Return 1 if found, 0 if not found.
725 * If not found, allocate if DEPALLOC flag is passed.
726 * Found or allocated entry is returned in pagedeppp.
727 * This routine must be called with splbio interrupts blocked.
728 */
729static int
730pagedep_lookup(ip, lbn, flags, pagedeppp)
731	struct inode *ip;
732	ufs_lbn_t lbn;
733	int flags;
734	struct pagedep **pagedeppp;
735{
736	struct pagedep *pagedep;
737	struct pagedep_hashhead *pagedephd;
738	struct mount *mp;
739	int i;
740
741#ifdef DEBUG
742	if (lk.lkt_held == -1)
743		panic("pagedep_lookup: lock not held");
744#endif
745	mp = ITOV(ip)->v_mount;
746	pagedephd = PAGEDEP_HASH(mp, ip->i_number, lbn);
747top:
748	for (pagedep = LIST_FIRST(pagedephd); pagedep;
749	     pagedep = LIST_NEXT(pagedep, pd_hash))
750		if (ip->i_number == pagedep->pd_ino &&
751		    lbn == pagedep->pd_lbn &&
752		    mp == pagedep->pd_mnt)
753			break;
754	if (pagedep) {
755		*pagedeppp = pagedep;
756		return (1);
757	}
758	if ((flags & DEPALLOC) == 0) {
759		*pagedeppp = NULL;
760		return (0);
761	}
762	if (sema_get(&pagedep_in_progress, &lk) == 0) {
763		ACQUIRE_LOCK(&lk);
764		goto top;
765	}
766	MALLOC(pagedep, struct pagedep *, sizeof(struct pagedep), M_PAGEDEP,
767		M_WAITOK);
768	bzero(pagedep, sizeof(struct pagedep));
769	pagedep->pd_list.wk_type = D_PAGEDEP;
770	pagedep->pd_mnt = mp;
771	pagedep->pd_ino = ip->i_number;
772	pagedep->pd_lbn = lbn;
773	LIST_INIT(&pagedep->pd_dirremhd);
774	LIST_INIT(&pagedep->pd_pendinghd);
775	for (i = 0; i < DAHASHSZ; i++)
776		LIST_INIT(&pagedep->pd_diraddhd[i]);
777	ACQUIRE_LOCK(&lk);
778	LIST_INSERT_HEAD(pagedephd, pagedep, pd_hash);
779	sema_release(&pagedep_in_progress);
780	*pagedeppp = pagedep;
781	return (0);
782}
783
784/*
785 * Structures and routines associated with inodedep caching.
786 */
787LIST_HEAD(inodedep_hashhead, inodedep) *inodedep_hashtbl;
788static u_long	inodedep_hash;	/* size of hash table - 1 */
789static long	num_inodedep;	/* number of inodedep allocated */
790#define	INODEDEP_HASH(fs, inum) \
791      (&inodedep_hashtbl[((((register_t)(fs)) >> 13) + (inum)) & inodedep_hash])
792static struct sema inodedep_in_progress;
793
794/*
795 * Look up a inodedep. Return 1 if found, 0 if not found.
796 * If not found, allocate if DEPALLOC flag is passed.
797 * Found or allocated entry is returned in inodedeppp.
798 * This routine must be called with splbio interrupts blocked.
799 */
800static int
801inodedep_lookup(fs, inum, flags, inodedeppp)
802	struct fs *fs;
803	ino_t inum;
804	int flags;
805	struct inodedep **inodedeppp;
806{
807	struct inodedep *inodedep;
808	struct inodedep_hashhead *inodedephd;
809	int firsttry;
810
811#ifdef DEBUG
812	if (lk.lkt_held == -1)
813		panic("inodedep_lookup: lock not held");
814#endif
815	firsttry = 1;
816	inodedephd = INODEDEP_HASH(fs, inum);
817top:
818	for (inodedep = LIST_FIRST(inodedephd); inodedep;
819	     inodedep = LIST_NEXT(inodedep, id_hash))
820		if (inum == inodedep->id_ino && fs == inodedep->id_fs)
821			break;
822	if (inodedep) {
823		*inodedeppp = inodedep;
824		return (1);
825	}
826	if ((flags & DEPALLOC) == 0) {
827		*inodedeppp = NULL;
828		return (0);
829	}
830	/*
831	 * If we are over our limit, try to improve the situation.
832	 */
833	if (num_inodedep > max_softdeps && firsttry && speedup_syncer() == 0 &&
834	    request_cleanup(FLUSH_INODES, 1)) {
835		firsttry = 0;
836		goto top;
837	}
838	if (sema_get(&inodedep_in_progress, &lk) == 0) {
839		ACQUIRE_LOCK(&lk);
840		goto top;
841	}
842	num_inodedep += 1;
843	MALLOC(inodedep, struct inodedep *, sizeof(struct inodedep),
844		M_INODEDEP, M_WAITOK);
845	inodedep->id_list.wk_type = D_INODEDEP;
846	inodedep->id_fs = fs;
847	inodedep->id_ino = inum;
848	inodedep->id_state = ALLCOMPLETE;
849	inodedep->id_nlinkdelta = 0;
850	inodedep->id_savedino = NULL;
851	inodedep->id_savedsize = -1;
852	inodedep->id_buf = NULL;
853	LIST_INIT(&inodedep->id_pendinghd);
854	LIST_INIT(&inodedep->id_inowait);
855	LIST_INIT(&inodedep->id_bufwait);
856	TAILQ_INIT(&inodedep->id_inoupdt);
857	TAILQ_INIT(&inodedep->id_newinoupdt);
858	ACQUIRE_LOCK(&lk);
859	LIST_INSERT_HEAD(inodedephd, inodedep, id_hash);
860	sema_release(&inodedep_in_progress);
861	*inodedeppp = inodedep;
862	return (0);
863}
864
865/*
866 * Structures and routines associated with newblk caching.
867 */
868LIST_HEAD(newblk_hashhead, newblk) *newblk_hashtbl;
869u_long	newblk_hash;		/* size of hash table - 1 */
870#define	NEWBLK_HASH(fs, inum) \
871	(&newblk_hashtbl[((((register_t)(fs)) >> 13) + (inum)) & newblk_hash])
872static struct sema newblk_in_progress;
873
874/*
875 * Look up a newblk. Return 1 if found, 0 if not found.
876 * If not found, allocate if DEPALLOC flag is passed.
877 * Found or allocated entry is returned in newblkpp.
878 */
879static int
880newblk_lookup(fs, newblkno, flags, newblkpp)
881	struct fs *fs;
882	ufs_daddr_t newblkno;
883	int flags;
884	struct newblk **newblkpp;
885{
886	struct newblk *newblk;
887	struct newblk_hashhead *newblkhd;
888
889	newblkhd = NEWBLK_HASH(fs, newblkno);
890top:
891	for (newblk = LIST_FIRST(newblkhd); newblk;
892	     newblk = LIST_NEXT(newblk, nb_hash))
893		if (newblkno == newblk->nb_newblkno && fs == newblk->nb_fs)
894			break;
895	if (newblk) {
896		*newblkpp = newblk;
897		return (1);
898	}
899	if ((flags & DEPALLOC) == 0) {
900		*newblkpp = NULL;
901		return (0);
902	}
903	if (sema_get(&newblk_in_progress, 0) == 0)
904		goto top;
905	MALLOC(newblk, struct newblk *, sizeof(struct newblk),
906		M_NEWBLK, M_WAITOK);
907	newblk->nb_state = 0;
908	newblk->nb_fs = fs;
909	newblk->nb_newblkno = newblkno;
910	LIST_INSERT_HEAD(newblkhd, newblk, nb_hash);
911	sema_release(&newblk_in_progress);
912	*newblkpp = newblk;
913	return (0);
914}
915
916/*
917 * Executed during filesystem system initialization before
918 * mounting any file systems.
919 */
920void
921softdep_initialize()
922{
923
924	LIST_INIT(&mkdirlisthd);
925	LIST_INIT(&softdep_workitem_pending);
926	max_softdeps = desiredvnodes * 8;
927	pagedep_hashtbl = hashinit(desiredvnodes / 5, M_PAGEDEP,
928	    &pagedep_hash);
929	sema_init(&pagedep_in_progress, "pagedep", PRIBIO, 0);
930	inodedep_hashtbl = hashinit(desiredvnodes, M_INODEDEP, &inodedep_hash);
931	sema_init(&inodedep_in_progress, "inodedep", PRIBIO, 0);
932	newblk_hashtbl = hashinit(64, M_NEWBLK, &newblk_hash);
933	sema_init(&newblk_in_progress, "newblk", PRIBIO, 0);
934}
935
936/*
937 * Called at mount time to notify the dependency code that a
938 * filesystem wishes to use it.
939 */
940int
941softdep_mount(devvp, mp, fs, cred)
942	struct vnode *devvp;
943	struct mount *mp;
944	struct fs *fs;
945	struct ucred *cred;
946{
947	struct csum cstotal;
948	struct cg *cgp;
949	struct buf *bp;
950	int error, cyl;
951
952	mp->mnt_flag &= ~MNT_ASYNC;
953	mp->mnt_flag |= MNT_SOFTDEP;
954	/*
955	 * When doing soft updates, the counters in the
956	 * superblock may have gotten out of sync, so we have
957	 * to scan the cylinder groups and recalculate them.
958	 */
959	if (fs->fs_clean != 0)
960		return (0);
961	bzero(&cstotal, sizeof cstotal);
962	for (cyl = 0; cyl < fs->fs_ncg; cyl++) {
963		if ((error = bread(devvp, fsbtodb(fs, cgtod(fs, cyl)),
964		    fs->fs_cgsize, cred, &bp)) != 0) {
965			brelse(bp);
966			return (error);
967		}
968		cgp = (struct cg *)bp->b_data;
969		cstotal.cs_nffree += cgp->cg_cs.cs_nffree;
970		cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree;
971		cstotal.cs_nifree += cgp->cg_cs.cs_nifree;
972		cstotal.cs_ndir += cgp->cg_cs.cs_ndir;
973		fs->fs_cs(fs, cyl) = cgp->cg_cs;
974		brelse(bp);
975	}
976#ifdef DEBUG
977	if (bcmp(&cstotal, &fs->fs_cstotal, sizeof cstotal))
978		printf("ffs_mountfs: superblock updated for soft updates\n");
979#endif
980	bcopy(&cstotal, &fs->fs_cstotal, sizeof cstotal);
981	return (0);
982}
983
984/*
985 * Protecting the freemaps (or bitmaps).
986 *
987 * To eliminate the need to execute fsck before mounting a file system
988 * after a power failure, one must (conservatively) guarantee that the
989 * on-disk copy of the bitmaps never indicate that a live inode or block is
990 * free.  So, when a block or inode is allocated, the bitmap should be
991 * updated (on disk) before any new pointers.  When a block or inode is
992 * freed, the bitmap should not be updated until all pointers have been
993 * reset.  The latter dependency is handled by the delayed de-allocation
994 * approach described below for block and inode de-allocation.  The former
995 * dependency is handled by calling the following procedure when a block or
996 * inode is allocated. When an inode is allocated an "inodedep" is created
997 * with its DEPCOMPLETE flag cleared until its bitmap is written to disk.
998 * Each "inodedep" is also inserted into the hash indexing structure so
999 * that any additional link additions can be made dependent on the inode
1000 * allocation.
1001 *
1002 * The ufs file system maintains a number of free block counts (e.g., per
1003 * cylinder group, per cylinder and per <cylinder, rotational position> pair)
1004 * in addition to the bitmaps.  These counts are used to improve efficiency
1005 * during allocation and therefore must be consistent with the bitmaps.
1006 * There is no convenient way to guarantee post-crash consistency of these
1007 * counts with simple update ordering, for two main reasons: (1) The counts
1008 * and bitmaps for a single cylinder group block are not in the same disk
1009 * sector.  If a disk write is interrupted (e.g., by power failure), one may
1010 * be written and the other not.  (2) Some of the counts are located in the
1011 * superblock rather than the cylinder group block. So, we focus our soft
1012 * updates implementation on protecting the bitmaps. When mounting a
1013 * filesystem, we recompute the auxiliary counts from the bitmaps.
1014 */
1015
1016/*
1017 * Called just after updating the cylinder group block to allocate an inode.
1018 */
1019void
1020softdep_setup_inomapdep(bp, ip, newinum)
1021	struct buf *bp;		/* buffer for cylgroup block with inode map */
1022	struct inode *ip;	/* inode related to allocation */
1023	ino_t newinum;		/* new inode number being allocated */
1024{
1025	struct inodedep *inodedep;
1026	struct bmsafemap *bmsafemap;
1027
1028	/*
1029	 * Create a dependency for the newly allocated inode.
1030	 * Panic if it already exists as something is seriously wrong.
1031	 * Otherwise add it to the dependency list for the buffer holding
1032	 * the cylinder group map from which it was allocated.
1033	 */
1034	ACQUIRE_LOCK(&lk);
1035	if (inodedep_lookup(ip->i_fs, newinum, DEPALLOC, &inodedep) != 0)
1036		panic("softdep_setup_inomapdep: found inode");
1037	inodedep->id_buf = bp;
1038	inodedep->id_state &= ~DEPCOMPLETE;
1039	bmsafemap = bmsafemap_lookup(bp);
1040	LIST_INSERT_HEAD(&bmsafemap->sm_inodedephd, inodedep, id_deps);
1041	FREE_LOCK(&lk);
1042}
1043
1044/*
1045 * Called just after updating the cylinder group block to
1046 * allocate block or fragment.
1047 */
1048void
1049softdep_setup_blkmapdep(bp, fs, newblkno)
1050	struct buf *bp;		/* buffer for cylgroup block with block map */
1051	struct fs *fs;		/* filesystem doing allocation */
1052	ufs_daddr_t newblkno;	/* number of newly allocated block */
1053{
1054	struct newblk *newblk;
1055	struct bmsafemap *bmsafemap;
1056
1057	/*
1058	 * Create a dependency for the newly allocated block.
1059	 * Add it to the dependency list for the buffer holding
1060	 * the cylinder group map from which it was allocated.
1061	 */
1062	if (newblk_lookup(fs, newblkno, DEPALLOC, &newblk) != 0)
1063		panic("softdep_setup_blkmapdep: found block");
1064	ACQUIRE_LOCK(&lk);
1065	newblk->nb_bmsafemap = bmsafemap = bmsafemap_lookup(bp);
1066	LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
1067	FREE_LOCK(&lk);
1068}
1069
1070/*
1071 * Find the bmsafemap associated with a cylinder group buffer.
1072 * If none exists, create one. The buffer must be locked when
1073 * this routine is called and this routine must be called with
1074 * splbio interrupts blocked.
1075 */
1076static struct bmsafemap *
1077bmsafemap_lookup(bp)
1078	struct buf *bp;
1079{
1080	struct bmsafemap *bmsafemap;
1081	struct worklist *wk;
1082
1083#ifdef DEBUG
1084	if (lk.lkt_held == -1)
1085		panic("bmsafemap_lookup: lock not held");
1086#endif
1087	for (wk = LIST_FIRST(&bp->b_dep); wk; wk = LIST_NEXT(wk, wk_list))
1088		if (wk->wk_type == D_BMSAFEMAP)
1089			return (WK_BMSAFEMAP(wk));
1090	FREE_LOCK(&lk);
1091	MALLOC(bmsafemap, struct bmsafemap *, sizeof(struct bmsafemap),
1092		M_BMSAFEMAP, M_WAITOK);
1093	bmsafemap->sm_list.wk_type = D_BMSAFEMAP;
1094	bmsafemap->sm_list.wk_state = 0;
1095	bmsafemap->sm_buf = bp;
1096	LIST_INIT(&bmsafemap->sm_allocdirecthd);
1097	LIST_INIT(&bmsafemap->sm_allocindirhd);
1098	LIST_INIT(&bmsafemap->sm_inodedephd);
1099	LIST_INIT(&bmsafemap->sm_newblkhd);
1100	ACQUIRE_LOCK(&lk);
1101	WORKLIST_INSERT(&bp->b_dep, &bmsafemap->sm_list);
1102	return (bmsafemap);
1103}
1104
1105/*
1106 * Direct block allocation dependencies.
1107 *
1108 * When a new block is allocated, the corresponding disk locations must be
1109 * initialized (with zeros or new data) before the on-disk inode points to
1110 * them.  Also, the freemap from which the block was allocated must be
1111 * updated (on disk) before the inode's pointer. These two dependencies are
1112 * independent of each other and are needed for all file blocks and indirect
1113 * blocks that are pointed to directly by the inode.  Just before the
1114 * "in-core" version of the inode is updated with a newly allocated block
1115 * number, a procedure (below) is called to setup allocation dependency
1116 * structures.  These structures are removed when the corresponding
1117 * dependencies are satisfied or when the block allocation becomes obsolete
1118 * (i.e., the file is deleted, the block is de-allocated, or the block is a
1119 * fragment that gets upgraded).  All of these cases are handled in
1120 * procedures described later.
1121 *
1122 * When a file extension causes a fragment to be upgraded, either to a larger
1123 * fragment or to a full block, the on-disk location may change (if the
1124 * previous fragment could not simply be extended). In this case, the old
1125 * fragment must be de-allocated, but not until after the inode's pointer has
1126 * been updated. In most cases, this is handled by later procedures, which
1127 * will construct a "freefrag" structure to be added to the workitem queue
1128 * when the inode update is complete (or obsolete).  The main exception to
1129 * this is when an allocation occurs while a pending allocation dependency
1130 * (for the same block pointer) remains.  This case is handled in the main
1131 * allocation dependency setup procedure by immediately freeing the
1132 * unreferenced fragments.
1133 */
1134void
1135softdep_setup_allocdirect(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
1136	struct inode *ip;	/* inode to which block is being added */
1137	ufs_lbn_t lbn;		/* block pointer within inode */
1138	ufs_daddr_t newblkno;	/* disk block number being added */
1139	ufs_daddr_t oldblkno;	/* previous block number, 0 unless frag */
1140	long newsize;		/* size of new block */
1141	long oldsize;		/* size of new block */
1142	struct buf *bp;		/* bp for allocated block */
1143{
1144	struct allocdirect *adp, *oldadp;
1145	struct allocdirectlst *adphead;
1146	struct bmsafemap *bmsafemap;
1147	struct inodedep *inodedep;
1148	struct pagedep *pagedep;
1149	struct newblk *newblk;
1150
1151	MALLOC(adp, struct allocdirect *, sizeof(struct allocdirect),
1152		M_ALLOCDIRECT, M_WAITOK);
1153	bzero(adp, sizeof(struct allocdirect));
1154	adp->ad_list.wk_type = D_ALLOCDIRECT;
1155	adp->ad_lbn = lbn;
1156	adp->ad_newblkno = newblkno;
1157	adp->ad_oldblkno = oldblkno;
1158	adp->ad_newsize = newsize;
1159	adp->ad_oldsize = oldsize;
1160	adp->ad_state = ATTACHED;
1161	if (newblkno == oldblkno)
1162		adp->ad_freefrag = NULL;
1163	else
1164		adp->ad_freefrag = newfreefrag(ip, oldblkno, oldsize);
1165
1166	if (newblk_lookup(ip->i_fs, newblkno, 0, &newblk) == 0)
1167		panic("softdep_setup_allocdirect: lost block");
1168
1169	ACQUIRE_LOCK(&lk);
1170	(void) inodedep_lookup(ip->i_fs, ip->i_number, DEPALLOC, &inodedep);
1171	adp->ad_inodedep = inodedep;
1172
1173	if (newblk->nb_state == DEPCOMPLETE) {
1174		adp->ad_state |= DEPCOMPLETE;
1175		adp->ad_buf = NULL;
1176	} else {
1177		bmsafemap = newblk->nb_bmsafemap;
1178		adp->ad_buf = bmsafemap->sm_buf;
1179		LIST_REMOVE(newblk, nb_deps);
1180		LIST_INSERT_HEAD(&bmsafemap->sm_allocdirecthd, adp, ad_deps);
1181	}
1182	LIST_REMOVE(newblk, nb_hash);
1183	FREE(newblk, M_NEWBLK);
1184
1185	WORKLIST_INSERT(&bp->b_dep, &adp->ad_list);
1186	if (lbn >= NDADDR) {
1187		/* allocating an indirect block */
1188		if (oldblkno != 0)
1189			panic("softdep_setup_allocdirect: non-zero indir");
1190	} else {
1191		/*
1192		 * Allocating a direct block.
1193		 *
1194		 * If we are allocating a directory block, then we must
1195		 * allocate an associated pagedep to track additions and
1196		 * deletions.
1197		 */
1198		if ((ip->i_mode & IFMT) == IFDIR &&
1199		    pagedep_lookup(ip, lbn, DEPALLOC, &pagedep) == 0)
1200			WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
1201	}
1202	/*
1203	 * The list of allocdirects must be kept in sorted and ascending
1204	 * order so that the rollback routines can quickly determine the
1205	 * first uncommitted block (the size of the file stored on disk
1206	 * ends at the end of the lowest committed fragment, or if there
1207	 * are no fragments, at the end of the highest committed block).
1208	 * Since files generally grow, the typical case is that the new
1209	 * block is to be added at the end of the list. We speed this
1210	 * special case by checking against the last allocdirect in the
1211	 * list before laboriously traversing the list looking for the
1212	 * insertion point.
1213	 */
1214	adphead = &inodedep->id_newinoupdt;
1215	oldadp = TAILQ_LAST(adphead, allocdirectlst);
1216	if (oldadp == NULL || oldadp->ad_lbn <= lbn) {
1217		/* insert at end of list */
1218		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
1219		if (oldadp != NULL && oldadp->ad_lbn == lbn)
1220			allocdirect_merge(adphead, adp, oldadp);
1221		FREE_LOCK(&lk);
1222		return;
1223	}
1224	for (oldadp = TAILQ_FIRST(adphead); oldadp;
1225	     oldadp = TAILQ_NEXT(oldadp, ad_next)) {
1226		if (oldadp->ad_lbn >= lbn)
1227			break;
1228	}
1229	if (oldadp == NULL)
1230		panic("softdep_setup_allocdirect: lost entry");
1231	/* insert in middle of list */
1232	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
1233	if (oldadp->ad_lbn == lbn)
1234		allocdirect_merge(adphead, adp, oldadp);
1235	FREE_LOCK(&lk);
1236}
1237
1238/*
1239 * Replace an old allocdirect dependency with a newer one.
1240 * This routine must be called with splbio interrupts blocked.
1241 */
1242static void
1243allocdirect_merge(adphead, newadp, oldadp)
1244	struct allocdirectlst *adphead;	/* head of list holding allocdirects */
1245	struct allocdirect *newadp;	/* allocdirect being added */
1246	struct allocdirect *oldadp;	/* existing allocdirect being checked */
1247{
1248	struct freefrag *freefrag;
1249
1250#ifdef DEBUG
1251	if (lk.lkt_held == -1)
1252		panic("allocdirect_merge: lock not held");
1253#endif
1254	if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
1255	    newadp->ad_oldsize != oldadp->ad_newsize ||
1256	    newadp->ad_lbn >= NDADDR)
1257		panic("allocdirect_check: old %d != new %d || lbn %ld >= %d",
1258		    newadp->ad_oldblkno, oldadp->ad_newblkno, newadp->ad_lbn,
1259		    NDADDR);
1260	newadp->ad_oldblkno = oldadp->ad_oldblkno;
1261	newadp->ad_oldsize = oldadp->ad_oldsize;
1262	/*
1263	 * If the old dependency had a fragment to free or had never
1264	 * previously had a block allocated, then the new dependency
1265	 * can immediately post its freefrag and adopt the old freefrag.
1266	 * This action is done by swapping the freefrag dependencies.
1267	 * The new dependency gains the old one's freefrag, and the
1268	 * old one gets the new one and then immediately puts it on
1269	 * the worklist when it is freed by free_allocdirect. It is
1270	 * not possible to do this swap when the old dependency had a
1271	 * non-zero size but no previous fragment to free. This condition
1272	 * arises when the new block is an extension of the old block.
1273	 * Here, the first part of the fragment allocated to the new
1274	 * dependency is part of the block currently claimed on disk by
1275	 * the old dependency, so cannot legitimately be freed until the
1276	 * conditions for the new dependency are fulfilled.
1277	 */
1278	if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
1279		freefrag = newadp->ad_freefrag;
1280		newadp->ad_freefrag = oldadp->ad_freefrag;
1281		oldadp->ad_freefrag = freefrag;
1282	}
1283	free_allocdirect(adphead, oldadp, 0);
1284}
1285
1286/*
1287 * Allocate a new freefrag structure if needed.
1288 */
1289static struct freefrag *
1290newfreefrag(ip, blkno, size)
1291	struct inode *ip;
1292	ufs_daddr_t blkno;
1293	long size;
1294{
1295	struct freefrag *freefrag;
1296	struct fs *fs;
1297
1298	if (blkno == 0)
1299		return (NULL);
1300	fs = ip->i_fs;
1301	if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
1302		panic("newfreefrag: frag size");
1303	MALLOC(freefrag, struct freefrag *, sizeof(struct freefrag),
1304		M_FREEFRAG, M_WAITOK);
1305	freefrag->ff_list.wk_type = D_FREEFRAG;
1306	freefrag->ff_state = ip->i_uid & ~ONWORKLIST;	/* XXX - used below */
1307	freefrag->ff_inum = ip->i_number;
1308	freefrag->ff_fs = fs;
1309	freefrag->ff_devvp = ip->i_devvp;
1310	freefrag->ff_blkno = blkno;
1311	freefrag->ff_fragsize = size;
1312	return (freefrag);
1313}
1314
1315/*
1316 * This workitem de-allocates fragments that were replaced during
1317 * file block allocation.
1318 */
1319static void
1320handle_workitem_freefrag(freefrag)
1321	struct freefrag *freefrag;
1322{
1323	struct inode tip;
1324
1325	tip.i_fs = freefrag->ff_fs;
1326	tip.i_devvp = freefrag->ff_devvp;
1327	tip.i_dev = freefrag->ff_devvp->v_rdev;
1328	tip.i_number = freefrag->ff_inum;
1329	tip.i_uid = freefrag->ff_state & ~ONWORKLIST;	/* XXX - set above */
1330	ffs_blkfree(&tip, freefrag->ff_blkno, freefrag->ff_fragsize);
1331	FREE(freefrag, M_FREEFRAG);
1332}
1333
1334/*
1335 * Indirect block allocation dependencies.
1336 *
1337 * The same dependencies that exist for a direct block also exist when
1338 * a new block is allocated and pointed to by an entry in a block of
1339 * indirect pointers. The undo/redo states described above are also
1340 * used here. Because an indirect block contains many pointers that
1341 * may have dependencies, a second copy of the entire in-memory indirect
1342 * block is kept. The buffer cache copy is always completely up-to-date.
1343 * The second copy, which is used only as a source for disk writes,
1344 * contains only the safe pointers (i.e., those that have no remaining
1345 * update dependencies). The second copy is freed when all pointers
1346 * are safe. The cache is not allowed to replace indirect blocks with
1347 * pending update dependencies. If a buffer containing an indirect
1348 * block with dependencies is written, these routines will mark it
1349 * dirty again. It can only be successfully written once all the
1350 * dependencies are removed. The ffs_fsync routine in conjunction with
1351 * softdep_sync_metadata work together to get all the dependencies
1352 * removed so that a file can be successfully written to disk. Three
1353 * procedures are used when setting up indirect block pointer
1354 * dependencies. The division is necessary because of the organization
1355 * of the "balloc" routine and because of the distinction between file
1356 * pages and file metadata blocks.
1357 */
1358
1359/*
1360 * Allocate a new allocindir structure.
1361 */
1362static struct allocindir *
1363newallocindir(ip, ptrno, newblkno, oldblkno)
1364	struct inode *ip;	/* inode for file being extended */
1365	int ptrno;		/* offset of pointer in indirect block */
1366	ufs_daddr_t newblkno;	/* disk block number being added */
1367	ufs_daddr_t oldblkno;	/* previous block number, 0 if none */
1368{
1369	struct allocindir *aip;
1370
1371	MALLOC(aip, struct allocindir *, sizeof(struct allocindir),
1372		M_ALLOCINDIR, M_WAITOK);
1373	bzero(aip, sizeof(struct allocindir));
1374	aip->ai_list.wk_type = D_ALLOCINDIR;
1375	aip->ai_state = ATTACHED;
1376	aip->ai_offset = ptrno;
1377	aip->ai_newblkno = newblkno;
1378	aip->ai_oldblkno = oldblkno;
1379	aip->ai_freefrag = newfreefrag(ip, oldblkno, ip->i_fs->fs_bsize);
1380	return (aip);
1381}
1382
1383/*
1384 * Called just before setting an indirect block pointer
1385 * to a newly allocated file page.
1386 */
1387void
1388softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
1389	struct inode *ip;	/* inode for file being extended */
1390	ufs_lbn_t lbn;		/* allocated block number within file */
1391	struct buf *bp;		/* buffer with indirect blk referencing page */
1392	int ptrno;		/* offset of pointer in indirect block */
1393	ufs_daddr_t newblkno;	/* disk block number being added */
1394	ufs_daddr_t oldblkno;	/* previous block number, 0 if none */
1395	struct buf *nbp;	/* buffer holding allocated page */
1396{
1397	struct allocindir *aip;
1398	struct pagedep *pagedep;
1399
1400	aip = newallocindir(ip, ptrno, newblkno, oldblkno);
1401	ACQUIRE_LOCK(&lk);
1402	/*
1403	 * If we are allocating a directory page, then we must
1404	 * allocate an associated pagedep to track additions and
1405	 * deletions.
1406	 */
1407	if ((ip->i_mode & IFMT) == IFDIR &&
1408	    pagedep_lookup(ip, lbn, DEPALLOC, &pagedep) == 0)
1409		WORKLIST_INSERT(&nbp->b_dep, &pagedep->pd_list);
1410	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_list);
1411	FREE_LOCK(&lk);
1412	setup_allocindir_phase2(bp, ip, aip);
1413}
1414
1415/*
1416 * Called just before setting an indirect block pointer to a
1417 * newly allocated indirect block.
1418 */
1419void
1420softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
1421	struct buf *nbp;	/* newly allocated indirect block */
1422	struct inode *ip;	/* inode for file being extended */
1423	struct buf *bp;		/* indirect block referencing allocated block */
1424	int ptrno;		/* offset of pointer in indirect block */
1425	ufs_daddr_t newblkno;	/* disk block number being added */
1426{
1427	struct allocindir *aip;
1428
1429	aip = newallocindir(ip, ptrno, newblkno, 0);
1430	ACQUIRE_LOCK(&lk);
1431	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_list);
1432	FREE_LOCK(&lk);
1433	setup_allocindir_phase2(bp, ip, aip);
1434}
1435
1436/*
1437 * Called to finish the allocation of the "aip" allocated
1438 * by one of the two routines above.
1439 */
1440static void
1441setup_allocindir_phase2(bp, ip, aip)
1442	struct buf *bp;		/* in-memory copy of the indirect block */
1443	struct inode *ip;	/* inode for file being extended */
1444	struct allocindir *aip;	/* allocindir allocated by the above routines */
1445{
1446	struct worklist *wk;
1447	struct indirdep *indirdep, *newindirdep;
1448	struct bmsafemap *bmsafemap;
1449	struct allocindir *oldaip;
1450	struct freefrag *freefrag;
1451	struct newblk *newblk;
1452
1453	if (bp->b_lblkno >= 0)
1454		panic("setup_allocindir_phase2: not indir blk");
1455	for (indirdep = NULL, newindirdep = NULL; ; ) {
1456		ACQUIRE_LOCK(&lk);
1457		for (wk = LIST_FIRST(&bp->b_dep); wk;
1458		     wk = LIST_NEXT(wk, wk_list)) {
1459			if (wk->wk_type != D_INDIRDEP)
1460				continue;
1461			indirdep = WK_INDIRDEP(wk);
1462			break;
1463		}
1464		if (indirdep == NULL && newindirdep) {
1465			indirdep = newindirdep;
1466			WORKLIST_INSERT(&bp->b_dep, &indirdep->ir_list);
1467			newindirdep = NULL;
1468		}
1469		FREE_LOCK(&lk);
1470		if (indirdep) {
1471			if (newblk_lookup(ip->i_fs, aip->ai_newblkno, 0,
1472			    &newblk) == 0)
1473				panic("setup_allocindir: lost block");
1474			ACQUIRE_LOCK(&lk);
1475			if (newblk->nb_state == DEPCOMPLETE) {
1476				aip->ai_state |= DEPCOMPLETE;
1477				aip->ai_buf = NULL;
1478			} else {
1479				bmsafemap = newblk->nb_bmsafemap;
1480				aip->ai_buf = bmsafemap->sm_buf;
1481				LIST_REMOVE(newblk, nb_deps);
1482				LIST_INSERT_HEAD(&bmsafemap->sm_allocindirhd,
1483				    aip, ai_deps);
1484			}
1485			LIST_REMOVE(newblk, nb_hash);
1486			FREE(newblk, M_NEWBLK);
1487			aip->ai_indirdep = indirdep;
1488			/*
1489			 * Check to see if there is an existing dependency
1490			 * for this block. If there is, merge the old
1491			 * dependency into the new one.
1492			 */
1493			if (aip->ai_oldblkno == 0)
1494				oldaip = NULL;
1495			else
1496				for (oldaip=LIST_FIRST(&indirdep->ir_deplisthd);
1497				    oldaip; oldaip = LIST_NEXT(oldaip, ai_next))
1498					if (oldaip->ai_offset == aip->ai_offset)
1499						break;
1500			if (oldaip != NULL) {
1501				if (oldaip->ai_newblkno != aip->ai_oldblkno)
1502					panic("setup_allocindir_phase2: blkno");
1503				aip->ai_oldblkno = oldaip->ai_oldblkno;
1504				freefrag = oldaip->ai_freefrag;
1505				oldaip->ai_freefrag = aip->ai_freefrag;
1506				aip->ai_freefrag = freefrag;
1507				free_allocindir(oldaip, NULL);
1508			}
1509			LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
1510			((ufs_daddr_t *)indirdep->ir_savebp->b_data)
1511			    [aip->ai_offset] = aip->ai_oldblkno;
1512			FREE_LOCK(&lk);
1513		}
1514		if (newindirdep) {
1515			if (indirdep->ir_savebp != NULL)
1516				brelse(newindirdep->ir_savebp);
1517			WORKITEM_FREE((caddr_t)newindirdep, D_INDIRDEP);
1518		}
1519		if (indirdep)
1520			break;
1521		MALLOC(newindirdep, struct indirdep *, sizeof(struct indirdep),
1522			M_INDIRDEP, M_WAITOK);
1523		newindirdep->ir_list.wk_type = D_INDIRDEP;
1524		newindirdep->ir_state = ATTACHED;
1525		LIST_INIT(&newindirdep->ir_deplisthd);
1526		LIST_INIT(&newindirdep->ir_donehd);
1527		if (bp->b_blkno == bp->b_lblkno) {
1528			VOP_BMAP(bp->b_vp, bp->b_lblkno, NULL, &bp->b_blkno,
1529				NULL, NULL);
1530		}
1531		newindirdep->ir_savebp =
1532		    getblk(ip->i_devvp, bp->b_blkno, bp->b_bcount, 0, 0);
1533		newindirdep->ir_savebp->b_flags |= B_ASYNC;
1534		BUF_KERNPROC(newindirdep->ir_savebp);
1535		bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
1536	}
1537}
1538
1539/*
1540 * Block de-allocation dependencies.
1541 *
1542 * When blocks are de-allocated, the on-disk pointers must be nullified before
1543 * the blocks are made available for use by other files.  (The true
1544 * requirement is that old pointers must be nullified before new on-disk
1545 * pointers are set.  We chose this slightly more stringent requirement to
1546 * reduce complexity.) Our implementation handles this dependency by updating
1547 * the inode (or indirect block) appropriately but delaying the actual block
1548 * de-allocation (i.e., freemap and free space count manipulation) until
1549 * after the updated versions reach stable storage.  After the disk is
1550 * updated, the blocks can be safely de-allocated whenever it is convenient.
1551 * This implementation handles only the common case of reducing a file's
1552 * length to zero. Other cases are handled by the conventional synchronous
1553 * write approach.
1554 *
1555 * The ffs implementation with which we worked double-checks
1556 * the state of the block pointers and file size as it reduces
1557 * a file's length.  Some of this code is replicated here in our
1558 * soft updates implementation.  The freeblks->fb_chkcnt field is
1559 * used to transfer a part of this information to the procedure
1560 * that eventually de-allocates the blocks.
1561 *
1562 * This routine should be called from the routine that shortens
1563 * a file's length, before the inode's size or block pointers
1564 * are modified. It will save the block pointer information for
1565 * later release and zero the inode so that the calling routine
1566 * can release it.
1567 */
1568static long num_freeblks;	/* number of freeblks allocated */
1569void
1570softdep_setup_freeblocks(ip, length)
1571	struct inode *ip;	/* The inode whose length is to be reduced */
1572	off_t length;		/* The new length for the file */
1573{
1574	struct freeblks *freeblks;
1575	struct inodedep *inodedep;
1576	struct allocdirect *adp;
1577	struct vnode *vp;
1578	struct buf *bp;
1579	struct fs *fs;
1580	int i, error;
1581
1582	fs = ip->i_fs;
1583	if (length != 0)
1584		panic("softde_setup_freeblocks: non-zero length");
1585	/*
1586	 * If we are over our limit, try to improve the situation.
1587	 */
1588	if (num_freeblks > max_softdeps / 2 && speedup_syncer() == 0)
1589		(void) request_cleanup(FLUSH_REMOVE, 0);
1590	num_freeblks += 1;
1591	MALLOC(freeblks, struct freeblks *, sizeof(struct freeblks),
1592		M_FREEBLKS, M_WAITOK);
1593	bzero(freeblks, sizeof(struct freeblks));
1594	freeblks->fb_list.wk_type = D_FREEBLKS;
1595	freeblks->fb_uid = ip->i_uid;
1596	freeblks->fb_previousinum = ip->i_number;
1597	freeblks->fb_devvp = ip->i_devvp;
1598	freeblks->fb_fs = fs;
1599	freeblks->fb_oldsize = ip->i_size;
1600	freeblks->fb_newsize = length;
1601	freeblks->fb_chkcnt = ip->i_blocks;
1602	for (i = 0; i < NDADDR; i++) {
1603		freeblks->fb_dblks[i] = ip->i_db[i];
1604		ip->i_db[i] = 0;
1605	}
1606	for (i = 0; i < NIADDR; i++) {
1607		freeblks->fb_iblks[i] = ip->i_ib[i];
1608		ip->i_ib[i] = 0;
1609	}
1610	ip->i_blocks = 0;
1611	ip->i_size = 0;
1612	/*
1613	 * Push the zero'ed inode to to its disk buffer so that we are free
1614	 * to delete its dependencies below. Once the dependencies are gone
1615	 * the buffer can be safely released.
1616	 */
1617	if ((error = bread(ip->i_devvp,
1618	    fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
1619	    (int)fs->fs_bsize, NOCRED, &bp)) != 0)
1620		softdep_error("softdep_setup_freeblocks", error);
1621	*((struct dinode *)bp->b_data + ino_to_fsbo(fs, ip->i_number)) =
1622	    ip->i_din;
1623	/*
1624	 * Find and eliminate any inode dependencies.
1625	 */
1626	ACQUIRE_LOCK(&lk);
1627	(void) inodedep_lookup(fs, ip->i_number, DEPALLOC, &inodedep);
1628	if ((inodedep->id_state & IOSTARTED) != 0)
1629		panic("softdep_setup_freeblocks: inode busy");
1630	/*
1631	 * Add the freeblks structure to the list of operations that
1632	 * must await the zero'ed inode being written to disk.
1633	 */
1634	WORKLIST_INSERT(&inodedep->id_bufwait, &freeblks->fb_list);
1635	/*
1636	 * Because the file length has been truncated to zero, any
1637	 * pending block allocation dependency structures associated
1638	 * with this inode are obsolete and can simply be de-allocated.
1639	 * We must first merge the two dependency lists to get rid of
1640	 * any duplicate freefrag structures, then purge the merged list.
1641	 */
1642	merge_inode_lists(inodedep);
1643	while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != 0)
1644		free_allocdirect(&inodedep->id_inoupdt, adp, 1);
1645	FREE_LOCK(&lk);
1646	bdwrite(bp);
1647	/*
1648	 * We must wait for any I/O in progress to finish so that
1649	 * all potential buffers on the dirty list will be visible.
1650	 * Once they are all there, walk the list and get rid of
1651	 * any dependencies.
1652	 */
1653	vp = ITOV(ip);
1654	ACQUIRE_LOCK(&lk);
1655	drain_output(vp, 1);
1656	while (getdirtybuf(&TAILQ_FIRST(&vp->v_dirtyblkhd), MNT_WAIT)) {
1657		bp = TAILQ_FIRST(&vp->v_dirtyblkhd);
1658		(void) inodedep_lookup(fs, ip->i_number, 0, &inodedep);
1659		deallocate_dependencies(bp, inodedep);
1660		bp->b_flags |= B_INVAL | B_NOCACHE;
1661		FREE_LOCK(&lk);
1662		brelse(bp);
1663		ACQUIRE_LOCK(&lk);
1664	}
1665	/*
1666	 * Try freeing the inodedep in case that was the last dependency.
1667	 */
1668	if ((inodedep_lookup(fs, ip->i_number, 0, &inodedep)) != 0)
1669		(void) free_inodedep(inodedep);
1670	FREE_LOCK(&lk);
1671}
1672
1673/*
1674 * Reclaim any dependency structures from a buffer that is about to
1675 * be reallocated to a new vnode. The buffer must be locked, thus,
1676 * no I/O completion operations can occur while we are manipulating
1677 * its associated dependencies. The mutex is held so that other I/O's
1678 * associated with related dependencies do not occur.
1679 */
1680static void
1681deallocate_dependencies(bp, inodedep)
1682	struct buf *bp;
1683	struct inodedep *inodedep;
1684{
1685	struct worklist *wk;
1686	struct indirdep *indirdep;
1687	struct allocindir *aip;
1688	struct pagedep *pagedep;
1689	struct dirrem *dirrem;
1690	struct diradd *dap;
1691	int i;
1692
1693	while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
1694		switch (wk->wk_type) {
1695
1696		case D_INDIRDEP:
1697			indirdep = WK_INDIRDEP(wk);
1698			/*
1699			 * None of the indirect pointers will ever be visible,
1700			 * so they can simply be tossed. GOINGAWAY ensures
1701			 * that allocated pointers will be saved in the buffer
1702			 * cache until they are freed. Note that they will
1703			 * only be able to be found by their physical address
1704			 * since the inode mapping the logical address will
1705			 * be gone. The save buffer used for the safe copy
1706			 * was allocated in setup_allocindir_phase2 using
1707			 * the physical address so it could be used for this
1708			 * purpose. Hence we swap the safe copy with the real
1709			 * copy, allowing the safe copy to be freed and holding
1710			 * on to the real copy for later use in indir_trunc.
1711			 */
1712			if (indirdep->ir_state & GOINGAWAY)
1713				panic("deallocate_dependencies: already gone");
1714			indirdep->ir_state |= GOINGAWAY;
1715			while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != 0)
1716				free_allocindir(aip, inodedep);
1717			if (bp->b_lblkno >= 0 ||
1718			    bp->b_blkno != indirdep->ir_savebp->b_lblkno)
1719				panic("deallocate_dependencies: not indir");
1720			bcopy(bp->b_data, indirdep->ir_savebp->b_data,
1721			    bp->b_bcount);
1722			WORKLIST_REMOVE(wk);
1723			WORKLIST_INSERT(&indirdep->ir_savebp->b_dep, wk);
1724			continue;
1725
1726		case D_PAGEDEP:
1727			pagedep = WK_PAGEDEP(wk);
1728			/*
1729			 * None of the directory additions will ever be
1730			 * visible, so they can simply be tossed.
1731			 */
1732			for (i = 0; i < DAHASHSZ; i++)
1733				while ((dap =
1734				    LIST_FIRST(&pagedep->pd_diraddhd[i])))
1735					free_diradd(dap);
1736			while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != 0)
1737				free_diradd(dap);
1738			/*
1739			 * Copy any directory remove dependencies to the list
1740			 * to be processed after the zero'ed inode is written.
1741			 * If the inode has already been written, then they
1742			 * can be dumped directly onto the work list.
1743			 */
1744			for (dirrem = LIST_FIRST(&pagedep->pd_dirremhd); dirrem;
1745			     dirrem = LIST_NEXT(dirrem, dm_next)) {
1746				LIST_REMOVE(dirrem, dm_next);
1747				dirrem->dm_dirinum = pagedep->pd_ino;
1748				if (inodedep == NULL)
1749					add_to_worklist(&dirrem->dm_list);
1750				else
1751					WORKLIST_INSERT(&inodedep->id_bufwait,
1752					    &dirrem->dm_list);
1753			}
1754			WORKLIST_REMOVE(&pagedep->pd_list);
1755			LIST_REMOVE(pagedep, pd_hash);
1756			WORKITEM_FREE(pagedep, D_PAGEDEP);
1757			continue;
1758
1759		case D_ALLOCINDIR:
1760			free_allocindir(WK_ALLOCINDIR(wk), inodedep);
1761			continue;
1762
1763		case D_ALLOCDIRECT:
1764		case D_INODEDEP:
1765			panic("deallocate_dependencies: Unexpected type %s",
1766			    TYPENAME(wk->wk_type));
1767			/* NOTREACHED */
1768
1769		default:
1770			panic("deallocate_dependencies: Unknown type %s",
1771			    TYPENAME(wk->wk_type));
1772			/* NOTREACHED */
1773		}
1774	}
1775}
1776
1777/*
1778 * Free an allocdirect. Generate a new freefrag work request if appropriate.
1779 * This routine must be called with splbio interrupts blocked.
1780 */
1781static void
1782free_allocdirect(adphead, adp, delay)
1783	struct allocdirectlst *adphead;
1784	struct allocdirect *adp;
1785	int delay;
1786{
1787
1788#ifdef DEBUG
1789	if (lk.lkt_held == -1)
1790		panic("free_allocdirect: lock not held");
1791#endif
1792	if ((adp->ad_state & DEPCOMPLETE) == 0)
1793		LIST_REMOVE(adp, ad_deps);
1794	TAILQ_REMOVE(adphead, adp, ad_next);
1795	if ((adp->ad_state & COMPLETE) == 0)
1796		WORKLIST_REMOVE(&adp->ad_list);
1797	if (adp->ad_freefrag != NULL) {
1798		if (delay)
1799			WORKLIST_INSERT(&adp->ad_inodedep->id_bufwait,
1800			    &adp->ad_freefrag->ff_list);
1801		else
1802			add_to_worklist(&adp->ad_freefrag->ff_list);
1803	}
1804	WORKITEM_FREE(adp, D_ALLOCDIRECT);
1805}
1806
1807/*
1808 * Prepare an inode to be freed. The actual free operation is not
1809 * done until the zero'ed inode has been written to disk.
1810 */
1811static long num_freefile;	/* number of freefile allocated */
1812void
1813softdep_freefile(pvp, ino, mode)
1814		struct vnode *pvp;
1815		ino_t ino;
1816		int mode;
1817{
1818	struct inode *ip = VTOI(pvp);
1819	struct inodedep *inodedep;
1820	struct freefile *freefile;
1821
1822	/*
1823	 * If we are over our limit, try to improve the situation.
1824	 */
1825	if (num_freefile > max_softdeps / 2 && speedup_syncer() == 0)
1826		(void) request_cleanup(FLUSH_REMOVE, 0);
1827	/*
1828	 * This sets up the inode de-allocation dependency.
1829	 */
1830	num_freefile += 1;
1831	MALLOC(freefile, struct freefile *, sizeof(struct freefile),
1832		M_FREEFILE, M_WAITOK);
1833	freefile->fx_list.wk_type = D_FREEFILE;
1834	freefile->fx_list.wk_state = 0;
1835	freefile->fx_mode = mode;
1836	freefile->fx_oldinum = ino;
1837	freefile->fx_devvp = ip->i_devvp;
1838	freefile->fx_fs = ip->i_fs;
1839
1840	/*
1841	 * If the inodedep does not exist, then the zero'ed inode has
1842	 * been written to disk and we can free the file immediately.
1843	 */
1844	ACQUIRE_LOCK(&lk);
1845	if (inodedep_lookup(ip->i_fs, ino, 0, &inodedep) == 0) {
1846		add_to_worklist(&freefile->fx_list);
1847		FREE_LOCK(&lk);
1848		return;
1849	}
1850
1851	/*
1852	 * If we still have a bitmap dependency, then the inode has never
1853	 * been written to disk. Drop the dependency as it is no longer
1854	 * necessary since the inode is being deallocated. We could process
1855	 * the freefile immediately, but then we would have to clear the
1856	 * id_inowait dependencies here and it is easier just to let the
1857	 * zero'ed inode be written and let them be cleaned up in the
1858	 * normal followup actions that follow the inode write.
1859	 */
1860	 if ((inodedep->id_state & DEPCOMPLETE) == 0) {
1861		inodedep->id_state |= DEPCOMPLETE;
1862		LIST_REMOVE(inodedep, id_deps);
1863		inodedep->id_buf = NULL;
1864	}
1865	/*
1866	 * If the inodedep has no dependencies associated with it,
1867	 * then we must free it here and free the file immediately.
1868	 * This case arises when an early allocation fails (for
1869	 * example, the user is over their file quota).
1870	 */
1871	if (free_inodedep(inodedep) == 0)
1872		WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
1873	else
1874		add_to_worklist(&freefile->fx_list);
1875	FREE_LOCK(&lk);
1876}
1877
1878/*
1879 * Try to free an inodedep structure. Return 1 if it could be freed.
1880 */
1881static int
1882free_inodedep(inodedep)
1883	struct inodedep *inodedep;
1884{
1885
1886	if ((inodedep->id_state & ONWORKLIST) != 0 ||
1887	    (inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
1888	    LIST_FIRST(&inodedep->id_pendinghd) != NULL ||
1889	    LIST_FIRST(&inodedep->id_bufwait) != NULL ||
1890	    LIST_FIRST(&inodedep->id_inowait) != NULL ||
1891	    TAILQ_FIRST(&inodedep->id_inoupdt) != NULL ||
1892	    TAILQ_FIRST(&inodedep->id_newinoupdt) != NULL ||
1893	    inodedep->id_nlinkdelta != 0 || inodedep->id_savedino != NULL)
1894		return (0);
1895	LIST_REMOVE(inodedep, id_hash);
1896	WORKITEM_FREE(inodedep, D_INODEDEP);
1897	num_inodedep -= 1;
1898	return (1);
1899}
1900
1901/*
1902 * This workitem routine performs the block de-allocation.
1903 * The workitem is added to the pending list after the updated
1904 * inode block has been written to disk.  As mentioned above,
1905 * checks regarding the number of blocks de-allocated (compared
1906 * to the number of blocks allocated for the file) are also
1907 * performed in this function.
1908 */
1909static void
1910handle_workitem_freeblocks(freeblks)
1911	struct freeblks *freeblks;
1912{
1913	struct inode tip;
1914	ufs_daddr_t bn;
1915	struct fs *fs;
1916	int i, level, bsize;
1917	long nblocks, blocksreleased = 0;
1918	int error, allerror = 0;
1919	ufs_lbn_t baselbns[NIADDR], tmpval;
1920
1921	tip.i_number = freeblks->fb_previousinum;
1922	tip.i_devvp = freeblks->fb_devvp;
1923	tip.i_dev = freeblks->fb_devvp->v_rdev;
1924	tip.i_fs = freeblks->fb_fs;
1925	tip.i_size = freeblks->fb_oldsize;
1926	tip.i_uid = freeblks->fb_uid;
1927	fs = freeblks->fb_fs;
1928	tmpval = 1;
1929	baselbns[0] = NDADDR;
1930	for (i = 1; i < NIADDR; i++) {
1931		tmpval *= NINDIR(fs);
1932		baselbns[i] = baselbns[i - 1] + tmpval;
1933	}
1934	nblocks = btodb(fs->fs_bsize);
1935	blocksreleased = 0;
1936	/*
1937	 * Indirect blocks first.
1938	 */
1939	for (level = (NIADDR - 1); level >= 0; level--) {
1940		if ((bn = freeblks->fb_iblks[level]) == 0)
1941			continue;
1942		if ((error = indir_trunc(&tip, fsbtodb(fs, bn), level,
1943		    baselbns[level], &blocksreleased)) == 0)
1944			allerror = error;
1945		ffs_blkfree(&tip, bn, fs->fs_bsize);
1946		blocksreleased += nblocks;
1947	}
1948	/*
1949	 * All direct blocks or frags.
1950	 */
1951	for (i = (NDADDR - 1); i >= 0; i--) {
1952		if ((bn = freeblks->fb_dblks[i]) == 0)
1953			continue;
1954		bsize = blksize(fs, &tip, i);
1955		ffs_blkfree(&tip, bn, bsize);
1956		blocksreleased += btodb(bsize);
1957	}
1958
1959#ifdef DIAGNOSTIC
1960	if (freeblks->fb_chkcnt != blocksreleased)
1961		panic("handle_workitem_freeblocks: block count");
1962	if (allerror)
1963		softdep_error("handle_workitem_freeblks", allerror);
1964#endif /* DIAGNOSTIC */
1965	WORKITEM_FREE(freeblks, D_FREEBLKS);
1966	num_freeblks -= 1;
1967}
1968
1969/*
1970 * Release blocks associated with the inode ip and stored in the indirect
1971 * block dbn. If level is greater than SINGLE, the block is an indirect block
1972 * and recursive calls to indirtrunc must be used to cleanse other indirect
1973 * blocks.
1974 */
1975static int
1976indir_trunc(ip, dbn, level, lbn, countp)
1977	struct inode *ip;
1978	ufs_daddr_t dbn;
1979	int level;
1980	ufs_lbn_t lbn;
1981	long *countp;
1982{
1983	struct buf *bp;
1984	ufs_daddr_t *bap;
1985	ufs_daddr_t nb;
1986	struct fs *fs;
1987	struct worklist *wk;
1988	struct indirdep *indirdep;
1989	int i, lbnadd, nblocks;
1990	int error, allerror = 0;
1991
1992	fs = ip->i_fs;
1993	lbnadd = 1;
1994	for (i = level; i > 0; i--)
1995		lbnadd *= NINDIR(fs);
1996	/*
1997	 * Get buffer of block pointers to be freed. This routine is not
1998	 * called until the zero'ed inode has been written, so it is safe
1999	 * to free blocks as they are encountered. Because the inode has
2000	 * been zero'ed, calls to bmap on these blocks will fail. So, we
2001	 * have to use the on-disk address and the block device for the
2002	 * filesystem to look them up. If the file was deleted before its
2003	 * indirect blocks were all written to disk, the routine that set
2004	 * us up (deallocate_dependencies) will have arranged to leave
2005	 * a complete copy of the indirect block in memory for our use.
2006	 * Otherwise we have to read the blocks in from the disk.
2007	 */
2008	ACQUIRE_LOCK(&lk);
2009	if ((bp = incore(ip->i_devvp, dbn)) != NULL &&
2010	    (wk = LIST_FIRST(&bp->b_dep)) != NULL) {
2011		if (wk->wk_type != D_INDIRDEP ||
2012		    (indirdep = WK_INDIRDEP(wk))->ir_savebp != bp ||
2013		    (indirdep->ir_state & GOINGAWAY) == 0)
2014			panic("indir_trunc: lost indirdep");
2015		WORKLIST_REMOVE(wk);
2016		WORKITEM_FREE(indirdep, D_INDIRDEP);
2017		if (LIST_FIRST(&bp->b_dep) != NULL)
2018			panic("indir_trunc: dangling dep");
2019		FREE_LOCK(&lk);
2020	} else {
2021		FREE_LOCK(&lk);
2022		error = bread(ip->i_devvp, dbn, (int)fs->fs_bsize, NOCRED, &bp);
2023		if (error)
2024			return (error);
2025	}
2026	/*
2027	 * Recursively free indirect blocks.
2028	 */
2029	bap = (ufs_daddr_t *)bp->b_data;
2030	nblocks = btodb(fs->fs_bsize);
2031	for (i = NINDIR(fs) - 1; i >= 0; i--) {
2032		if ((nb = bap[i]) == 0)
2033			continue;
2034		if (level != 0) {
2035			if ((error = indir_trunc(ip, fsbtodb(fs, nb),
2036			     level - 1, lbn + (i * lbnadd), countp)) != 0)
2037				allerror = error;
2038		}
2039		ffs_blkfree(ip, nb, fs->fs_bsize);
2040		*countp += nblocks;
2041	}
2042	bp->b_flags |= B_INVAL | B_NOCACHE;
2043	brelse(bp);
2044	return (allerror);
2045}
2046
2047/*
2048 * Free an allocindir.
2049 * This routine must be called with splbio interrupts blocked.
2050 */
2051static void
2052free_allocindir(aip, inodedep)
2053	struct allocindir *aip;
2054	struct inodedep *inodedep;
2055{
2056	struct freefrag *freefrag;
2057
2058#ifdef DEBUG
2059	if (lk.lkt_held == -1)
2060		panic("free_allocindir: lock not held");
2061#endif
2062	if ((aip->ai_state & DEPCOMPLETE) == 0)
2063		LIST_REMOVE(aip, ai_deps);
2064	if (aip->ai_state & ONWORKLIST)
2065		WORKLIST_REMOVE(&aip->ai_list);
2066	LIST_REMOVE(aip, ai_next);
2067	if ((freefrag = aip->ai_freefrag) != NULL) {
2068		if (inodedep == NULL)
2069			add_to_worklist(&freefrag->ff_list);
2070		else
2071			WORKLIST_INSERT(&inodedep->id_bufwait,
2072			    &freefrag->ff_list);
2073	}
2074	WORKITEM_FREE(aip, D_ALLOCINDIR);
2075}
2076
2077/*
2078 * Directory entry addition dependencies.
2079 *
2080 * When adding a new directory entry, the inode (with its incremented link
2081 * count) must be written to disk before the directory entry's pointer to it.
2082 * Also, if the inode is newly allocated, the corresponding freemap must be
2083 * updated (on disk) before the directory entry's pointer. These requirements
2084 * are met via undo/redo on the directory entry's pointer, which consists
2085 * simply of the inode number.
2086 *
2087 * As directory entries are added and deleted, the free space within a
2088 * directory block can become fragmented.  The ufs file system will compact
2089 * a fragmented directory block to make space for a new entry. When this
2090 * occurs, the offsets of previously added entries change. Any "diradd"
2091 * dependency structures corresponding to these entries must be updated with
2092 * the new offsets.
2093 */
2094
2095/*
2096 * This routine is called after the in-memory inode's link
2097 * count has been incremented, but before the directory entry's
2098 * pointer to the inode has been set.
2099 */
2100void
2101softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp)
2102	struct buf *bp;		/* buffer containing directory block */
2103	struct inode *dp;	/* inode for directory */
2104	off_t diroffset;	/* offset of new entry in directory */
2105	long newinum;		/* inode referenced by new directory entry */
2106	struct buf *newdirbp;	/* non-NULL => contents of new mkdir */
2107{
2108	int offset;		/* offset of new entry within directory block */
2109	ufs_lbn_t lbn;		/* block in directory containing new entry */
2110	struct fs *fs;
2111	struct diradd *dap;
2112	struct pagedep *pagedep;
2113	struct inodedep *inodedep;
2114	struct mkdir *mkdir1, *mkdir2;
2115
2116	/*
2117	 * Whiteouts have no dependencies.
2118	 */
2119	if (newinum == WINO) {
2120		if (newdirbp != NULL)
2121			bdwrite(newdirbp);
2122		return;
2123	}
2124
2125	fs = dp->i_fs;
2126	lbn = lblkno(fs, diroffset);
2127	offset = blkoff(fs, diroffset);
2128	MALLOC(dap, struct diradd *, sizeof(struct diradd), M_DIRADD, M_WAITOK);
2129	bzero(dap, sizeof(struct diradd));
2130	dap->da_list.wk_type = D_DIRADD;
2131	dap->da_offset = offset;
2132	dap->da_newinum = newinum;
2133	dap->da_state = ATTACHED;
2134	if (newdirbp == NULL) {
2135		dap->da_state |= DEPCOMPLETE;
2136		ACQUIRE_LOCK(&lk);
2137	} else {
2138		dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
2139		MALLOC(mkdir1, struct mkdir *, sizeof(struct mkdir), M_MKDIR,
2140		    M_WAITOK);
2141		mkdir1->md_list.wk_type = D_MKDIR;
2142		mkdir1->md_state = MKDIR_BODY;
2143		mkdir1->md_diradd = dap;
2144		MALLOC(mkdir2, struct mkdir *, sizeof(struct mkdir), M_MKDIR,
2145		    M_WAITOK);
2146		mkdir2->md_list.wk_type = D_MKDIR;
2147		mkdir2->md_state = MKDIR_PARENT;
2148		mkdir2->md_diradd = dap;
2149		/*
2150		 * Dependency on "." and ".." being written to disk.
2151		 */
2152		mkdir1->md_buf = newdirbp;
2153		ACQUIRE_LOCK(&lk);
2154		LIST_INSERT_HEAD(&mkdirlisthd, mkdir1, md_mkdirs);
2155		WORKLIST_INSERT(&newdirbp->b_dep, &mkdir1->md_list);
2156		FREE_LOCK(&lk);
2157		bdwrite(newdirbp);
2158		/*
2159		 * Dependency on link count increase for parent directory
2160		 */
2161		ACQUIRE_LOCK(&lk);
2162		if (inodedep_lookup(dp->i_fs, dp->i_number, 0, &inodedep) == 0
2163		    || (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
2164			dap->da_state &= ~MKDIR_PARENT;
2165			WORKITEM_FREE(mkdir2, D_MKDIR);
2166		} else {
2167			LIST_INSERT_HEAD(&mkdirlisthd, mkdir2, md_mkdirs);
2168			WORKLIST_INSERT(&inodedep->id_bufwait,&mkdir2->md_list);
2169		}
2170	}
2171	/*
2172	 * Link into parent directory pagedep to await its being written.
2173	 */
2174	if (pagedep_lookup(dp, lbn, DEPALLOC, &pagedep) == 0)
2175		WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
2176	dap->da_pagedep = pagedep;
2177	LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
2178	    da_pdlist);
2179	/*
2180	 * Link into its inodedep. Put it on the id_bufwait list if the inode
2181	 * is not yet written. If it is written, do the post-inode write
2182	 * processing to put it on the id_pendinghd list.
2183	 */
2184	(void) inodedep_lookup(fs, newinum, DEPALLOC, &inodedep);
2185	if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
2186		diradd_inode_written(dap, inodedep);
2187	else
2188		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
2189	FREE_LOCK(&lk);
2190}
2191
2192/*
2193 * This procedure is called to change the offset of a directory
2194 * entry when compacting a directory block which must be owned
2195 * exclusively by the caller. Note that the actual entry movement
2196 * must be done in this procedure to ensure that no I/O completions
2197 * occur while the move is in progress.
2198 */
2199void
2200softdep_change_directoryentry_offset(dp, base, oldloc, newloc, entrysize)
2201	struct inode *dp;	/* inode for directory */
2202	caddr_t base;		/* address of dp->i_offset */
2203	caddr_t oldloc;		/* address of old directory location */
2204	caddr_t newloc;		/* address of new directory location */
2205	int entrysize;		/* size of directory entry */
2206{
2207	int offset, oldoffset, newoffset;
2208	struct pagedep *pagedep;
2209	struct diradd *dap;
2210	ufs_lbn_t lbn;
2211
2212	ACQUIRE_LOCK(&lk);
2213	lbn = lblkno(dp->i_fs, dp->i_offset);
2214	offset = blkoff(dp->i_fs, dp->i_offset);
2215	if (pagedep_lookup(dp, lbn, 0, &pagedep) == 0)
2216		goto done;
2217	oldoffset = offset + (oldloc - base);
2218	newoffset = offset + (newloc - base);
2219	for (dap = LIST_FIRST(&pagedep->pd_diraddhd[DIRADDHASH(oldoffset)]);
2220	     dap; dap = LIST_NEXT(dap, da_pdlist)) {
2221		if (dap->da_offset != oldoffset)
2222			continue;
2223		dap->da_offset = newoffset;
2224		if (DIRADDHASH(newoffset) == DIRADDHASH(oldoffset))
2225			break;
2226		LIST_REMOVE(dap, da_pdlist);
2227		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(newoffset)],
2228		    dap, da_pdlist);
2229		break;
2230	}
2231	if (dap == NULL) {
2232		for (dap = LIST_FIRST(&pagedep->pd_pendinghd);
2233		     dap; dap = LIST_NEXT(dap, da_pdlist)) {
2234			if (dap->da_offset == oldoffset) {
2235				dap->da_offset = newoffset;
2236				break;
2237			}
2238		}
2239	}
2240done:
2241	bcopy(oldloc, newloc, entrysize);
2242	FREE_LOCK(&lk);
2243}
2244
2245/*
2246 * Free a diradd dependency structure. This routine must be called
2247 * with splbio interrupts blocked.
2248 */
2249static void
2250free_diradd(dap)
2251	struct diradd *dap;
2252{
2253	struct dirrem *dirrem;
2254	struct pagedep *pagedep;
2255	struct inodedep *inodedep;
2256	struct mkdir *mkdir, *nextmd;
2257
2258#ifdef DEBUG
2259	if (lk.lkt_held == -1)
2260		panic("free_diradd: lock not held");
2261#endif
2262	WORKLIST_REMOVE(&dap->da_list);
2263	LIST_REMOVE(dap, da_pdlist);
2264	if ((dap->da_state & DIRCHG) == 0) {
2265		pagedep = dap->da_pagedep;
2266	} else {
2267		dirrem = dap->da_previous;
2268		pagedep = dirrem->dm_pagedep;
2269		dirrem->dm_dirinum = pagedep->pd_ino;
2270		add_to_worklist(&dirrem->dm_list);
2271	}
2272	if (inodedep_lookup(VFSTOUFS(pagedep->pd_mnt)->um_fs, dap->da_newinum,
2273	    0, &inodedep) != 0)
2274		(void) free_inodedep(inodedep);
2275	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
2276		for (mkdir = LIST_FIRST(&mkdirlisthd); mkdir; mkdir = nextmd) {
2277			nextmd = LIST_NEXT(mkdir, md_mkdirs);
2278			if (mkdir->md_diradd != dap)
2279				continue;
2280			dap->da_state &= ~mkdir->md_state;
2281			WORKLIST_REMOVE(&mkdir->md_list);
2282			LIST_REMOVE(mkdir, md_mkdirs);
2283			WORKITEM_FREE(mkdir, D_MKDIR);
2284		}
2285		if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
2286			panic("free_diradd: unfound ref");
2287	}
2288	WORKITEM_FREE(dap, D_DIRADD);
2289}
2290
2291/*
2292 * Directory entry removal dependencies.
2293 *
2294 * When removing a directory entry, the entry's inode pointer must be
2295 * zero'ed on disk before the corresponding inode's link count is decremented
2296 * (possibly freeing the inode for re-use). This dependency is handled by
2297 * updating the directory entry but delaying the inode count reduction until
2298 * after the directory block has been written to disk. After this point, the
2299 * inode count can be decremented whenever it is convenient.
2300 */
2301
2302/*
2303 * This routine should be called immediately after removing
2304 * a directory entry.  The inode's link count should not be
2305 * decremented by the calling procedure -- the soft updates
2306 * code will do this task when it is safe.
2307 */
2308void
2309softdep_setup_remove(bp, dp, ip, isrmdir)
2310	struct buf *bp;		/* buffer containing directory block */
2311	struct inode *dp;	/* inode for the directory being modified */
2312	struct inode *ip;	/* inode for directory entry being removed */
2313	int isrmdir;		/* indicates if doing RMDIR */
2314{
2315	struct dirrem *dirrem;
2316
2317	/*
2318	 * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.
2319	 */
2320	dirrem = newdirrem(bp, dp, ip, isrmdir);
2321	if ((dirrem->dm_state & COMPLETE) == 0) {
2322		LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
2323		    dm_next);
2324	} else {
2325		dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
2326		add_to_worklist(&dirrem->dm_list);
2327	}
2328	FREE_LOCK(&lk);
2329}
2330
2331/*
2332 * Allocate a new dirrem if appropriate and return it along with
2333 * its associated pagedep. Called without a lock, returns with lock.
2334 */
2335static struct dirrem *
2336newdirrem(bp, dp, ip, isrmdir)
2337	struct buf *bp;		/* buffer containing directory block */
2338	struct inode *dp;	/* inode for the directory being modified */
2339	struct inode *ip;	/* inode for directory entry being removed */
2340	int isrmdir;		/* indicates if doing RMDIR */
2341{
2342	int offset;
2343	ufs_lbn_t lbn;
2344	struct diradd *dap;
2345	struct dirrem *dirrem;
2346	struct pagedep *pagedep;
2347
2348	/*
2349	 * Whiteouts have no deletion dependencies.
2350	 */
2351	if (ip == NULL)
2352		panic("newdirrem: whiteout");
2353	MALLOC(dirrem, struct dirrem *, sizeof(struct dirrem),
2354		M_DIRREM, M_WAITOK);
2355	bzero(dirrem, sizeof(struct dirrem));
2356	dirrem->dm_list.wk_type = D_DIRREM;
2357	dirrem->dm_state = isrmdir ? RMDIR : 0;
2358	dirrem->dm_mnt = ITOV(ip)->v_mount;
2359	dirrem->dm_oldinum = ip->i_number;
2360
2361	ACQUIRE_LOCK(&lk);
2362	lbn = lblkno(dp->i_fs, dp->i_offset);
2363	offset = blkoff(dp->i_fs, dp->i_offset);
2364	if (pagedep_lookup(dp, lbn, DEPALLOC, &pagedep) == 0)
2365		WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
2366	dirrem->dm_pagedep = pagedep;
2367	/*
2368	 * Check for a diradd dependency for the same directory entry.
2369	 * If present, then both dependencies become obsolete and can
2370	 * be de-allocated. Check for an entry on both the pd_dirraddhd
2371	 * list and the pd_pendinghd list.
2372	 */
2373	for (dap = LIST_FIRST(&pagedep->pd_diraddhd[DIRADDHASH(offset)]);
2374	     dap; dap = LIST_NEXT(dap, da_pdlist))
2375		if (dap->da_offset == offset)
2376			break;
2377	if (dap == NULL) {
2378		for (dap = LIST_FIRST(&pagedep->pd_pendinghd);
2379		     dap; dap = LIST_NEXT(dap, da_pdlist))
2380			if (dap->da_offset == offset)
2381				break;
2382		if (dap == NULL)
2383			return (dirrem);
2384	}
2385	/*
2386	 * Must be ATTACHED at this point, so just delete it.
2387	 */
2388	if ((dap->da_state & ATTACHED) == 0)
2389		panic("newdirrem: not ATTACHED");
2390	if (dap->da_newinum != ip->i_number)
2391		panic("newdirrem: inum %d should be %d",
2392		    ip->i_number, dap->da_newinum);
2393	free_diradd(dap);
2394	dirrem->dm_state |= COMPLETE;
2395	return (dirrem);
2396}
2397
2398/*
2399 * Directory entry change dependencies.
2400 *
2401 * Changing an existing directory entry requires that an add operation
2402 * be completed first followed by a deletion. The semantics for the addition
2403 * are identical to the description of adding a new entry above except
2404 * that the rollback is to the old inode number rather than zero. Once
2405 * the addition dependency is completed, the removal is done as described
2406 * in the removal routine above.
2407 */
2408
2409/*
2410 * This routine should be called immediately after changing
2411 * a directory entry.  The inode's link count should not be
2412 * decremented by the calling procedure -- the soft updates
2413 * code will perform this task when it is safe.
2414 */
2415void
2416softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
2417	struct buf *bp;		/* buffer containing directory block */
2418	struct inode *dp;	/* inode for the directory being modified */
2419	struct inode *ip;	/* inode for directory entry being removed */
2420	long newinum;		/* new inode number for changed entry */
2421	int isrmdir;		/* indicates if doing RMDIR */
2422{
2423	int offset;
2424	struct diradd *dap = NULL;
2425	struct dirrem *dirrem;
2426	struct pagedep *pagedep;
2427	struct inodedep *inodedep;
2428
2429	offset = blkoff(dp->i_fs, dp->i_offset);
2430
2431	/*
2432	 * Whiteouts do not need diradd dependencies.
2433	 */
2434	if (newinum != WINO) {
2435		MALLOC(dap, struct diradd *, sizeof(struct diradd),
2436		    M_DIRADD, M_WAITOK);
2437		bzero(dap, sizeof(struct diradd));
2438		dap->da_list.wk_type = D_DIRADD;
2439		dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
2440		dap->da_offset = offset;
2441		dap->da_newinum = newinum;
2442	}
2443
2444	/*
2445	 * Allocate a new dirrem and ACQUIRE_LOCK.
2446	 */
2447	dirrem = newdirrem(bp, dp, ip, isrmdir);
2448	pagedep = dirrem->dm_pagedep;
2449	/*
2450	 * The possible values for isrmdir:
2451	 *	0 - non-directory file rename
2452	 *	1 - directory rename within same directory
2453	 *   inum - directory rename to new directory of given inode number
2454	 * When renaming to a new directory, we are both deleting and
2455	 * creating a new directory entry, so the link count on the new
2456	 * directory should not change. Thus we do not need the followup
2457	 * dirrem which is usually done in handle_workitem_remove. We set
2458	 * the DIRCHG flag to tell handle_workitem_remove to skip the
2459	 * followup dirrem.
2460	 */
2461	if (isrmdir > 1)
2462		dirrem->dm_state |= DIRCHG;
2463
2464	/*
2465	 * Whiteouts have no additional dependencies,
2466	 * so just put the dirrem on the correct list.
2467	 */
2468	if (newinum == WINO) {
2469		if ((dirrem->dm_state & COMPLETE) == 0) {
2470			LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
2471			    dm_next);
2472		} else {
2473			dirrem->dm_dirinum = pagedep->pd_ino;
2474			add_to_worklist(&dirrem->dm_list);
2475		}
2476		FREE_LOCK(&lk);
2477		return;
2478	}
2479
2480	/*
2481	 * Link into its inodedep. Put it on the id_bufwait list if the inode
2482	 * is not yet written. If it is written, do the post-inode write
2483	 * processing to put it on the id_pendinghd list.
2484	 */
2485	dap->da_previous = dirrem;
2486	if (inodedep_lookup(dp->i_fs, newinum, DEPALLOC, &inodedep) == 0 ||
2487	    (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
2488		dap->da_state |= COMPLETE;
2489		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
2490		WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
2491	} else {
2492		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
2493		    dap, da_pdlist);
2494		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
2495	}
2496	/*
2497	 * If the previous inode was never written or its previous directory
2498	 * entry was never written, then we do not want to roll back to this
2499	 * previous value. Instead we want to roll back to zero and immediately
2500	 * free the unwritten or unreferenced inode.
2501	 */
2502	if (dirrem->dm_state & COMPLETE) {
2503		dap->da_state &= ~DIRCHG;
2504		dap->da_pagedep = pagedep;
2505		dirrem->dm_dirinum = pagedep->pd_ino;
2506		add_to_worklist(&dirrem->dm_list);
2507	}
2508	FREE_LOCK(&lk);
2509}
2510
2511/*
2512 * Called whenever the link count on an inode is increased.
2513 * It creates an inode dependency so that the new reference(s)
2514 * to the inode cannot be committed to disk until the updated
2515 * inode has been written.
2516 */
2517void
2518softdep_increase_linkcnt(ip)
2519	struct inode *ip;	/* the inode with the increased link count */
2520{
2521	struct inodedep *inodedep;
2522
2523	ACQUIRE_LOCK(&lk);
2524	(void) inodedep_lookup(ip->i_fs, ip->i_number, DEPALLOC, &inodedep);
2525	FREE_LOCK(&lk);
2526}
2527
2528/*
2529 * This workitem decrements the inode's link count.
2530 * If the link count reaches zero, the file is removed.
2531 */
2532static void
2533handle_workitem_remove(dirrem)
2534	struct dirrem *dirrem;
2535{
2536	struct proc *p = CURPROC;	/* XXX */
2537	struct inodedep *inodedep;
2538	struct vnode *vp;
2539	struct inode *ip;
2540	int error;
2541
2542	if ((error = VFS_VGET(dirrem->dm_mnt, dirrem->dm_oldinum, &vp)) != 0) {
2543		softdep_error("handle_workitem_remove: vget", error);
2544		return;
2545	}
2546	ip = VTOI(vp);
2547	/*
2548	 * Normal file deletion.
2549	 */
2550	if ((dirrem->dm_state & RMDIR) == 0) {
2551		ip->i_nlink--;
2552		if (ip->i_nlink < ip->i_effnlink)
2553			panic("handle_workitem_remove: bad file delta");
2554		ip->i_flag |= IN_CHANGE;
2555		vput(vp);
2556		WORKITEM_FREE(dirrem, D_DIRREM);
2557		return;
2558	}
2559	/*
2560	 * Directory deletion. Decrement reference count for both the
2561	 * just deleted parent directory entry and the reference for ".".
2562	 * Next truncate the directory to length zero. When the
2563	 * truncation completes, arrange to have the reference count on
2564	 * the parent decremented to account for the loss of "..".
2565	 */
2566	ip->i_nlink -= 2;
2567	if (ip->i_nlink < ip->i_effnlink)
2568		panic("handle_workitem_remove: bad dir delta");
2569	ip->i_flag |= IN_CHANGE;
2570	if ((error = UFS_TRUNCATE(vp, (off_t)0, 0, p->p_ucred, p)) != 0)
2571		softdep_error("handle_workitem_remove: truncate", error);
2572	/*
2573	 * Rename a directory to a new parent. Since, we are both deleting
2574	 * and creating a new directory entry, the link count on the new
2575	 * directory should not change. Thus we skip the followup dirrem.
2576	 */
2577	if (dirrem->dm_state & DIRCHG) {
2578		vput(vp);
2579		WORKITEM_FREE(dirrem, D_DIRREM);
2580		return;
2581	}
2582	ACQUIRE_LOCK(&lk);
2583	(void) inodedep_lookup(ip->i_fs, dirrem->dm_oldinum, DEPALLOC,
2584	    &inodedep);
2585	dirrem->dm_state = 0;
2586	dirrem->dm_oldinum = dirrem->dm_dirinum;
2587	WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
2588	FREE_LOCK(&lk);
2589	vput(vp);
2590}
2591
2592/*
2593 * Inode de-allocation dependencies.
2594 *
2595 * When an inode's link count is reduced to zero, it can be de-allocated. We
2596 * found it convenient to postpone de-allocation until after the inode is
2597 * written to disk with its new link count (zero).  At this point, all of the
2598 * on-disk inode's block pointers are nullified and, with careful dependency
2599 * list ordering, all dependencies related to the inode will be satisfied and
2600 * the corresponding dependency structures de-allocated.  So, if/when the
2601 * inode is reused, there will be no mixing of old dependencies with new
2602 * ones.  This artificial dependency is set up by the block de-allocation
2603 * procedure above (softdep_setup_freeblocks) and completed by the
2604 * following procedure.
2605 */
2606static void
2607handle_workitem_freefile(freefile)
2608	struct freefile *freefile;
2609{
2610	struct vnode vp;
2611	struct inode tip;
2612	struct inodedep *idp;
2613	int error;
2614
2615#ifdef DEBUG
2616	ACQUIRE_LOCK(&lk);
2617	if (inodedep_lookup(freefile->fx_fs, freefile->fx_oldinum, 0, &idp))
2618		panic("handle_workitem_freefile: inodedep survived");
2619	FREE_LOCK(&lk);
2620#endif
2621	tip.i_devvp = freefile->fx_devvp;
2622	tip.i_dev = freefile->fx_devvp->v_rdev;
2623	tip.i_fs = freefile->fx_fs;
2624	vp.v_data = &tip;
2625	if ((error = ffs_freefile(&vp, freefile->fx_oldinum, freefile->fx_mode)) != 0)
2626		softdep_error("handle_workitem_freefile", error);
2627	WORKITEM_FREE(freefile, D_FREEFILE);
2628	num_freefile -= 1;
2629}
2630
2631/*
2632 * Disk writes.
2633 *
2634 * The dependency structures constructed above are most actively used when file
2635 * system blocks are written to disk.  No constraints are placed on when a
2636 * block can be written, but unsatisfied update dependencies are made safe by
2637 * modifying (or replacing) the source memory for the duration of the disk
2638 * write.  When the disk write completes, the memory block is again brought
2639 * up-to-date.
2640 *
2641 * In-core inode structure reclamation.
2642 *
2643 * Because there are a finite number of "in-core" inode structures, they are
2644 * reused regularly.  By transferring all inode-related dependencies to the
2645 * in-memory inode block and indexing them separately (via "inodedep"s), we
2646 * can allow "in-core" inode structures to be reused at any time and avoid
2647 * any increase in contention.
2648 *
2649 * Called just before entering the device driver to initiate a new disk I/O.
2650 * The buffer must be locked, thus, no I/O completion operations can occur
2651 * while we are manipulating its associated dependencies.
2652 */
2653void
2654softdep_disk_io_initiation(bp)
2655	struct buf *bp;		/* structure describing disk write to occur */
2656{
2657	struct worklist *wk, *nextwk;
2658	struct indirdep *indirdep;
2659
2660	/*
2661	 * We only care about write operations. There should never
2662	 * be dependencies for reads.
2663	 */
2664	if (bp->b_flags & B_READ)
2665		panic("softdep_disk_io_initiation: read");
2666	/*
2667	 * Do any necessary pre-I/O processing.
2668	 */
2669	for (wk = LIST_FIRST(&bp->b_dep); wk; wk = nextwk) {
2670		nextwk = LIST_NEXT(wk, wk_list);
2671		switch (wk->wk_type) {
2672
2673		case D_PAGEDEP:
2674			initiate_write_filepage(WK_PAGEDEP(wk), bp);
2675			continue;
2676
2677		case D_INODEDEP:
2678			initiate_write_inodeblock(WK_INODEDEP(wk), bp);
2679			continue;
2680
2681		case D_INDIRDEP:
2682			indirdep = WK_INDIRDEP(wk);
2683			if (indirdep->ir_state & GOINGAWAY)
2684				panic("disk_io_initiation: indirdep gone");
2685			/*
2686			 * If there are no remaining dependencies, this
2687			 * will be writing the real pointers, so the
2688			 * dependency can be freed.
2689			 */
2690			if (LIST_FIRST(&indirdep->ir_deplisthd) == NULL) {
2691				indirdep->ir_savebp->b_flags |= B_INVAL | B_NOCACHE;
2692				brelse(indirdep->ir_savebp);
2693				/* inline expand WORKLIST_REMOVE(wk); */
2694				wk->wk_state &= ~ONWORKLIST;
2695				LIST_REMOVE(wk, wk_list);
2696				WORKITEM_FREE(indirdep, D_INDIRDEP);
2697				continue;
2698			}
2699			/*
2700			 * Replace up-to-date version with safe version.
2701			 */
2702			ACQUIRE_LOCK(&lk);
2703			indirdep->ir_state &= ~ATTACHED;
2704			indirdep->ir_state |= UNDONE;
2705			MALLOC(indirdep->ir_saveddata, caddr_t, bp->b_bcount,
2706			    M_INDIRDEP, M_WAITOK);
2707			bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
2708			bcopy(indirdep->ir_savebp->b_data, bp->b_data,
2709			    bp->b_bcount);
2710			FREE_LOCK(&lk);
2711			continue;
2712
2713		case D_MKDIR:
2714		case D_BMSAFEMAP:
2715		case D_ALLOCDIRECT:
2716		case D_ALLOCINDIR:
2717			continue;
2718
2719		default:
2720			panic("handle_disk_io_initiation: Unexpected type %s",
2721			    TYPENAME(wk->wk_type));
2722			/* NOTREACHED */
2723		}
2724	}
2725}
2726
2727/*
2728 * Called from within the procedure above to deal with unsatisfied
2729 * allocation dependencies in a directory. The buffer must be locked,
2730 * thus, no I/O completion operations can occur while we are
2731 * manipulating its associated dependencies.
2732 */
2733static void
2734initiate_write_filepage(pagedep, bp)
2735	struct pagedep *pagedep;
2736	struct buf *bp;
2737{
2738	struct diradd *dap;
2739	struct direct *ep;
2740	int i;
2741
2742	if (pagedep->pd_state & IOSTARTED) {
2743		/*
2744		 * This can only happen if there is a driver that does not
2745		 * understand chaining. Here biodone will reissue the call
2746		 * to strategy for the incomplete buffers.
2747		 */
2748		printf("initiate_write_filepage: already started\n");
2749		return;
2750	}
2751	pagedep->pd_state |= IOSTARTED;
2752	ACQUIRE_LOCK(&lk);
2753	for (i = 0; i < DAHASHSZ; i++) {
2754		for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
2755		     dap = LIST_NEXT(dap, da_pdlist)) {
2756			ep = (struct direct *)
2757			    ((char *)bp->b_data + dap->da_offset);
2758			if (ep->d_ino != dap->da_newinum)
2759				panic("%s: dir inum %d != new %d",
2760				    "initiate_write_filepage",
2761				    ep->d_ino, dap->da_newinum);
2762			if (dap->da_state & DIRCHG)
2763				ep->d_ino = dap->da_previous->dm_oldinum;
2764			else
2765				ep->d_ino = 0;
2766			dap->da_state &= ~ATTACHED;
2767			dap->da_state |= UNDONE;
2768		}
2769	}
2770	FREE_LOCK(&lk);
2771}
2772
2773/*
2774 * Called from within the procedure above to deal with unsatisfied
2775 * allocation dependencies in an inodeblock. The buffer must be
2776 * locked, thus, no I/O completion operations can occur while we
2777 * are manipulating its associated dependencies.
2778 */
2779static void
2780initiate_write_inodeblock(inodedep, bp)
2781	struct inodedep *inodedep;
2782	struct buf *bp;			/* The inode block */
2783{
2784	struct allocdirect *adp, *lastadp;
2785	struct dinode *dp;
2786	struct fs *fs;
2787	ufs_lbn_t prevlbn = 0;
2788	int i, deplist;
2789
2790	if (inodedep->id_state & IOSTARTED)
2791		panic("initiate_write_inodeblock: already started");
2792	inodedep->id_state |= IOSTARTED;
2793	fs = inodedep->id_fs;
2794	dp = (struct dinode *)bp->b_data +
2795	    ino_to_fsbo(fs, inodedep->id_ino);
2796	/*
2797	 * If the bitmap is not yet written, then the allocated
2798	 * inode cannot be written to disk.
2799	 */
2800	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
2801		if (inodedep->id_savedino != NULL)
2802			panic("initiate_write_inodeblock: already doing I/O");
2803		MALLOC(inodedep->id_savedino, struct dinode *,
2804		    sizeof(struct dinode), M_INODEDEP, M_WAITOK);
2805		*inodedep->id_savedino = *dp;
2806		bzero((caddr_t)dp, sizeof(struct dinode));
2807		return;
2808	}
2809	/*
2810	 * If no dependencies, then there is nothing to roll back.
2811	 */
2812	inodedep->id_savedsize = dp->di_size;
2813	if (TAILQ_FIRST(&inodedep->id_inoupdt) == NULL)
2814		return;
2815	/*
2816	 * Set the dependencies to busy.
2817	 */
2818	ACQUIRE_LOCK(&lk);
2819	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
2820	     adp = TAILQ_NEXT(adp, ad_next)) {
2821#ifdef DIAGNOSTIC
2822		if (deplist != 0 && prevlbn >= adp->ad_lbn)
2823			panic("softdep_write_inodeblock: lbn order");
2824		prevlbn = adp->ad_lbn;
2825		if (adp->ad_lbn < NDADDR &&
2826		    dp->di_db[adp->ad_lbn] != adp->ad_newblkno)
2827			panic("%s: direct pointer #%ld mismatch %d != %d",
2828			    "softdep_write_inodeblock", adp->ad_lbn,
2829			    dp->di_db[adp->ad_lbn], adp->ad_newblkno);
2830		if (adp->ad_lbn >= NDADDR &&
2831		    dp->di_ib[adp->ad_lbn - NDADDR] != adp->ad_newblkno)
2832			panic("%s: indirect pointer #%ld mismatch %d != %d",
2833			    "softdep_write_inodeblock", adp->ad_lbn - NDADDR,
2834			    dp->di_ib[adp->ad_lbn - NDADDR], adp->ad_newblkno);
2835		deplist |= 1 << adp->ad_lbn;
2836		if ((adp->ad_state & ATTACHED) == 0)
2837			panic("softdep_write_inodeblock: Unknown state 0x%x",
2838			    adp->ad_state);
2839#endif /* DIAGNOSTIC */
2840		adp->ad_state &= ~ATTACHED;
2841		adp->ad_state |= UNDONE;
2842	}
2843	/*
2844	 * The on-disk inode cannot claim to be any larger than the last
2845	 * fragment that has been written. Otherwise, the on-disk inode
2846	 * might have fragments that were not the last block in the file
2847	 * which would corrupt the filesystem.
2848	 */
2849	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
2850	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
2851		if (adp->ad_lbn >= NDADDR)
2852			break;
2853		dp->di_db[adp->ad_lbn] = adp->ad_oldblkno;
2854		/* keep going until hitting a rollback to a frag */
2855		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
2856			continue;
2857		dp->di_size = fs->fs_bsize * adp->ad_lbn + adp->ad_oldsize;
2858		for (i = adp->ad_lbn + 1; i < NDADDR; i++) {
2859#ifdef DIAGNOSTIC
2860			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
2861				panic("softdep_write_inodeblock: lost dep1");
2862#endif /* DIAGNOSTIC */
2863			dp->di_db[i] = 0;
2864		}
2865		for (i = 0; i < NIADDR; i++) {
2866#ifdef DIAGNOSTIC
2867			if (dp->di_ib[i] != 0 &&
2868			    (deplist & ((1 << NDADDR) << i)) == 0)
2869				panic("softdep_write_inodeblock: lost dep2");
2870#endif /* DIAGNOSTIC */
2871			dp->di_ib[i] = 0;
2872		}
2873		FREE_LOCK(&lk);
2874		return;
2875	}
2876	/*
2877	 * If we have zero'ed out the last allocated block of the file,
2878	 * roll back the size to the last currently allocated block.
2879	 * We know that this last allocated block is a full-sized as
2880	 * we already checked for fragments in the loop above.
2881	 */
2882	if (lastadp != NULL &&
2883	    dp->di_size <= (lastadp->ad_lbn + 1) * fs->fs_bsize) {
2884		for (i = lastadp->ad_lbn; i >= 0; i--)
2885			if (dp->di_db[i] != 0)
2886				break;
2887		dp->di_size = (i + 1) * fs->fs_bsize;
2888	}
2889	/*
2890	 * The only dependencies are for indirect blocks.
2891	 *
2892	 * The file size for indirect block additions is not guaranteed.
2893	 * Such a guarantee would be non-trivial to achieve. The conventional
2894	 * synchronous write implementation also does not make this guarantee.
2895	 * Fsck should catch and fix discrepancies. Arguably, the file size
2896	 * can be over-estimated without destroying integrity when the file
2897	 * moves into the indirect blocks (i.e., is large). If we want to
2898	 * postpone fsck, we are stuck with this argument.
2899	 */
2900	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
2901		dp->di_ib[adp->ad_lbn - NDADDR] = 0;
2902	FREE_LOCK(&lk);
2903}
2904
2905/*
2906 * This routine is called during the completion interrupt
2907 * service routine for a disk write (from the procedure called
2908 * by the device driver to inform the file system caches of
2909 * a request completion).  It should be called early in this
2910 * procedure, before the block is made available to other
2911 * processes or other routines are called.
2912 */
2913void
2914softdep_disk_write_complete(bp)
2915	struct buf *bp;		/* describes the completed disk write */
2916{
2917	struct worklist *wk;
2918	struct workhead reattach;
2919	struct newblk *newblk;
2920	struct allocindir *aip;
2921	struct allocdirect *adp;
2922	struct indirdep *indirdep;
2923	struct inodedep *inodedep;
2924	struct bmsafemap *bmsafemap;
2925
2926#ifdef DEBUG
2927	if (lk.lkt_held != -1)
2928		panic("softdep_disk_write_complete: lock is held");
2929	lk.lkt_held = -2;
2930#endif
2931	LIST_INIT(&reattach);
2932	while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
2933		WORKLIST_REMOVE(wk);
2934		switch (wk->wk_type) {
2935
2936		case D_PAGEDEP:
2937			if (handle_written_filepage(WK_PAGEDEP(wk), bp))
2938				WORKLIST_INSERT(&reattach, wk);
2939			continue;
2940
2941		case D_INODEDEP:
2942			if (handle_written_inodeblock(WK_INODEDEP(wk), bp))
2943				WORKLIST_INSERT(&reattach, wk);
2944			continue;
2945
2946		case D_BMSAFEMAP:
2947			bmsafemap = WK_BMSAFEMAP(wk);
2948			while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkhd))) {
2949				newblk->nb_state |= DEPCOMPLETE;
2950				newblk->nb_bmsafemap = NULL;
2951				LIST_REMOVE(newblk, nb_deps);
2952			}
2953			while ((adp =
2954			   LIST_FIRST(&bmsafemap->sm_allocdirecthd))) {
2955				adp->ad_state |= DEPCOMPLETE;
2956				adp->ad_buf = NULL;
2957				LIST_REMOVE(adp, ad_deps);
2958				handle_allocdirect_partdone(adp);
2959			}
2960			while ((aip =
2961			    LIST_FIRST(&bmsafemap->sm_allocindirhd))) {
2962				aip->ai_state |= DEPCOMPLETE;
2963				aip->ai_buf = NULL;
2964				LIST_REMOVE(aip, ai_deps);
2965				handle_allocindir_partdone(aip);
2966			}
2967			while ((inodedep =
2968			     LIST_FIRST(&bmsafemap->sm_inodedephd)) != NULL) {
2969				inodedep->id_state |= DEPCOMPLETE;
2970				LIST_REMOVE(inodedep, id_deps);
2971				inodedep->id_buf = NULL;
2972			}
2973			WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
2974			continue;
2975
2976		case D_MKDIR:
2977			handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
2978			continue;
2979
2980		case D_ALLOCDIRECT:
2981			adp = WK_ALLOCDIRECT(wk);
2982			adp->ad_state |= COMPLETE;
2983			handle_allocdirect_partdone(adp);
2984			continue;
2985
2986		case D_ALLOCINDIR:
2987			aip = WK_ALLOCINDIR(wk);
2988			aip->ai_state |= COMPLETE;
2989			handle_allocindir_partdone(aip);
2990			continue;
2991
2992		case D_INDIRDEP:
2993			indirdep = WK_INDIRDEP(wk);
2994			if (indirdep->ir_state & GOINGAWAY)
2995				panic("disk_write_complete: indirdep gone");
2996			bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
2997			FREE(indirdep->ir_saveddata, M_INDIRDEP);
2998			indirdep->ir_saveddata = 0;
2999			indirdep->ir_state &= ~UNDONE;
3000			indirdep->ir_state |= ATTACHED;
3001			while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != 0) {
3002				handle_allocindir_partdone(aip);
3003				if (aip == LIST_FIRST(&indirdep->ir_donehd))
3004					panic("disk_write_complete: not gone");
3005			}
3006			WORKLIST_INSERT(&reattach, wk);
3007			if ((bp->b_flags & B_DELWRI) == 0)
3008				stat_indir_blk_ptrs++;
3009			bdirty(bp);
3010			continue;
3011
3012		default:
3013			panic("handle_disk_write_complete: Unknown type %s",
3014			    TYPENAME(wk->wk_type));
3015			/* NOTREACHED */
3016		}
3017	}
3018	/*
3019	 * Reattach any requests that must be redone.
3020	 */
3021	while ((wk = LIST_FIRST(&reattach)) != NULL) {
3022		WORKLIST_REMOVE(wk);
3023		WORKLIST_INSERT(&bp->b_dep, wk);
3024	}
3025#ifdef DEBUG
3026	if (lk.lkt_held != -2)
3027		panic("softdep_disk_write_complete: lock lost");
3028	lk.lkt_held = -1;
3029#endif
3030}
3031
3032/*
3033 * Called from within softdep_disk_write_complete above. Note that
3034 * this routine is always called from interrupt level with further
3035 * splbio interrupts blocked.
3036 */
3037static void
3038handle_allocdirect_partdone(adp)
3039	struct allocdirect *adp;	/* the completed allocdirect */
3040{
3041	struct allocdirect *listadp;
3042	struct inodedep *inodedep;
3043	long bsize;
3044
3045	if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
3046		return;
3047	if (adp->ad_buf != NULL)
3048		panic("handle_allocdirect_partdone: dangling dep");
3049	/*
3050	 * The on-disk inode cannot claim to be any larger than the last
3051	 * fragment that has been written. Otherwise, the on-disk inode
3052	 * might have fragments that were not the last block in the file
3053	 * which would corrupt the filesystem. Thus, we cannot free any
3054	 * allocdirects after one whose ad_oldblkno claims a fragment as
3055	 * these blocks must be rolled back to zero before writing the inode.
3056	 * We check the currently active set of allocdirects in id_inoupdt.
3057	 */
3058	inodedep = adp->ad_inodedep;
3059	bsize = inodedep->id_fs->fs_bsize;
3060	for (listadp = TAILQ_FIRST(&inodedep->id_inoupdt); listadp;
3061	     listadp = TAILQ_NEXT(listadp, ad_next)) {
3062		/* found our block */
3063		if (listadp == adp)
3064			break;
3065		/* continue if ad_oldlbn is not a fragment */
3066		if (listadp->ad_oldsize == 0 ||
3067		    listadp->ad_oldsize == bsize)
3068			continue;
3069		/* hit a fragment */
3070		return;
3071	}
3072	/*
3073	 * If we have reached the end of the current list without
3074	 * finding the just finished dependency, then it must be
3075	 * on the future dependency list. Future dependencies cannot
3076	 * be freed until they are moved to the current list.
3077	 */
3078	if (listadp == NULL) {
3079#ifdef DEBUG
3080		for (listadp = TAILQ_FIRST(&inodedep->id_newinoupdt); listadp;
3081		     listadp = TAILQ_NEXT(listadp, ad_next))
3082			/* found our block */
3083			if (listadp == adp)
3084				break;
3085		if (listadp == NULL)
3086			panic("handle_allocdirect_partdone: lost dep");
3087#endif /* DEBUG */
3088		return;
3089	}
3090	/*
3091	 * If we have found the just finished dependency, then free
3092	 * it along with anything that follows it that is complete.
3093	 */
3094	for (; adp; adp = listadp) {
3095		listadp = TAILQ_NEXT(adp, ad_next);
3096		if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
3097			return;
3098		free_allocdirect(&inodedep->id_inoupdt, adp, 1);
3099	}
3100}
3101
3102/*
3103 * Called from within softdep_disk_write_complete above. Note that
3104 * this routine is always called from interrupt level with further
3105 * splbio interrupts blocked.
3106 */
3107static void
3108handle_allocindir_partdone(aip)
3109	struct allocindir *aip;		/* the completed allocindir */
3110{
3111	struct indirdep *indirdep;
3112
3113	if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
3114		return;
3115	if (aip->ai_buf != NULL)
3116		panic("handle_allocindir_partdone: dangling dependency");
3117	indirdep = aip->ai_indirdep;
3118	if (indirdep->ir_state & UNDONE) {
3119		LIST_REMOVE(aip, ai_next);
3120		LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
3121		return;
3122	}
3123	((ufs_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
3124	    aip->ai_newblkno;
3125	LIST_REMOVE(aip, ai_next);
3126	if (aip->ai_freefrag != NULL)
3127		add_to_worklist(&aip->ai_freefrag->ff_list);
3128	WORKITEM_FREE(aip, D_ALLOCINDIR);
3129}
3130
3131/*
3132 * Called from within softdep_disk_write_complete above to restore
3133 * in-memory inode block contents to their most up-to-date state. Note
3134 * that this routine is always called from interrupt level with further
3135 * splbio interrupts blocked.
3136 */
3137static int
3138handle_written_inodeblock(inodedep, bp)
3139	struct inodedep *inodedep;
3140	struct buf *bp;		/* buffer containing the inode block */
3141{
3142	struct worklist *wk, *filefree;
3143	struct allocdirect *adp, *nextadp;
3144	struct dinode *dp;
3145	int hadchanges;
3146
3147	if ((inodedep->id_state & IOSTARTED) == 0)
3148		panic("handle_written_inodeblock: not started");
3149	inodedep->id_state &= ~IOSTARTED;
3150	inodedep->id_state |= COMPLETE;
3151	dp = (struct dinode *)bp->b_data +
3152	    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
3153	/*
3154	 * If we had to rollback the inode allocation because of
3155	 * bitmaps being incomplete, then simply restore it.
3156	 * Keep the block dirty so that it will not be reclaimed until
3157	 * all associated dependencies have been cleared and the
3158	 * corresponding updates written to disk.
3159	 */
3160	if (inodedep->id_savedino != NULL) {
3161		*dp = *inodedep->id_savedino;
3162		FREE(inodedep->id_savedino, M_INODEDEP);
3163		inodedep->id_savedino = NULL;
3164		if ((bp->b_flags & B_DELWRI) == 0)
3165			stat_inode_bitmap++;
3166		bdirty(bp);
3167		return (1);
3168	}
3169	/*
3170	 * Roll forward anything that had to be rolled back before
3171	 * the inode could be updated.
3172	 */
3173	hadchanges = 0;
3174	for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
3175		nextadp = TAILQ_NEXT(adp, ad_next);
3176		if (adp->ad_state & ATTACHED)
3177			panic("handle_written_inodeblock: new entry");
3178		if (adp->ad_lbn < NDADDR) {
3179			if (dp->di_db[adp->ad_lbn] != adp->ad_oldblkno)
3180				panic("%s: %s #%ld mismatch %d != %d",
3181				    "handle_written_inodeblock",
3182				    "direct pointer", adp->ad_lbn,
3183				    dp->di_db[adp->ad_lbn], adp->ad_oldblkno);
3184			dp->di_db[adp->ad_lbn] = adp->ad_newblkno;
3185		} else {
3186			if (dp->di_ib[adp->ad_lbn - NDADDR] != 0)
3187				panic("%s: %s #%ld allocated as %d",
3188				    "handle_written_inodeblock",
3189				    "indirect pointer", adp->ad_lbn - NDADDR,
3190				    dp->di_ib[adp->ad_lbn - NDADDR]);
3191			dp->di_ib[adp->ad_lbn - NDADDR] = adp->ad_newblkno;
3192		}
3193		adp->ad_state &= ~UNDONE;
3194		adp->ad_state |= ATTACHED;
3195		hadchanges = 1;
3196	}
3197	if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
3198		stat_direct_blk_ptrs++;
3199	/*
3200	 * Reset the file size to its most up-to-date value.
3201	 */
3202	if (inodedep->id_savedsize == -1)
3203		panic("handle_written_inodeblock: bad size");
3204	if (dp->di_size != inodedep->id_savedsize) {
3205		dp->di_size = inodedep->id_savedsize;
3206		hadchanges = 1;
3207	}
3208	inodedep->id_savedsize = -1;
3209	/*
3210	 * If there were any rollbacks in the inode block, then it must be
3211	 * marked dirty so that its will eventually get written back in
3212	 * its correct form.
3213	 */
3214	if (hadchanges)
3215		bdirty(bp);
3216	/*
3217	 * Process any allocdirects that completed during the update.
3218	 */
3219	if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
3220		handle_allocdirect_partdone(adp);
3221	/*
3222	 * Process deallocations that were held pending until the
3223	 * inode had been written to disk. Freeing of the inode
3224	 * is delayed until after all blocks have been freed to
3225	 * avoid creation of new <vfsid, inum, lbn> triples
3226	 * before the old ones have been deleted.
3227	 */
3228	filefree = NULL;
3229	while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
3230		WORKLIST_REMOVE(wk);
3231		switch (wk->wk_type) {
3232
3233		case D_FREEFILE:
3234			/*
3235			 * We defer adding filefree to the worklist until
3236			 * all other additions have been made to ensure
3237			 * that it will be done after all the old blocks
3238			 * have been freed.
3239			 */
3240			if (filefree != NULL)
3241				panic("handle_written_inodeblock: filefree");
3242			filefree = wk;
3243			continue;
3244
3245		case D_MKDIR:
3246			handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
3247			continue;
3248
3249		case D_DIRADD:
3250			diradd_inode_written(WK_DIRADD(wk), inodedep);
3251			continue;
3252
3253		case D_FREEBLKS:
3254		case D_FREEFRAG:
3255		case D_DIRREM:
3256			add_to_worklist(wk);
3257			continue;
3258
3259		default:
3260			panic("handle_written_inodeblock: Unknown type %s",
3261			    TYPENAME(wk->wk_type));
3262			/* NOTREACHED */
3263		}
3264	}
3265	if (filefree != NULL) {
3266		if (free_inodedep(inodedep) == 0)
3267			panic("handle_written_inodeblock: live inodedep");
3268		add_to_worklist(filefree);
3269		return (0);
3270	}
3271
3272	/*
3273	 * If no outstanding dependencies, free it.
3274	 */
3275	if (free_inodedep(inodedep) || TAILQ_FIRST(&inodedep->id_inoupdt) == 0)
3276		return (0);
3277	return (hadchanges);
3278}
3279
3280/*
3281 * Process a diradd entry after its dependent inode has been written.
3282 * This routine must be called with splbio interrupts blocked.
3283 */
3284static void
3285diradd_inode_written(dap, inodedep)
3286	struct diradd *dap;
3287	struct inodedep *inodedep;
3288{
3289	struct pagedep *pagedep;
3290
3291	dap->da_state |= COMPLETE;
3292	if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
3293		if (dap->da_state & DIRCHG)
3294			pagedep = dap->da_previous->dm_pagedep;
3295		else
3296			pagedep = dap->da_pagedep;
3297		LIST_REMOVE(dap, da_pdlist);
3298		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
3299	}
3300	WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
3301}
3302
3303/*
3304 * Handle the completion of a mkdir dependency.
3305 */
3306static void
3307handle_written_mkdir(mkdir, type)
3308	struct mkdir *mkdir;
3309	int type;
3310{
3311	struct diradd *dap;
3312	struct pagedep *pagedep;
3313
3314	if (mkdir->md_state != type)
3315		panic("handle_written_mkdir: bad type");
3316	dap = mkdir->md_diradd;
3317	dap->da_state &= ~type;
3318	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
3319		dap->da_state |= DEPCOMPLETE;
3320	if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
3321		if (dap->da_state & DIRCHG)
3322			pagedep = dap->da_previous->dm_pagedep;
3323		else
3324			pagedep = dap->da_pagedep;
3325		LIST_REMOVE(dap, da_pdlist);
3326		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
3327	}
3328	LIST_REMOVE(mkdir, md_mkdirs);
3329	WORKITEM_FREE(mkdir, D_MKDIR);
3330}
3331
3332/*
3333 * Called from within softdep_disk_write_complete above.
3334 * A write operation was just completed. Removed inodes can
3335 * now be freed and associated block pointers may be committed.
3336 * Note that this routine is always called from interrupt level
3337 * with further splbio interrupts blocked.
3338 */
3339static int
3340handle_written_filepage(pagedep, bp)
3341	struct pagedep *pagedep;
3342	struct buf *bp;		/* buffer containing the written page */
3343{
3344	struct dirrem *dirrem;
3345	struct diradd *dap, *nextdap;
3346	struct direct *ep;
3347	int i, chgs;
3348
3349	if ((pagedep->pd_state & IOSTARTED) == 0)
3350		panic("handle_written_filepage: not started");
3351	pagedep->pd_state &= ~IOSTARTED;
3352	/*
3353	 * Process any directory removals that have been committed.
3354	 */
3355	while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
3356		LIST_REMOVE(dirrem, dm_next);
3357		dirrem->dm_dirinum = pagedep->pd_ino;
3358		add_to_worklist(&dirrem->dm_list);
3359	}
3360	/*
3361	 * Free any directory additions that have been committed.
3362	 */
3363	while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
3364		free_diradd(dap);
3365	/*
3366	 * Uncommitted directory entries must be restored.
3367	 */
3368	for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
3369		for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
3370		     dap = nextdap) {
3371			nextdap = LIST_NEXT(dap, da_pdlist);
3372			if (dap->da_state & ATTACHED)
3373				panic("handle_written_filepage: attached");
3374			ep = (struct direct *)
3375			    ((char *)bp->b_data + dap->da_offset);
3376			ep->d_ino = dap->da_newinum;
3377			dap->da_state &= ~UNDONE;
3378			dap->da_state |= ATTACHED;
3379			chgs = 1;
3380			/*
3381			 * If the inode referenced by the directory has
3382			 * been written out, then the dependency can be
3383			 * moved to the pending list.
3384			 */
3385			if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
3386				LIST_REMOVE(dap, da_pdlist);
3387				LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
3388				    da_pdlist);
3389			}
3390		}
3391	}
3392	/*
3393	 * If there were any rollbacks in the directory, then it must be
3394	 * marked dirty so that its will eventually get written back in
3395	 * its correct form.
3396	 */
3397	if (chgs) {
3398		if ((bp->b_flags & B_DELWRI) == 0)
3399			stat_dir_entry++;
3400		bdirty(bp);
3401	}
3402	/*
3403	 * If no dependencies remain, the pagedep will be freed.
3404	 * Otherwise it will remain to update the page before it
3405	 * is written back to disk.
3406	 */
3407	if (LIST_FIRST(&pagedep->pd_pendinghd) == 0) {
3408		for (i = 0; i < DAHASHSZ; i++)
3409			if (LIST_FIRST(&pagedep->pd_diraddhd[i]) != NULL)
3410				break;
3411		if (i == DAHASHSZ) {
3412			LIST_REMOVE(pagedep, pd_hash);
3413			WORKITEM_FREE(pagedep, D_PAGEDEP);
3414			return (0);
3415		}
3416	}
3417	return (1);
3418}
3419
3420/*
3421 * Writing back in-core inode structures.
3422 *
3423 * The file system only accesses an inode's contents when it occupies an
3424 * "in-core" inode structure.  These "in-core" structures are separate from
3425 * the page frames used to cache inode blocks.  Only the latter are
3426 * transferred to/from the disk.  So, when the updated contents of the
3427 * "in-core" inode structure are copied to the corresponding in-memory inode
3428 * block, the dependencies are also transferred.  The following procedure is
3429 * called when copying a dirty "in-core" inode to a cached inode block.
3430 */
3431
3432/*
3433 * Called when an inode is loaded from disk. If the effective link count
3434 * differed from the actual link count when it was last flushed, then we
3435 * need to ensure that the correct effective link count is put back.
3436 */
3437void
3438softdep_load_inodeblock(ip)
3439	struct inode *ip;	/* the "in_core" copy of the inode */
3440{
3441	struct inodedep *inodedep;
3442
3443	/*
3444	 * Check for alternate nlink count.
3445	 */
3446	ip->i_effnlink = ip->i_nlink;
3447	ACQUIRE_LOCK(&lk);
3448	if (inodedep_lookup(ip->i_fs, ip->i_number, 0, &inodedep) == 0) {
3449		FREE_LOCK(&lk);
3450		return;
3451	}
3452	if (inodedep->id_nlinkdelta != 0) {
3453		ip->i_effnlink -= inodedep->id_nlinkdelta;
3454		ip->i_flag |= IN_MODIFIED;
3455		inodedep->id_nlinkdelta = 0;
3456		(void) free_inodedep(inodedep);
3457	}
3458	FREE_LOCK(&lk);
3459}
3460
3461/*
3462 * This routine is called just before the "in-core" inode
3463 * information is to be copied to the in-memory inode block.
3464 * Recall that an inode block contains several inodes. If
3465 * the force flag is set, then the dependencies will be
3466 * cleared so that the update can always be made. Note that
3467 * the buffer is locked when this routine is called, so we
3468 * will never be in the middle of writing the inode block
3469 * to disk.
3470 */
3471void
3472softdep_update_inodeblock(ip, bp, waitfor)
3473	struct inode *ip;	/* the "in_core" copy of the inode */
3474	struct buf *bp;		/* the buffer containing the inode block */
3475	int waitfor;		/* nonzero => update must be allowed */
3476{
3477	struct inodedep *inodedep;
3478	struct worklist *wk;
3479	int error, gotit;
3480
3481	/*
3482	 * If the effective link count is not equal to the actual link
3483	 * count, then we must track the difference in an inodedep while
3484	 * the inode is (potentially) tossed out of the cache. Otherwise,
3485	 * if there is no existing inodedep, then there are no dependencies
3486	 * to track.
3487	 */
3488	ACQUIRE_LOCK(&lk);
3489	if (ip->i_effnlink != ip->i_nlink) {
3490		(void) inodedep_lookup(ip->i_fs, ip->i_number, DEPALLOC,
3491		    &inodedep);
3492	} else if (inodedep_lookup(ip->i_fs, ip->i_number, 0, &inodedep) == 0) {
3493		FREE_LOCK(&lk);
3494		return;
3495	}
3496	if (ip->i_nlink < ip->i_effnlink)
3497		panic("softdep_update_inodeblock: bad delta");
3498	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
3499	/*
3500	 * Changes have been initiated. Anything depending on these
3501	 * changes cannot occur until this inode has been written.
3502	 */
3503	inodedep->id_state &= ~COMPLETE;
3504	if ((inodedep->id_state & ONWORKLIST) == 0)
3505		WORKLIST_INSERT(&bp->b_dep, &inodedep->id_list);
3506	/*
3507	 * Any new dependencies associated with the incore inode must
3508	 * now be moved to the list associated with the buffer holding
3509	 * the in-memory copy of the inode. Once merged process any
3510	 * allocdirects that are completed by the merger.
3511	 */
3512	merge_inode_lists(inodedep);
3513	if (TAILQ_FIRST(&inodedep->id_inoupdt) != NULL)
3514		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt));
3515	/*
3516	 * Now that the inode has been pushed into the buffer, the
3517	 * operations dependent on the inode being written to disk
3518	 * can be moved to the id_bufwait so that they will be
3519	 * processed when the buffer I/O completes.
3520	 */
3521	while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
3522		WORKLIST_REMOVE(wk);
3523		WORKLIST_INSERT(&inodedep->id_bufwait, wk);
3524	}
3525	/*
3526	 * Newly allocated inodes cannot be written until the bitmap
3527	 * that allocates them have been written (indicated by
3528	 * DEPCOMPLETE being set in id_state). If we are doing a
3529	 * forced sync (e.g., an fsync on a file), we force the bitmap
3530	 * to be written so that the update can be done.
3531	 */
3532	if ((inodedep->id_state & DEPCOMPLETE) != 0 || waitfor == 0) {
3533		FREE_LOCK(&lk);
3534		return;
3535	}
3536	gotit = getdirtybuf(&inodedep->id_buf, MNT_WAIT);
3537	FREE_LOCK(&lk);
3538	if (gotit &&
3539	    (error = VOP_BWRITE(inodedep->id_buf->b_vp, inodedep->id_buf)) != 0)
3540		softdep_error("softdep_update_inodeblock: bwrite", error);
3541	if ((inodedep->id_state & DEPCOMPLETE) == 0)
3542		panic("softdep_update_inodeblock: update failed");
3543}
3544
3545/*
3546 * Merge the new inode dependency list (id_newinoupdt) into the old
3547 * inode dependency list (id_inoupdt). This routine must be called
3548 * with splbio interrupts blocked.
3549 */
3550static void
3551merge_inode_lists(inodedep)
3552	struct inodedep *inodedep;
3553{
3554	struct allocdirect *listadp, *newadp;
3555
3556	newadp = TAILQ_FIRST(&inodedep->id_newinoupdt);
3557	for (listadp = TAILQ_FIRST(&inodedep->id_inoupdt); listadp && newadp;) {
3558		if (listadp->ad_lbn < newadp->ad_lbn) {
3559			listadp = TAILQ_NEXT(listadp, ad_next);
3560			continue;
3561		}
3562		TAILQ_REMOVE(&inodedep->id_newinoupdt, newadp, ad_next);
3563		TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
3564		if (listadp->ad_lbn == newadp->ad_lbn) {
3565			allocdirect_merge(&inodedep->id_inoupdt, newadp,
3566			    listadp);
3567			listadp = newadp;
3568		}
3569		newadp = TAILQ_FIRST(&inodedep->id_newinoupdt);
3570	}
3571	while ((newadp = TAILQ_FIRST(&inodedep->id_newinoupdt)) != NULL) {
3572		TAILQ_REMOVE(&inodedep->id_newinoupdt, newadp, ad_next);
3573		TAILQ_INSERT_TAIL(&inodedep->id_inoupdt, newadp, ad_next);
3574	}
3575}
3576
3577/*
3578 * If we are doing an fsync, then we must ensure that any directory
3579 * entries for the inode have been written after the inode gets to disk.
3580 */
3581int
3582softdep_fsync(vp)
3583	struct vnode *vp;	/* the "in_core" copy of the inode */
3584{
3585	struct diradd *dap, *olddap;
3586	struct inodedep *inodedep;
3587	struct pagedep *pagedep;
3588	struct worklist *wk;
3589	struct mount *mnt;
3590	struct vnode *pvp;
3591	struct inode *ip;
3592	struct buf *bp;
3593	struct fs *fs;
3594	struct proc *p = CURPROC;		/* XXX */
3595	int error, ret, flushparent;
3596	ino_t parentino;
3597	ufs_lbn_t lbn;
3598
3599	ip = VTOI(vp);
3600	fs = ip->i_fs;
3601	for (error = 0, flushparent = 0, olddap = NULL; ; ) {
3602		ACQUIRE_LOCK(&lk);
3603		if (inodedep_lookup(fs, ip->i_number, 0, &inodedep) == 0)
3604			break;
3605		if (LIST_FIRST(&inodedep->id_inowait) != NULL ||
3606		    LIST_FIRST(&inodedep->id_bufwait) != NULL ||
3607		    TAILQ_FIRST(&inodedep->id_inoupdt) != NULL ||
3608		    TAILQ_FIRST(&inodedep->id_newinoupdt) != NULL)
3609			panic("softdep_fsync: pending ops");
3610		if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
3611			break;
3612		if (wk->wk_type != D_DIRADD)
3613			panic("softdep_fsync: Unexpected type %s",
3614			    TYPENAME(wk->wk_type));
3615		dap = WK_DIRADD(wk);
3616		/*
3617		 * If we have failed to get rid of all the dependencies
3618		 * then something is seriously wrong.
3619		 */
3620		if (dap == olddap)
3621			panic("softdep_fsync: flush failed");
3622		olddap = dap;
3623		/*
3624		 * Flush our parent if this directory entry
3625		 * has a MKDIR_PARENT dependency.
3626		 */
3627		if (dap->da_state & DIRCHG)
3628			pagedep = dap->da_previous->dm_pagedep;
3629		else
3630			pagedep = dap->da_pagedep;
3631		mnt = pagedep->pd_mnt;
3632		parentino = pagedep->pd_ino;
3633		lbn = pagedep->pd_lbn;
3634		if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE)
3635			panic("softdep_fsync: dirty");
3636		flushparent = dap->da_state & MKDIR_PARENT;
3637		/*
3638		 * If we are being fsync'ed as part of vgone'ing this vnode,
3639		 * then we will not be able to release and recover the
3640		 * vnode below, so we just have to give up on writing its
3641		 * directory entry out. It will eventually be written, just
3642		 * not now, but then the user was not asking to have it
3643		 * written, so we are not breaking any promises.
3644		 */
3645		if (vp->v_flag & VXLOCK)
3646			break;
3647		/*
3648		 * We prevent deadlock by always fetching inodes from the
3649		 * root, moving down the directory tree. Thus, when fetching
3650		 * our parent directory, we must unlock ourselves before
3651		 * requesting the lock on our parent. See the comment in
3652		 * ufs_lookup for details on possible races.
3653		 */
3654		FREE_LOCK(&lk);
3655		VOP_UNLOCK(vp, 0, p);
3656		if ((error = VFS_VGET(mnt, parentino, &pvp)) != 0) {
3657			vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, p);
3658			return (error);
3659		}
3660		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, p);
3661		if (flushparent) {
3662			if ((error = UFS_UPDATE(pvp, 1)) != 0) {
3663				vput(pvp);
3664				return (error);
3665			}
3666		}
3667		/*
3668		 * Flush directory page containing the inode's name.
3669		 */
3670		error = bread(pvp, lbn, blksize(fs, VTOI(pvp), lbn), p->p_ucred,
3671		    &bp);
3672		ret = VOP_BWRITE(bp->b_vp, bp);
3673		vput(pvp);
3674		if (error != 0)
3675			return (error);
3676		if (ret != 0)
3677			return (ret);
3678	}
3679	FREE_LOCK(&lk);
3680	return (0);
3681}
3682
3683/*
3684 * Flush all the dirty bitmaps associated with the block device
3685 * before flushing the rest of the dirty blocks so as to reduce
3686 * the number of dependencies that will have to be rolled back.
3687 */
3688void
3689softdep_fsync_mountdev(vp)
3690	struct vnode *vp;
3691{
3692	struct buf *bp, *nbp;
3693	struct worklist *wk;
3694
3695	if (vp->v_type != VBLK)
3696		panic("softdep_fsync_mountdev: vnode not VBLK");
3697	ACQUIRE_LOCK(&lk);
3698	for (bp = TAILQ_FIRST(&vp->v_dirtyblkhd); bp; bp = nbp) {
3699		nbp = TAILQ_NEXT(bp, b_vnbufs);
3700		/*
3701		 * If it is already scheduled, skip to the next buffer.
3702		 */
3703		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT))
3704			continue;
3705		if ((bp->b_flags & B_DELWRI) == 0)
3706			panic("softdep_fsync_mountdev: not dirty");
3707		/*
3708		 * We are only interested in bitmaps with outstanding
3709		 * dependencies.
3710		 */
3711		if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
3712		    wk->wk_type != D_BMSAFEMAP) {
3713			BUF_UNLOCK(bp);
3714			continue;
3715		}
3716		bremfree(bp);
3717		FREE_LOCK(&lk);
3718		(void) bawrite(bp);
3719		ACQUIRE_LOCK(&lk);
3720		/*
3721		 * Since we may have slept during the I/O, we need
3722		 * to start from a known point.
3723		 */
3724		nbp = TAILQ_FIRST(&vp->v_dirtyblkhd);
3725	}
3726	drain_output(vp, 1);
3727	FREE_LOCK(&lk);
3728}
3729
3730/*
3731 * This routine is called when we are trying to synchronously flush a
3732 * file. This routine must eliminate any filesystem metadata dependencies
3733 * so that the syncing routine can succeed by pushing the dirty blocks
3734 * associated with the file. If any I/O errors occur, they are returned.
3735 */
3736int
3737softdep_sync_metadata(ap)
3738	struct vop_fsync_args /* {
3739		struct vnode *a_vp;
3740		struct ucred *a_cred;
3741		int a_waitfor;
3742		struct proc *a_p;
3743	} */ *ap;
3744{
3745	struct vnode *vp = ap->a_vp;
3746	struct pagedep *pagedep;
3747	struct allocdirect *adp;
3748	struct allocindir *aip;
3749	struct buf *bp, *nbp;
3750	struct worklist *wk;
3751	int i, error, waitfor;
3752
3753	/*
3754	 * Check whether this vnode is involved in a filesystem
3755	 * that is doing soft dependency processing.
3756	 */
3757	if (vp->v_type != VBLK) {
3758		if (!DOINGSOFTDEP(vp))
3759			return (0);
3760	} else
3761		if (vp->v_specmountpoint == NULL ||
3762		    (vp->v_specmountpoint->mnt_flag & MNT_SOFTDEP) == 0)
3763			return (0);
3764	/*
3765	 * Ensure that any direct block dependencies have been cleared.
3766	 */
3767	ACQUIRE_LOCK(&lk);
3768	if ((error = flush_inodedep_deps(VTOI(vp)->i_fs, VTOI(vp)->i_number))) {
3769		FREE_LOCK(&lk);
3770		return (error);
3771	}
3772	/*
3773	 * For most files, the only metadata dependencies are the
3774	 * cylinder group maps that allocate their inode or blocks.
3775	 * The block allocation dependencies can be found by traversing
3776	 * the dependency lists for any buffers that remain on their
3777	 * dirty buffer list. The inode allocation dependency will
3778	 * be resolved when the inode is updated with MNT_WAIT.
3779	 * This work is done in two passes. The first pass grabs most
3780	 * of the buffers and begins asynchronously writing them. The
3781	 * only way to wait for these asynchronous writes is to sleep
3782	 * on the filesystem vnode which may stay busy for a long time
3783	 * if the filesystem is active. So, instead, we make a second
3784	 * pass over the dependencies blocking on each write. In the
3785	 * usual case we will be blocking against a write that we
3786	 * initiated, so when it is done the dependency will have been
3787	 * resolved. Thus the second pass is expected to end quickly.
3788	 */
3789	waitfor = MNT_NOWAIT;
3790top:
3791	if (getdirtybuf(&TAILQ_FIRST(&vp->v_dirtyblkhd), MNT_WAIT) == 0) {
3792		FREE_LOCK(&lk);
3793		return (0);
3794	}
3795	bp = TAILQ_FIRST(&vp->v_dirtyblkhd);
3796loop:
3797	/*
3798	 * As we hold the buffer locked, none of its dependencies
3799	 * will disappear.
3800	 */
3801	for (wk = LIST_FIRST(&bp->b_dep); wk;
3802	     wk = LIST_NEXT(wk, wk_list)) {
3803		switch (wk->wk_type) {
3804
3805		case D_ALLOCDIRECT:
3806			adp = WK_ALLOCDIRECT(wk);
3807			if (adp->ad_state & DEPCOMPLETE)
3808				break;
3809			nbp = adp->ad_buf;
3810			if (getdirtybuf(&nbp, waitfor) == 0)
3811				break;
3812			FREE_LOCK(&lk);
3813			if (waitfor == MNT_NOWAIT) {
3814				bawrite(nbp);
3815			} else if ((error = VOP_BWRITE(nbp->b_vp, nbp)) != 0) {
3816				bawrite(bp);
3817				return (error);
3818			}
3819			ACQUIRE_LOCK(&lk);
3820			break;
3821
3822		case D_ALLOCINDIR:
3823			aip = WK_ALLOCINDIR(wk);
3824			if (aip->ai_state & DEPCOMPLETE)
3825				break;
3826			nbp = aip->ai_buf;
3827			if (getdirtybuf(&nbp, waitfor) == 0)
3828				break;
3829			FREE_LOCK(&lk);
3830			if (waitfor == MNT_NOWAIT) {
3831				bawrite(nbp);
3832			} else if ((error = VOP_BWRITE(nbp->b_vp, nbp)) != 0) {
3833				bawrite(bp);
3834				return (error);
3835			}
3836			ACQUIRE_LOCK(&lk);
3837			break;
3838
3839		case D_INDIRDEP:
3840		restart:
3841			for (aip = LIST_FIRST(&WK_INDIRDEP(wk)->ir_deplisthd);
3842			     aip; aip = LIST_NEXT(aip, ai_next)) {
3843				if (aip->ai_state & DEPCOMPLETE)
3844					continue;
3845				nbp = aip->ai_buf;
3846				if (getdirtybuf(&nbp, MNT_WAIT) == 0)
3847					goto restart;
3848				FREE_LOCK(&lk);
3849				if ((error = VOP_BWRITE(nbp->b_vp, nbp)) != 0) {
3850					bawrite(bp);
3851					return (error);
3852				}
3853				ACQUIRE_LOCK(&lk);
3854				goto restart;
3855			}
3856			break;
3857
3858		case D_INODEDEP:
3859			if ((error = flush_inodedep_deps(WK_INODEDEP(wk)->id_fs,
3860			    WK_INODEDEP(wk)->id_ino)) != 0) {
3861				FREE_LOCK(&lk);
3862				bawrite(bp);
3863				return (error);
3864			}
3865			break;
3866
3867		case D_PAGEDEP:
3868			/*
3869			 * We are trying to sync a directory that may
3870			 * have dependencies on both its own metadata
3871			 * and/or dependencies on the inodes of any
3872			 * recently allocated files. We walk its diradd
3873			 * lists pushing out the associated inode.
3874			 */
3875			pagedep = WK_PAGEDEP(wk);
3876			for (i = 0; i < DAHASHSZ; i++) {
3877				if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
3878					continue;
3879				if ((error =
3880				    flush_pagedep_deps(vp, pagedep->pd_mnt,
3881						&pagedep->pd_diraddhd[i]))) {
3882					FREE_LOCK(&lk);
3883					bawrite(bp);
3884					return (error);
3885				}
3886			}
3887			break;
3888
3889		case D_MKDIR:
3890			/*
3891			 * This case should never happen if the vnode has
3892			 * been properly sync'ed. However, if this function
3893			 * is used at a place where the vnode has not yet
3894			 * been sync'ed, this dependency can show up. So,
3895			 * rather than panic, just flush it.
3896			 */
3897			nbp = WK_MKDIR(wk)->md_buf;
3898			if (getdirtybuf(&nbp, waitfor) == 0)
3899				break;
3900			FREE_LOCK(&lk);
3901			if (waitfor == MNT_NOWAIT) {
3902				bawrite(nbp);
3903			} else if ((error = VOP_BWRITE(nbp->b_vp, nbp)) != 0) {
3904				bawrite(bp);
3905				return (error);
3906			}
3907			ACQUIRE_LOCK(&lk);
3908			break;
3909
3910		case D_BMSAFEMAP:
3911			/*
3912			 * This case should never happen if the vnode has
3913			 * been properly sync'ed. However, if this function
3914			 * is used at a place where the vnode has not yet
3915			 * been sync'ed, this dependency can show up. So,
3916			 * rather than panic, just flush it.
3917			 */
3918			nbp = WK_BMSAFEMAP(wk)->sm_buf;
3919			if (getdirtybuf(&nbp, waitfor) == 0)
3920				break;
3921			FREE_LOCK(&lk);
3922			if (waitfor == MNT_NOWAIT) {
3923				bawrite(nbp);
3924			} else if ((error = VOP_BWRITE(nbp->b_vp, nbp)) != 0) {
3925				bawrite(bp);
3926				return (error);
3927			}
3928			ACQUIRE_LOCK(&lk);
3929			break;
3930
3931		default:
3932			panic("softdep_sync_metadata: Unknown type %s",
3933			    TYPENAME(wk->wk_type));
3934			/* NOTREACHED */
3935		}
3936	}
3937	(void) getdirtybuf(&TAILQ_NEXT(bp, b_vnbufs), MNT_WAIT);
3938	nbp = TAILQ_NEXT(bp, b_vnbufs);
3939	FREE_LOCK(&lk);
3940	bawrite(bp);
3941	ACQUIRE_LOCK(&lk);
3942	if (nbp != NULL) {
3943		bp = nbp;
3944		goto loop;
3945	}
3946	/*
3947	 * We must wait for any I/O in progress to finish so that
3948	 * all potential buffers on the dirty list will be visible.
3949	 * Once they are all there, proceed with the second pass
3950	 * which will wait for the I/O as per above.
3951	 */
3952	drain_output(vp, 1);
3953	/*
3954	 * The brief unlock is to allow any pent up dependency
3955	 * processing to be done.
3956	 */
3957	if (waitfor == MNT_NOWAIT) {
3958		waitfor = MNT_WAIT;
3959		FREE_LOCK(&lk);
3960		ACQUIRE_LOCK(&lk);
3961		goto top;
3962	}
3963
3964	/*
3965	 * If we have managed to get rid of all the dirty buffers,
3966	 * then we are done. For certain directories and block
3967	 * devices, we may need to do further work.
3968	 */
3969	if (TAILQ_FIRST(&vp->v_dirtyblkhd) == NULL) {
3970		FREE_LOCK(&lk);
3971		return (0);
3972	}
3973
3974	FREE_LOCK(&lk);
3975	/*
3976	 * If we are trying to sync a block device, some of its buffers may
3977	 * contain metadata that cannot be written until the contents of some
3978	 * partially written files have been written to disk. The only easy
3979	 * way to accomplish this is to sync the entire filesystem (luckily
3980	 * this happens rarely).
3981	 */
3982	if (vp->v_type == VBLK && vp->v_specmountpoint && !VOP_ISLOCKED(vp) &&
3983	    (error = VFS_SYNC(vp->v_specmountpoint, MNT_WAIT, ap->a_cred,
3984	     ap->a_p)) != 0)
3985		return (error);
3986	return (0);
3987}
3988
3989/*
3990 * Flush the dependencies associated with an inodedep.
3991 * Called with splbio blocked.
3992 */
3993static int
3994flush_inodedep_deps(fs, ino)
3995	struct fs *fs;
3996	ino_t ino;
3997{
3998	struct inodedep *inodedep;
3999	struct allocdirect *adp;
4000	int error, waitfor;
4001	struct buf *bp;
4002
4003	/*
4004	 * This work is done in two passes. The first pass grabs most
4005	 * of the buffers and begins asynchronously writing them. The
4006	 * only way to wait for these asynchronous writes is to sleep
4007	 * on the filesystem vnode which may stay busy for a long time
4008	 * if the filesystem is active. So, instead, we make a second
4009	 * pass over the dependencies blocking on each write. In the
4010	 * usual case we will be blocking against a write that we
4011	 * initiated, so when it is done the dependency will have been
4012	 * resolved. Thus the second pass is expected to end quickly.
4013	 * We give a brief window at the top of the loop to allow
4014	 * any pending I/O to complete.
4015	 */
4016	for (waitfor = MNT_NOWAIT; ; ) {
4017		FREE_LOCK(&lk);
4018		ACQUIRE_LOCK(&lk);
4019		if (inodedep_lookup(fs, ino, 0, &inodedep) == 0)
4020			return (0);
4021		for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
4022		     adp = TAILQ_NEXT(adp, ad_next)) {
4023			if (adp->ad_state & DEPCOMPLETE)
4024				continue;
4025			bp = adp->ad_buf;
4026			if (getdirtybuf(&bp, waitfor) == 0) {
4027				if (waitfor == MNT_NOWAIT)
4028					continue;
4029				break;
4030			}
4031			FREE_LOCK(&lk);
4032			if (waitfor == MNT_NOWAIT) {
4033				bawrite(bp);
4034			} else if ((error = VOP_BWRITE(bp->b_vp, bp)) != 0) {
4035				ACQUIRE_LOCK(&lk);
4036				return (error);
4037			}
4038			ACQUIRE_LOCK(&lk);
4039			break;
4040		}
4041		if (adp != NULL)
4042			continue;
4043		for (adp = TAILQ_FIRST(&inodedep->id_newinoupdt); adp;
4044		     adp = TAILQ_NEXT(adp, ad_next)) {
4045			if (adp->ad_state & DEPCOMPLETE)
4046				continue;
4047			bp = adp->ad_buf;
4048			if (getdirtybuf(&bp, waitfor) == 0) {
4049				if (waitfor == MNT_NOWAIT)
4050					continue;
4051				break;
4052			}
4053			FREE_LOCK(&lk);
4054			if (waitfor == MNT_NOWAIT) {
4055				bawrite(bp);
4056			} else if ((error = VOP_BWRITE(bp->b_vp, bp)) != 0) {
4057				ACQUIRE_LOCK(&lk);
4058				return (error);
4059			}
4060			ACQUIRE_LOCK(&lk);
4061			break;
4062		}
4063		if (adp != NULL)
4064			continue;
4065		/*
4066		 * If pass2, we are done, otherwise do pass 2.
4067		 */
4068		if (waitfor == MNT_WAIT)
4069			break;
4070		waitfor = MNT_WAIT;
4071	}
4072	/*
4073	 * Try freeing inodedep in case all dependencies have been removed.
4074	 */
4075	if (inodedep_lookup(fs, ino, 0, &inodedep) != 0)
4076		(void) free_inodedep(inodedep);
4077	return (0);
4078}
4079
4080/*
4081 * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
4082 * Called with splbio blocked.
4083 */
4084static int
4085flush_pagedep_deps(pvp, mp, diraddhdp)
4086	struct vnode *pvp;
4087	struct mount *mp;
4088	struct diraddhd *diraddhdp;
4089{
4090	struct proc *p = CURPROC;	/* XXX */
4091	struct inodedep *inodedep;
4092	struct ufsmount *ump;
4093	struct diradd *dap;
4094	struct vnode *vp;
4095	int gotit, error = 0;
4096	struct buf *bp;
4097	ino_t inum;
4098
4099	ump = VFSTOUFS(mp);
4100	while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
4101		/*
4102		 * Flush ourselves if this directory entry
4103		 * has a MKDIR_PARENT dependency.
4104		 */
4105		if (dap->da_state & MKDIR_PARENT) {
4106			FREE_LOCK(&lk);
4107			if ((error = UFS_UPDATE(pvp, 1)) != 0)
4108				break;
4109			ACQUIRE_LOCK(&lk);
4110			/*
4111			 * If that cleared dependencies, go on to next.
4112			 */
4113			if (dap != LIST_FIRST(diraddhdp))
4114				continue;
4115			if (dap->da_state & MKDIR_PARENT)
4116				panic("flush_pagedep_deps: MKDIR");
4117		}
4118		/*
4119		 * Flush the file on which the directory entry depends.
4120		 * If the inode has already been pushed out of the cache,
4121		 * then all the block dependencies will have been flushed
4122		 * leaving only inode dependencies (e.g., bitmaps). Thus,
4123		 * we do a ufs_ihashget to check for the vnode in the cache.
4124		 * If it is there, we do a full flush. If it is no longer
4125		 * there we need only dispose of any remaining bitmap
4126		 * dependencies and write the inode to disk.
4127		 */
4128		inum = dap->da_newinum;
4129		FREE_LOCK(&lk);
4130		if ((vp = ufs_ihashget(ump->um_dev, inum)) == NULL) {
4131			ACQUIRE_LOCK(&lk);
4132			if (inodedep_lookup(ump->um_fs, inum, 0, &inodedep) == 0
4133			    && dap == LIST_FIRST(diraddhdp))
4134				panic("flush_pagedep_deps: flush 1 failed");
4135			/*
4136			 * If the inode still has bitmap dependencies,
4137			 * push them to disk.
4138			 */
4139			if ((inodedep->id_state & DEPCOMPLETE) == 0) {
4140				gotit = getdirtybuf(&inodedep->id_buf,MNT_WAIT);
4141				FREE_LOCK(&lk);
4142				if (gotit &&
4143				    (error = VOP_BWRITE(inodedep->id_buf->b_vp,
4144				     inodedep->id_buf)) != 0)
4145					break;
4146				ACQUIRE_LOCK(&lk);
4147			}
4148			if (dap != LIST_FIRST(diraddhdp))
4149				continue;
4150			/*
4151			 * If the inode is still sitting in a buffer waiting
4152			 * to be written, push it to disk.
4153			 */
4154			FREE_LOCK(&lk);
4155			if ((error = bread(ump->um_devvp,
4156			    fsbtodb(ump->um_fs, ino_to_fsba(ump->um_fs, inum)),
4157			    (int)ump->um_fs->fs_bsize, NOCRED, &bp)) != 0)
4158				break;
4159			if ((error = VOP_BWRITE(bp->b_vp, bp)) != 0)
4160				break;
4161			ACQUIRE_LOCK(&lk);
4162			if (dap == LIST_FIRST(diraddhdp))
4163				panic("flush_pagedep_deps: flush 2 failed");
4164			continue;
4165		}
4166		if (vp->v_type == VDIR) {
4167			/*
4168			 * A newly allocated directory must have its "." and
4169			 * ".." entries written out before its name can be
4170			 * committed in its parent. We do not want or need
4171			 * the full semantics of a synchronous VOP_FSYNC as
4172			 * that may end up here again, once for each directory
4173			 * level in the filesystem. Instead, we push the blocks
4174			 * and wait for them to clear.
4175			 */
4176			if ((error =
4177			    VOP_FSYNC(vp, p->p_ucred, MNT_NOWAIT, p))) {
4178				vput(vp);
4179				break;
4180			}
4181			drain_output(vp, 0);
4182		}
4183		error = UFS_UPDATE(vp, 1);
4184		vput(vp);
4185		if (error)
4186			break;
4187		/*
4188		 * If we have failed to get rid of all the dependencies
4189		 * then something is seriously wrong.
4190		 */
4191		if (dap == LIST_FIRST(diraddhdp))
4192			panic("flush_pagedep_deps: flush 3 failed");
4193		ACQUIRE_LOCK(&lk);
4194	}
4195	if (error)
4196		ACQUIRE_LOCK(&lk);
4197	return (error);
4198}
4199
4200/*
4201 * A large burst of file addition or deletion activity can drive the
4202 * memory load excessively high. Therefore we deliberately slow things
4203 * down and speed up the I/O processing if we find ourselves with too
4204 * many dependencies in progress.
4205 */
4206static int
4207request_cleanup(resource, islocked)
4208	int resource;
4209	int islocked;
4210{
4211	struct callout_handle handle;
4212	struct proc *p = CURPROC;
4213
4214	/*
4215	 * We never hold up the filesystem syncer process.
4216	 */
4217	if (p == filesys_syncer)
4218		return (0);
4219	/*
4220	 * If we are resource constrained on inode dependencies, try
4221	 * flushing some dirty inodes. Otherwise, we are constrained
4222	 * by file deletions, so try accelerating flushes of directories
4223	 * with removal dependencies. We would like to do the cleanup
4224	 * here, but we probably hold an inode locked at this point and
4225	 * that might deadlock against one that we try to clean. So,
4226	 * the best that we can do is request the syncer daemon to do
4227	 * the cleanup for us.
4228	 */
4229	switch (resource) {
4230
4231	case FLUSH_INODES:
4232		stat_ino_limit_push += 1;
4233		req_clear_inodedeps = 1;
4234		break;
4235
4236	case FLUSH_REMOVE:
4237		stat_blk_limit_push += 1;
4238		req_clear_remove = 1;
4239		break;
4240
4241	default:
4242		panic("request_cleanup: unknown type");
4243	}
4244	/*
4245	 * Hopefully the syncer daemon will catch up and awaken us.
4246	 * We wait at most tickdelay before proceeding in any case.
4247	 */
4248	if (islocked == 0)
4249		ACQUIRE_LOCK(&lk);
4250	if (proc_waiting == 0) {
4251		proc_waiting = 1;
4252		handle = timeout(pause_timer, NULL,
4253		    tickdelay > 2 ? tickdelay : 2);
4254	}
4255	FREE_LOCK_INTERLOCKED(&lk);
4256	(void) tsleep((caddr_t)&proc_waiting, PPAUSE | PCATCH, "softupdate", 0);
4257	ACQUIRE_LOCK_INTERLOCKED(&lk);
4258	if (proc_waiting) {
4259		untimeout(pause_timer, NULL, handle);
4260		proc_waiting = 0;
4261	} else {
4262		switch (resource) {
4263
4264		case FLUSH_INODES:
4265			stat_ino_limit_hit += 1;
4266			break;
4267
4268		case FLUSH_REMOVE:
4269			stat_blk_limit_hit += 1;
4270			break;
4271		}
4272	}
4273	if (islocked == 0)
4274		FREE_LOCK(&lk);
4275	return (1);
4276}
4277
4278/*
4279 * Awaken processes pausing in request_cleanup and clear proc_waiting
4280 * to indicate that there is no longer a timer running.
4281 */
4282void
4283pause_timer(arg)
4284	void *arg;
4285{
4286
4287	proc_waiting = 0;
4288	wakeup(&proc_waiting);
4289}
4290
4291/*
4292 * Flush out a directory with at least one removal dependency in an effort
4293 * to reduce the number of freefile and freeblks dependency structures.
4294 */
4295static void
4296clear_remove(p)
4297	struct proc *p;
4298{
4299	struct pagedep_hashhead *pagedephd;
4300	struct pagedep *pagedep;
4301	static int next = 0;
4302	struct mount *mp;
4303	struct vnode *vp;
4304	int error, cnt;
4305	ino_t ino;
4306
4307	ACQUIRE_LOCK(&lk);
4308	for (cnt = 0; cnt < pagedep_hash; cnt++) {
4309		pagedephd = &pagedep_hashtbl[next++];
4310		if (next >= pagedep_hash)
4311			next = 0;
4312		for (pagedep = LIST_FIRST(pagedephd); pagedep;
4313		     pagedep = LIST_NEXT(pagedep, pd_hash)) {
4314			if (LIST_FIRST(&pagedep->pd_dirremhd) == NULL)
4315				continue;
4316			mp = pagedep->pd_mnt;
4317			ino = pagedep->pd_ino;
4318			FREE_LOCK(&lk);
4319			if ((error = VFS_VGET(mp, ino, &vp)) != 0) {
4320				softdep_error("clear_remove: vget", error);
4321				return;
4322			}
4323			if ((error = VOP_FSYNC(vp, p->p_ucred, MNT_NOWAIT, p)))
4324				softdep_error("clear_remove: fsync", error);
4325			drain_output(vp, 0);
4326			vput(vp);
4327			return;
4328		}
4329	}
4330	FREE_LOCK(&lk);
4331}
4332
4333/*
4334 * Clear out a block of dirty inodes in an effort to reduce
4335 * the number of inodedep dependency structures.
4336 */
4337static void
4338clear_inodedeps(p)
4339	struct proc *p;
4340{
4341	struct inodedep_hashhead *inodedephd;
4342	struct inodedep *inodedep;
4343	static int next = 0;
4344	struct mount *mp;
4345	struct vnode *vp;
4346	struct fs *fs;
4347	int error, cnt;
4348	ino_t firstino, lastino, ino;
4349
4350	ACQUIRE_LOCK(&lk);
4351	/*
4352	 * Pick a random inode dependency to be cleared.
4353	 * We will then gather up all the inodes in its block
4354	 * that have dependencies and flush them out.
4355	 */
4356	for (cnt = 0; cnt < inodedep_hash; cnt++) {
4357		inodedephd = &inodedep_hashtbl[next++];
4358		if (next >= inodedep_hash)
4359			next = 0;
4360		if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
4361			break;
4362	}
4363	/*
4364	 * Ugly code to find mount point given pointer to superblock.
4365	 */
4366	fs = inodedep->id_fs;
4367	for (mp = CIRCLEQ_FIRST(&mountlist); mp != (void *)&mountlist;
4368	     mp = CIRCLEQ_NEXT(mp, mnt_list))
4369		if ((mp->mnt_flag & MNT_SOFTDEP) && fs == VFSTOUFS(mp)->um_fs)
4370			break;
4371	/*
4372	 * Find the last inode in the block with dependencies.
4373	 */
4374	firstino = inodedep->id_ino & ~(INOPB(fs) - 1);
4375	for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
4376		if (inodedep_lookup(fs, lastino, 0, &inodedep) != 0)
4377			break;
4378	/*
4379	 * Asynchronously push all but the last inode with dependencies.
4380	 * Synchronously push the last inode with dependencies to ensure
4381	 * that the inode block gets written to free up the inodedeps.
4382	 */
4383	for (ino = firstino; ino <= lastino; ino++) {
4384		if (inodedep_lookup(fs, ino, 0, &inodedep) == 0)
4385			continue;
4386		FREE_LOCK(&lk);
4387		if ((error = VFS_VGET(mp, ino, &vp)) != 0) {
4388			softdep_error("clear_inodedeps: vget", error);
4389			return;
4390		}
4391		if (ino == lastino) {
4392			if ((error = VOP_FSYNC(vp, p->p_ucred, MNT_WAIT, p)))
4393				softdep_error("clear_inodedeps: fsync1", error);
4394		} else {
4395			if ((error = VOP_FSYNC(vp, p->p_ucred, MNT_NOWAIT, p)))
4396				softdep_error("clear_inodedeps: fsync2", error);
4397			drain_output(vp, 0);
4398		}
4399		vput(vp);
4400		ACQUIRE_LOCK(&lk);
4401	}
4402	FREE_LOCK(&lk);
4403}
4404
4405/*
4406 * Acquire exclusive access to a buffer.
4407 * Must be called with splbio blocked.
4408 * Return 1 if buffer was acquired.
4409 */
4410static int
4411getdirtybuf(bpp, waitfor)
4412	struct buf **bpp;
4413	int waitfor;
4414{
4415	struct buf *bp;
4416
4417	for (;;) {
4418		if ((bp = *bpp) == NULL)
4419			return (0);
4420		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) == 0)
4421			break;
4422		if (waitfor != MNT_WAIT)
4423			return (0);
4424		FREE_LOCK_INTERLOCKED(&lk);
4425		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL) != ENOLCK)
4426			panic("getdirtybuf: inconsistent lock");
4427		ACQUIRE_LOCK_INTERLOCKED(&lk);
4428	}
4429	if ((bp->b_flags & B_DELWRI) == 0) {
4430		BUF_UNLOCK(bp);
4431		return (0);
4432	}
4433	bremfree(bp);
4434	return (1);
4435}
4436
4437/*
4438 * Wait for pending output on a vnode to complete.
4439 * Must be called with vnode locked.
4440 */
4441static void
4442drain_output(vp, islocked)
4443	struct vnode *vp;
4444	int islocked;
4445{
4446
4447	if (!islocked)
4448		ACQUIRE_LOCK(&lk);
4449	while (vp->v_numoutput) {
4450		vp->v_flag |= VBWAIT;
4451		FREE_LOCK_INTERLOCKED(&lk);
4452		tsleep((caddr_t)&vp->v_numoutput, PRIBIO + 1, "drainvp", 0);
4453		ACQUIRE_LOCK_INTERLOCKED(&lk);
4454	}
4455	if (!islocked)
4456		FREE_LOCK(&lk);
4457}
4458
4459/*
4460 * Called whenever a buffer that is being invalidated or reallocated
4461 * contains dependencies. This should only happen if an I/O error has
4462 * occurred. The routine is called with the buffer locked.
4463 */
4464void
4465softdep_deallocate_dependencies(bp)
4466	struct buf *bp;
4467{
4468
4469	if ((bp->b_flags & B_ERROR) == 0)
4470		panic("softdep_deallocate_dependencies: dangling deps");
4471	softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntonname, bp->b_error);
4472	panic("softdep_deallocate_dependencies: unrecovered I/O error");
4473}
4474
4475/*
4476 * Function to handle asynchronous write errors in the filesystem.
4477 */
4478void
4479softdep_error(func, error)
4480	char *func;
4481	int error;
4482{
4483
4484	/* XXX should do something better! */
4485	printf("%s: got error %d while accessing filesystem\n", func, error);
4486}
4487