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