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