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