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