ffs_softdep.c revision 168353
182899Sjake/*-
282899Sjake * Copyright 1998, 2000 Marshall Kirk McKusick. All Rights Reserved.
380708Sjake *
480708Sjake * The soft updates code is derived from the appendix of a University
582899Sjake * of Michigan technical report (Gregory R. Ganger and Yale N. Patt,
682899Sjake * "Soft Updates: A Solution to the Metadata Update Problem in File
782899Sjake * Systems", CSE-TR-254-95, August 1995).
882899Sjake *
980708Sjake * Further information about soft updates can be obtained from:
1080708Sjake *
1180708Sjake *	Marshall Kirk McKusick		http://www.mckusick.com/softdep/
1280708Sjake *	1614 Oxford Street		mckusick@mckusick.com
1380708Sjake *	Berkeley, CA 94709-1608		+1-510-843-9542
1480708Sjake *	USA
1580708Sjake *
1680708Sjake * Redistribution and use in source and binary forms, with or without
1782899Sjake * modification, are permitted provided that the following conditions
1882899Sjake * are met:
1982899Sjake *
2080708Sjake * 1. Redistributions of source code must retain the above copyright
2182899Sjake *    notice, this list of conditions and the following disclaimer.
2280708Sjake * 2. Redistributions in binary form must reproduce the above copyright
2380708Sjake *    notice, this list of conditions and the following disclaimer in the
2482899Sjake *    documentation and/or other materials provided with the distribution.
2580708Sjake *
2680708Sjake * THIS SOFTWARE IS PROVIDED BY MARSHALL KIRK MCKUSICK ``AS IS'' AND ANY
2780708Sjake * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
2880708Sjake * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
2980708Sjake * DISCLAIMED.  IN NO EVENT SHALL MARSHALL KIRK MCKUSICK BE LIABLE FOR
3080708Sjake * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3180708Sjake * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3280708Sjake * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3382899Sjake * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3482899Sjake * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3582899Sjake * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3680708Sjake * SUCH DAMAGE.
3780708Sjake *
3880708Sjake *	from: @(#)ffs_softdep.c	9.59 (McKusick) 6/21/00
3980708Sjake */
4080708Sjake
4180708Sjake#include <sys/cdefs.h>
42104265Sjake__FBSDID("$FreeBSD: head/sys/ufs/ffs/ffs_softdep.c 168353 2007-04-04 07:29:53Z delphij $");
43133451Salc
44133451Salc/*
45112399Sjake * For now we want the safety net that the DIAGNOSTIC and DEBUG flags provide.
4680709Sjake */
4780709Sjake#ifndef DIAGNOSTIC
4880709Sjake#define DIAGNOSTIC
4980709Sjake#endif
5080709Sjake#ifndef DEBUG
5180709Sjake#define DEBUG
5283053Sobrien#endif
53108166Sjake
54108166Sjake#include <sys/param.h>
55108166Sjake#include <sys/kernel.h>
56108166Sjake#include <sys/systm.h>
57108166Sjake#include <sys/bio.h>
5880708Sjake#include <sys/buf.h>
5980708Sjake#include <sys/kdb.h>
6083053Sobrien#include <sys/kthread.h>
61133451Salc#include <sys/lock.h>
6288651Sjake#include <sys/malloc.h>
6388651Sjake#include <sys/mount.h>
6480709Sjake#include <sys/mutex.h>
6591288Sjake#include <sys/proc.h>
6680709Sjake#include <sys/stat.h>
6780708Sjake#include <sys/sysctl.h>
6880708Sjake#include <sys/syslog.h>
69133451Salc#include <sys/vnode.h>
70133451Salc#include <sys/conf.h>
71133451Salc#include <ufs/ufs/dir.h>
72133451Salc#include <ufs/ufs/extattr.h>
73133451Salc#include <ufs/ufs/quota.h>
74133451Salc#include <ufs/ufs/inode.h>
75133451Salc#include <ufs/ufs/ufsmount.h>
76133451Salc#include <ufs/ffs/fs.h>
77133451Salc#include <ufs/ffs/softdep.h>
78133451Salc#include <ufs/ffs/ffs_extern.h>
79133451Salc#include <ufs/ufs/ufs_extern.h>
8085241Sjake
81113238Sjake#include <vm/vm.h>
82113238Sjake
83112312Sjake#include "opt_ffs.h"
84113238Sjake#include "opt_quota.h"
8598813Sjake
86129068Salc#ifndef SOFTUPDATES
8780708Sjake
8888651Sjakeint
8988651Sjakesoftdep_flushfiles(oldmnt, flags, td)
9088651Sjake	struct mount *oldmnt;
9197447Sjake	int flags;
9297447Sjake	struct thread *td;
9397447Sjake{
9497447Sjake
9597447Sjake	panic("softdep_flushfiles called");
9689041Sjake}
9789041Sjake
9897447Sjakeint
9997447Sjakesoftdep_mount(devvp, mp, fs, cred)
100101957Sjake	struct vnode *devvp;
10184844Stmm	struct mount *mp;
10288651Sjake	struct fs *fs;
10388651Sjake	struct ucred *cred;
104113238Sjake{
10580708Sjake
10680708Sjake	return (0);
10780708Sjake}
108113238Sjake
10985241Sjakevoid
11081087Sjakesoftdep_initialize()
11188651Sjake{
11281087Sjake
11388651Sjake	return;
11488651Sjake}
11588651Sjake
11688651Sjakevoid
11781087Sjakesoftdep_uninitialize()
11881087Sjake{
119108700Sjake
120108700Sjake	return;
121108700Sjake}
122108700Sjake
123108700Sjakevoid
124108700Sjakesoftdep_setup_inomapdep(bp, ip, newinum)
125113171Sjake	struct buf *bp;
126108700Sjake	struct inode *ip;
127108700Sjake	ino_t newinum;
128108700Sjake{
129108700Sjake
130108700Sjake	panic("softdep_setup_inomapdep called");
131108700Sjake}
132108700Sjake
133108700Sjakevoid
134108700Sjakesoftdep_setup_blkmapdep(bp, mp, newblkno)
135108700Sjake	struct buf *bp;
136108700Sjake	struct mount *mp;
137108700Sjake	ufs2_daddr_t newblkno;
13880708Sjake{
139
140	panic("softdep_setup_blkmapdep called");
141}
142
143void
144softdep_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
157void
158softdep_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
171void
172softdep_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
185void
186softdep_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
197void
198softdep_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
207void
208softdep_freefile(pvp, ino, mode)
209		struct vnode *pvp;
210		ino_t ino;
211		int mode;
212{
213
214	panic("softdep_freefile called");
215}
216
217int
218softdep_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
230void
231softdep_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
242void
243softdep_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
253void
254softdep_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
265void
266softdep_change_linkcnt(ip)
267	struct inode *ip;
268{
269
270	panic("softdep_change_linkcnt called");
271}
272
273void
274softdep_load_inodeblock(ip)
275	struct inode *ip;
276{
277
278	panic("softdep_load_inodeblock called");
279}
280
281void
282softdep_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
291int
292softdep_fsync(vp)
293	struct vnode *vp;	/* the "in_core" copy of the inode */
294{
295
296	return (0);
297}
298
299void
300softdep_fsync_mountdev(vp)
301	struct vnode *vp;
302{
303
304	return;
305}
306
307int
308softdep_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
318int
319softdep_sync_metadata(struct vnode *vp)
320{
321
322	return (0);
323}
324
325int
326softdep_slowdown(vp)
327	struct vnode *vp;
328{
329
330	panic("softdep_slowdown called");
331}
332
333void
334softdep_releasefile(ip)
335	struct inode *ip;	/* inode with the zero effective link count */
336{
337
338	panic("softdep_releasefile called");
339}
340
341int
342softdep_request_cleanup(fs, vp)
343	struct fs *fs;
344	struct vnode *vp;
345{
346
347	return (0);
348}
349
350int
351softdep_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
402void
403softdep_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 */
420static MALLOC_DEFINE(M_PAGEDEP, "pagedep","File page dependencies");
421static MALLOC_DEFINE(M_INODEDEP, "inodedep","Inode dependencies");
422static MALLOC_DEFINE(M_NEWBLK, "newblk","New block allocation");
423static MALLOC_DEFINE(M_BMSAFEMAP, "bmsafemap","Block or frag allocated from cyl group map");
424static MALLOC_DEFINE(M_ALLOCDIRECT, "allocdirect","Block or frag dependency for an inode");
425static MALLOC_DEFINE(M_INDIRDEP, "indirdep","Indirect block dependencies");
426static MALLOC_DEFINE(M_ALLOCINDIR, "allocindir","Block dependency for an indirect block");
427static MALLOC_DEFINE(M_FREEFRAG, "freefrag","Previously used frag for an inode");
428static MALLOC_DEFINE(M_FREEBLKS, "freeblks","Blocks freed from an inode");
429static MALLOC_DEFINE(M_FREEFILE, "freefile","Inode deallocated");
430static MALLOC_DEFINE(M_DIRADD, "diradd","New directory entry");
431static MALLOC_DEFINE(M_MKDIR, "mkdir","New directory");
432static MALLOC_DEFINE(M_DIRREM, "dirrem","Directory entry deleted");
433static MALLOC_DEFINE(M_NEWDIRBLK, "newdirblk","Unclaimed new directory block");
434static 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 */
458static 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 */
489struct inodedep_hashhead;
490struct newblk_hashhead;
491struct pagedep_hashhead;
492
493/*
494 * Internal function prototypes.
495 */
496static	void softdep_error(char *, int);
497static	void drain_output(struct vnode *);
498static	struct buf *getdirtybuf(struct buf *, struct mtx *, int);
499static	void clear_remove(struct thread *);
500static	void clear_inodedeps(struct thread *);
501static	int flush_pagedep_deps(struct vnode *, struct mount *,
502	    struct diraddhd *);
503static	int flush_inodedep_deps(struct mount *, ino_t);
504static	int flush_deplist(struct allocdirectlst *, int, int *);
505static	int handle_written_filepage(struct pagedep *, struct buf *);
506static  void diradd_inode_written(struct diradd *, struct inodedep *);
507static	int handle_written_inodeblock(struct inodedep *, struct buf *);
508static	void handle_allocdirect_partdone(struct allocdirect *);
509static	void handle_allocindir_partdone(struct allocindir *);
510static	void initiate_write_filepage(struct pagedep *, struct buf *);
511static	void handle_written_mkdir(struct mkdir *, int);
512static	void initiate_write_inodeblock_ufs1(struct inodedep *, struct buf *);
513static	void initiate_write_inodeblock_ufs2(struct inodedep *, struct buf *);
514static	void handle_workitem_freefile(struct freefile *);
515static	void handle_workitem_remove(struct dirrem *, struct vnode *);
516static	struct dirrem *newdirrem(struct buf *, struct inode *,
517	    struct inode *, int, struct dirrem **);
518static	void free_diradd(struct diradd *);
519static	void free_allocindir(struct allocindir *, struct inodedep *);
520static	void free_newdirblk(struct newdirblk *);
521static	int indir_trunc(struct freeblks *, ufs2_daddr_t, int, ufs_lbn_t,
522	    ufs2_daddr_t *);
523static	void deallocate_dependencies(struct buf *, struct inodedep *);
524static	void free_allocdirect(struct allocdirectlst *,
525	    struct allocdirect *, int);
526static	int check_inode_unwritten(struct inodedep *);
527static	int free_inodedep(struct inodedep *);
528static	void handle_workitem_freeblocks(struct freeblks *, int);
529static	void merge_inode_lists(struct allocdirectlst *,struct allocdirectlst *);
530static	void setup_allocindir_phase2(struct buf *, struct inode *,
531	    struct allocindir *);
532static	struct allocindir *newallocindir(struct inode *, int, ufs2_daddr_t,
533	    ufs2_daddr_t);
534static	void handle_workitem_freefrag(struct freefrag *);
535static	struct freefrag *newfreefrag(struct inode *, ufs2_daddr_t, long);
536static	void allocdirect_merge(struct allocdirectlst *,
537	    struct allocdirect *, struct allocdirect *);
538static	struct bmsafemap *bmsafemap_lookup(struct mount *, struct buf *);
539static	int newblk_find(struct newblk_hashhead *, struct fs *, ufs2_daddr_t,
540	    struct newblk **);
541static	int newblk_lookup(struct fs *, ufs2_daddr_t, int, struct newblk **);
542static	int inodedep_find(struct inodedep_hashhead *, struct fs *, ino_t,
543	    struct inodedep **);
544static	int inodedep_lookup(struct mount *, ino_t, int, struct inodedep **);
545static	int pagedep_lookup(struct inode *, ufs_lbn_t, int, struct pagedep **);
546static	int pagedep_find(struct pagedep_hashhead *, ino_t, ufs_lbn_t,
547	    struct mount *mp, int, struct pagedep **);
548static	void pause_timer(void *);
549static	int request_cleanup(struct mount *, int);
550static	int process_worklist_item(struct mount *, int);
551static	void add_to_worklist(struct worklist *);
552static	void softdep_flush(void);
553static	int softdep_speedup(void);
554
555/*
556 * Exported softdep operations.
557 */
558static	void softdep_disk_io_initiation(struct buf *);
559static	void softdep_disk_write_complete(struct buf *);
560static	void softdep_deallocate_dependencies(struct buf *);
561static	int softdep_count_dependencies(struct buf *bp, int);
562
563static struct mtx lk;
564MTX_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 */
584static	void worklist_insert(struct workhead *, struct worklist *);
585static	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
590static void
591worklist_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
603static void
604worklist_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 */
619static	void workitem_free(struct worklist *, int);
620static	void workitem_alloc(struct worklist *, int, struct mount *);
621
622#define	WORKITEM_FREE(item, type) workitem_free((struct worklist *)(item), (type))
623
624static void
625workitem_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
644static void
645workitem_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 */
662static int max_softdeps;	/* maximum number of structs before slowdown */
663static int maxindirdeps = 50;	/* max number of indirdeps before slowdown */
664static int tickdelay = 2;	/* number of ticks to pause during slowdown */
665static int proc_waiting;	/* tracks whether we have a timeout posted */
666static int *stat_countp;	/* statistic to count in proc_waiting timeout */
667static struct callout_handle handle; /* handle on posted proc_waiting timeout */
668static int req_pending;
669static int req_clear_inodedeps;	/* syncer process flush some inodedeps */
670#define FLUSH_INODES		1
671static 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 */
677static int stat_worklist_push;	/* number of worklist cleanups */
678static int stat_blk_limit_push;	/* number of times block limit neared */
679static int stat_ino_limit_push;	/* number of times inode limit neared */
680static int stat_blk_limit_hit;	/* number of times block slowdown imposed */
681static int stat_ino_limit_hit;	/* number of times inode slowdown imposed */
682static int stat_sync_limit_hit;	/* number of synchronous slowdowns imposed */
683static int stat_indir_blk_ptrs;	/* bufs redirtied as indir ptrs not written */
684static int stat_inode_bitmap;	/* bufs redirtied as inode bitmap not written */
685static int stat_direct_blk_ptrs;/* bufs redirtied as direct ptrs not written */
686static int stat_dir_entry;	/* bufs redirtied as dir entry cannot write */
687
688SYSCTL_INT(_debug, OID_AUTO, max_softdeps, CTLFLAG_RW, &max_softdeps, 0, "");
689SYSCTL_INT(_debug, OID_AUTO, tickdelay, CTLFLAG_RW, &tickdelay, 0, "");
690SYSCTL_INT(_debug, OID_AUTO, maxindirdeps, CTLFLAG_RW, &maxindirdeps, 0, "");
691SYSCTL_INT(_debug, OID_AUTO, worklist_push, CTLFLAG_RW, &stat_worklist_push, 0,"");
692SYSCTL_INT(_debug, OID_AUTO, blk_limit_push, CTLFLAG_RW, &stat_blk_limit_push, 0,"");
693SYSCTL_INT(_debug, OID_AUTO, ino_limit_push, CTLFLAG_RW, &stat_ino_limit_push, 0,"");
694SYSCTL_INT(_debug, OID_AUTO, blk_limit_hit, CTLFLAG_RW, &stat_blk_limit_hit, 0, "");
695SYSCTL_INT(_debug, OID_AUTO, ino_limit_hit, CTLFLAG_RW, &stat_ino_limit_hit, 0, "");
696SYSCTL_INT(_debug, OID_AUTO, sync_limit_hit, CTLFLAG_RW, &stat_sync_limit_hit, 0, "");
697SYSCTL_INT(_debug, OID_AUTO, indir_blk_ptrs, CTLFLAG_RW, &stat_indir_blk_ptrs, 0, "");
698SYSCTL_INT(_debug, OID_AUTO, inode_bitmap, CTLFLAG_RW, &stat_inode_bitmap, 0, "");
699SYSCTL_INT(_debug, OID_AUTO, direct_blk_ptrs, CTLFLAG_RW, &stat_direct_blk_ptrs, 0, "");
700SYSCTL_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
703SYSCTL_DECL(_vfs_ffs);
704
705static int compute_summary_at_mount = 0;	/* Whether to recompute the summary at mount time */
706SYSCTL_INT(_vfs_ffs, OID_AUTO, compute_summary_at_mount, CTLFLAG_RW,
707	   &compute_summary_at_mount, 0, "Recompute summary at mount");
708
709static struct proc *softdepproc;
710static struct kproc_desc softdep_kp = {
711	"softdepflush",
712	softdep_flush,
713	&softdepproc
714};
715SYSINIT(sdproc, SI_SUB_KTHREAD_UPDATE, SI_ORDER_ANY, kproc_start, &softdep_kp)
716
717static void
718softdep_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
778static int
779softdep_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 */
798static void
799add_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 */
826int
827softdep_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 */
890static int
891process_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 */
989void
990softdep_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 */
1014int
1015softdep_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
1044int
1045softdep_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",
1065		    mp);
1066	}
1067
1068	return (error);
1069}
1070
1071/*
1072 * Flush all vnodes and worklist items associated with a specified mount point.
1073 */
1074int
1075softdep_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 */
1144LIST_HEAD(pagedep_hashhead, pagedep) *pagedep_hashtbl;
1145u_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
1150static int
1151pagedep_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 */
1183static int
1184pagedep_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 */
1227LIST_HEAD(inodedep_hashhead, inodedep) *inodedep_hashtbl;
1228static u_long	inodedep_hash;	/* size of hash table - 1 */
1229static long	num_inodedep;	/* number of inodedep allocated */
1230#define	INODEDEP_HASH(fs, inum) \
1231      (&inodedep_hashtbl[((((register_t)(fs)) >> 13) + (inum)) & inodedep_hash])
1232
1233static int
1234inodedep_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 */
1259static int
1260inodedep_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 */
1316LIST_HEAD(newblk_hashhead, newblk) *newblk_hashtbl;
1317u_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
1321static int
1322newblk_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 */
1346static int
1347newblk_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 */
1381void
1382softdep_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 */
1403void
1404softdep_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 */
1416int
1417softdep_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 */
1510void
1511softdep_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 */
1541void
1542softdep_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 */
1571static struct bmsafemap *
1572bmsafemap_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 */
1626void
1627softdep_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 */
1733static void
1734allocdirect_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 */
1792static struct freefrag *
1793newfreefrag(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 */
1819static void
1820handle_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 */
1837void
1838softdep_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 */
1956static struct allocindir *
1957newallocindir(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 */
1980void
1981softdep_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 */
2013void
2014softdep_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 */
2035static void
2036setup_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 */
2179void
2180softdep_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);
2315restart:
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 */
2368static void
2369deallocate_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 */
2485static void
2486free_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 */
2525static void
2526free_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 */
2566void
2567softdep_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 */
2623static int
2624check_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 */
2665static int
2666free_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 */
2696static void
2697handle_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 */
2803static int
2804indir_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 */
2912static void
2913free_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 */
2958int
2959softdep_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 */
3113void
3114softdep_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	}
3154done:
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 */
3163static void
3164free_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 */
3219void
3220softdep_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 */
3262static long num_dirrem;		/* number of dirrem allocated */
3263static struct dirrem *
3264newdirrem(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 */
3367void
3368softdep_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 */
3482void
3483softdep_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 */
3504void
3505softdep_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 */
3550static void
3551handle_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		FREE_LOCK(&lk);
3630		vput(vp);
3631		handle_workitem_remove(dirrem, NULL);
3632		return;
3633	}
3634	WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
3635	FREE_LOCK(&lk);
3636	ip->i_flag |= IN_CHANGE;
3637	ffs_update(vp, 0);
3638	vput(vp);
3639}
3640
3641/*
3642 * Inode de-allocation dependencies.
3643 *
3644 * When an inode's link count is reduced to zero, it can be de-allocated. We
3645 * found it convenient to postpone de-allocation until after the inode is
3646 * written to disk with its new link count (zero).  At this point, all of the
3647 * on-disk inode's block pointers are nullified and, with careful dependency
3648 * list ordering, all dependencies related to the inode will be satisfied and
3649 * the corresponding dependency structures de-allocated.  So, if/when the
3650 * inode is reused, there will be no mixing of old dependencies with new
3651 * ones.  This artificial dependency is set up by the block de-allocation
3652 * procedure above (softdep_setup_freeblocks) and completed by the
3653 * following procedure.
3654 */
3655static void
3656handle_workitem_freefile(freefile)
3657	struct freefile *freefile;
3658{
3659	struct fs *fs;
3660	struct inodedep *idp;
3661	struct ufsmount *ump;
3662	int error;
3663
3664	ump = VFSTOUFS(freefile->fx_list.wk_mp);
3665	fs = ump->um_fs;
3666#ifdef DEBUG
3667	ACQUIRE_LOCK(&lk);
3668	error = inodedep_lookup(UFSTOVFS(ump), freefile->fx_oldinum, 0, &idp);
3669	FREE_LOCK(&lk);
3670	if (error)
3671		panic("handle_workitem_freefile: inodedep survived");
3672#endif
3673	UFS_LOCK(ump);
3674	fs->fs_pendinginodes -= 1;
3675	UFS_UNLOCK(ump);
3676	if ((error = ffs_freefile(ump, fs, freefile->fx_devvp,
3677	    freefile->fx_oldinum, freefile->fx_mode)) != 0)
3678		softdep_error("handle_workitem_freefile", error);
3679	ACQUIRE_LOCK(&lk);
3680	WORKITEM_FREE(freefile, D_FREEFILE);
3681	FREE_LOCK(&lk);
3682}
3683
3684
3685/*
3686 * Helper function which unlinks marker element from work list and returns
3687 * the next element on the list.
3688 */
3689static __inline struct worklist *
3690markernext(struct worklist *marker)
3691{
3692	struct worklist *next;
3693
3694	next = LIST_NEXT(marker, wk_list);
3695	LIST_REMOVE(marker, wk_list);
3696	return next;
3697}
3698
3699/*
3700 * Disk writes.
3701 *
3702 * The dependency structures constructed above are most actively used when file
3703 * system blocks are written to disk.  No constraints are placed on when a
3704 * block can be written, but unsatisfied update dependencies are made safe by
3705 * modifying (or replacing) the source memory for the duration of the disk
3706 * write.  When the disk write completes, the memory block is again brought
3707 * up-to-date.
3708 *
3709 * In-core inode structure reclamation.
3710 *
3711 * Because there are a finite number of "in-core" inode structures, they are
3712 * reused regularly.  By transferring all inode-related dependencies to the
3713 * in-memory inode block and indexing them separately (via "inodedep"s), we
3714 * can allow "in-core" inode structures to be reused at any time and avoid
3715 * any increase in contention.
3716 *
3717 * Called just before entering the device driver to initiate a new disk I/O.
3718 * The buffer must be locked, thus, no I/O completion operations can occur
3719 * while we are manipulating its associated dependencies.
3720 */
3721static void
3722softdep_disk_io_initiation(bp)
3723	struct buf *bp;		/* structure describing disk write to occur */
3724{
3725	struct worklist *wk;
3726	struct worklist marker;
3727	struct indirdep *indirdep;
3728	struct inodedep *inodedep;
3729
3730	/*
3731	 * We only care about write operations. There should never
3732	 * be dependencies for reads.
3733	 */
3734	if (bp->b_iocmd != BIO_WRITE)
3735		panic("softdep_disk_io_initiation: not write");
3736
3737	marker.wk_type = D_LAST + 1;	/* Not a normal workitem */
3738	PHOLD(curproc);			/* Don't swap out kernel stack */
3739
3740	ACQUIRE_LOCK(&lk);
3741	/*
3742	 * Do any necessary pre-I/O processing.
3743	 */
3744	for (wk = LIST_FIRST(&bp->b_dep); wk != NULL;
3745	     wk = markernext(&marker)) {
3746		LIST_INSERT_AFTER(wk, &marker, wk_list);
3747		switch (wk->wk_type) {
3748
3749		case D_PAGEDEP:
3750			initiate_write_filepage(WK_PAGEDEP(wk), bp);
3751			continue;
3752
3753		case D_INODEDEP:
3754			inodedep = WK_INODEDEP(wk);
3755			if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC)
3756				initiate_write_inodeblock_ufs1(inodedep, bp);
3757			else
3758				initiate_write_inodeblock_ufs2(inodedep, bp);
3759			continue;
3760
3761		case D_INDIRDEP:
3762			indirdep = WK_INDIRDEP(wk);
3763			if (indirdep->ir_state & GOINGAWAY)
3764				panic("disk_io_initiation: indirdep gone");
3765			/*
3766			 * If there are no remaining dependencies, this
3767			 * will be writing the real pointers, so the
3768			 * dependency can be freed.
3769			 */
3770			if (LIST_EMPTY(&indirdep->ir_deplisthd)) {
3771				struct buf *bp;
3772
3773				bp = indirdep->ir_savebp;
3774				bp->b_flags |= B_INVAL | B_NOCACHE;
3775				/* inline expand WORKLIST_REMOVE(wk); */
3776				wk->wk_state &= ~ONWORKLIST;
3777				LIST_REMOVE(wk, wk_list);
3778				WORKITEM_FREE(indirdep, D_INDIRDEP);
3779				FREE_LOCK(&lk);
3780				brelse(bp);
3781				ACQUIRE_LOCK(&lk);
3782				continue;
3783			}
3784			/*
3785			 * Replace up-to-date version with safe version.
3786			 */
3787			FREE_LOCK(&lk);
3788			MALLOC(indirdep->ir_saveddata, caddr_t, bp->b_bcount,
3789			    M_INDIRDEP, M_SOFTDEP_FLAGS);
3790			ACQUIRE_LOCK(&lk);
3791			indirdep->ir_state &= ~ATTACHED;
3792			indirdep->ir_state |= UNDONE;
3793			bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
3794			bcopy(indirdep->ir_savebp->b_data, bp->b_data,
3795			    bp->b_bcount);
3796			continue;
3797
3798		case D_MKDIR:
3799		case D_BMSAFEMAP:
3800		case D_ALLOCDIRECT:
3801		case D_ALLOCINDIR:
3802			continue;
3803
3804		default:
3805			panic("handle_disk_io_initiation: Unexpected type %s",
3806			    TYPENAME(wk->wk_type));
3807			/* NOTREACHED */
3808		}
3809	}
3810	FREE_LOCK(&lk);
3811	PRELE(curproc);			/* Allow swapout of kernel stack */
3812}
3813
3814/*
3815 * Called from within the procedure above to deal with unsatisfied
3816 * allocation dependencies in a directory. The buffer must be locked,
3817 * thus, no I/O completion operations can occur while we are
3818 * manipulating its associated dependencies.
3819 */
3820static void
3821initiate_write_filepage(pagedep, bp)
3822	struct pagedep *pagedep;
3823	struct buf *bp;
3824{
3825	struct diradd *dap;
3826	struct direct *ep;
3827	int i;
3828
3829	if (pagedep->pd_state & IOSTARTED) {
3830		/*
3831		 * This can only happen if there is a driver that does not
3832		 * understand chaining. Here biodone will reissue the call
3833		 * to strategy for the incomplete buffers.
3834		 */
3835		printf("initiate_write_filepage: already started\n");
3836		return;
3837	}
3838	pagedep->pd_state |= IOSTARTED;
3839	for (i = 0; i < DAHASHSZ; i++) {
3840		LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
3841			ep = (struct direct *)
3842			    ((char *)bp->b_data + dap->da_offset);
3843			if (ep->d_ino != dap->da_newinum)
3844				panic("%s: dir inum %d != new %d",
3845				    "initiate_write_filepage",
3846				    ep->d_ino, dap->da_newinum);
3847			if (dap->da_state & DIRCHG)
3848				ep->d_ino = dap->da_previous->dm_oldinum;
3849			else
3850				ep->d_ino = 0;
3851			dap->da_state &= ~ATTACHED;
3852			dap->da_state |= UNDONE;
3853		}
3854	}
3855}
3856
3857/*
3858 * Version of initiate_write_inodeblock that handles UFS1 dinodes.
3859 * Note that any bug fixes made to this routine must be done in the
3860 * version found below.
3861 *
3862 * Called from within the procedure above to deal with unsatisfied
3863 * allocation dependencies in an inodeblock. The buffer must be
3864 * locked, thus, no I/O completion operations can occur while we
3865 * are manipulating its associated dependencies.
3866 */
3867static void
3868initiate_write_inodeblock_ufs1(inodedep, bp)
3869	struct inodedep *inodedep;
3870	struct buf *bp;			/* The inode block */
3871{
3872	struct allocdirect *adp, *lastadp;
3873	struct ufs1_dinode *dp;
3874	struct ufs1_dinode *sip;
3875	struct fs *fs;
3876	ufs_lbn_t i, prevlbn = 0;
3877	int deplist;
3878
3879	if (inodedep->id_state & IOSTARTED)
3880		panic("initiate_write_inodeblock_ufs1: already started");
3881	inodedep->id_state |= IOSTARTED;
3882	fs = inodedep->id_fs;
3883	dp = (struct ufs1_dinode *)bp->b_data +
3884	    ino_to_fsbo(fs, inodedep->id_ino);
3885	/*
3886	 * If the bitmap is not yet written, then the allocated
3887	 * inode cannot be written to disk.
3888	 */
3889	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
3890		if (inodedep->id_savedino1 != NULL)
3891			panic("initiate_write_inodeblock_ufs1: I/O underway");
3892		FREE_LOCK(&lk);
3893		MALLOC(sip, struct ufs1_dinode *,
3894		    sizeof(struct ufs1_dinode), M_SAVEDINO, M_SOFTDEP_FLAGS);
3895		ACQUIRE_LOCK(&lk);
3896		inodedep->id_savedino1 = sip;
3897		*inodedep->id_savedino1 = *dp;
3898		bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
3899		dp->di_gen = inodedep->id_savedino1->di_gen;
3900		return;
3901	}
3902	/*
3903	 * If no dependencies, then there is nothing to roll back.
3904	 */
3905	inodedep->id_savedsize = dp->di_size;
3906	inodedep->id_savedextsize = 0;
3907	if (TAILQ_EMPTY(&inodedep->id_inoupdt))
3908		return;
3909	/*
3910	 * Set the dependencies to busy.
3911	 */
3912	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
3913	     adp = TAILQ_NEXT(adp, ad_next)) {
3914#ifdef DIAGNOSTIC
3915		if (deplist != 0 && prevlbn >= adp->ad_lbn)
3916			panic("softdep_write_inodeblock: lbn order");
3917		prevlbn = adp->ad_lbn;
3918		if (adp->ad_lbn < NDADDR &&
3919		    dp->di_db[adp->ad_lbn] != adp->ad_newblkno)
3920			panic("%s: direct pointer #%jd mismatch %d != %jd",
3921			    "softdep_write_inodeblock",
3922			    (intmax_t)adp->ad_lbn,
3923			    dp->di_db[adp->ad_lbn],
3924			    (intmax_t)adp->ad_newblkno);
3925		if (adp->ad_lbn >= NDADDR &&
3926		    dp->di_ib[adp->ad_lbn - NDADDR] != adp->ad_newblkno)
3927			panic("%s: indirect pointer #%jd mismatch %d != %jd",
3928			    "softdep_write_inodeblock",
3929			    (intmax_t)adp->ad_lbn - NDADDR,
3930			    dp->di_ib[adp->ad_lbn - NDADDR],
3931			    (intmax_t)adp->ad_newblkno);
3932		deplist |= 1 << adp->ad_lbn;
3933		if ((adp->ad_state & ATTACHED) == 0)
3934			panic("softdep_write_inodeblock: Unknown state 0x%x",
3935			    adp->ad_state);
3936#endif /* DIAGNOSTIC */
3937		adp->ad_state &= ~ATTACHED;
3938		adp->ad_state |= UNDONE;
3939	}
3940	/*
3941	 * The on-disk inode cannot claim to be any larger than the last
3942	 * fragment that has been written. Otherwise, the on-disk inode
3943	 * might have fragments that were not the last block in the file
3944	 * which would corrupt the filesystem.
3945	 */
3946	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
3947	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
3948		if (adp->ad_lbn >= NDADDR)
3949			break;
3950		dp->di_db[adp->ad_lbn] = adp->ad_oldblkno;
3951		/* keep going until hitting a rollback to a frag */
3952		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
3953			continue;
3954		dp->di_size = fs->fs_bsize * adp->ad_lbn + adp->ad_oldsize;
3955		for (i = adp->ad_lbn + 1; i < NDADDR; i++) {
3956#ifdef DIAGNOSTIC
3957			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
3958				panic("softdep_write_inodeblock: lost dep1");
3959#endif /* DIAGNOSTIC */
3960			dp->di_db[i] = 0;
3961		}
3962		for (i = 0; i < NIADDR; i++) {
3963#ifdef DIAGNOSTIC
3964			if (dp->di_ib[i] != 0 &&
3965			    (deplist & ((1 << NDADDR) << i)) == 0)
3966				panic("softdep_write_inodeblock: lost dep2");
3967#endif /* DIAGNOSTIC */
3968			dp->di_ib[i] = 0;
3969		}
3970		return;
3971	}
3972	/*
3973	 * If we have zero'ed out the last allocated block of the file,
3974	 * roll back the size to the last currently allocated block.
3975	 * We know that this last allocated block is a full-sized as
3976	 * we already checked for fragments in the loop above.
3977	 */
3978	if (lastadp != NULL &&
3979	    dp->di_size <= (lastadp->ad_lbn + 1) * fs->fs_bsize) {
3980		for (i = lastadp->ad_lbn; i >= 0; i--)
3981			if (dp->di_db[i] != 0)
3982				break;
3983		dp->di_size = (i + 1) * fs->fs_bsize;
3984	}
3985	/*
3986	 * The only dependencies are for indirect blocks.
3987	 *
3988	 * The file size for indirect block additions is not guaranteed.
3989	 * Such a guarantee would be non-trivial to achieve. The conventional
3990	 * synchronous write implementation also does not make this guarantee.
3991	 * Fsck should catch and fix discrepancies. Arguably, the file size
3992	 * can be over-estimated without destroying integrity when the file
3993	 * moves into the indirect blocks (i.e., is large). If we want to
3994	 * postpone fsck, we are stuck with this argument.
3995	 */
3996	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
3997		dp->di_ib[adp->ad_lbn - NDADDR] = 0;
3998}
3999
4000/*
4001 * Version of initiate_write_inodeblock that handles UFS2 dinodes.
4002 * Note that any bug fixes made to this routine must be done in the
4003 * version found above.
4004 *
4005 * Called from within the procedure above to deal with unsatisfied
4006 * allocation dependencies in an inodeblock. The buffer must be
4007 * locked, thus, no I/O completion operations can occur while we
4008 * are manipulating its associated dependencies.
4009 */
4010static void
4011initiate_write_inodeblock_ufs2(inodedep, bp)
4012	struct inodedep *inodedep;
4013	struct buf *bp;			/* The inode block */
4014{
4015	struct allocdirect *adp, *lastadp;
4016	struct ufs2_dinode *dp;
4017	struct ufs2_dinode *sip;
4018	struct fs *fs;
4019	ufs_lbn_t i, prevlbn = 0;
4020	int deplist;
4021
4022	if (inodedep->id_state & IOSTARTED)
4023		panic("initiate_write_inodeblock_ufs2: already started");
4024	inodedep->id_state |= IOSTARTED;
4025	fs = inodedep->id_fs;
4026	dp = (struct ufs2_dinode *)bp->b_data +
4027	    ino_to_fsbo(fs, inodedep->id_ino);
4028	/*
4029	 * If the bitmap is not yet written, then the allocated
4030	 * inode cannot be written to disk.
4031	 */
4032	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
4033		if (inodedep->id_savedino2 != NULL)
4034			panic("initiate_write_inodeblock_ufs2: I/O underway");
4035		FREE_LOCK(&lk);
4036		MALLOC(sip, struct ufs2_dinode *,
4037		    sizeof(struct ufs2_dinode), M_SAVEDINO, M_SOFTDEP_FLAGS);
4038		ACQUIRE_LOCK(&lk);
4039		inodedep->id_savedino2 = sip;
4040		*inodedep->id_savedino2 = *dp;
4041		bzero((caddr_t)dp, sizeof(struct ufs2_dinode));
4042		dp->di_gen = inodedep->id_savedino2->di_gen;
4043		return;
4044	}
4045	/*
4046	 * If no dependencies, then there is nothing to roll back.
4047	 */
4048	inodedep->id_savedsize = dp->di_size;
4049	inodedep->id_savedextsize = dp->di_extsize;
4050	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
4051	    TAILQ_EMPTY(&inodedep->id_extupdt))
4052		return;
4053	/*
4054	 * Set the ext data dependencies to busy.
4055	 */
4056	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
4057	     adp = TAILQ_NEXT(adp, ad_next)) {
4058#ifdef DIAGNOSTIC
4059		if (deplist != 0 && prevlbn >= adp->ad_lbn)
4060			panic("softdep_write_inodeblock: lbn order");
4061		prevlbn = adp->ad_lbn;
4062		if (dp->di_extb[adp->ad_lbn] != adp->ad_newblkno)
4063			panic("%s: direct pointer #%jd mismatch %jd != %jd",
4064			    "softdep_write_inodeblock",
4065			    (intmax_t)adp->ad_lbn,
4066			    (intmax_t)dp->di_extb[adp->ad_lbn],
4067			    (intmax_t)adp->ad_newblkno);
4068		deplist |= 1 << adp->ad_lbn;
4069		if ((adp->ad_state & ATTACHED) == 0)
4070			panic("softdep_write_inodeblock: Unknown state 0x%x",
4071			    adp->ad_state);
4072#endif /* DIAGNOSTIC */
4073		adp->ad_state &= ~ATTACHED;
4074		adp->ad_state |= UNDONE;
4075	}
4076	/*
4077	 * The on-disk inode cannot claim to be any larger than the last
4078	 * fragment that has been written. Otherwise, the on-disk inode
4079	 * might have fragments that were not the last block in the ext
4080	 * data which would corrupt the filesystem.
4081	 */
4082	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
4083	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
4084		dp->di_extb[adp->ad_lbn] = adp->ad_oldblkno;
4085		/* keep going until hitting a rollback to a frag */
4086		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
4087			continue;
4088		dp->di_extsize = fs->fs_bsize * adp->ad_lbn + adp->ad_oldsize;
4089		for (i = adp->ad_lbn + 1; i < NXADDR; i++) {
4090#ifdef DIAGNOSTIC
4091			if (dp->di_extb[i] != 0 && (deplist & (1 << i)) == 0)
4092				panic("softdep_write_inodeblock: lost dep1");
4093#endif /* DIAGNOSTIC */
4094			dp->di_extb[i] = 0;
4095		}
4096		lastadp = NULL;
4097		break;
4098	}
4099	/*
4100	 * If we have zero'ed out the last allocated block of the ext
4101	 * data, roll back the size to the last currently allocated block.
4102	 * We know that this last allocated block is a full-sized as
4103	 * we already checked for fragments in the loop above.
4104	 */
4105	if (lastadp != NULL &&
4106	    dp->di_extsize <= (lastadp->ad_lbn + 1) * fs->fs_bsize) {
4107		for (i = lastadp->ad_lbn; i >= 0; i--)
4108			if (dp->di_extb[i] != 0)
4109				break;
4110		dp->di_extsize = (i + 1) * fs->fs_bsize;
4111	}
4112	/*
4113	 * Set the file data dependencies to busy.
4114	 */
4115	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
4116	     adp = TAILQ_NEXT(adp, ad_next)) {
4117#ifdef DIAGNOSTIC
4118		if (deplist != 0 && prevlbn >= adp->ad_lbn)
4119			panic("softdep_write_inodeblock: lbn order");
4120		prevlbn = adp->ad_lbn;
4121		if (adp->ad_lbn < NDADDR &&
4122		    dp->di_db[adp->ad_lbn] != adp->ad_newblkno)
4123			panic("%s: direct pointer #%jd mismatch %jd != %jd",
4124			    "softdep_write_inodeblock",
4125			    (intmax_t)adp->ad_lbn,
4126			    (intmax_t)dp->di_db[adp->ad_lbn],
4127			    (intmax_t)adp->ad_newblkno);
4128		if (adp->ad_lbn >= NDADDR &&
4129		    dp->di_ib[adp->ad_lbn - NDADDR] != adp->ad_newblkno)
4130			panic("%s indirect pointer #%jd mismatch %jd != %jd",
4131			    "softdep_write_inodeblock:",
4132			    (intmax_t)adp->ad_lbn - NDADDR,
4133			    (intmax_t)dp->di_ib[adp->ad_lbn - NDADDR],
4134			    (intmax_t)adp->ad_newblkno);
4135		deplist |= 1 << adp->ad_lbn;
4136		if ((adp->ad_state & ATTACHED) == 0)
4137			panic("softdep_write_inodeblock: Unknown state 0x%x",
4138			    adp->ad_state);
4139#endif /* DIAGNOSTIC */
4140		adp->ad_state &= ~ATTACHED;
4141		adp->ad_state |= UNDONE;
4142	}
4143	/*
4144	 * The on-disk inode cannot claim to be any larger than the last
4145	 * fragment that has been written. Otherwise, the on-disk inode
4146	 * might have fragments that were not the last block in the file
4147	 * which would corrupt the filesystem.
4148	 */
4149	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
4150	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
4151		if (adp->ad_lbn >= NDADDR)
4152			break;
4153		dp->di_db[adp->ad_lbn] = adp->ad_oldblkno;
4154		/* keep going until hitting a rollback to a frag */
4155		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
4156			continue;
4157		dp->di_size = fs->fs_bsize * adp->ad_lbn + adp->ad_oldsize;
4158		for (i = adp->ad_lbn + 1; i < NDADDR; i++) {
4159#ifdef DIAGNOSTIC
4160			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
4161				panic("softdep_write_inodeblock: lost dep2");
4162#endif /* DIAGNOSTIC */
4163			dp->di_db[i] = 0;
4164		}
4165		for (i = 0; i < NIADDR; i++) {
4166#ifdef DIAGNOSTIC
4167			if (dp->di_ib[i] != 0 &&
4168			    (deplist & ((1 << NDADDR) << i)) == 0)
4169				panic("softdep_write_inodeblock: lost dep3");
4170#endif /* DIAGNOSTIC */
4171			dp->di_ib[i] = 0;
4172		}
4173		return;
4174	}
4175	/*
4176	 * If we have zero'ed out the last allocated block of the file,
4177	 * roll back the size to the last currently allocated block.
4178	 * We know that this last allocated block is a full-sized as
4179	 * we already checked for fragments in the loop above.
4180	 */
4181	if (lastadp != NULL &&
4182	    dp->di_size <= (lastadp->ad_lbn + 1) * fs->fs_bsize) {
4183		for (i = lastadp->ad_lbn; i >= 0; i--)
4184			if (dp->di_db[i] != 0)
4185				break;
4186		dp->di_size = (i + 1) * fs->fs_bsize;
4187	}
4188	/*
4189	 * The only dependencies are for indirect blocks.
4190	 *
4191	 * The file size for indirect block additions is not guaranteed.
4192	 * Such a guarantee would be non-trivial to achieve. The conventional
4193	 * synchronous write implementation also does not make this guarantee.
4194	 * Fsck should catch and fix discrepancies. Arguably, the file size
4195	 * can be over-estimated without destroying integrity when the file
4196	 * moves into the indirect blocks (i.e., is large). If we want to
4197	 * postpone fsck, we are stuck with this argument.
4198	 */
4199	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
4200		dp->di_ib[adp->ad_lbn - NDADDR] = 0;
4201}
4202
4203/*
4204 * This routine is called during the completion interrupt
4205 * service routine for a disk write (from the procedure called
4206 * by the device driver to inform the filesystem caches of
4207 * a request completion).  It should be called early in this
4208 * procedure, before the block is made available to other
4209 * processes or other routines are called.
4210 */
4211static void
4212softdep_disk_write_complete(bp)
4213	struct buf *bp;		/* describes the completed disk write */
4214{
4215	struct worklist *wk;
4216	struct worklist *owk;
4217	struct workhead reattach;
4218	struct newblk *newblk;
4219	struct allocindir *aip;
4220	struct allocdirect *adp;
4221	struct indirdep *indirdep;
4222	struct inodedep *inodedep;
4223	struct bmsafemap *bmsafemap;
4224
4225	/*
4226	 * If an error occurred while doing the write, then the data
4227	 * has not hit the disk and the dependencies cannot be unrolled.
4228	 */
4229	if ((bp->b_ioflags & BIO_ERROR) != 0 && (bp->b_flags & B_INVAL) == 0)
4230		return;
4231	LIST_INIT(&reattach);
4232	/*
4233	 * This lock must not be released anywhere in this code segment.
4234	 */
4235	ACQUIRE_LOCK(&lk);
4236	owk = NULL;
4237	while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
4238		WORKLIST_REMOVE(wk);
4239		if (wk == owk)
4240			panic("duplicate worklist: %p\n", wk);
4241		owk = wk;
4242		switch (wk->wk_type) {
4243
4244		case D_PAGEDEP:
4245			if (handle_written_filepage(WK_PAGEDEP(wk), bp))
4246				WORKLIST_INSERT(&reattach, wk);
4247			continue;
4248
4249		case D_INODEDEP:
4250			if (handle_written_inodeblock(WK_INODEDEP(wk), bp))
4251				WORKLIST_INSERT(&reattach, wk);
4252			continue;
4253
4254		case D_BMSAFEMAP:
4255			bmsafemap = WK_BMSAFEMAP(wk);
4256			while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkhd))) {
4257				newblk->nb_state |= DEPCOMPLETE;
4258				newblk->nb_bmsafemap = NULL;
4259				LIST_REMOVE(newblk, nb_deps);
4260			}
4261			while ((adp =
4262			   LIST_FIRST(&bmsafemap->sm_allocdirecthd))) {
4263				adp->ad_state |= DEPCOMPLETE;
4264				adp->ad_buf = NULL;
4265				LIST_REMOVE(adp, ad_deps);
4266				handle_allocdirect_partdone(adp);
4267			}
4268			while ((aip =
4269			    LIST_FIRST(&bmsafemap->sm_allocindirhd))) {
4270				aip->ai_state |= DEPCOMPLETE;
4271				aip->ai_buf = NULL;
4272				LIST_REMOVE(aip, ai_deps);
4273				handle_allocindir_partdone(aip);
4274			}
4275			while ((inodedep =
4276			     LIST_FIRST(&bmsafemap->sm_inodedephd)) != NULL) {
4277				inodedep->id_state |= DEPCOMPLETE;
4278				LIST_REMOVE(inodedep, id_deps);
4279				inodedep->id_buf = NULL;
4280			}
4281			WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
4282			continue;
4283
4284		case D_MKDIR:
4285			handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
4286			continue;
4287
4288		case D_ALLOCDIRECT:
4289			adp = WK_ALLOCDIRECT(wk);
4290			adp->ad_state |= COMPLETE;
4291			handle_allocdirect_partdone(adp);
4292			continue;
4293
4294		case D_ALLOCINDIR:
4295			aip = WK_ALLOCINDIR(wk);
4296			aip->ai_state |= COMPLETE;
4297			handle_allocindir_partdone(aip);
4298			continue;
4299
4300		case D_INDIRDEP:
4301			indirdep = WK_INDIRDEP(wk);
4302			if (indirdep->ir_state & GOINGAWAY)
4303				panic("disk_write_complete: indirdep gone");
4304			bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
4305			FREE(indirdep->ir_saveddata, M_INDIRDEP);
4306			indirdep->ir_saveddata = 0;
4307			indirdep->ir_state &= ~UNDONE;
4308			indirdep->ir_state |= ATTACHED;
4309			while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != 0) {
4310				handle_allocindir_partdone(aip);
4311				if (aip == LIST_FIRST(&indirdep->ir_donehd))
4312					panic("disk_write_complete: not gone");
4313			}
4314			WORKLIST_INSERT(&reattach, wk);
4315			if ((bp->b_flags & B_DELWRI) == 0)
4316				stat_indir_blk_ptrs++;
4317			bdirty(bp);
4318			continue;
4319
4320		default:
4321			panic("handle_disk_write_complete: Unknown type %s",
4322			    TYPENAME(wk->wk_type));
4323			/* NOTREACHED */
4324		}
4325	}
4326	/*
4327	 * Reattach any requests that must be redone.
4328	 */
4329	while ((wk = LIST_FIRST(&reattach)) != NULL) {
4330		WORKLIST_REMOVE(wk);
4331		WORKLIST_INSERT(&bp->b_dep, wk);
4332	}
4333	FREE_LOCK(&lk);
4334}
4335
4336/*
4337 * Called from within softdep_disk_write_complete above. Note that
4338 * this routine is always called from interrupt level with further
4339 * splbio interrupts blocked.
4340 */
4341static void
4342handle_allocdirect_partdone(adp)
4343	struct allocdirect *adp;	/* the completed allocdirect */
4344{
4345	struct allocdirectlst *listhead;
4346	struct allocdirect *listadp;
4347	struct inodedep *inodedep;
4348	long bsize, delay;
4349
4350	if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
4351		return;
4352	if (adp->ad_buf != NULL)
4353		panic("handle_allocdirect_partdone: dangling dep");
4354	/*
4355	 * The on-disk inode cannot claim to be any larger than the last
4356	 * fragment that has been written. Otherwise, the on-disk inode
4357	 * might have fragments that were not the last block in the file
4358	 * which would corrupt the filesystem. Thus, we cannot free any
4359	 * allocdirects after one whose ad_oldblkno claims a fragment as
4360	 * these blocks must be rolled back to zero before writing the inode.
4361	 * We check the currently active set of allocdirects in id_inoupdt
4362	 * or id_extupdt as appropriate.
4363	 */
4364	inodedep = adp->ad_inodedep;
4365	bsize = inodedep->id_fs->fs_bsize;
4366	if (adp->ad_state & EXTDATA)
4367		listhead = &inodedep->id_extupdt;
4368	else
4369		listhead = &inodedep->id_inoupdt;
4370	TAILQ_FOREACH(listadp, listhead, ad_next) {
4371		/* found our block */
4372		if (listadp == adp)
4373			break;
4374		/* continue if ad_oldlbn is not a fragment */
4375		if (listadp->ad_oldsize == 0 ||
4376		    listadp->ad_oldsize == bsize)
4377			continue;
4378		/* hit a fragment */
4379		return;
4380	}
4381	/*
4382	 * If we have reached the end of the current list without
4383	 * finding the just finished dependency, then it must be
4384	 * on the future dependency list. Future dependencies cannot
4385	 * be freed until they are moved to the current list.
4386	 */
4387	if (listadp == NULL) {
4388#ifdef DEBUG
4389		if (adp->ad_state & EXTDATA)
4390			listhead = &inodedep->id_newextupdt;
4391		else
4392			listhead = &inodedep->id_newinoupdt;
4393		TAILQ_FOREACH(listadp, listhead, ad_next)
4394			/* found our block */
4395			if (listadp == adp)
4396				break;
4397		if (listadp == NULL)
4398			panic("handle_allocdirect_partdone: lost dep");
4399#endif /* DEBUG */
4400		return;
4401	}
4402	/*
4403	 * If we have found the just finished dependency, then free
4404	 * it along with anything that follows it that is complete.
4405	 * If the inode still has a bitmap dependency, then it has
4406	 * never been written to disk, hence the on-disk inode cannot
4407	 * reference the old fragment so we can free it without delay.
4408	 */
4409	delay = (inodedep->id_state & DEPCOMPLETE);
4410	for (; adp; adp = listadp) {
4411		listadp = TAILQ_NEXT(adp, ad_next);
4412		if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
4413			return;
4414		free_allocdirect(listhead, adp, delay);
4415	}
4416}
4417
4418/*
4419 * Called from within softdep_disk_write_complete above. Note that
4420 * this routine is always called from interrupt level with further
4421 * splbio interrupts blocked.
4422 */
4423static void
4424handle_allocindir_partdone(aip)
4425	struct allocindir *aip;		/* the completed allocindir */
4426{
4427	struct indirdep *indirdep;
4428
4429	if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
4430		return;
4431	if (aip->ai_buf != NULL)
4432		panic("handle_allocindir_partdone: dangling dependency");
4433	indirdep = aip->ai_indirdep;
4434	if (indirdep->ir_state & UNDONE) {
4435		LIST_REMOVE(aip, ai_next);
4436		LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
4437		return;
4438	}
4439	if (indirdep->ir_state & UFS1FMT)
4440		((ufs1_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
4441		    aip->ai_newblkno;
4442	else
4443		((ufs2_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
4444		    aip->ai_newblkno;
4445	LIST_REMOVE(aip, ai_next);
4446	if (aip->ai_freefrag != NULL)
4447		add_to_worklist(&aip->ai_freefrag->ff_list);
4448	WORKITEM_FREE(aip, D_ALLOCINDIR);
4449}
4450
4451/*
4452 * Called from within softdep_disk_write_complete above to restore
4453 * in-memory inode block contents to their most up-to-date state. Note
4454 * that this routine is always called from interrupt level with further
4455 * splbio interrupts blocked.
4456 */
4457static int
4458handle_written_inodeblock(inodedep, bp)
4459	struct inodedep *inodedep;
4460	struct buf *bp;		/* buffer containing the inode block */
4461{
4462	struct worklist *wk, *filefree;
4463	struct allocdirect *adp, *nextadp;
4464	struct ufs1_dinode *dp1 = NULL;
4465	struct ufs2_dinode *dp2 = NULL;
4466	int hadchanges, fstype;
4467
4468	if ((inodedep->id_state & IOSTARTED) == 0)
4469		panic("handle_written_inodeblock: not started");
4470	inodedep->id_state &= ~IOSTARTED;
4471	if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC) {
4472		fstype = UFS1;
4473		dp1 = (struct ufs1_dinode *)bp->b_data +
4474		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
4475	} else {
4476		fstype = UFS2;
4477		dp2 = (struct ufs2_dinode *)bp->b_data +
4478		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
4479	}
4480	/*
4481	 * If we had to rollback the inode allocation because of
4482	 * bitmaps being incomplete, then simply restore it.
4483	 * Keep the block dirty so that it will not be reclaimed until
4484	 * all associated dependencies have been cleared and the
4485	 * corresponding updates written to disk.
4486	 */
4487	if (inodedep->id_savedino1 != NULL) {
4488		if (fstype == UFS1)
4489			*dp1 = *inodedep->id_savedino1;
4490		else
4491			*dp2 = *inodedep->id_savedino2;
4492		FREE(inodedep->id_savedino1, M_SAVEDINO);
4493		inodedep->id_savedino1 = NULL;
4494		if ((bp->b_flags & B_DELWRI) == 0)
4495			stat_inode_bitmap++;
4496		bdirty(bp);
4497		return (1);
4498	}
4499	inodedep->id_state |= COMPLETE;
4500	/*
4501	 * Roll forward anything that had to be rolled back before
4502	 * the inode could be updated.
4503	 */
4504	hadchanges = 0;
4505	for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
4506		nextadp = TAILQ_NEXT(adp, ad_next);
4507		if (adp->ad_state & ATTACHED)
4508			panic("handle_written_inodeblock: new entry");
4509		if (fstype == UFS1) {
4510			if (adp->ad_lbn < NDADDR) {
4511				if (dp1->di_db[adp->ad_lbn]!=adp->ad_oldblkno)
4512					panic("%s %s #%jd mismatch %d != %jd",
4513					    "handle_written_inodeblock:",
4514					    "direct pointer",
4515					    (intmax_t)adp->ad_lbn,
4516					    dp1->di_db[adp->ad_lbn],
4517					    (intmax_t)adp->ad_oldblkno);
4518				dp1->di_db[adp->ad_lbn] = adp->ad_newblkno;
4519			} else {
4520				if (dp1->di_ib[adp->ad_lbn - NDADDR] != 0)
4521					panic("%s: %s #%jd allocated as %d",
4522					    "handle_written_inodeblock",
4523					    "indirect pointer",
4524					    (intmax_t)adp->ad_lbn - NDADDR,
4525					    dp1->di_ib[adp->ad_lbn - NDADDR]);
4526				dp1->di_ib[adp->ad_lbn - NDADDR] =
4527				    adp->ad_newblkno;
4528			}
4529		} else {
4530			if (adp->ad_lbn < NDADDR) {
4531				if (dp2->di_db[adp->ad_lbn]!=adp->ad_oldblkno)
4532					panic("%s: %s #%jd %s %jd != %jd",
4533					    "handle_written_inodeblock",
4534					    "direct pointer",
4535					    (intmax_t)adp->ad_lbn, "mismatch",
4536					    (intmax_t)dp2->di_db[adp->ad_lbn],
4537					    (intmax_t)adp->ad_oldblkno);
4538				dp2->di_db[adp->ad_lbn] = adp->ad_newblkno;
4539			} else {
4540				if (dp2->di_ib[adp->ad_lbn - NDADDR] != 0)
4541					panic("%s: %s #%jd allocated as %jd",
4542					    "handle_written_inodeblock",
4543					    "indirect pointer",
4544					    (intmax_t)adp->ad_lbn - NDADDR,
4545					    (intmax_t)
4546					    dp2->di_ib[adp->ad_lbn - NDADDR]);
4547				dp2->di_ib[adp->ad_lbn - NDADDR] =
4548				    adp->ad_newblkno;
4549			}
4550		}
4551		adp->ad_state &= ~UNDONE;
4552		adp->ad_state |= ATTACHED;
4553		hadchanges = 1;
4554	}
4555	for (adp = TAILQ_FIRST(&inodedep->id_extupdt); adp; adp = nextadp) {
4556		nextadp = TAILQ_NEXT(adp, ad_next);
4557		if (adp->ad_state & ATTACHED)
4558			panic("handle_written_inodeblock: new entry");
4559		if (dp2->di_extb[adp->ad_lbn] != adp->ad_oldblkno)
4560			panic("%s: direct pointers #%jd %s %jd != %jd",
4561			    "handle_written_inodeblock",
4562			    (intmax_t)adp->ad_lbn, "mismatch",
4563			    (intmax_t)dp2->di_extb[adp->ad_lbn],
4564			    (intmax_t)adp->ad_oldblkno);
4565		dp2->di_extb[adp->ad_lbn] = adp->ad_newblkno;
4566		adp->ad_state &= ~UNDONE;
4567		adp->ad_state |= ATTACHED;
4568		hadchanges = 1;
4569	}
4570	if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
4571		stat_direct_blk_ptrs++;
4572	/*
4573	 * Reset the file size to its most up-to-date value.
4574	 */
4575	if (inodedep->id_savedsize == -1 || inodedep->id_savedextsize == -1)
4576		panic("handle_written_inodeblock: bad size");
4577	if (fstype == UFS1) {
4578		if (dp1->di_size != inodedep->id_savedsize) {
4579			dp1->di_size = inodedep->id_savedsize;
4580			hadchanges = 1;
4581		}
4582	} else {
4583		if (dp2->di_size != inodedep->id_savedsize) {
4584			dp2->di_size = inodedep->id_savedsize;
4585			hadchanges = 1;
4586		}
4587		if (dp2->di_extsize != inodedep->id_savedextsize) {
4588			dp2->di_extsize = inodedep->id_savedextsize;
4589			hadchanges = 1;
4590		}
4591	}
4592	inodedep->id_savedsize = -1;
4593	inodedep->id_savedextsize = -1;
4594	/*
4595	 * If there were any rollbacks in the inode block, then it must be
4596	 * marked dirty so that its will eventually get written back in
4597	 * its correct form.
4598	 */
4599	if (hadchanges)
4600		bdirty(bp);
4601	/*
4602	 * Process any allocdirects that completed during the update.
4603	 */
4604	if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
4605		handle_allocdirect_partdone(adp);
4606	if ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
4607		handle_allocdirect_partdone(adp);
4608	/*
4609	 * Process deallocations that were held pending until the
4610	 * inode had been written to disk. Freeing of the inode
4611	 * is delayed until after all blocks have been freed to
4612	 * avoid creation of new <vfsid, inum, lbn> triples
4613	 * before the old ones have been deleted.
4614	 */
4615	filefree = NULL;
4616	while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
4617		WORKLIST_REMOVE(wk);
4618		switch (wk->wk_type) {
4619
4620		case D_FREEFILE:
4621			/*
4622			 * We defer adding filefree to the worklist until
4623			 * all other additions have been made to ensure
4624			 * that it will be done after all the old blocks
4625			 * have been freed.
4626			 */
4627			if (filefree != NULL)
4628				panic("handle_written_inodeblock: filefree");
4629			filefree = wk;
4630			continue;
4631
4632		case D_MKDIR:
4633			handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
4634			continue;
4635
4636		case D_DIRADD:
4637			diradd_inode_written(WK_DIRADD(wk), inodedep);
4638			continue;
4639
4640		case D_FREEBLKS:
4641			wk->wk_state |= COMPLETE;
4642			if ((wk->wk_state  & ALLCOMPLETE) != ALLCOMPLETE)
4643				continue;
4644			 /* -- fall through -- */
4645		case D_FREEFRAG:
4646		case D_DIRREM:
4647			add_to_worklist(wk);
4648			continue;
4649
4650		case D_NEWDIRBLK:
4651			free_newdirblk(WK_NEWDIRBLK(wk));
4652			continue;
4653
4654		default:
4655			panic("handle_written_inodeblock: Unknown type %s",
4656			    TYPENAME(wk->wk_type));
4657			/* NOTREACHED */
4658		}
4659	}
4660	if (filefree != NULL) {
4661		if (free_inodedep(inodedep) == 0)
4662			panic("handle_written_inodeblock: live inodedep");
4663		add_to_worklist(filefree);
4664		return (0);
4665	}
4666
4667	/*
4668	 * If no outstanding dependencies, free it.
4669	 */
4670	if (free_inodedep(inodedep) ||
4671	    (TAILQ_FIRST(&inodedep->id_inoupdt) == 0 &&
4672	     TAILQ_FIRST(&inodedep->id_extupdt) == 0))
4673		return (0);
4674	return (hadchanges);
4675}
4676
4677/*
4678 * Process a diradd entry after its dependent inode has been written.
4679 * This routine must be called with splbio interrupts blocked.
4680 */
4681static void
4682diradd_inode_written(dap, inodedep)
4683	struct diradd *dap;
4684	struct inodedep *inodedep;
4685{
4686	struct pagedep *pagedep;
4687
4688	dap->da_state |= COMPLETE;
4689	if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
4690		if (dap->da_state & DIRCHG)
4691			pagedep = dap->da_previous->dm_pagedep;
4692		else
4693			pagedep = dap->da_pagedep;
4694		LIST_REMOVE(dap, da_pdlist);
4695		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
4696	}
4697	WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
4698}
4699
4700/*
4701 * Handle the completion of a mkdir dependency.
4702 */
4703static void
4704handle_written_mkdir(mkdir, type)
4705	struct mkdir *mkdir;
4706	int type;
4707{
4708	struct diradd *dap;
4709	struct pagedep *pagedep;
4710
4711	if (mkdir->md_state != type)
4712		panic("handle_written_mkdir: bad type");
4713	dap = mkdir->md_diradd;
4714	dap->da_state &= ~type;
4715	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
4716		dap->da_state |= DEPCOMPLETE;
4717	if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
4718		if (dap->da_state & DIRCHG)
4719			pagedep = dap->da_previous->dm_pagedep;
4720		else
4721			pagedep = dap->da_pagedep;
4722		LIST_REMOVE(dap, da_pdlist);
4723		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
4724	}
4725	LIST_REMOVE(mkdir, md_mkdirs);
4726	WORKITEM_FREE(mkdir, D_MKDIR);
4727}
4728
4729/*
4730 * Called from within softdep_disk_write_complete above.
4731 * A write operation was just completed. Removed inodes can
4732 * now be freed and associated block pointers may be committed.
4733 * Note that this routine is always called from interrupt level
4734 * with further splbio interrupts blocked.
4735 */
4736static int
4737handle_written_filepage(pagedep, bp)
4738	struct pagedep *pagedep;
4739	struct buf *bp;		/* buffer containing the written page */
4740{
4741	struct dirrem *dirrem;
4742	struct diradd *dap, *nextdap;
4743	struct direct *ep;
4744	int i, chgs;
4745
4746	if ((pagedep->pd_state & IOSTARTED) == 0)
4747		panic("handle_written_filepage: not started");
4748	pagedep->pd_state &= ~IOSTARTED;
4749	/*
4750	 * Process any directory removals that have been committed.
4751	 */
4752	while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
4753		LIST_REMOVE(dirrem, dm_next);
4754		dirrem->dm_dirinum = pagedep->pd_ino;
4755		add_to_worklist(&dirrem->dm_list);
4756	}
4757	/*
4758	 * Free any directory additions that have been committed.
4759	 * If it is a newly allocated block, we have to wait until
4760	 * the on-disk directory inode claims the new block.
4761	 */
4762	if ((pagedep->pd_state & NEWBLOCK) == 0)
4763		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
4764			free_diradd(dap);
4765	/*
4766	 * Uncommitted directory entries must be restored.
4767	 */
4768	for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
4769		for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
4770		     dap = nextdap) {
4771			nextdap = LIST_NEXT(dap, da_pdlist);
4772			if (dap->da_state & ATTACHED)
4773				panic("handle_written_filepage: attached");
4774			ep = (struct direct *)
4775			    ((char *)bp->b_data + dap->da_offset);
4776			ep->d_ino = dap->da_newinum;
4777			dap->da_state &= ~UNDONE;
4778			dap->da_state |= ATTACHED;
4779			chgs = 1;
4780			/*
4781			 * If the inode referenced by the directory has
4782			 * been written out, then the dependency can be
4783			 * moved to the pending list.
4784			 */
4785			if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
4786				LIST_REMOVE(dap, da_pdlist);
4787				LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
4788				    da_pdlist);
4789			}
4790		}
4791	}
4792	/*
4793	 * If there were any rollbacks in the directory, then it must be
4794	 * marked dirty so that its will eventually get written back in
4795	 * its correct form.
4796	 */
4797	if (chgs) {
4798		if ((bp->b_flags & B_DELWRI) == 0)
4799			stat_dir_entry++;
4800		bdirty(bp);
4801		return (1);
4802	}
4803	/*
4804	 * If we are not waiting for a new directory block to be
4805	 * claimed by its inode, then the pagedep will be freed.
4806	 * Otherwise it will remain to track any new entries on
4807	 * the page in case they are fsync'ed.
4808	 */
4809	if ((pagedep->pd_state & NEWBLOCK) == 0) {
4810		LIST_REMOVE(pagedep, pd_hash);
4811		WORKITEM_FREE(pagedep, D_PAGEDEP);
4812	}
4813	return (0);
4814}
4815
4816/*
4817 * Writing back in-core inode structures.
4818 *
4819 * The filesystem only accesses an inode's contents when it occupies an
4820 * "in-core" inode structure.  These "in-core" structures are separate from
4821 * the page frames used to cache inode blocks.  Only the latter are
4822 * transferred to/from the disk.  So, when the updated contents of the
4823 * "in-core" inode structure are copied to the corresponding in-memory inode
4824 * block, the dependencies are also transferred.  The following procedure is
4825 * called when copying a dirty "in-core" inode to a cached inode block.
4826 */
4827
4828/*
4829 * Called when an inode is loaded from disk. If the effective link count
4830 * differed from the actual link count when it was last flushed, then we
4831 * need to ensure that the correct effective link count is put back.
4832 */
4833void
4834softdep_load_inodeblock(ip)
4835	struct inode *ip;	/* the "in_core" copy of the inode */
4836{
4837	struct inodedep *inodedep;
4838
4839	/*
4840	 * Check for alternate nlink count.
4841	 */
4842	ip->i_effnlink = ip->i_nlink;
4843	ACQUIRE_LOCK(&lk);
4844	if (inodedep_lookup(UFSTOVFS(ip->i_ump),
4845	    ip->i_number, 0, &inodedep) == 0) {
4846		FREE_LOCK(&lk);
4847		return;
4848	}
4849	ip->i_effnlink -= inodedep->id_nlinkdelta;
4850	if (inodedep->id_state & SPACECOUNTED)
4851		ip->i_flag |= IN_SPACECOUNTED;
4852	FREE_LOCK(&lk);
4853}
4854
4855/*
4856 * This routine is called just before the "in-core" inode
4857 * information is to be copied to the in-memory inode block.
4858 * Recall that an inode block contains several inodes. If
4859 * the force flag is set, then the dependencies will be
4860 * cleared so that the update can always be made. Note that
4861 * the buffer is locked when this routine is called, so we
4862 * will never be in the middle of writing the inode block
4863 * to disk.
4864 */
4865void
4866softdep_update_inodeblock(ip, bp, waitfor)
4867	struct inode *ip;	/* the "in_core" copy of the inode */
4868	struct buf *bp;		/* the buffer containing the inode block */
4869	int waitfor;		/* nonzero => update must be allowed */
4870{
4871	struct inodedep *inodedep;
4872	struct worklist *wk;
4873	struct mount *mp;
4874	struct buf *ibp;
4875	int error;
4876
4877	/*
4878	 * If the effective link count is not equal to the actual link
4879	 * count, then we must track the difference in an inodedep while
4880	 * the inode is (potentially) tossed out of the cache. Otherwise,
4881	 * if there is no existing inodedep, then there are no dependencies
4882	 * to track.
4883	 */
4884	mp = UFSTOVFS(ip->i_ump);
4885	ACQUIRE_LOCK(&lk);
4886	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
4887		FREE_LOCK(&lk);
4888		if (ip->i_effnlink != ip->i_nlink)
4889			panic("softdep_update_inodeblock: bad link count");
4890		return;
4891	}
4892	if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink)
4893		panic("softdep_update_inodeblock: bad delta");
4894	/*
4895	 * Changes have been initiated. Anything depending on these
4896	 * changes cannot occur until this inode has been written.
4897	 */
4898	inodedep->id_state &= ~COMPLETE;
4899	if ((inodedep->id_state & ONWORKLIST) == 0)
4900		WORKLIST_INSERT(&bp->b_dep, &inodedep->id_list);
4901	/*
4902	 * Any new dependencies associated with the incore inode must
4903	 * now be moved to the list associated with the buffer holding
4904	 * the in-memory copy of the inode. Once merged process any
4905	 * allocdirects that are completed by the merger.
4906	 */
4907	merge_inode_lists(&inodedep->id_newinoupdt, &inodedep->id_inoupdt);
4908	if (!TAILQ_EMPTY(&inodedep->id_inoupdt))
4909		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt));
4910	merge_inode_lists(&inodedep->id_newextupdt, &inodedep->id_extupdt);
4911	if (!TAILQ_EMPTY(&inodedep->id_extupdt))
4912		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_extupdt));
4913	/*
4914	 * Now that the inode has been pushed into the buffer, the
4915	 * operations dependent on the inode being written to disk
4916	 * can be moved to the id_bufwait so that they will be
4917	 * processed when the buffer I/O completes.
4918	 */
4919	while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
4920		WORKLIST_REMOVE(wk);
4921		WORKLIST_INSERT(&inodedep->id_bufwait, wk);
4922	}
4923	/*
4924	 * Newly allocated inodes cannot be written until the bitmap
4925	 * that allocates them have been written (indicated by
4926	 * DEPCOMPLETE being set in id_state). If we are doing a
4927	 * forced sync (e.g., an fsync on a file), we force the bitmap
4928	 * to be written so that the update can be done.
4929	 */
4930	if (waitfor == 0) {
4931		FREE_LOCK(&lk);
4932		return;
4933	}
4934retry:
4935	if ((inodedep->id_state & DEPCOMPLETE) != 0) {
4936		FREE_LOCK(&lk);
4937		return;
4938	}
4939	ibp = inodedep->id_buf;
4940	ibp = getdirtybuf(ibp, &lk, MNT_WAIT);
4941	if (ibp == NULL) {
4942		/*
4943		 * If ibp came back as NULL, the dependency could have been
4944		 * freed while we slept.  Look it up again, and check to see
4945		 * that it has completed.
4946		 */
4947		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
4948			goto retry;
4949		FREE_LOCK(&lk);
4950		return;
4951	}
4952	FREE_LOCK(&lk);
4953	if ((error = bwrite(ibp)) != 0)
4954		softdep_error("softdep_update_inodeblock: bwrite", error);
4955}
4956
4957/*
4958 * Merge the a new inode dependency list (such as id_newinoupdt) into an
4959 * old inode dependency list (such as id_inoupdt). This routine must be
4960 * called with splbio interrupts blocked.
4961 */
4962static void
4963merge_inode_lists(newlisthead, oldlisthead)
4964	struct allocdirectlst *newlisthead;
4965	struct allocdirectlst *oldlisthead;
4966{
4967	struct allocdirect *listadp, *newadp;
4968
4969	newadp = TAILQ_FIRST(newlisthead);
4970	for (listadp = TAILQ_FIRST(oldlisthead); listadp && newadp;) {
4971		if (listadp->ad_lbn < newadp->ad_lbn) {
4972			listadp = TAILQ_NEXT(listadp, ad_next);
4973			continue;
4974		}
4975		TAILQ_REMOVE(newlisthead, newadp, ad_next);
4976		TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
4977		if (listadp->ad_lbn == newadp->ad_lbn) {
4978			allocdirect_merge(oldlisthead, newadp,
4979			    listadp);
4980			listadp = newadp;
4981		}
4982		newadp = TAILQ_FIRST(newlisthead);
4983	}
4984	while ((newadp = TAILQ_FIRST(newlisthead)) != NULL) {
4985		TAILQ_REMOVE(newlisthead, newadp, ad_next);
4986		TAILQ_INSERT_TAIL(oldlisthead, newadp, ad_next);
4987	}
4988}
4989
4990/*
4991 * If we are doing an fsync, then we must ensure that any directory
4992 * entries for the inode have been written after the inode gets to disk.
4993 */
4994int
4995softdep_fsync(vp)
4996	struct vnode *vp;	/* the "in_core" copy of the inode */
4997{
4998	struct inodedep *inodedep;
4999	struct pagedep *pagedep;
5000	struct worklist *wk;
5001	struct diradd *dap;
5002	struct mount *mp;
5003	struct vnode *pvp;
5004	struct inode *ip;
5005	struct buf *bp;
5006	struct fs *fs;
5007	struct thread *td = curthread;
5008	int error, flushparent;
5009	ino_t parentino;
5010	ufs_lbn_t lbn;
5011
5012	ip = VTOI(vp);
5013	fs = ip->i_fs;
5014	mp = vp->v_mount;
5015	ACQUIRE_LOCK(&lk);
5016	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
5017		FREE_LOCK(&lk);
5018		return (0);
5019	}
5020	if (!LIST_EMPTY(&inodedep->id_inowait) ||
5021	    !LIST_EMPTY(&inodedep->id_bufwait) ||
5022	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
5023	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
5024	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
5025	    !TAILQ_EMPTY(&inodedep->id_newinoupdt))
5026		panic("softdep_fsync: pending ops");
5027	for (error = 0, flushparent = 0; ; ) {
5028		if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
5029			break;
5030		if (wk->wk_type != D_DIRADD)
5031			panic("softdep_fsync: Unexpected type %s",
5032			    TYPENAME(wk->wk_type));
5033		dap = WK_DIRADD(wk);
5034		/*
5035		 * Flush our parent if this directory entry has a MKDIR_PARENT
5036		 * dependency or is contained in a newly allocated block.
5037		 */
5038		if (dap->da_state & DIRCHG)
5039			pagedep = dap->da_previous->dm_pagedep;
5040		else
5041			pagedep = dap->da_pagedep;
5042		parentino = pagedep->pd_ino;
5043		lbn = pagedep->pd_lbn;
5044		if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE)
5045			panic("softdep_fsync: dirty");
5046		if ((dap->da_state & MKDIR_PARENT) ||
5047		    (pagedep->pd_state & NEWBLOCK))
5048			flushparent = 1;
5049		else
5050			flushparent = 0;
5051		/*
5052		 * If we are being fsync'ed as part of vgone'ing this vnode,
5053		 * then we will not be able to release and recover the
5054		 * vnode below, so we just have to give up on writing its
5055		 * directory entry out. It will eventually be written, just
5056		 * not now, but then the user was not asking to have it
5057		 * written, so we are not breaking any promises.
5058		 */
5059		if (vp->v_iflag & VI_DOOMED)
5060			break;
5061		/*
5062		 * We prevent deadlock by always fetching inodes from the
5063		 * root, moving down the directory tree. Thus, when fetching
5064		 * our parent directory, we first try to get the lock. If
5065		 * that fails, we must unlock ourselves before requesting
5066		 * the lock on our parent. See the comment in ufs_lookup
5067		 * for details on possible races.
5068		 */
5069		FREE_LOCK(&lk);
5070		if (ffs_vget(mp, parentino, LK_NOWAIT | LK_EXCLUSIVE, &pvp)) {
5071			VOP_UNLOCK(vp, 0, td);
5072			error = ffs_vget(mp, parentino, LK_EXCLUSIVE, &pvp);
5073			vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, td);
5074			if (error != 0)
5075				return (error);
5076		}
5077		/*
5078		 * All MKDIR_PARENT dependencies and all the NEWBLOCK pagedeps
5079		 * that are contained in direct blocks will be resolved by
5080		 * doing a ffs_update. Pagedeps contained in indirect blocks
5081		 * may require a complete sync'ing of the directory. So, we
5082		 * try the cheap and fast ffs_update first, and if that fails,
5083		 * then we do the slower ffs_syncvnode of the directory.
5084		 */
5085		if (flushparent) {
5086			if ((error = ffs_update(pvp, 1)) != 0) {
5087				vput(pvp);
5088				return (error);
5089			}
5090			if ((pagedep->pd_state & NEWBLOCK) &&
5091			    (error = ffs_syncvnode(pvp, MNT_WAIT))) {
5092				vput(pvp);
5093				return (error);
5094			}
5095		}
5096		/*
5097		 * Flush directory page containing the inode's name.
5098		 */
5099		error = bread(pvp, lbn, blksize(fs, VTOI(pvp), lbn), td->td_ucred,
5100		    &bp);
5101		if (error == 0)
5102			error = bwrite(bp);
5103		else
5104			brelse(bp);
5105		vput(pvp);
5106		if (error != 0)
5107			return (error);
5108		ACQUIRE_LOCK(&lk);
5109		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
5110			break;
5111	}
5112	FREE_LOCK(&lk);
5113	return (0);
5114}
5115
5116/*
5117 * Flush all the dirty bitmaps associated with the block device
5118 * before flushing the rest of the dirty blocks so as to reduce
5119 * the number of dependencies that will have to be rolled back.
5120 */
5121void
5122softdep_fsync_mountdev(vp)
5123	struct vnode *vp;
5124{
5125	struct buf *bp, *nbp;
5126	struct worklist *wk;
5127
5128	if (!vn_isdisk(vp, NULL))
5129		panic("softdep_fsync_mountdev: vnode not a disk");
5130restart:
5131	ACQUIRE_LOCK(&lk);
5132	VI_LOCK(vp);
5133	TAILQ_FOREACH_SAFE(bp, &vp->v_bufobj.bo_dirty.bv_hd, b_bobufs, nbp) {
5134		/*
5135		 * If it is already scheduled, skip to the next buffer.
5136		 */
5137		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL))
5138			continue;
5139
5140		if ((bp->b_flags & B_DELWRI) == 0)
5141			panic("softdep_fsync_mountdev: not dirty");
5142		/*
5143		 * We are only interested in bitmaps with outstanding
5144		 * dependencies.
5145		 */
5146		if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
5147		    wk->wk_type != D_BMSAFEMAP ||
5148		    (bp->b_vflags & BV_BKGRDINPROG)) {
5149			BUF_UNLOCK(bp);
5150			continue;
5151		}
5152		VI_UNLOCK(vp);
5153		FREE_LOCK(&lk);
5154		bremfree(bp);
5155		(void) bawrite(bp);
5156		goto restart;
5157	}
5158	FREE_LOCK(&lk);
5159	drain_output(vp);
5160	VI_UNLOCK(vp);
5161}
5162
5163/*
5164 * This routine is called when we are trying to synchronously flush a
5165 * file. This routine must eliminate any filesystem metadata dependencies
5166 * so that the syncing routine can succeed by pushing the dirty blocks
5167 * associated with the file. If any I/O errors occur, they are returned.
5168 */
5169int
5170softdep_sync_metadata(struct vnode *vp)
5171{
5172	struct pagedep *pagedep;
5173	struct allocdirect *adp;
5174	struct allocindir *aip;
5175	struct buf *bp, *nbp;
5176	struct worklist *wk;
5177	int i, error, waitfor;
5178
5179	if (!DOINGSOFTDEP(vp))
5180		return (0);
5181	/*
5182	 * Ensure that any direct block dependencies have been cleared.
5183	 */
5184	ACQUIRE_LOCK(&lk);
5185	if ((error = flush_inodedep_deps(vp->v_mount, VTOI(vp)->i_number))) {
5186		FREE_LOCK(&lk);
5187		return (error);
5188	}
5189	FREE_LOCK(&lk);
5190	/*
5191	 * For most files, the only metadata dependencies are the
5192	 * cylinder group maps that allocate their inode or blocks.
5193	 * The block allocation dependencies can be found by traversing
5194	 * the dependency lists for any buffers that remain on their
5195	 * dirty buffer list. The inode allocation dependency will
5196	 * be resolved when the inode is updated with MNT_WAIT.
5197	 * This work is done in two passes. The first pass grabs most
5198	 * of the buffers and begins asynchronously writing them. The
5199	 * only way to wait for these asynchronous writes is to sleep
5200	 * on the filesystem vnode which may stay busy for a long time
5201	 * if the filesystem is active. So, instead, we make a second
5202	 * pass over the dependencies blocking on each write. In the
5203	 * usual case we will be blocking against a write that we
5204	 * initiated, so when it is done the dependency will have been
5205	 * resolved. Thus the second pass is expected to end quickly.
5206	 */
5207	waitfor = MNT_NOWAIT;
5208
5209top:
5210	/*
5211	 * We must wait for any I/O in progress to finish so that
5212	 * all potential buffers on the dirty list will be visible.
5213	 */
5214	VI_LOCK(vp);
5215	drain_output(vp);
5216	while ((bp = TAILQ_FIRST(&vp->v_bufobj.bo_dirty.bv_hd)) != NULL) {
5217		bp = getdirtybuf(bp, VI_MTX(vp), MNT_WAIT);
5218		if (bp)
5219			break;
5220	}
5221	VI_UNLOCK(vp);
5222	if (bp == NULL)
5223		return (0);
5224loop:
5225	/* While syncing snapshots, we must allow recursive lookups */
5226	bp->b_lock.lk_flags |= LK_CANRECURSE;
5227	ACQUIRE_LOCK(&lk);
5228	/*
5229	 * As we hold the buffer locked, none of its dependencies
5230	 * will disappear.
5231	 */
5232	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5233		switch (wk->wk_type) {
5234
5235		case D_ALLOCDIRECT:
5236			adp = WK_ALLOCDIRECT(wk);
5237			if (adp->ad_state & DEPCOMPLETE)
5238				continue;
5239			nbp = adp->ad_buf;
5240			nbp = getdirtybuf(nbp, &lk, waitfor);
5241			if (nbp == NULL)
5242				continue;
5243			FREE_LOCK(&lk);
5244			if (waitfor == MNT_NOWAIT) {
5245				bawrite(nbp);
5246			} else if ((error = bwrite(nbp)) != 0) {
5247				break;
5248			}
5249			ACQUIRE_LOCK(&lk);
5250			continue;
5251
5252		case D_ALLOCINDIR:
5253			aip = WK_ALLOCINDIR(wk);
5254			if (aip->ai_state & DEPCOMPLETE)
5255				continue;
5256			nbp = aip->ai_buf;
5257			nbp = getdirtybuf(nbp, &lk, waitfor);
5258			if (nbp == NULL)
5259				continue;
5260			FREE_LOCK(&lk);
5261			if (waitfor == MNT_NOWAIT) {
5262				bawrite(nbp);
5263			} else if ((error = bwrite(nbp)) != 0) {
5264				break;
5265			}
5266			ACQUIRE_LOCK(&lk);
5267			continue;
5268
5269		case D_INDIRDEP:
5270		restart:
5271
5272			LIST_FOREACH(aip, &WK_INDIRDEP(wk)->ir_deplisthd, ai_next) {
5273				if (aip->ai_state & DEPCOMPLETE)
5274					continue;
5275				nbp = aip->ai_buf;
5276				nbp = getdirtybuf(nbp, &lk, MNT_WAIT);
5277				if (nbp == NULL)
5278					goto restart;
5279				FREE_LOCK(&lk);
5280				if ((error = bwrite(nbp)) != 0) {
5281					goto loop_end;
5282				}
5283				ACQUIRE_LOCK(&lk);
5284				goto restart;
5285			}
5286			continue;
5287
5288		case D_INODEDEP:
5289			if ((error = flush_inodedep_deps(wk->wk_mp,
5290			    WK_INODEDEP(wk)->id_ino)) != 0) {
5291				FREE_LOCK(&lk);
5292				break;
5293			}
5294			continue;
5295
5296		case D_PAGEDEP:
5297			/*
5298			 * We are trying to sync a directory that may
5299			 * have dependencies on both its own metadata
5300			 * and/or dependencies on the inodes of any
5301			 * recently allocated files. We walk its diradd
5302			 * lists pushing out the associated inode.
5303			 */
5304			pagedep = WK_PAGEDEP(wk);
5305			for (i = 0; i < DAHASHSZ; i++) {
5306				if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
5307					continue;
5308				if ((error =
5309				    flush_pagedep_deps(vp, wk->wk_mp,
5310						&pagedep->pd_diraddhd[i]))) {
5311					FREE_LOCK(&lk);
5312					goto loop_end;
5313				}
5314			}
5315			continue;
5316
5317		case D_MKDIR:
5318			/*
5319			 * This case should never happen if the vnode has
5320			 * been properly sync'ed. However, if this function
5321			 * is used at a place where the vnode has not yet
5322			 * been sync'ed, this dependency can show up. So,
5323			 * rather than panic, just flush it.
5324			 */
5325			nbp = WK_MKDIR(wk)->md_buf;
5326			nbp = getdirtybuf(nbp, &lk, waitfor);
5327			if (nbp == NULL)
5328				continue;
5329			FREE_LOCK(&lk);
5330			if (waitfor == MNT_NOWAIT) {
5331				bawrite(nbp);
5332			} else if ((error = bwrite(nbp)) != 0) {
5333				break;
5334			}
5335			ACQUIRE_LOCK(&lk);
5336			continue;
5337
5338		case D_BMSAFEMAP:
5339			/*
5340			 * This case should never happen if the vnode has
5341			 * been properly sync'ed. However, if this function
5342			 * is used at a place where the vnode has not yet
5343			 * been sync'ed, this dependency can show up. So,
5344			 * rather than panic, just flush it.
5345			 */
5346			nbp = WK_BMSAFEMAP(wk)->sm_buf;
5347			nbp = getdirtybuf(nbp, &lk, waitfor);
5348			if (nbp == NULL)
5349				continue;
5350			FREE_LOCK(&lk);
5351			if (waitfor == MNT_NOWAIT) {
5352				bawrite(nbp);
5353			} else if ((error = bwrite(nbp)) != 0) {
5354				break;
5355			}
5356			ACQUIRE_LOCK(&lk);
5357			continue;
5358
5359		default:
5360			panic("softdep_sync_metadata: Unknown type %s",
5361			    TYPENAME(wk->wk_type));
5362			/* NOTREACHED */
5363		}
5364	loop_end:
5365		/* We reach here only in error and unlocked */
5366		if (error == 0)
5367			panic("softdep_sync_metadata: zero error");
5368		bp->b_lock.lk_flags &= ~LK_CANRECURSE;
5369		bawrite(bp);
5370		return (error);
5371	}
5372	FREE_LOCK(&lk);
5373	VI_LOCK(vp);
5374	while ((nbp = TAILQ_NEXT(bp, b_bobufs)) != NULL) {
5375		nbp = getdirtybuf(nbp, VI_MTX(vp), MNT_WAIT);
5376		if (nbp)
5377			break;
5378	}
5379	VI_UNLOCK(vp);
5380	bp->b_lock.lk_flags &= ~LK_CANRECURSE;
5381	bawrite(bp);
5382	if (nbp != NULL) {
5383		bp = nbp;
5384		goto loop;
5385	}
5386	/*
5387	 * The brief unlock is to allow any pent up dependency
5388	 * processing to be done. Then proceed with the second pass.
5389	 */
5390	if (waitfor == MNT_NOWAIT) {
5391		waitfor = MNT_WAIT;
5392		goto top;
5393	}
5394
5395	/*
5396	 * If we have managed to get rid of all the dirty buffers,
5397	 * then we are done. For certain directories and block
5398	 * devices, we may need to do further work.
5399	 *
5400	 * We must wait for any I/O in progress to finish so that
5401	 * all potential buffers on the dirty list will be visible.
5402	 */
5403	VI_LOCK(vp);
5404	drain_output(vp);
5405	VI_UNLOCK(vp);
5406	return (0);
5407}
5408
5409/*
5410 * Flush the dependencies associated with an inodedep.
5411 * Called with splbio blocked.
5412 */
5413static int
5414flush_inodedep_deps(mp, ino)
5415	struct mount *mp;
5416	ino_t ino;
5417{
5418	struct inodedep *inodedep;
5419	int error, waitfor;
5420
5421	/*
5422	 * This work is done in two passes. The first pass grabs most
5423	 * of the buffers and begins asynchronously writing them. The
5424	 * only way to wait for these asynchronous writes is to sleep
5425	 * on the filesystem vnode which may stay busy for a long time
5426	 * if the filesystem is active. So, instead, we make a second
5427	 * pass over the dependencies blocking on each write. In the
5428	 * usual case we will be blocking against a write that we
5429	 * initiated, so when it is done the dependency will have been
5430	 * resolved. Thus the second pass is expected to end quickly.
5431	 * We give a brief window at the top of the loop to allow
5432	 * any pending I/O to complete.
5433	 */
5434	for (error = 0, waitfor = MNT_NOWAIT; ; ) {
5435		if (error)
5436			return (error);
5437		FREE_LOCK(&lk);
5438		ACQUIRE_LOCK(&lk);
5439		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
5440			return (0);
5441		if (flush_deplist(&inodedep->id_inoupdt, waitfor, &error) ||
5442		    flush_deplist(&inodedep->id_newinoupdt, waitfor, &error) ||
5443		    flush_deplist(&inodedep->id_extupdt, waitfor, &error) ||
5444		    flush_deplist(&inodedep->id_newextupdt, waitfor, &error))
5445			continue;
5446		/*
5447		 * If pass2, we are done, otherwise do pass 2.
5448		 */
5449		if (waitfor == MNT_WAIT)
5450			break;
5451		waitfor = MNT_WAIT;
5452	}
5453	/*
5454	 * Try freeing inodedep in case all dependencies have been removed.
5455	 */
5456	if (inodedep_lookup(mp, ino, 0, &inodedep) != 0)
5457		(void) free_inodedep(inodedep);
5458	return (0);
5459}
5460
5461/*
5462 * Flush an inode dependency list.
5463 * Called with splbio blocked.
5464 */
5465static int
5466flush_deplist(listhead, waitfor, errorp)
5467	struct allocdirectlst *listhead;
5468	int waitfor;
5469	int *errorp;
5470{
5471	struct allocdirect *adp;
5472	struct buf *bp;
5473
5474	mtx_assert(&lk, MA_OWNED);
5475	TAILQ_FOREACH(adp, listhead, ad_next) {
5476		if (adp->ad_state & DEPCOMPLETE)
5477			continue;
5478		bp = adp->ad_buf;
5479		bp = getdirtybuf(bp, &lk, waitfor);
5480		if (bp == NULL) {
5481			if (waitfor == MNT_NOWAIT)
5482				continue;
5483			return (1);
5484		}
5485		FREE_LOCK(&lk);
5486		if (waitfor == MNT_NOWAIT) {
5487			bawrite(bp);
5488		} else if ((*errorp = bwrite(bp)) != 0) {
5489			ACQUIRE_LOCK(&lk);
5490			return (1);
5491		}
5492		ACQUIRE_LOCK(&lk);
5493		return (1);
5494	}
5495	return (0);
5496}
5497
5498/*
5499 * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
5500 * Called with splbio blocked.
5501 */
5502static int
5503flush_pagedep_deps(pvp, mp, diraddhdp)
5504	struct vnode *pvp;
5505	struct mount *mp;
5506	struct diraddhd *diraddhdp;
5507{
5508	struct inodedep *inodedep;
5509	struct ufsmount *ump;
5510	struct diradd *dap;
5511	struct vnode *vp;
5512	int error = 0;
5513	struct buf *bp;
5514	ino_t inum;
5515	struct worklist *wk;
5516
5517	ump = VFSTOUFS(mp);
5518	while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
5519		/*
5520		 * Flush ourselves if this directory entry
5521		 * has a MKDIR_PARENT dependency.
5522		 */
5523		if (dap->da_state & MKDIR_PARENT) {
5524			FREE_LOCK(&lk);
5525			if ((error = ffs_update(pvp, 1)) != 0)
5526				break;
5527			ACQUIRE_LOCK(&lk);
5528			/*
5529			 * If that cleared dependencies, go on to next.
5530			 */
5531			if (dap != LIST_FIRST(diraddhdp))
5532				continue;
5533			if (dap->da_state & MKDIR_PARENT)
5534				panic("flush_pagedep_deps: MKDIR_PARENT");
5535		}
5536		/*
5537		 * A newly allocated directory must have its "." and
5538		 * ".." entries written out before its name can be
5539		 * committed in its parent. We do not want or need
5540		 * the full semantics of a synchronous ffs_syncvnode as
5541		 * that may end up here again, once for each directory
5542		 * level in the filesystem. Instead, we push the blocks
5543		 * and wait for them to clear. We have to fsync twice
5544		 * because the first call may choose to defer blocks
5545		 * that still have dependencies, but deferral will
5546		 * happen at most once.
5547		 */
5548		inum = dap->da_newinum;
5549		if (dap->da_state & MKDIR_BODY) {
5550			FREE_LOCK(&lk);
5551			if ((error = ffs_vget(mp, inum, LK_EXCLUSIVE, &vp)))
5552				break;
5553			if ((error=ffs_syncvnode(vp, MNT_NOWAIT)) ||
5554			    (error=ffs_syncvnode(vp, MNT_NOWAIT))) {
5555				vput(vp);
5556				break;
5557			}
5558			VI_LOCK(vp);
5559			drain_output(vp);
5560			/*
5561			 * If first block is still dirty with a D_MKDIR
5562			 * dependency then it needs to be written now.
5563			 */
5564			for (;;) {
5565				error = 0;
5566				bp = gbincore(&vp->v_bufobj, 0);
5567				if (bp == NULL)
5568					break;	/* First block not present */
5569				error = BUF_LOCK(bp,
5570						 LK_EXCLUSIVE |
5571						 LK_SLEEPFAIL |
5572						 LK_INTERLOCK,
5573						 VI_MTX(vp));
5574				VI_LOCK(vp);
5575				if (error == ENOLCK)
5576					continue;	/* Slept, retry */
5577				if (error != 0)
5578					break;		/* Failed */
5579				if ((bp->b_flags & B_DELWRI) == 0) {
5580					BUF_UNLOCK(bp);
5581					break;	/* Buffer not dirty */
5582				}
5583				for (wk = LIST_FIRST(&bp->b_dep);
5584				     wk != NULL;
5585				     wk = LIST_NEXT(wk, wk_list))
5586					if (wk->wk_type == D_MKDIR)
5587						break;
5588				if (wk == NULL)
5589					BUF_UNLOCK(bp);	/* Dependency gone */
5590				else {
5591					/*
5592					 * D_MKDIR dependency remains,
5593					 * must write buffer to stable
5594					 * storage.
5595					 */
5596					VI_UNLOCK(vp);
5597					bremfree(bp);
5598					error = bwrite(bp);
5599					VI_LOCK(vp);
5600				}
5601				break;
5602			}
5603			VI_UNLOCK(vp);
5604			vput(vp);
5605			if (error != 0)
5606				break;	/* Flushing of first block failed */
5607			ACQUIRE_LOCK(&lk);
5608			/*
5609			 * If that cleared dependencies, go on to next.
5610			 */
5611			if (dap != LIST_FIRST(diraddhdp))
5612				continue;
5613			if (dap->da_state & MKDIR_BODY)
5614				panic("flush_pagedep_deps: MKDIR_BODY");
5615		}
5616		/*
5617		 * Flush the inode on which the directory entry depends.
5618		 * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
5619		 * the only remaining dependency is that the updated inode
5620		 * count must get pushed to disk. The inode has already
5621		 * been pushed into its inode buffer (via VOP_UPDATE) at
5622		 * the time of the reference count change. So we need only
5623		 * locate that buffer, ensure that there will be no rollback
5624		 * caused by a bitmap dependency, then write the inode buffer.
5625		 */
5626retry:
5627		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
5628			panic("flush_pagedep_deps: lost inode");
5629		/*
5630		 * If the inode still has bitmap dependencies,
5631		 * push them to disk.
5632		 */
5633		if ((inodedep->id_state & DEPCOMPLETE) == 0) {
5634			bp = inodedep->id_buf;
5635			bp = getdirtybuf(bp, &lk, MNT_WAIT);
5636			if (bp == NULL)
5637				goto retry;
5638			FREE_LOCK(&lk);
5639			if ((error = bwrite(bp)) != 0)
5640				break;
5641			ACQUIRE_LOCK(&lk);
5642			if (dap != LIST_FIRST(diraddhdp))
5643				continue;
5644		}
5645		/*
5646		 * If the inode is still sitting in a buffer waiting
5647		 * to be written, push it to disk.
5648		 */
5649		FREE_LOCK(&lk);
5650		if ((error = bread(ump->um_devvp,
5651		    fsbtodb(ump->um_fs, ino_to_fsba(ump->um_fs, inum)),
5652		    (int)ump->um_fs->fs_bsize, NOCRED, &bp)) != 0) {
5653			brelse(bp);
5654			break;
5655		}
5656		if ((error = bwrite(bp)) != 0)
5657			break;
5658		ACQUIRE_LOCK(&lk);
5659		/*
5660		 * If we have failed to get rid of all the dependencies
5661		 * then something is seriously wrong.
5662		 */
5663		if (dap == LIST_FIRST(diraddhdp))
5664			panic("flush_pagedep_deps: flush failed");
5665	}
5666	if (error)
5667		ACQUIRE_LOCK(&lk);
5668	return (error);
5669}
5670
5671/*
5672 * A large burst of file addition or deletion activity can drive the
5673 * memory load excessively high. First attempt to slow things down
5674 * using the techniques below. If that fails, this routine requests
5675 * the offending operations to fall back to running synchronously
5676 * until the memory load returns to a reasonable level.
5677 */
5678int
5679softdep_slowdown(vp)
5680	struct vnode *vp;
5681{
5682	int max_softdeps_hard;
5683
5684	ACQUIRE_LOCK(&lk);
5685	max_softdeps_hard = max_softdeps * 11 / 10;
5686	if (num_dirrem < max_softdeps_hard / 2 &&
5687	    num_inodedep < max_softdeps_hard &&
5688	    VFSTOUFS(vp->v_mount)->um_numindirdeps < maxindirdeps) {
5689		FREE_LOCK(&lk);
5690  		return (0);
5691	}
5692	if (VFSTOUFS(vp->v_mount)->um_numindirdeps >= maxindirdeps)
5693		softdep_speedup();
5694	stat_sync_limit_hit += 1;
5695	FREE_LOCK(&lk);
5696	return (1);
5697}
5698
5699/*
5700 * Called by the allocation routines when they are about to fail
5701 * in the hope that we can free up some disk space.
5702 *
5703 * First check to see if the work list has anything on it. If it has,
5704 * clean up entries until we successfully free some space. Because this
5705 * process holds inodes locked, we cannot handle any remove requests
5706 * that might block on a locked inode as that could lead to deadlock.
5707 * If the worklist yields no free space, encourage the syncer daemon
5708 * to help us. In no event will we try for longer than tickdelay seconds.
5709 */
5710int
5711softdep_request_cleanup(fs, vp)
5712	struct fs *fs;
5713	struct vnode *vp;
5714{
5715	struct ufsmount *ump;
5716	long starttime;
5717	ufs2_daddr_t needed;
5718	int error;
5719
5720	ump = VTOI(vp)->i_ump;
5721	mtx_assert(UFS_MTX(ump), MA_OWNED);
5722	needed = fs->fs_cstotal.cs_nbfree + fs->fs_contigsumsize;
5723	starttime = time_second + tickdelay;
5724	/*
5725	 * If we are being called because of a process doing a
5726	 * copy-on-write, then it is not safe to update the vnode
5727	 * as we may recurse into the copy-on-write routine.
5728	 */
5729	if (!(curthread->td_pflags & TDP_COWINPROGRESS)) {
5730		UFS_UNLOCK(ump);
5731		error = ffs_update(vp, 1);
5732		UFS_LOCK(ump);
5733		if (error != 0)
5734			return (0);
5735	}
5736	while (fs->fs_pendingblocks > 0 && fs->fs_cstotal.cs_nbfree <= needed) {
5737		if (time_second > starttime)
5738			return (0);
5739		UFS_UNLOCK(ump);
5740		ACQUIRE_LOCK(&lk);
5741		if (ump->softdep_on_worklist > 0 &&
5742		    process_worklist_item(UFSTOVFS(ump), LK_NOWAIT) != -1) {
5743			stat_worklist_push += 1;
5744			FREE_LOCK(&lk);
5745			UFS_LOCK(ump);
5746			continue;
5747		}
5748		request_cleanup(UFSTOVFS(ump), FLUSH_REMOVE_WAIT);
5749		FREE_LOCK(&lk);
5750		UFS_LOCK(ump);
5751	}
5752	return (1);
5753}
5754
5755/*
5756 * If memory utilization has gotten too high, deliberately slow things
5757 * down and speed up the I/O processing.
5758 */
5759extern struct thread *syncertd;
5760static int
5761request_cleanup(mp, resource)
5762	struct mount *mp;
5763	int resource;
5764{
5765	struct thread *td = curthread;
5766	struct ufsmount *ump;
5767
5768	mtx_assert(&lk, MA_OWNED);
5769	/*
5770	 * We never hold up the filesystem syncer or buf daemon.
5771	 */
5772	if (td->td_pflags & (TDP_SOFTDEP|TDP_NORUNNINGBUF))
5773		return (0);
5774	ump = VFSTOUFS(mp);
5775	/*
5776	 * First check to see if the work list has gotten backlogged.
5777	 * If it has, co-opt this process to help clean up two entries.
5778	 * Because this process may hold inodes locked, we cannot
5779	 * handle any remove requests that might block on a locked
5780	 * inode as that could lead to deadlock.  We set TDP_SOFTDEP
5781	 * to avoid recursively processing the worklist.
5782	 */
5783	if (ump->softdep_on_worklist > max_softdeps / 10) {
5784		td->td_pflags |= TDP_SOFTDEP;
5785		process_worklist_item(mp, LK_NOWAIT);
5786		process_worklist_item(mp, LK_NOWAIT);
5787		td->td_pflags &= ~TDP_SOFTDEP;
5788		stat_worklist_push += 2;
5789		return(1);
5790	}
5791	/*
5792	 * Next, we attempt to speed up the syncer process. If that
5793	 * is successful, then we allow the process to continue.
5794	 */
5795	if (softdep_speedup() && resource != FLUSH_REMOVE_WAIT)
5796		return(0);
5797	/*
5798	 * If we are resource constrained on inode dependencies, try
5799	 * flushing some dirty inodes. Otherwise, we are constrained
5800	 * by file deletions, so try accelerating flushes of directories
5801	 * with removal dependencies. We would like to do the cleanup
5802	 * here, but we probably hold an inode locked at this point and
5803	 * that might deadlock against one that we try to clean. So,
5804	 * the best that we can do is request the syncer daemon to do
5805	 * the cleanup for us.
5806	 */
5807	switch (resource) {
5808
5809	case FLUSH_INODES:
5810		stat_ino_limit_push += 1;
5811		req_clear_inodedeps += 1;
5812		stat_countp = &stat_ino_limit_hit;
5813		break;
5814
5815	case FLUSH_REMOVE:
5816	case FLUSH_REMOVE_WAIT:
5817		stat_blk_limit_push += 1;
5818		req_clear_remove += 1;
5819		stat_countp = &stat_blk_limit_hit;
5820		break;
5821
5822	default:
5823		panic("request_cleanup: unknown type");
5824	}
5825	/*
5826	 * Hopefully the syncer daemon will catch up and awaken us.
5827	 * We wait at most tickdelay before proceeding in any case.
5828	 */
5829	proc_waiting += 1;
5830	if (handle.callout == NULL)
5831		handle = timeout(pause_timer, 0, tickdelay > 2 ? tickdelay : 2);
5832	msleep((caddr_t)&proc_waiting, &lk, PPAUSE, "softupdate", 0);
5833	proc_waiting -= 1;
5834	return (1);
5835}
5836
5837/*
5838 * Awaken processes pausing in request_cleanup and clear proc_waiting
5839 * to indicate that there is no longer a timer running.
5840 */
5841static void
5842pause_timer(arg)
5843	void *arg;
5844{
5845
5846	ACQUIRE_LOCK(&lk);
5847	*stat_countp += 1;
5848	wakeup_one(&proc_waiting);
5849	if (proc_waiting > 0)
5850		handle = timeout(pause_timer, 0, tickdelay > 2 ? tickdelay : 2);
5851	else
5852		handle.callout = NULL;
5853	FREE_LOCK(&lk);
5854}
5855
5856/*
5857 * Flush out a directory with at least one removal dependency in an effort to
5858 * reduce the number of dirrem, freefile, and freeblks dependency structures.
5859 */
5860static void
5861clear_remove(td)
5862	struct thread *td;
5863{
5864	struct pagedep_hashhead *pagedephd;
5865	struct pagedep *pagedep;
5866	static int next = 0;
5867	struct mount *mp;
5868	struct vnode *vp;
5869	int error, cnt;
5870	ino_t ino;
5871
5872	mtx_assert(&lk, MA_OWNED);
5873
5874	for (cnt = 0; cnt < pagedep_hash; cnt++) {
5875		pagedephd = &pagedep_hashtbl[next++];
5876		if (next >= pagedep_hash)
5877			next = 0;
5878		LIST_FOREACH(pagedep, pagedephd, pd_hash) {
5879			if (LIST_EMPTY(&pagedep->pd_dirremhd))
5880				continue;
5881			mp = pagedep->pd_list.wk_mp;
5882			ino = pagedep->pd_ino;
5883			if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
5884				continue;
5885			FREE_LOCK(&lk);
5886			if ((error = ffs_vget(mp, ino, LK_EXCLUSIVE, &vp))) {
5887				softdep_error("clear_remove: vget", error);
5888				vn_finished_write(mp);
5889				ACQUIRE_LOCK(&lk);
5890				return;
5891			}
5892			if ((error = ffs_syncvnode(vp, MNT_NOWAIT)))
5893				softdep_error("clear_remove: fsync", error);
5894			VI_LOCK(vp);
5895			drain_output(vp);
5896			VI_UNLOCK(vp);
5897			vput(vp);
5898			vn_finished_write(mp);
5899			ACQUIRE_LOCK(&lk);
5900			return;
5901		}
5902	}
5903}
5904
5905/*
5906 * Clear out a block of dirty inodes in an effort to reduce
5907 * the number of inodedep dependency structures.
5908 */
5909static void
5910clear_inodedeps(td)
5911	struct thread *td;
5912{
5913	struct inodedep_hashhead *inodedephd;
5914	struct inodedep *inodedep;
5915	static int next = 0;
5916	struct mount *mp;
5917	struct vnode *vp;
5918	struct fs *fs;
5919	int error, cnt;
5920	ino_t firstino, lastino, ino;
5921
5922	mtx_assert(&lk, MA_OWNED);
5923	/*
5924	 * Pick a random inode dependency to be cleared.
5925	 * We will then gather up all the inodes in its block
5926	 * that have dependencies and flush them out.
5927	 */
5928	for (cnt = 0; cnt < inodedep_hash; cnt++) {
5929		inodedephd = &inodedep_hashtbl[next++];
5930		if (next >= inodedep_hash)
5931			next = 0;
5932		if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
5933			break;
5934	}
5935	if (inodedep == NULL)
5936		return;
5937	fs = inodedep->id_fs;
5938	mp = inodedep->id_list.wk_mp;
5939	/*
5940	 * Find the last inode in the block with dependencies.
5941	 */
5942	firstino = inodedep->id_ino & ~(INOPB(fs) - 1);
5943	for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
5944		if (inodedep_lookup(mp, lastino, 0, &inodedep) != 0)
5945			break;
5946	/*
5947	 * Asynchronously push all but the last inode with dependencies.
5948	 * Synchronously push the last inode with dependencies to ensure
5949	 * that the inode block gets written to free up the inodedeps.
5950	 */
5951	for (ino = firstino; ino <= lastino; ino++) {
5952		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
5953			continue;
5954		if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
5955			continue;
5956		FREE_LOCK(&lk);
5957		if ((error = ffs_vget(mp, ino, LK_EXCLUSIVE, &vp)) != 0) {
5958			softdep_error("clear_inodedeps: vget", error);
5959			vn_finished_write(mp);
5960			ACQUIRE_LOCK(&lk);
5961			return;
5962		}
5963		if (ino == lastino) {
5964			if ((error = ffs_syncvnode(vp, MNT_WAIT)))
5965				softdep_error("clear_inodedeps: fsync1", error);
5966		} else {
5967			if ((error = ffs_syncvnode(vp, MNT_NOWAIT)))
5968				softdep_error("clear_inodedeps: fsync2", error);
5969			VI_LOCK(vp);
5970			drain_output(vp);
5971			VI_UNLOCK(vp);
5972		}
5973		vput(vp);
5974		vn_finished_write(mp);
5975		ACQUIRE_LOCK(&lk);
5976	}
5977}
5978
5979/*
5980 * Function to determine if the buffer has outstanding dependencies
5981 * that will cause a roll-back if the buffer is written. If wantcount
5982 * is set, return number of dependencies, otherwise just yes or no.
5983 */
5984static int
5985softdep_count_dependencies(bp, wantcount)
5986	struct buf *bp;
5987	int wantcount;
5988{
5989	struct worklist *wk;
5990	struct inodedep *inodedep;
5991	struct indirdep *indirdep;
5992	struct allocindir *aip;
5993	struct pagedep *pagedep;
5994	struct diradd *dap;
5995	int i, retval;
5996
5997	retval = 0;
5998	ACQUIRE_LOCK(&lk);
5999	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
6000		switch (wk->wk_type) {
6001
6002		case D_INODEDEP:
6003			inodedep = WK_INODEDEP(wk);
6004			if ((inodedep->id_state & DEPCOMPLETE) == 0) {
6005				/* bitmap allocation dependency */
6006				retval += 1;
6007				if (!wantcount)
6008					goto out;
6009			}
6010			if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
6011				/* direct block pointer dependency */
6012				retval += 1;
6013				if (!wantcount)
6014					goto out;
6015			}
6016			if (TAILQ_FIRST(&inodedep->id_extupdt)) {
6017				/* direct block pointer dependency */
6018				retval += 1;
6019				if (!wantcount)
6020					goto out;
6021			}
6022			continue;
6023
6024		case D_INDIRDEP:
6025			indirdep = WK_INDIRDEP(wk);
6026
6027			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
6028				/* indirect block pointer dependency */
6029				retval += 1;
6030				if (!wantcount)
6031					goto out;
6032			}
6033			continue;
6034
6035		case D_PAGEDEP:
6036			pagedep = WK_PAGEDEP(wk);
6037			for (i = 0; i < DAHASHSZ; i++) {
6038
6039				LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
6040					/* directory entry dependency */
6041					retval += 1;
6042					if (!wantcount)
6043						goto out;
6044				}
6045			}
6046			continue;
6047
6048		case D_BMSAFEMAP:
6049		case D_ALLOCDIRECT:
6050		case D_ALLOCINDIR:
6051		case D_MKDIR:
6052			/* never a dependency on these blocks */
6053			continue;
6054
6055		default:
6056			panic("softdep_check_for_rollback: Unexpected type %s",
6057			    TYPENAME(wk->wk_type));
6058			/* NOTREACHED */
6059		}
6060	}
6061out:
6062	FREE_LOCK(&lk);
6063	return retval;
6064}
6065
6066/*
6067 * Acquire exclusive access to a buffer.
6068 * Must be called with a locked mtx parameter.
6069 * Return acquired buffer or NULL on failure.
6070 */
6071static struct buf *
6072getdirtybuf(bp, mtx, waitfor)
6073	struct buf *bp;
6074	struct mtx *mtx;
6075	int waitfor;
6076{
6077	int error;
6078
6079	mtx_assert(mtx, MA_OWNED);
6080	if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0) {
6081		if (waitfor != MNT_WAIT)
6082			return (NULL);
6083		error = BUF_LOCK(bp,
6084		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, mtx);
6085		/*
6086		 * Even if we sucessfully acquire bp here, we have dropped
6087		 * mtx, which may violates our guarantee.
6088		 */
6089		if (error == 0)
6090			BUF_UNLOCK(bp);
6091		else if (error != ENOLCK)
6092			panic("getdirtybuf: inconsistent lock: %d", error);
6093		mtx_lock(mtx);
6094		return (NULL);
6095	}
6096	if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
6097		if (mtx == &lk && waitfor == MNT_WAIT) {
6098			mtx_unlock(mtx);
6099			BO_LOCK(bp->b_bufobj);
6100			BUF_UNLOCK(bp);
6101			if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
6102				bp->b_vflags |= BV_BKGRDWAIT;
6103				msleep(&bp->b_xflags, BO_MTX(bp->b_bufobj),
6104				       PRIBIO | PDROP, "getbuf", 0);
6105			} else
6106				BO_UNLOCK(bp->b_bufobj);
6107			mtx_lock(mtx);
6108			return (NULL);
6109		}
6110		BUF_UNLOCK(bp);
6111		if (waitfor != MNT_WAIT)
6112			return (NULL);
6113		/*
6114		 * The mtx argument must be bp->b_vp's mutex in
6115		 * this case.
6116		 */
6117#ifdef	DEBUG_VFS_LOCKS
6118		if (bp->b_vp->v_type != VCHR)
6119			ASSERT_VI_LOCKED(bp->b_vp, "getdirtybuf");
6120#endif
6121		bp->b_vflags |= BV_BKGRDWAIT;
6122		msleep(&bp->b_xflags, mtx, PRIBIO, "getbuf", 0);
6123		return (NULL);
6124	}
6125	if ((bp->b_flags & B_DELWRI) == 0) {
6126		BUF_UNLOCK(bp);
6127		return (NULL);
6128	}
6129	bremfree(bp);
6130	return (bp);
6131}
6132
6133
6134/*
6135 * Check if it is safe to suspend the file system now.  On entry,
6136 * the vnode interlock for devvp should be held.  Return 0 with
6137 * the mount interlock held if the file system can be suspended now,
6138 * otherwise return EAGAIN with the mount interlock held.
6139 */
6140int
6141softdep_check_suspend(struct mount *mp,
6142		      struct vnode *devvp,
6143		      int softdep_deps,
6144		      int softdep_accdeps,
6145		      int secondary_writes,
6146		      int secondary_accwrites)
6147{
6148	struct bufobj *bo;
6149	struct ufsmount *ump;
6150	int error;
6151
6152	ASSERT_VI_LOCKED(devvp, "softdep_check_suspend");
6153	ump = VFSTOUFS(mp);
6154	bo = &devvp->v_bufobj;
6155
6156	for (;;) {
6157		if (!TRY_ACQUIRE_LOCK(&lk)) {
6158			VI_UNLOCK(devvp);
6159			ACQUIRE_LOCK(&lk);
6160			FREE_LOCK(&lk);
6161			VI_LOCK(devvp);
6162			continue;
6163		}
6164		if (!MNT_ITRYLOCK(mp)) {
6165			FREE_LOCK(&lk);
6166			VI_UNLOCK(devvp);
6167			MNT_ILOCK(mp);
6168			MNT_IUNLOCK(mp);
6169			VI_LOCK(devvp);
6170			continue;
6171		}
6172		if (mp->mnt_secondary_writes != 0) {
6173			FREE_LOCK(&lk);
6174			VI_UNLOCK(devvp);
6175			msleep(&mp->mnt_secondary_writes,
6176			       MNT_MTX(mp),
6177			       (PUSER - 1) | PDROP, "secwr", 0);
6178			VI_LOCK(devvp);
6179			continue;
6180		}
6181		break;
6182	}
6183
6184	/*
6185	 * Reasons for needing more work before suspend:
6186	 * - Dirty buffers on devvp.
6187	 * - Softdep activity occurred after start of vnode sync loop
6188	 * - Secondary writes occurred after start of vnode sync loop
6189	 */
6190	error = 0;
6191	if (bo->bo_numoutput > 0 ||
6192	    bo->bo_dirty.bv_cnt > 0 ||
6193	    softdep_deps != 0 ||
6194	    ump->softdep_deps != 0 ||
6195	    softdep_accdeps != ump->softdep_accdeps ||
6196	    secondary_writes != 0 ||
6197	    mp->mnt_secondary_writes != 0 ||
6198	    secondary_accwrites != mp->mnt_secondary_accwrites)
6199		error = EAGAIN;
6200	FREE_LOCK(&lk);
6201	VI_UNLOCK(devvp);
6202	return (error);
6203}
6204
6205
6206/*
6207 * Get the number of dependency structures for the file system, both
6208 * the current number and the total number allocated.  These will
6209 * later be used to detect that softdep processing has occurred.
6210 */
6211void
6212softdep_get_depcounts(struct mount *mp,
6213		      int *softdep_depsp,
6214		      int *softdep_accdepsp)
6215{
6216	struct ufsmount *ump;
6217
6218	ump = VFSTOUFS(mp);
6219	ACQUIRE_LOCK(&lk);
6220	*softdep_depsp = ump->softdep_deps;
6221	*softdep_accdepsp = ump->softdep_accdeps;
6222	FREE_LOCK(&lk);
6223}
6224
6225/*
6226 * Wait for pending output on a vnode to complete.
6227 * Must be called with vnode lock and interlock locked.
6228 *
6229 * XXX: Should just be a call to bufobj_wwait().
6230 */
6231static void
6232drain_output(vp)
6233	struct vnode *vp;
6234{
6235	ASSERT_VOP_LOCKED(vp, "drain_output");
6236	ASSERT_VI_LOCKED(vp, "drain_output");
6237
6238	while (vp->v_bufobj.bo_numoutput) {
6239		vp->v_bufobj.bo_flag |= BO_WWAIT;
6240		msleep((caddr_t)&vp->v_bufobj.bo_numoutput,
6241		    VI_MTX(vp), PRIBIO + 1, "drainvp", 0);
6242	}
6243}
6244
6245/*
6246 * Called whenever a buffer that is being invalidated or reallocated
6247 * contains dependencies. This should only happen if an I/O error has
6248 * occurred. The routine is called with the buffer locked.
6249 */
6250static void
6251softdep_deallocate_dependencies(bp)
6252	struct buf *bp;
6253{
6254
6255	if ((bp->b_ioflags & BIO_ERROR) == 0)
6256		panic("softdep_deallocate_dependencies: dangling deps");
6257	softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntonname, bp->b_error);
6258	panic("softdep_deallocate_dependencies: unrecovered I/O error");
6259}
6260
6261/*
6262 * Function to handle asynchronous write errors in the filesystem.
6263 */
6264static void
6265softdep_error(func, error)
6266	char *func;
6267	int error;
6268{
6269
6270	/* XXX should do something better! */
6271	printf("%s: got error %d while accessing filesystem\n", func, error);
6272}
6273
6274#endif /* SOFTUPDATES */
6275