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