ufs_dirhash.c revision 214359
1139825Simp/*-
2107868Siedowse * Copyright (c) 2001, 2002 Ian Dowse.  All rights reserved.
379561Siedowse *
479561Siedowse * Redistribution and use in source and binary forms, with or without
579561Siedowse * modification, are permitted provided that the following conditions
679561Siedowse * are met:
779561Siedowse * 1. Redistributions of source code must retain the above copyright
879561Siedowse *    notice, this list of conditions and the following disclaimer.
979561Siedowse * 2. Redistributions in binary form must reproduce the above copyright
1079561Siedowse *    notice, this list of conditions and the following disclaimer in the
1179561Siedowse *    documentation and/or other materials provided with the distribution.
1279561Siedowse *
1379561Siedowse * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
1479561Siedowse * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1579561Siedowse * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1679561Siedowse * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
1779561Siedowse * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1879561Siedowse * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
1979561Siedowse * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2079561Siedowse * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2179561Siedowse * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2279561Siedowse * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
2379561Siedowse * SUCH DAMAGE.
2479561Siedowse */
25116192Sobrien
2679561Siedowse/*
2779561Siedowse * This implements a hash-based lookup scheme for UFS directories.
2879561Siedowse */
2979561Siedowse
30116192Sobrien#include <sys/cdefs.h>
31116192Sobrien__FBSDID("$FreeBSD: head/sys/ufs/ufs/ufs_dirhash.c 214359 2010-10-25 21:46:23Z ivoras $");
32116192Sobrien
3379561Siedowse#include "opt_ufs.h"
3479561Siedowse
3579561Siedowse#ifdef UFS_DIRHASH
3679561Siedowse
3779561Siedowse#include <sys/param.h>
3879561Siedowse#include <sys/systm.h>
3979561Siedowse#include <sys/kernel.h>
4084811Sjhb#include <sys/lock.h>
4179561Siedowse#include <sys/mutex.h>
4279561Siedowse#include <sys/malloc.h>
4379561Siedowse#include <sys/fnv_hash.h>
4479561Siedowse#include <sys/proc.h>
4579561Siedowse#include <sys/bio.h>
4679561Siedowse#include <sys/buf.h>
4779561Siedowse#include <sys/vnode.h>
4879561Siedowse#include <sys/mount.h>
49183080Sjhb#include <sys/refcount.h>
5079561Siedowse#include <sys/sysctl.h>
51183080Sjhb#include <sys/sx.h>
52193375Ssnb#include <sys/eventhandler.h>
53193375Ssnb#include <sys/time.h>
5492768Sjeff#include <vm/uma.h>
5579561Siedowse
5679561Siedowse#include <ufs/ufs/quota.h>
5779561Siedowse#include <ufs/ufs/inode.h>
5879561Siedowse#include <ufs/ufs/dir.h>
5979561Siedowse#include <ufs/ufs/dirhash.h>
6079561Siedowse#include <ufs/ufs/extattr.h>
6179561Siedowse#include <ufs/ufs/ufsmount.h>
6279561Siedowse#include <ufs/ufs/ufs_extern.h>
6379561Siedowse
6479561Siedowse#define WRAPINCR(val, limit)	(((val) + 1 == (limit)) ? 0 : ((val) + 1))
6592807Sdwmalone#define WRAPDECR(val, limit)	(((val) == 0) ? ((limit) - 1) : ((val) - 1))
6679561Siedowse#define OFSFMT(vp)		((vp)->v_mount->mnt_maxsymlinklen <= 0)
6792098Siedowse#define BLKFREE2IDX(n)		((n) > DH_NFSTATS ? DH_NFSTATS : (n))
6879561Siedowse
69151897Srwatsonstatic MALLOC_DEFINE(M_DIRHASH, "ufs_dirhash", "UFS directory hash tables");
7079561Siedowse
7179561Siedowsestatic int ufs_mindirhashsize = DIRBLKSIZ * 5;
7279561SiedowseSYSCTL_INT(_vfs_ufs, OID_AUTO, dirhash_minsize, CTLFLAG_RW,
7379561Siedowse    &ufs_mindirhashsize,
7479561Siedowse    0, "minimum directory size in bytes for which to use hashed lookup");
75214359Sivorasstatic int ufs_dirhashmaxmem = 2 * 1024 * 1024;	/* NOTE: initial value. It is
76214359Sivoras						   tuned in ufsdirhash_init() */
7779561SiedowseSYSCTL_INT(_vfs_ufs, OID_AUTO, dirhash_maxmem, CTLFLAG_RW, &ufs_dirhashmaxmem,
7879561Siedowse    0, "maximum allowed dirhash memory usage");
7979561Siedowsestatic int ufs_dirhashmem;
8079561SiedowseSYSCTL_INT(_vfs_ufs, OID_AUTO, dirhash_mem, CTLFLAG_RD, &ufs_dirhashmem,
8179561Siedowse    0, "current dirhash memory usage");
8285512Siedowsestatic int ufs_dirhashcheck = 0;
8379561SiedowseSYSCTL_INT(_vfs_ufs, OID_AUTO, dirhash_docheck, CTLFLAG_RW, &ufs_dirhashcheck,
8479561Siedowse    0, "enable extra sanity tests");
85193375Ssnbstatic int ufs_dirhashlowmemcount = 0;
86193375SsnbSYSCTL_INT(_vfs_ufs, OID_AUTO, dirhash_lowmemcount, CTLFLAG_RD,
87193375Ssnb    &ufs_dirhashlowmemcount, 0, "number of times low memory hook called");
88193375Ssnbstatic int ufs_dirhashreclaimage = 5;
89193375SsnbSYSCTL_INT(_vfs_ufs, OID_AUTO, dirhash_reclaimage, CTLFLAG_RW,
90193375Ssnb    &ufs_dirhashreclaimage, 0,
91193375Ssnb    "max time in seconds of hash inactivity before deletion in low VM events");
9279561Siedowse
9379561Siedowse
9479561Siedowsestatic int ufsdirhash_hash(struct dirhash *dh, char *name, int namelen);
9579561Siedowsestatic void ufsdirhash_adjfree(struct dirhash *dh, doff_t offset, int diff);
9679561Siedowsestatic void ufsdirhash_delslot(struct dirhash *dh, int slot);
9779561Siedowsestatic int ufsdirhash_findslot(struct dirhash *dh, char *name, int namelen,
9879561Siedowse	   doff_t offset);
9979561Siedowsestatic doff_t ufsdirhash_getprev(struct direct *dp, doff_t offset);
10079561Siedowsestatic int ufsdirhash_recycle(int wanted);
101193375Ssnbstatic void ufsdirhash_lowmem(void);
102178110Sjeffstatic void ufsdirhash_free_locked(struct inode *ip);
10379561Siedowse
10492768Sjeffstatic uma_zone_t	ufsdirhash_zone;
10579561Siedowse
106125854Sdwmalone#define DIRHASHLIST_LOCK() 		mtx_lock(&ufsdirhash_mtx)
107125854Sdwmalone#define DIRHASHLIST_UNLOCK() 		mtx_unlock(&ufsdirhash_mtx)
108125854Sdwmalone#define DIRHASH_BLKALLOC_WAITOK() 	uma_zalloc(ufsdirhash_zone, M_WAITOK)
109125854Sdwmalone#define DIRHASH_BLKFREE(ptr) 		uma_zfree(ufsdirhash_zone, (ptr))
110178110Sjeff#define	DIRHASH_ASSERT_LOCKED(dh)					\
111183080Sjhb    sx_assert(&(dh)->dh_lock, SA_LOCKED)
112125854Sdwmalone
11379561Siedowse/* Dirhash list; recently-used entries are near the tail. */
11479561Siedowsestatic TAILQ_HEAD(, dirhash) ufsdirhash_list;
11579561Siedowse
11679561Siedowse/* Protects: ufsdirhash_list, `dh_list' field, ufs_dirhashmem. */
11779561Siedowsestatic struct mtx	ufsdirhash_mtx;
11879561Siedowse
11979561Siedowse/*
120178110Sjeff * Locking:
12179561Siedowse *
122178110Sjeff * The relationship between inode and dirhash is protected either by an
123178110Sjeff * exclusive vnode lock or the vnode interlock where a shared vnode lock
124183080Sjhb * may be used.  The dirhash_mtx is acquired after the dirhash lock.  To
125183080Sjhb * handle teardown races, code wishing to lock the dirhash for an inode
126183080Sjhb * when using a shared vnode lock must obtain a private reference on the
127183080Sjhb * dirhash while holding the vnode interlock.  They can drop it once they
128183080Sjhb * have obtained the dirhash lock and verified that the dirhash wasn't
129183080Sjhb * recycled while they waited for the dirhash lock.
130178110Sjeff *
131178110Sjeff * ufsdirhash_build() acquires a shared lock on the dirhash when it is
132178110Sjeff * successful.  This lock is released after a call to ufsdirhash_lookup().
133178110Sjeff *
134178110Sjeff * Functions requiring exclusive access use ufsdirhash_acquire() which may
135178110Sjeff * free a dirhash structure that was recycled by ufsdirhash_recycle().
136178110Sjeff *
137178110Sjeff * The dirhash lock may be held across io operations.
138187474Sjhb *
139187474Sjhb * WITNESS reports a lock order reversal between the "bufwait" lock
140187474Sjhb * and the "dirhash" lock.  However, this specific reversal will not
141187474Sjhb * cause a deadlock.  To get a deadlock, one would have to lock a
142187474Sjhb * buffer followed by the dirhash while a second thread locked a
143187474Sjhb * buffer while holding the dirhash lock.  The second order can happen
144187474Sjhb * under a shared or exclusive vnode lock for the associated directory
145187474Sjhb * in lookup().  The first order, however, can only happen under an
146187474Sjhb * exclusive vnode lock (e.g. unlink(), rename(), etc.).  Thus, for
147187474Sjhb * a thread to be doing a "bufwait" -> "dirhash" order, it has to hold
148187474Sjhb * an exclusive vnode lock.  That exclusive vnode lock will prevent
149187474Sjhb * any other threads from doing a "dirhash" -> "bufwait" order.
15079561Siedowse */
15179561Siedowse
152183080Sjhbstatic void
153183080Sjhbufsdirhash_hold(struct dirhash *dh)
154183080Sjhb{
155183080Sjhb
156183080Sjhb	refcount_acquire(&dh->dh_refcount);
157183080Sjhb}
158183080Sjhb
159183080Sjhbstatic void
160183080Sjhbufsdirhash_drop(struct dirhash *dh)
161183080Sjhb{
162183080Sjhb
163183080Sjhb	if (refcount_release(&dh->dh_refcount)) {
164183080Sjhb		sx_destroy(&dh->dh_lock);
165183080Sjhb		free(dh, M_DIRHASH);
166183080Sjhb	}
167183080Sjhb}
168183080Sjhb
16979561Siedowse/*
170178110Sjeff * Release the lock on a dirhash.
171178110Sjeff */
172178110Sjeffstatic void
173178110Sjeffufsdirhash_release(struct dirhash *dh)
174178110Sjeff{
175178110Sjeff
176183080Sjhb	sx_unlock(&dh->dh_lock);
177178110Sjeff}
178178110Sjeff
179178110Sjeff/*
180178110Sjeff * Either acquire an existing hash locked shared or create a new hash and
181178110Sjeff * return it exclusively locked.  May return NULL if the allocation fails.
182178110Sjeff *
183178110Sjeff * The vnode interlock is used to protect the i_dirhash pointer from
184178110Sjeff * simultaneous access while only a shared vnode lock is held.
185178110Sjeff */
186178110Sjeffstatic struct dirhash *
187178110Sjeffufsdirhash_create(struct inode *ip)
188178110Sjeff{
189178110Sjeff	struct dirhash *ndh;
190178110Sjeff	struct dirhash *dh;
191178110Sjeff	struct vnode *vp;
192178110Sjeff	int error;
193178110Sjeff
194178110Sjeff	error = 0;
195178110Sjeff	ndh = dh = NULL;
196178110Sjeff	vp = ip->i_vnode;
197178110Sjeff	for (;;) {
198185102Sjhb		/* Racy check for i_dirhash to prefetch a dirhash structure. */
199178110Sjeff		if (ip->i_dirhash == NULL && ndh == NULL) {
200184205Sdes			ndh = malloc(sizeof *dh, M_DIRHASH,
201178110Sjeff			    M_NOWAIT | M_ZERO);
202178110Sjeff			if (ndh == NULL)
203178110Sjeff				return (NULL);
204183080Sjhb			refcount_init(&ndh->dh_refcount, 1);
205184651Sjhb
206184651Sjhb			/*
207184651Sjhb			 * The DUPOK is to prevent warnings from the
208184651Sjhb			 * sx_slock() a few lines down which is safe
209184651Sjhb			 * since the duplicate lock in that case is
210184651Sjhb			 * the one for this dirhash we are creating
211184651Sjhb			 * now which has no external references until
212184651Sjhb			 * after this function returns.
213184651Sjhb			 */
214184651Sjhb			sx_init_flags(&ndh->dh_lock, "dirhash", SX_DUPOK);
215183080Sjhb			sx_xlock(&ndh->dh_lock);
216178110Sjeff		}
217178110Sjeff		/*
218178110Sjeff		 * Check i_dirhash.  If it's NULL just try to use a
219178110Sjeff		 * preallocated structure.  If none exists loop and try again.
220178110Sjeff		 */
221178110Sjeff		VI_LOCK(vp);
222178110Sjeff		dh = ip->i_dirhash;
223178110Sjeff		if (dh == NULL) {
224178110Sjeff			ip->i_dirhash = ndh;
225178110Sjeff			VI_UNLOCK(vp);
226178110Sjeff			if (ndh == NULL)
227178110Sjeff				continue;
228178110Sjeff			return (ndh);
229178110Sjeff		}
230183080Sjhb		ufsdirhash_hold(dh);
231183080Sjhb		VI_UNLOCK(vp);
232183080Sjhb
233183080Sjhb		/* Acquire a shared lock on existing hashes. */
234183080Sjhb		sx_slock(&dh->dh_lock);
235183080Sjhb
236178110Sjeff		/* The hash could've been recycled while we were waiting. */
237183080Sjhb		VI_LOCK(vp);
238178110Sjeff		if (ip->i_dirhash != dh) {
239183080Sjhb			VI_UNLOCK(vp);
240178110Sjeff			ufsdirhash_release(dh);
241183080Sjhb			ufsdirhash_drop(dh);
242178110Sjeff			continue;
243178110Sjeff		}
244183080Sjhb		VI_UNLOCK(vp);
245183080Sjhb		ufsdirhash_drop(dh);
246183080Sjhb
247178110Sjeff		/* If the hash is still valid we've succeeded. */
248178110Sjeff		if (dh->dh_hash != NULL)
249178110Sjeff			break;
250178110Sjeff		/*
251178110Sjeff		 * If the hash is NULL it has been recycled.  Try to upgrade
252183080Sjhb		 * so we can recreate it.  If we fail the upgrade, drop our
253183080Sjhb		 * lock and try again.
254178110Sjeff		 */
255183080Sjhb		if (sx_try_upgrade(&dh->dh_lock))
256178110Sjeff			break;
257183080Sjhb		sx_sunlock(&dh->dh_lock);
258178110Sjeff	}
259178110Sjeff	/* Free the preallocated structure if it was not necessary. */
260178110Sjeff	if (ndh) {
261183080Sjhb		ufsdirhash_release(ndh);
262183080Sjhb		ufsdirhash_drop(ndh);
263178110Sjeff	}
264178110Sjeff	return (dh);
265178110Sjeff}
266178110Sjeff
267178110Sjeff/*
268178110Sjeff * Acquire an exclusive lock on an existing hash.  Requires an exclusive
269178110Sjeff * vnode lock to protect the i_dirhash pointer.  hashes that have been
270178110Sjeff * recycled are reclaimed here and NULL is returned.
271178110Sjeff */
272178110Sjeffstatic struct dirhash *
273178110Sjeffufsdirhash_acquire(struct inode *ip)
274178110Sjeff{
275178110Sjeff	struct dirhash *dh;
276178110Sjeff	struct vnode *vp;
277178110Sjeff
278178110Sjeff	ASSERT_VOP_ELOCKED(ip->i_vnode, __FUNCTION__);
279178110Sjeff
280178110Sjeff	vp = ip->i_vnode;
281178110Sjeff	dh = ip->i_dirhash;
282178110Sjeff	if (dh == NULL)
283178110Sjeff		return (NULL);
284183080Sjhb	sx_xlock(&dh->dh_lock);
285178110Sjeff	if (dh->dh_hash != NULL)
286178110Sjeff		return (dh);
287178110Sjeff	ufsdirhash_free_locked(ip);
288178110Sjeff	return (NULL);
289178110Sjeff}
290178110Sjeff
291178110Sjeff/*
292178110Sjeff * Acquire exclusively and free the hash pointed to by ip.  Works with a
293178110Sjeff * shared or exclusive vnode lock.
294178110Sjeff */
295178110Sjeffvoid
296178110Sjeffufsdirhash_free(struct inode *ip)
297178110Sjeff{
298178110Sjeff	struct dirhash *dh;
299178110Sjeff	struct vnode *vp;
300178110Sjeff
301178110Sjeff	vp = ip->i_vnode;
302178110Sjeff	for (;;) {
303183080Sjhb		/* Grab a reference on this inode's dirhash if it has one. */
304178110Sjeff		VI_LOCK(vp);
305178110Sjeff		dh = ip->i_dirhash;
306178110Sjeff		if (dh == NULL) {
307178110Sjeff			VI_UNLOCK(vp);
308178110Sjeff			return;
309178110Sjeff		}
310183080Sjhb		ufsdirhash_hold(dh);
311183080Sjhb		VI_UNLOCK(vp);
312183080Sjhb
313183080Sjhb		/* Exclusively lock the dirhash. */
314183080Sjhb		sx_xlock(&dh->dh_lock);
315183080Sjhb
316183080Sjhb		/* If this dirhash still belongs to this inode, then free it. */
317183080Sjhb		VI_LOCK(vp);
318183080Sjhb		if (ip->i_dirhash == dh) {
319183080Sjhb			VI_UNLOCK(vp);
320183080Sjhb			ufsdirhash_drop(dh);
321178110Sjeff			break;
322183080Sjhb		}
323183080Sjhb		VI_UNLOCK(vp);
324183080Sjhb
325183080Sjhb		/*
326183080Sjhb		 * This inode's dirhash has changed while we were
327183080Sjhb		 * waiting for the dirhash lock, so try again.
328183080Sjhb		 */
329178110Sjeff		ufsdirhash_release(dh);
330183080Sjhb		ufsdirhash_drop(dh);
331178110Sjeff	}
332178110Sjeff	ufsdirhash_free_locked(ip);
333178110Sjeff}
334178110Sjeff
335178110Sjeff/*
33679561Siedowse * Attempt to build up a hash table for the directory contents in
33779561Siedowse * inode 'ip'. Returns 0 on success, or -1 of the operation failed.
33879561Siedowse */
33979561Siedowseint
34079561Siedowseufsdirhash_build(struct inode *ip)
34179561Siedowse{
34279561Siedowse	struct dirhash *dh;
34379561Siedowse	struct buf *bp = NULL;
34479561Siedowse	struct direct *ep;
34579561Siedowse	struct vnode *vp;
34679561Siedowse	doff_t bmask, pos;
34779561Siedowse	int dirblocks, i, j, memreqd, nblocks, narrays, nslots, slot;
34879561Siedowse
349178110Sjeff	/* Take care of a decreased sysctl value. */
350195003Ssnb	while (ufs_dirhashmem > ufs_dirhashmaxmem) {
351178110Sjeff		if (ufsdirhash_recycle(0) != 0)
352178110Sjeff			return (-1);
353195003Ssnb		/* Recycled enough memory, so unlock the list. */
354195003Ssnb		DIRHASHLIST_UNLOCK();
355195003Ssnb	}
356178110Sjeff
35779561Siedowse	/* Check if we can/should use dirhash. */
358178110Sjeff	if (ip->i_size < ufs_mindirhashsize || OFSFMT(ip->i_vnode) ||
359178110Sjeff	    ip->i_effnlink == 0) {
360178110Sjeff		if (ip->i_dirhash)
36179561Siedowse			ufsdirhash_free(ip);
362178110Sjeff		return (-1);
36379561Siedowse	}
364178110Sjeff	dh = ufsdirhash_create(ip);
365178110Sjeff	if (dh == NULL)
36682364Siedowse		return (-1);
367178110Sjeff	if (dh->dh_hash != NULL)
368178110Sjeff		return (0);
36982364Siedowse
37079561Siedowse	vp = ip->i_vnode;
37179561Siedowse	/* Allocate 50% more entries than this dir size could ever need. */
37279561Siedowse	KASSERT(ip->i_size >= DIRBLKSIZ, ("ufsdirhash_build size"));
37379561Siedowse	nslots = ip->i_size / DIRECTSIZ(1);
37479561Siedowse	nslots = (nslots * 3 + 1) / 2;
37579561Siedowse	narrays = howmany(nslots, DH_NBLKOFF);
37679561Siedowse	nslots = narrays * DH_NBLKOFF;
37779561Siedowse	dirblocks = howmany(ip->i_size, DIRBLKSIZ);
37879561Siedowse	nblocks = (dirblocks * 3 + 1) / 2;
37979561Siedowse	memreqd = sizeof(*dh) + narrays * sizeof(*dh->dh_hash) +
38079561Siedowse	    narrays * DH_NBLKOFF * sizeof(**dh->dh_hash) +
38179561Siedowse	    nblocks * sizeof(*dh->dh_blkfree);
382125854Sdwmalone	DIRHASHLIST_LOCK();
38379561Siedowse	if (memreqd + ufs_dirhashmem > ufs_dirhashmaxmem) {
384125854Sdwmalone		DIRHASHLIST_UNLOCK();
38579561Siedowse		if (memreqd > ufs_dirhashmaxmem / 2)
386178110Sjeff			goto fail;
38779561Siedowse		/* Try to free some space. */
38879561Siedowse		if (ufsdirhash_recycle(memreqd) != 0)
389178110Sjeff			goto fail;
390125854Sdwmalone		/* Enough was freed, and list has been locked. */
39179561Siedowse	}
39279561Siedowse	ufs_dirhashmem += memreqd;
393125854Sdwmalone	DIRHASHLIST_UNLOCK();
39479561Siedowse
395178110Sjeff	/* Initialise the hash table and block statistics. */
396178110Sjeff	dh->dh_memreq = memreqd;
397178110Sjeff	dh->dh_narrays = narrays;
398178110Sjeff	dh->dh_hlen = nslots;
399178110Sjeff	dh->dh_nblk = nblocks;
400178110Sjeff	dh->dh_dirblks = dirblocks;
401178110Sjeff	for (i = 0; i < DH_NFSTATS; i++)
402178110Sjeff		dh->dh_firstfree[i] = -1;
403178110Sjeff	dh->dh_firstfree[DH_NFSTATS] = 0;
404178110Sjeff	dh->dh_hused = 0;
405178110Sjeff	dh->dh_seqopt = 0;
406178110Sjeff	dh->dh_seqoff = 0;
407178110Sjeff	dh->dh_score = DH_SCOREINIT;
408193375Ssnb	dh->dh_lastused = time_second;
409178110Sjeff
41079561Siedowse	/*
41179561Siedowse	 * Use non-blocking mallocs so that we will revert to a linear
41279561Siedowse	 * lookup on failure rather than potentially blocking forever.
41379561Siedowse	 */
414184205Sdes	dh->dh_hash = malloc(narrays * sizeof(dh->dh_hash[0]),
41579561Siedowse	    M_DIRHASH, M_NOWAIT | M_ZERO);
416178110Sjeff	if (dh->dh_hash == NULL)
417178110Sjeff		goto fail;
418184205Sdes	dh->dh_blkfree = malloc(nblocks * sizeof(dh->dh_blkfree[0]),
41979561Siedowse	    M_DIRHASH, M_NOWAIT);
420178110Sjeff	if (dh->dh_blkfree == NULL)
42179561Siedowse		goto fail;
42279561Siedowse	for (i = 0; i < narrays; i++) {
423125854Sdwmalone		if ((dh->dh_hash[i] = DIRHASH_BLKALLOC_WAITOK()) == NULL)
42479561Siedowse			goto fail;
42579561Siedowse		for (j = 0; j < DH_NBLKOFF; j++)
42679561Siedowse			dh->dh_hash[i][j] = DIRHASH_EMPTY;
42779561Siedowse	}
42879561Siedowse	for (i = 0; i < dirblocks; i++)
42979561Siedowse		dh->dh_blkfree[i] = DIRBLKSIZ / DIRALIGN;
43079561Siedowse	bmask = VFSTOUFS(vp->v_mount)->um_mountp->mnt_stat.f_iosize - 1;
43179561Siedowse	pos = 0;
43279561Siedowse	while (pos < ip->i_size) {
43379561Siedowse		/* If necessary, get the next directory block. */
43479561Siedowse		if ((pos & bmask) == 0) {
43579561Siedowse			if (bp != NULL)
43679561Siedowse				brelse(bp);
43779561Siedowse			if (UFS_BLKATOFF(vp, (off_t)pos, NULL, &bp) != 0)
43879561Siedowse				goto fail;
43979561Siedowse		}
44079561Siedowse
44179561Siedowse		/* Add this entry to the hash. */
44279561Siedowse		ep = (struct direct *)((char *)bp->b_data + (pos & bmask));
44379561Siedowse		if (ep->d_reclen == 0 || ep->d_reclen >
44479561Siedowse		    DIRBLKSIZ - (pos & (DIRBLKSIZ - 1))) {
44579561Siedowse			/* Corrupted directory. */
44679561Siedowse			brelse(bp);
44779561Siedowse			goto fail;
44879561Siedowse		}
44979561Siedowse		if (ep->d_ino != 0) {
45079561Siedowse			/* Add the entry (simplified ufsdirhash_add). */
45179561Siedowse			slot = ufsdirhash_hash(dh, ep->d_name, ep->d_namlen);
45279561Siedowse			while (DH_ENTRY(dh, slot) != DIRHASH_EMPTY)
45379561Siedowse				slot = WRAPINCR(slot, dh->dh_hlen);
45479561Siedowse			dh->dh_hused++;
45579561Siedowse			DH_ENTRY(dh, slot) = pos;
45679561Siedowse			ufsdirhash_adjfree(dh, pos, -DIRSIZ(0, ep));
45779561Siedowse		}
45879561Siedowse		pos += ep->d_reclen;
45979561Siedowse	}
46079561Siedowse
46179561Siedowse	if (bp != NULL)
46279561Siedowse		brelse(bp);
463125854Sdwmalone	DIRHASHLIST_LOCK();
46479561Siedowse	TAILQ_INSERT_TAIL(&ufsdirhash_list, dh, dh_list);
46579561Siedowse	dh->dh_onlist = 1;
466125854Sdwmalone	DIRHASHLIST_UNLOCK();
467183080Sjhb	sx_downgrade(&dh->dh_lock);
46879561Siedowse	return (0);
46979561Siedowse
47079561Siedowsefail:
471178110Sjeff	ufsdirhash_free_locked(ip);
47279561Siedowse	return (-1);
47379561Siedowse}
47479561Siedowse
47579561Siedowse/*
47679561Siedowse * Free any hash table associated with inode 'ip'.
47779561Siedowse */
478178110Sjeffstatic void
479178110Sjeffufsdirhash_free_locked(struct inode *ip)
48079561Siedowse{
48179561Siedowse	struct dirhash *dh;
482178110Sjeff	struct vnode *vp;
483178110Sjeff	int i;
48479561Siedowse
485178110Sjeff	DIRHASH_ASSERT_LOCKED(ip->i_dirhash);
486183080Sjhb
487178110Sjeff	/*
488178110Sjeff	 * Clear the pointer in the inode to prevent new threads from
489178110Sjeff	 * finding the dead structure.
490178110Sjeff	 */
491178110Sjeff	vp = ip->i_vnode;
492178110Sjeff	VI_LOCK(vp);
493178110Sjeff	dh = ip->i_dirhash;
494178110Sjeff	ip->i_dirhash = NULL;
495178110Sjeff	VI_UNLOCK(vp);
496183080Sjhb
497178110Sjeff	/*
498183280Sjhb	 * Remove the hash from the list since we are going to free its
499183280Sjhb	 * memory.
500183280Sjhb	 */
501183280Sjhb	DIRHASHLIST_LOCK();
502183280Sjhb	if (dh->dh_onlist)
503183280Sjhb		TAILQ_REMOVE(&ufsdirhash_list, dh, dh_list);
504183280Sjhb	ufs_dirhashmem -= dh->dh_memreq;
505183280Sjhb	DIRHASHLIST_UNLOCK();
506183280Sjhb
507183280Sjhb	/*
508183080Sjhb	 * At this point, any waiters for the lock should hold their
509183080Sjhb	 * own reference on the dirhash structure.  They will drop
510183080Sjhb	 * that reference once they grab the vnode interlock and see
511183080Sjhb	 * that ip->i_dirhash is NULL.
512178110Sjeff	 */
513183080Sjhb	sx_xunlock(&dh->dh_lock);
514183080Sjhb
515178110Sjeff	/*
516178110Sjeff	 * Handle partially recycled as well as fully constructed hashes.
517178110Sjeff	 */
518178110Sjeff	if (dh->dh_hash != NULL) {
519178110Sjeff		for (i = 0; i < dh->dh_narrays; i++)
520178110Sjeff			if (dh->dh_hash[i] != NULL)
521178110Sjeff				DIRHASH_BLKFREE(dh->dh_hash[i]);
522184205Sdes		free(dh->dh_hash, M_DIRHASH);
523178110Sjeff		if (dh->dh_blkfree != NULL)
524184205Sdes			free(dh->dh_blkfree, M_DIRHASH);
525178110Sjeff	}
526183080Sjhb
527178110Sjeff	/*
528183080Sjhb	 * Drop the inode's reference to the data structure.
529178110Sjeff	 */
530183080Sjhb	ufsdirhash_drop(dh);
53179561Siedowse}
53279561Siedowse
53379561Siedowse/*
53479561Siedowse * Find the offset of the specified name within the given inode.
53579561Siedowse * Returns 0 on success, ENOENT if the entry does not exist, or
53679561Siedowse * EJUSTRETURN if the caller should revert to a linear search.
53779561Siedowse *
53879690Siedowse * If successful, the directory offset is stored in *offp, and a
53979690Siedowse * pointer to a struct buf containing the entry is stored in *bpp. If
54079561Siedowse * prevoffp is non-NULL, the offset of the previous entry within
54179561Siedowse * the DIRBLKSIZ-sized block is stored in *prevoffp (if the entry
54279561Siedowse * is the first in a block, the start of the block is used).
543178110Sjeff *
544178110Sjeff * Must be called with the hash locked.  Returns with the hash unlocked.
54579561Siedowse */
54679561Siedowseint
54779561Siedowseufsdirhash_lookup(struct inode *ip, char *name, int namelen, doff_t *offp,
54879690Siedowse    struct buf **bpp, doff_t *prevoffp)
54979561Siedowse{
55079561Siedowse	struct dirhash *dh, *dh_next;
55179561Siedowse	struct direct *dp;
55279561Siedowse	struct vnode *vp;
55379561Siedowse	struct buf *bp;
55479561Siedowse	doff_t blkoff, bmask, offset, prevoff;
55579561Siedowse	int i, slot;
556178110Sjeff	int error;
55779561Siedowse
558178110Sjeff	dh = ip->i_dirhash;
559178110Sjeff	KASSERT(dh != NULL && dh->dh_hash != NULL,
560178110Sjeff	    ("ufsdirhash_lookup: Invalid dirhash %p\n", dh));
561178110Sjeff	DIRHASH_ASSERT_LOCKED(dh);
56279561Siedowse	/*
56379561Siedowse	 * Move this dirhash towards the end of the list if it has a
564178110Sjeff	 * score higher than the next entry, and acquire the dh_lock.
56579561Siedowse	 */
566178110Sjeff	DIRHASHLIST_LOCK();
56779561Siedowse	if (TAILQ_NEXT(dh, dh_list) != NULL) {
56879561Siedowse		/*
56979561Siedowse		 * If the new score will be greater than that of the next
57079561Siedowse		 * entry, then move this entry past it. With both mutexes
57179561Siedowse		 * held, dh_next won't go away, but its dh_score could
57279561Siedowse		 * change; that's not important since it is just a hint.
57379561Siedowse		 */
574178110Sjeff		if ((dh_next = TAILQ_NEXT(dh, dh_list)) != NULL &&
57579561Siedowse		    dh->dh_score >= dh_next->dh_score) {
57679561Siedowse			KASSERT(dh->dh_onlist, ("dirhash: not on list"));
57779561Siedowse			TAILQ_REMOVE(&ufsdirhash_list, dh, dh_list);
57879561Siedowse			TAILQ_INSERT_AFTER(&ufsdirhash_list, dh_next, dh,
57979561Siedowse			    dh_list);
58079561Siedowse		}
58179561Siedowse	}
58279561Siedowse	/* Update the score. */
58379561Siedowse	if (dh->dh_score < DH_SCOREMAX)
58479561Siedowse		dh->dh_score++;
585193375Ssnb
586193375Ssnb	/* Update last used time. */
587193375Ssnb	dh->dh_lastused = time_second;
588178110Sjeff	DIRHASHLIST_UNLOCK();
58979561Siedowse
59079561Siedowse	vp = ip->i_vnode;
59179561Siedowse	bmask = VFSTOUFS(vp->v_mount)->um_mountp->mnt_stat.f_iosize - 1;
59279561Siedowse	blkoff = -1;
59379561Siedowse	bp = NULL;
59479561Siedowserestart:
59579561Siedowse	slot = ufsdirhash_hash(dh, name, namelen);
59679561Siedowse
59779561Siedowse	if (dh->dh_seqopt) {
59879561Siedowse		/*
59979561Siedowse		 * Sequential access optimisation. dh_seqoff contains the
60079561Siedowse		 * offset of the directory entry immediately following
60179561Siedowse		 * the last entry that was looked up. Check if this offset
60279561Siedowse		 * appears in the hash chain for the name we are looking for.
60379561Siedowse		 */
60479561Siedowse		for (i = slot; (offset = DH_ENTRY(dh, i)) != DIRHASH_EMPTY;
60579561Siedowse		    i = WRAPINCR(i, dh->dh_hlen))
60686350Siedowse			if (offset == dh->dh_seqoff)
60779561Siedowse				break;
60879561Siedowse		if (offset == dh->dh_seqoff) {
60979561Siedowse			/*
61079561Siedowse			 * We found an entry with the expected offset. This
61179561Siedowse			 * is probably the entry we want, but if not, the
612149178Siedowse			 * code below will turn off seqopt and retry.
61379561Siedowse			 */
61479561Siedowse			slot = i;
61579561Siedowse		} else
61679561Siedowse			dh->dh_seqopt = 0;
61779561Siedowse	}
61879561Siedowse
61979561Siedowse	for (; (offset = DH_ENTRY(dh, slot)) != DIRHASH_EMPTY;
62079561Siedowse	    slot = WRAPINCR(slot, dh->dh_hlen)) {
62179561Siedowse		if (offset == DIRHASH_DEL)
62279561Siedowse			continue;
62379561Siedowse		if (offset < 0 || offset >= ip->i_size)
62479561Siedowse			panic("ufsdirhash_lookup: bad offset in hash array");
62579561Siedowse		if ((offset & ~bmask) != blkoff) {
62679561Siedowse			if (bp != NULL)
62779561Siedowse				brelse(bp);
62879561Siedowse			blkoff = offset & ~bmask;
629178110Sjeff			if (UFS_BLKATOFF(vp, (off_t)blkoff, NULL, &bp) != 0) {
630178110Sjeff				error = EJUSTRETURN;
631178110Sjeff				goto fail;
632178110Sjeff			}
63379561Siedowse		}
634201717Smckusick		KASSERT(bp != NULL, ("no buffer allocated"));
63579561Siedowse		dp = (struct direct *)(bp->b_data + (offset & bmask));
63679561Siedowse		if (dp->d_reclen == 0 || dp->d_reclen >
63779561Siedowse		    DIRBLKSIZ - (offset & (DIRBLKSIZ - 1))) {
63879561Siedowse			/* Corrupted directory. */
639178110Sjeff			error = EJUSTRETURN;
640178110Sjeff			goto fail;
64179561Siedowse		}
64279561Siedowse		if (dp->d_namlen == namelen &&
64379561Siedowse		    bcmp(dp->d_name, name, namelen) == 0) {
64479561Siedowse			/* Found. Get the prev offset if needed. */
64579561Siedowse			if (prevoffp != NULL) {
64679561Siedowse				if (offset & (DIRBLKSIZ - 1)) {
64779561Siedowse					prevoff = ufsdirhash_getprev(dp,
64879561Siedowse					    offset);
64979561Siedowse					if (prevoff == -1) {
650178110Sjeff						error = EJUSTRETURN;
651178110Sjeff						goto fail;
65279561Siedowse					}
65379561Siedowse				} else
65479561Siedowse					prevoff = offset;
65579561Siedowse				*prevoffp = prevoff;
65679561Siedowse			}
65779561Siedowse
65879561Siedowse			/* Check for sequential access, and update offset. */
65979561Siedowse			if (dh->dh_seqopt == 0 && dh->dh_seqoff == offset)
66079561Siedowse				dh->dh_seqopt = 1;
66179561Siedowse			dh->dh_seqoff = offset + DIRSIZ(0, dp);
66279690Siedowse			*bpp = bp;
66379561Siedowse			*offp = offset;
664178110Sjeff			ufsdirhash_release(dh);
66579561Siedowse			return (0);
66679561Siedowse		}
66779561Siedowse
66879561Siedowse		/*
66979561Siedowse		 * When the name doesn't match in the seqopt case, go back
67079561Siedowse		 * and search normally.
67179561Siedowse		 */
67279561Siedowse		if (dh->dh_seqopt) {
67379561Siedowse			dh->dh_seqopt = 0;
67479561Siedowse			goto restart;
67579561Siedowse		}
67679561Siedowse	}
677178110Sjeff	error = ENOENT;
678178110Sjefffail:
679178110Sjeff	ufsdirhash_release(dh);
68079561Siedowse	if (bp != NULL)
68179561Siedowse		brelse(bp);
682178110Sjeff	return (error);
68379561Siedowse}
68479561Siedowse
68579561Siedowse/*
68679561Siedowse * Find a directory block with room for 'slotneeded' bytes. Returns
68779561Siedowse * the offset of the directory entry that begins the free space.
68879561Siedowse * This will either be the offset of an existing entry that has free
68979561Siedowse * space at the end, or the offset of an entry with d_ino == 0 at
69079561Siedowse * the start of a DIRBLKSIZ block.
69179561Siedowse *
69279561Siedowse * To use the space, the caller may need to compact existing entries in
69379561Siedowse * the directory. The total number of bytes in all of the entries involved
69479561Siedowse * in the compaction is stored in *slotsize. In other words, all of
69579561Siedowse * the entries that must be compacted are exactly contained in the
69679561Siedowse * region beginning at the returned offset and spanning *slotsize bytes.
69779561Siedowse *
69879561Siedowse * Returns -1 if no space was found, indicating that the directory
69979561Siedowse * must be extended.
70079561Siedowse */
70179561Siedowsedoff_t
70279561Siedowseufsdirhash_findfree(struct inode *ip, int slotneeded, int *slotsize)
70379561Siedowse{
70479561Siedowse	struct direct *dp;
70579561Siedowse	struct dirhash *dh;
70679561Siedowse	struct buf *bp;
70779561Siedowse	doff_t pos, slotstart;
70879561Siedowse	int dirblock, error, freebytes, i;
70979561Siedowse
710178110Sjeff	dh = ip->i_dirhash;
711178110Sjeff	KASSERT(dh != NULL && dh->dh_hash != NULL,
712178110Sjeff	    ("ufsdirhash_findfree: Invalid dirhash %p\n", dh));
713178110Sjeff	DIRHASH_ASSERT_LOCKED(dh);
71479561Siedowse
71579561Siedowse	/* Find a directory block with the desired free space. */
71679561Siedowse	dirblock = -1;
71779561Siedowse	for (i = howmany(slotneeded, DIRALIGN); i <= DH_NFSTATS; i++)
71879561Siedowse		if ((dirblock = dh->dh_firstfree[i]) != -1)
71979561Siedowse			break;
720178110Sjeff	if (dirblock == -1)
72179561Siedowse		return (-1);
72279561Siedowse
72379561Siedowse	KASSERT(dirblock < dh->dh_nblk &&
72479561Siedowse	    dh->dh_blkfree[dirblock] >= howmany(slotneeded, DIRALIGN),
72579561Siedowse	    ("ufsdirhash_findfree: bad stats"));
72679561Siedowse	pos = dirblock * DIRBLKSIZ;
72779561Siedowse	error = UFS_BLKATOFF(ip->i_vnode, (off_t)pos, (char **)&dp, &bp);
72879561Siedowse	if (error)
72979561Siedowse		return (-1);
73079561Siedowse
73179561Siedowse	/* Find the first entry with free space. */
73279561Siedowse	for (i = 0; i < DIRBLKSIZ; ) {
73379561Siedowse		if (dp->d_reclen == 0) {
73479561Siedowse			brelse(bp);
73579561Siedowse			return (-1);
73679561Siedowse		}
73779561Siedowse		if (dp->d_ino == 0 || dp->d_reclen > DIRSIZ(0, dp))
73879561Siedowse			break;
73979561Siedowse		i += dp->d_reclen;
74079561Siedowse		dp = (struct direct *)((char *)dp + dp->d_reclen);
74179561Siedowse	}
74279561Siedowse	if (i > DIRBLKSIZ) {
74379561Siedowse		brelse(bp);
74479561Siedowse		return (-1);
74579561Siedowse	}
74679561Siedowse	slotstart = pos + i;
74779561Siedowse
74879561Siedowse	/* Find the range of entries needed to get enough space */
74979561Siedowse	freebytes = 0;
75079561Siedowse	while (i < DIRBLKSIZ && freebytes < slotneeded) {
75179561Siedowse		freebytes += dp->d_reclen;
75279561Siedowse		if (dp->d_ino != 0)
75379561Siedowse			freebytes -= DIRSIZ(0, dp);
75479561Siedowse		if (dp->d_reclen == 0) {
75579561Siedowse			brelse(bp);
75679561Siedowse			return (-1);
75779561Siedowse		}
75879561Siedowse		i += dp->d_reclen;
75979561Siedowse		dp = (struct direct *)((char *)dp + dp->d_reclen);
76079561Siedowse	}
76179561Siedowse	if (i > DIRBLKSIZ) {
76279561Siedowse		brelse(bp);
76379561Siedowse		return (-1);
76479561Siedowse	}
76579561Siedowse	if (freebytes < slotneeded)
76679561Siedowse		panic("ufsdirhash_findfree: free mismatch");
76779561Siedowse	brelse(bp);
76879561Siedowse	*slotsize = pos + i - slotstart;
76979561Siedowse	return (slotstart);
77079561Siedowse}
77179561Siedowse
77279561Siedowse/*
77379561Siedowse * Return the start of the unused space at the end of a directory, or
77479561Siedowse * -1 if there are no trailing unused blocks.
77579561Siedowse */
77679561Siedowsedoff_t
77779561Siedowseufsdirhash_enduseful(struct inode *ip)
77879561Siedowse{
77979561Siedowse
78079561Siedowse	struct dirhash *dh;
78179561Siedowse	int i;
78279561Siedowse
783178110Sjeff	dh = ip->i_dirhash;
784178110Sjeff	DIRHASH_ASSERT_LOCKED(dh);
785178110Sjeff	KASSERT(dh != NULL && dh->dh_hash != NULL,
786178110Sjeff	    ("ufsdirhash_enduseful: Invalid dirhash %p\n", dh));
78779561Siedowse
788178110Sjeff	if (dh->dh_blkfree[dh->dh_dirblks - 1] != DIRBLKSIZ / DIRALIGN)
78979561Siedowse		return (-1);
79079561Siedowse
79179561Siedowse	for (i = dh->dh_dirblks - 1; i >= 0; i--)
79279561Siedowse		if (dh->dh_blkfree[i] != DIRBLKSIZ / DIRALIGN)
79379561Siedowse			break;
794178110Sjeff
79579561Siedowse	return ((doff_t)(i + 1) * DIRBLKSIZ);
79679561Siedowse}
79779561Siedowse
79879561Siedowse/*
79979561Siedowse * Insert information into the hash about a new directory entry. dirp
80079561Siedowse * points to a struct direct containing the entry, and offset specifies
80179561Siedowse * the offset of this entry.
80279561Siedowse */
80379561Siedowsevoid
80479561Siedowseufsdirhash_add(struct inode *ip, struct direct *dirp, doff_t offset)
80579561Siedowse{
80679561Siedowse	struct dirhash *dh;
80779561Siedowse	int slot;
80879561Siedowse
809178110Sjeff	if ((dh = ufsdirhash_acquire(ip)) == NULL)
81079561Siedowse		return;
811178110Sjeff
81279561Siedowse	KASSERT(offset < dh->dh_dirblks * DIRBLKSIZ,
81379561Siedowse	    ("ufsdirhash_add: bad offset"));
81479561Siedowse	/*
81579561Siedowse	 * Normal hash usage is < 66%. If the usage gets too high then
81679561Siedowse	 * remove the hash entirely and let it be rebuilt later.
81779561Siedowse	 */
81879561Siedowse	if (dh->dh_hused >= (dh->dh_hlen * 3) / 4) {
819178110Sjeff		ufsdirhash_free_locked(ip);
82079561Siedowse		return;
82179561Siedowse	}
82279561Siedowse
82379561Siedowse	/* Find a free hash slot (empty or deleted), and add the entry. */
82479561Siedowse	slot = ufsdirhash_hash(dh, dirp->d_name, dirp->d_namlen);
82579561Siedowse	while (DH_ENTRY(dh, slot) >= 0)
82679561Siedowse		slot = WRAPINCR(slot, dh->dh_hlen);
82779561Siedowse	if (DH_ENTRY(dh, slot) == DIRHASH_EMPTY)
82879561Siedowse		dh->dh_hused++;
82979561Siedowse	DH_ENTRY(dh, slot) = offset;
83079561Siedowse
831193375Ssnb	/* Update last used time. */
832193375Ssnb	dh->dh_lastused = time_second;
833193375Ssnb
83479561Siedowse	/* Update the per-block summary info. */
83579561Siedowse	ufsdirhash_adjfree(dh, offset, -DIRSIZ(0, dirp));
836178110Sjeff	ufsdirhash_release(dh);
83779561Siedowse}
83879561Siedowse
83979561Siedowse/*
84079561Siedowse * Remove the specified directory entry from the hash. The entry to remove
84179561Siedowse * is defined by the name in `dirp', which must exist at the specified
84279561Siedowse * `offset' within the directory.
84379561Siedowse */
84479561Siedowsevoid
84579561Siedowseufsdirhash_remove(struct inode *ip, struct direct *dirp, doff_t offset)
84679561Siedowse{
84779561Siedowse	struct dirhash *dh;
84879561Siedowse	int slot;
84979561Siedowse
850178110Sjeff	if ((dh = ufsdirhash_acquire(ip)) == NULL)
85179561Siedowse		return;
85279561Siedowse
85379561Siedowse	KASSERT(offset < dh->dh_dirblks * DIRBLKSIZ,
85479561Siedowse	    ("ufsdirhash_remove: bad offset"));
85579561Siedowse	/* Find the entry */
85679561Siedowse	slot = ufsdirhash_findslot(dh, dirp->d_name, dirp->d_namlen, offset);
85779561Siedowse
85879561Siedowse	/* Remove the hash entry. */
85979561Siedowse	ufsdirhash_delslot(dh, slot);
86079561Siedowse
86179561Siedowse	/* Update the per-block summary info. */
86279561Siedowse	ufsdirhash_adjfree(dh, offset, DIRSIZ(0, dirp));
863178110Sjeff	ufsdirhash_release(dh);
86479561Siedowse}
86579561Siedowse
86679561Siedowse/*
86779561Siedowse * Change the offset associated with a directory entry in the hash. Used
86879561Siedowse * when compacting directory blocks.
86979561Siedowse */
87079561Siedowsevoid
87179561Siedowseufsdirhash_move(struct inode *ip, struct direct *dirp, doff_t oldoff,
87279561Siedowse    doff_t newoff)
87379561Siedowse{
87479561Siedowse	struct dirhash *dh;
87579561Siedowse	int slot;
87679561Siedowse
877178110Sjeff	if ((dh = ufsdirhash_acquire(ip)) == NULL)
87879561Siedowse		return;
87979561Siedowse
88079561Siedowse	KASSERT(oldoff < dh->dh_dirblks * DIRBLKSIZ &&
88179561Siedowse	    newoff < dh->dh_dirblks * DIRBLKSIZ,
88279561Siedowse	    ("ufsdirhash_move: bad offset"));
88379561Siedowse	/* Find the entry, and update the offset. */
88479561Siedowse	slot = ufsdirhash_findslot(dh, dirp->d_name, dirp->d_namlen, oldoff);
88579561Siedowse	DH_ENTRY(dh, slot) = newoff;
886178110Sjeff	ufsdirhash_release(dh);
88779561Siedowse}
88879561Siedowse
88979561Siedowse/*
89079561Siedowse * Inform dirhash that the directory has grown by one block that
89179561Siedowse * begins at offset (i.e. the new length is offset + DIRBLKSIZ).
89279561Siedowse */
89379561Siedowsevoid
89479561Siedowseufsdirhash_newblk(struct inode *ip, doff_t offset)
89579561Siedowse{
89679561Siedowse	struct dirhash *dh;
89779561Siedowse	int block;
89879561Siedowse
899178110Sjeff	if ((dh = ufsdirhash_acquire(ip)) == NULL)
90079561Siedowse		return;
90179561Siedowse
90279561Siedowse	KASSERT(offset == dh->dh_dirblks * DIRBLKSIZ,
90379561Siedowse	    ("ufsdirhash_newblk: bad offset"));
90479561Siedowse	block = offset / DIRBLKSIZ;
90579561Siedowse	if (block >= dh->dh_nblk) {
90679561Siedowse		/* Out of space; must rebuild. */
907178110Sjeff		ufsdirhash_free_locked(ip);
90879561Siedowse		return;
90979561Siedowse	}
91079561Siedowse	dh->dh_dirblks = block + 1;
91179561Siedowse
91279561Siedowse	/* Account for the new free block. */
91379561Siedowse	dh->dh_blkfree[block] = DIRBLKSIZ / DIRALIGN;
91479561Siedowse	if (dh->dh_firstfree[DH_NFSTATS] == -1)
91579561Siedowse		dh->dh_firstfree[DH_NFSTATS] = block;
916178110Sjeff	ufsdirhash_release(dh);
91779561Siedowse}
91879561Siedowse
91979561Siedowse/*
92079561Siedowse * Inform dirhash that the directory is being truncated.
92179561Siedowse */
92279561Siedowsevoid
92379561Siedowseufsdirhash_dirtrunc(struct inode *ip, doff_t offset)
92479561Siedowse{
92579561Siedowse	struct dirhash *dh;
92679561Siedowse	int block, i;
92779561Siedowse
928178110Sjeff	if ((dh = ufsdirhash_acquire(ip)) == NULL)
92979561Siedowse		return;
93079561Siedowse
93179561Siedowse	KASSERT(offset <= dh->dh_dirblks * DIRBLKSIZ,
93279561Siedowse	    ("ufsdirhash_dirtrunc: bad offset"));
93379561Siedowse	block = howmany(offset, DIRBLKSIZ);
93479561Siedowse	/*
93579561Siedowse	 * If the directory shrinks to less than 1/8 of dh_nblk blocks
93679561Siedowse	 * (about 20% of its original size due to the 50% extra added in
93779561Siedowse	 * ufsdirhash_build) then free it, and let the caller rebuild
93879561Siedowse	 * if necessary.
93979561Siedowse	 */
94079561Siedowse	if (block < dh->dh_nblk / 8 && dh->dh_narrays > 1) {
941178110Sjeff		ufsdirhash_free_locked(ip);
94279561Siedowse		return;
94379561Siedowse	}
94479561Siedowse
94579561Siedowse	/*
94679561Siedowse	 * Remove any `first free' information pertaining to the
94779561Siedowse	 * truncated blocks. All blocks we're removing should be
94879561Siedowse	 * completely unused.
94979561Siedowse	 */
95079561Siedowse	if (dh->dh_firstfree[DH_NFSTATS] >= block)
95179561Siedowse		dh->dh_firstfree[DH_NFSTATS] = -1;
95279561Siedowse	for (i = block; i < dh->dh_dirblks; i++)
95379561Siedowse		if (dh->dh_blkfree[i] != DIRBLKSIZ / DIRALIGN)
95479561Siedowse			panic("ufsdirhash_dirtrunc: blocks in use");
95579561Siedowse	for (i = 0; i < DH_NFSTATS; i++)
95679561Siedowse		if (dh->dh_firstfree[i] >= block)
95779561Siedowse			panic("ufsdirhash_dirtrunc: first free corrupt");
95879561Siedowse	dh->dh_dirblks = block;
959178110Sjeff	ufsdirhash_release(dh);
96079561Siedowse}
96179561Siedowse
96279561Siedowse/*
96379561Siedowse * Debugging function to check that the dirhash information about
96479561Siedowse * a directory block matches its actual contents. Panics if a mismatch
96579561Siedowse * is detected.
96679561Siedowse *
96779561Siedowse * On entry, `buf' should point to the start of an in-core
96879561Siedowse * DIRBLKSIZ-sized directory block, and `offset' should contain the
96979561Siedowse * offset from the start of the directory of that block.
97079561Siedowse */
97179561Siedowsevoid
97279561Siedowseufsdirhash_checkblock(struct inode *ip, char *buf, doff_t offset)
97379561Siedowse{
97479561Siedowse	struct dirhash *dh;
97579561Siedowse	struct direct *dp;
97679561Siedowse	int block, ffslot, i, nfree;
97779561Siedowse
97879561Siedowse	if (!ufs_dirhashcheck)
97979561Siedowse		return;
980178110Sjeff	if ((dh = ufsdirhash_acquire(ip)) == NULL)
98179561Siedowse		return;
98279561Siedowse
98379561Siedowse	block = offset / DIRBLKSIZ;
98479561Siedowse	if ((offset & (DIRBLKSIZ - 1)) != 0 || block >= dh->dh_dirblks)
98579561Siedowse		panic("ufsdirhash_checkblock: bad offset");
98679561Siedowse
98779561Siedowse	nfree = 0;
98879561Siedowse	for (i = 0; i < DIRBLKSIZ; i += dp->d_reclen) {
98979561Siedowse		dp = (struct direct *)(buf + i);
99079561Siedowse		if (dp->d_reclen == 0 || i + dp->d_reclen > DIRBLKSIZ)
99179561Siedowse			panic("ufsdirhash_checkblock: bad dir");
99279561Siedowse
99379561Siedowse		if (dp->d_ino == 0) {
99480456Siedowse#if 0
99580456Siedowse			/*
99680456Siedowse			 * XXX entries with d_ino == 0 should only occur
99780456Siedowse			 * at the start of a DIRBLKSIZ block. However the
99880456Siedowse			 * ufs code is tolerant of such entries at other
99980456Siedowse			 * offsets, and fsck does not fix them.
100080456Siedowse			 */
100179561Siedowse			if (i != 0)
100279561Siedowse				panic("ufsdirhash_checkblock: bad dir inode");
100380456Siedowse#endif
100479561Siedowse			nfree += dp->d_reclen;
100579561Siedowse			continue;
100679561Siedowse		}
100779561Siedowse
100879561Siedowse		/* Check that the entry	exists (will panic if it doesn't). */
100979561Siedowse		ufsdirhash_findslot(dh, dp->d_name, dp->d_namlen, offset + i);
101079561Siedowse
101179561Siedowse		nfree += dp->d_reclen - DIRSIZ(0, dp);
101279561Siedowse	}
101379561Siedowse	if (i != DIRBLKSIZ)
101479561Siedowse		panic("ufsdirhash_checkblock: bad dir end");
101579561Siedowse
101679561Siedowse	if (dh->dh_blkfree[block] * DIRALIGN != nfree)
101779561Siedowse		panic("ufsdirhash_checkblock: bad free count");
101879561Siedowse
101992098Siedowse	ffslot = BLKFREE2IDX(nfree / DIRALIGN);
102079561Siedowse	for (i = 0; i <= DH_NFSTATS; i++)
102179561Siedowse		if (dh->dh_firstfree[i] == block && i != ffslot)
102279561Siedowse			panic("ufsdirhash_checkblock: bad first-free");
102392098Siedowse	if (dh->dh_firstfree[ffslot] == -1)
102492098Siedowse		panic("ufsdirhash_checkblock: missing first-free entry");
1025178110Sjeff	ufsdirhash_release(dh);
102679561Siedowse}
102779561Siedowse
102879561Siedowse/*
102979561Siedowse * Hash the specified filename into a dirhash slot.
103079561Siedowse */
103179561Siedowsestatic int
103279561Siedowseufsdirhash_hash(struct dirhash *dh, char *name, int namelen)
103379561Siedowse{
103492807Sdwmalone	u_int32_t hash;
103592807Sdwmalone
103692807Sdwmalone	/*
1037107868Siedowse	 * We hash the name and then some other bit of data that is
1038107868Siedowse	 * invariant over the dirhash's lifetime. Otherwise names
103992807Sdwmalone	 * differing only in the last byte are placed close to one
104092807Sdwmalone	 * another in the table, which is bad for linear probing.
104192807Sdwmalone	 */
104292807Sdwmalone	hash = fnv_32_buf(name, namelen, FNV1_32_INIT);
1043133837Sdwmalone	hash = fnv_32_buf(&dh, sizeof(dh), hash);
104492807Sdwmalone	return (hash % dh->dh_hlen);
104579561Siedowse}
104679561Siedowse
104779561Siedowse/*
104879561Siedowse * Adjust the number of free bytes in the block containing `offset'
104979561Siedowse * by the value specified by `diff'.
105079561Siedowse *
105179561Siedowse * The caller must ensure we have exclusive access to `dh'; normally
1052178110Sjeff * that means that dh_lock should be held, but this is also called
105379561Siedowse * from ufsdirhash_build() where exclusive access can be assumed.
105479561Siedowse */
105579561Siedowsestatic void
105679561Siedowseufsdirhash_adjfree(struct dirhash *dh, doff_t offset, int diff)
105779561Siedowse{
105879561Siedowse	int block, i, nfidx, ofidx;
105979561Siedowse
106079561Siedowse	/* Update the per-block summary info. */
106179561Siedowse	block = offset / DIRBLKSIZ;
106279561Siedowse	KASSERT(block < dh->dh_nblk && block < dh->dh_dirblks,
106379561Siedowse	     ("dirhash bad offset"));
106492098Siedowse	ofidx = BLKFREE2IDX(dh->dh_blkfree[block]);
106579561Siedowse	dh->dh_blkfree[block] = (int)dh->dh_blkfree[block] + (diff / DIRALIGN);
106692098Siedowse	nfidx = BLKFREE2IDX(dh->dh_blkfree[block]);
106779561Siedowse
106879561Siedowse	/* Update the `first free' list if necessary. */
106979561Siedowse	if (ofidx != nfidx) {
107079561Siedowse		/* If removing, scan forward for the next block. */
107179561Siedowse		if (dh->dh_firstfree[ofidx] == block) {
107279561Siedowse			for (i = block + 1; i < dh->dh_dirblks; i++)
107392098Siedowse				if (BLKFREE2IDX(dh->dh_blkfree[i]) == ofidx)
107479561Siedowse					break;
107579561Siedowse			dh->dh_firstfree[ofidx] = (i < dh->dh_dirblks) ? i : -1;
107679561Siedowse		}
107779561Siedowse
107879561Siedowse		/* Make this the new `first free' if necessary */
107979561Siedowse		if (dh->dh_firstfree[nfidx] > block ||
108079561Siedowse		    dh->dh_firstfree[nfidx] == -1)
108179561Siedowse			dh->dh_firstfree[nfidx] = block;
108279561Siedowse	}
108379561Siedowse}
108479561Siedowse
108579561Siedowse/*
108679561Siedowse * Find the specified name which should have the specified offset.
108779561Siedowse * Returns a slot number, and panics on failure.
108879561Siedowse *
108979561Siedowse * `dh' must be locked on entry and remains so on return.
109079561Siedowse */
109179561Siedowsestatic int
109279561Siedowseufsdirhash_findslot(struct dirhash *dh, char *name, int namelen, doff_t offset)
109379561Siedowse{
109479561Siedowse	int slot;
109579561Siedowse
1096178110Sjeff	DIRHASH_ASSERT_LOCKED(dh);
109779561Siedowse
109879561Siedowse	/* Find the entry. */
109979561Siedowse	KASSERT(dh->dh_hused < dh->dh_hlen, ("dirhash find full"));
110079561Siedowse	slot = ufsdirhash_hash(dh, name, namelen);
110179561Siedowse	while (DH_ENTRY(dh, slot) != offset &&
110279561Siedowse	    DH_ENTRY(dh, slot) != DIRHASH_EMPTY)
110379561Siedowse		slot = WRAPINCR(slot, dh->dh_hlen);
110479561Siedowse	if (DH_ENTRY(dh, slot) != offset)
110579561Siedowse		panic("ufsdirhash_findslot: '%.*s' not found", namelen, name);
110679561Siedowse
110779561Siedowse	return (slot);
110879561Siedowse}
110979561Siedowse
111079561Siedowse/*
111179561Siedowse * Remove the entry corresponding to the specified slot from the hash array.
111279561Siedowse *
111379561Siedowse * `dh' must be locked on entry and remains so on return.
111479561Siedowse */
111579561Siedowsestatic void
111679561Siedowseufsdirhash_delslot(struct dirhash *dh, int slot)
111779561Siedowse{
111879561Siedowse	int i;
111979561Siedowse
1120178110Sjeff	DIRHASH_ASSERT_LOCKED(dh);
112179561Siedowse
112279561Siedowse	/* Mark the entry as deleted. */
112379561Siedowse	DH_ENTRY(dh, slot) = DIRHASH_DEL;
112479561Siedowse
112579561Siedowse	/* If this is the end of a chain of DIRHASH_DEL slots, remove them. */
112679561Siedowse	for (i = slot; DH_ENTRY(dh, i) == DIRHASH_DEL; )
112779561Siedowse		i = WRAPINCR(i, dh->dh_hlen);
112879561Siedowse	if (DH_ENTRY(dh, i) == DIRHASH_EMPTY) {
112992807Sdwmalone		i = WRAPDECR(i, dh->dh_hlen);
113092807Sdwmalone		while (DH_ENTRY(dh, i) == DIRHASH_DEL) {
113179561Siedowse			DH_ENTRY(dh, i) = DIRHASH_EMPTY;
113279561Siedowse			dh->dh_hused--;
113392807Sdwmalone			i = WRAPDECR(i, dh->dh_hlen);
113479561Siedowse		}
113579561Siedowse		KASSERT(dh->dh_hused >= 0, ("ufsdirhash_delslot neg hlen"));
113679561Siedowse	}
113779561Siedowse}
113879561Siedowse
113979561Siedowse/*
114079561Siedowse * Given a directory entry and its offset, find the offset of the
114179561Siedowse * previous entry in the same DIRBLKSIZ-sized block. Returns an
114279561Siedowse * offset, or -1 if there is no previous entry in the block or some
114379561Siedowse * other problem occurred.
114479561Siedowse */
114579561Siedowsestatic doff_t
114679561Siedowseufsdirhash_getprev(struct direct *dirp, doff_t offset)
114779561Siedowse{
114879561Siedowse	struct direct *dp;
114979561Siedowse	char *blkbuf;
115079561Siedowse	doff_t blkoff, prevoff;
115179561Siedowse	int entrypos, i;
115279561Siedowse
115379561Siedowse	blkoff = offset & ~(DIRBLKSIZ - 1);	/* offset of start of block */
115479561Siedowse	entrypos = offset & (DIRBLKSIZ - 1);	/* entry relative to block */
115579561Siedowse	blkbuf = (char *)dirp - entrypos;
115679561Siedowse	prevoff = blkoff;
115779561Siedowse
115879561Siedowse	/* If `offset' is the start of a block, there is no previous entry. */
115979561Siedowse	if (entrypos == 0)
116079561Siedowse		return (-1);
116179561Siedowse
116279561Siedowse	/* Scan from the start of the block until we get to the entry. */
116379561Siedowse	for (i = 0; i < entrypos; i += dp->d_reclen) {
116479561Siedowse		dp = (struct direct *)(blkbuf + i);
116579561Siedowse		if (dp->d_reclen == 0 || i + dp->d_reclen > entrypos)
116679561Siedowse			return (-1);	/* Corrupted directory. */
116779561Siedowse		prevoff = blkoff + i;
116879561Siedowse	}
116979561Siedowse	return (prevoff);
117079561Siedowse}
117179561Siedowse
117279561Siedowse/*
1173193375Ssnb * Delete the given dirhash and reclaim its memory. Assumes that
1174193375Ssnb * ufsdirhash_list is locked, and leaves it locked. Also assumes
1175193375Ssnb * that dh is locked. Returns the amount of memory freed.
1176193375Ssnb */
1177193375Ssnbstatic int
1178193375Ssnbufsdirhash_destroy(struct dirhash *dh)
1179193375Ssnb{
1180193375Ssnb	doff_t **hash;
1181193375Ssnb	u_int8_t *blkfree;
1182193375Ssnb	int i, mem, narrays;
1183193375Ssnb
1184193375Ssnb	KASSERT(dh->dh_hash != NULL, ("dirhash: NULL hash on list"));
1185193375Ssnb
1186193375Ssnb	/* Remove it from the list and detach its memory. */
1187193375Ssnb	TAILQ_REMOVE(&ufsdirhash_list, dh, dh_list);
1188193375Ssnb	dh->dh_onlist = 0;
1189193375Ssnb	hash = dh->dh_hash;
1190193375Ssnb	dh->dh_hash = NULL;
1191193375Ssnb	blkfree = dh->dh_blkfree;
1192193375Ssnb	dh->dh_blkfree = NULL;
1193193375Ssnb	narrays = dh->dh_narrays;
1194193375Ssnb	mem = dh->dh_memreq;
1195193375Ssnb	dh->dh_memreq = 0;
1196193375Ssnb
1197194387Ssnb	/* Unlock dirhash and free the detached memory. */
1198193375Ssnb	ufsdirhash_release(dh);
1199193375Ssnb	for (i = 0; i < narrays; i++)
1200193375Ssnb		DIRHASH_BLKFREE(hash[i]);
1201193375Ssnb	free(hash, M_DIRHASH);
1202193375Ssnb	free(blkfree, M_DIRHASH);
1203193375Ssnb
1204193375Ssnb	/* Account for the returned memory. */
1205193375Ssnb	ufs_dirhashmem -= mem;
1206193375Ssnb
1207193375Ssnb	return (mem);
1208193375Ssnb}
1209193375Ssnb
1210193375Ssnb/*
121179561Siedowse * Try to free up `wanted' bytes by stealing memory from existing
1212125854Sdwmalone * dirhashes. Returns zero with list locked if successful.
121379561Siedowse */
121479561Siedowsestatic int
121579561Siedowseufsdirhash_recycle(int wanted)
121679561Siedowse{
121779561Siedowse	struct dirhash *dh;
121879561Siedowse
1219125854Sdwmalone	DIRHASHLIST_LOCK();
1220178110Sjeff	dh = TAILQ_FIRST(&ufsdirhash_list);
122179561Siedowse	while (wanted + ufs_dirhashmem > ufs_dirhashmaxmem) {
1222178110Sjeff		/* Decrement the score; only recycle if it becomes zero. */
1223178110Sjeff		if (dh == NULL || --dh->dh_score > 0) {
1224125854Sdwmalone			DIRHASHLIST_UNLOCK();
122579561Siedowse			return (-1);
122679561Siedowse		}
1227178110Sjeff		/*
1228178110Sjeff		 * If we can't lock it it's in use and we don't want to
1229178110Sjeff		 * recycle it anyway.
1230178110Sjeff		 */
1231183080Sjhb		if (!sx_try_xlock(&dh->dh_lock)) {
1232178110Sjeff			dh = TAILQ_NEXT(dh, dh_list);
1233178110Sjeff			continue;
1234178110Sjeff		}
123579561Siedowse
1236193375Ssnb		ufsdirhash_destroy(dh);
123779561Siedowse
1238193375Ssnb		/* Repeat if necessary. */
1239178110Sjeff		dh = TAILQ_FIRST(&ufsdirhash_list);
124079561Siedowse	}
1241125854Sdwmalone	/* Success; return with list locked. */
124279561Siedowse	return (0);
124379561Siedowse}
124479561Siedowse
1245193375Ssnb/*
1246193375Ssnb * Callback that frees some dirhashes when the system is low on virtual memory.
1247193375Ssnb */
1248193375Ssnbstatic void
1249193375Ssnbufsdirhash_lowmem()
1250193375Ssnb{
1251194387Ssnb	struct dirhash *dh, *dh_temp;
1252193375Ssnb	int memfreed = 0;
1253193375Ssnb	/* XXX: this 10% may need to be adjusted */
1254193375Ssnb	int memwanted = ufs_dirhashmem / 10;
125579561Siedowse
1256193375Ssnb	ufs_dirhashlowmemcount++;
1257193375Ssnb
1258193375Ssnb	DIRHASHLIST_LOCK();
1259193375Ssnb	/*
1260193375Ssnb	 * Delete dirhashes not used for more than ufs_dirhashreclaimage
1261193375Ssnb	 * seconds. If we can't get a lock on the dirhash, it will be skipped.
1262193375Ssnb	 */
1263194387Ssnb	TAILQ_FOREACH_SAFE(dh, &ufsdirhash_list, dh_list, dh_temp) {
1264193375Ssnb		if (!sx_try_xlock(&dh->dh_lock))
1265193375Ssnb			continue;
1266193375Ssnb		if (time_second - dh->dh_lastused > ufs_dirhashreclaimage)
1267193375Ssnb			memfreed += ufsdirhash_destroy(dh);
1268193375Ssnb		/* Unlock if we didn't delete the dirhash */
1269193375Ssnb		else
1270193375Ssnb			ufsdirhash_release(dh);
1271193375Ssnb	}
1272193375Ssnb
1273193375Ssnb	/*
1274193375Ssnb	 * If not enough memory was freed, keep deleting hashes from the head
1275193375Ssnb	 * of the dirhash list. The ones closest to the head should be the
1276193375Ssnb	 * oldest.
1277193375Ssnb	 */
1278194387Ssnb	if (memfreed < memwanted) {
1279194387Ssnb		TAILQ_FOREACH_SAFE(dh, &ufsdirhash_list, dh_list, dh_temp) {
1280194387Ssnb			if (!sx_try_xlock(&dh->dh_lock))
1281194387Ssnb				continue;
1282194387Ssnb			memfreed += ufsdirhash_destroy(dh);
1283194387Ssnb			if (memfreed >= memwanted)
1284194387Ssnb				break;
1285194387Ssnb		}
1286193375Ssnb	}
1287193375Ssnb	DIRHASHLIST_UNLOCK();
1288193375Ssnb}
1289193375Ssnb
1290193375Ssnb
129199101Siedowsevoid
129279561Siedowseufsdirhash_init()
129379561Siedowse{
1294214359Sivoras	ufs_dirhashmaxmem = lmax(roundup(hibufspace / 64, PAGE_SIZE),
1295214359Sivoras	    2 * 1024 * 1024);
1296214359Sivoras
129796874Siedowse	ufsdirhash_zone = uma_zcreate("DIRHASH", DH_NBLKOFF * sizeof(doff_t),
129892768Sjeff	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
129993818Sjhb	mtx_init(&ufsdirhash_mtx, "dirhash list", NULL, MTX_DEF);
130079561Siedowse	TAILQ_INIT(&ufsdirhash_list);
1301193375Ssnb
1302193375Ssnb	/* Register a callback function to handle low memory signals */
1303193375Ssnb	EVENTHANDLER_REGISTER(vm_lowmem, ufsdirhash_lowmem, NULL,
1304193375Ssnb	    EVENTHANDLER_PRI_FIRST);
130579561Siedowse}
130679561Siedowse
130799101Siedowsevoid
130899101Siedowseufsdirhash_uninit()
130999101Siedowse{
131099101Siedowse	KASSERT(TAILQ_EMPTY(&ufsdirhash_list), ("ufsdirhash_uninit"));
131199101Siedowse	uma_zdestroy(ufsdirhash_zone);
131299101Siedowse	mtx_destroy(&ufsdirhash_mtx);
131399101Siedowse}
131479561Siedowse
131579561Siedowse#endif /* UFS_DIRHASH */
1316