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