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