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