ufs_dirhash.c revision 183080
1/*-
2 * Copyright (c) 2001, 2002 Ian Dowse.  All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 *    notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 *    notice, this list of conditions and the following disclaimer in the
11 *    documentation and/or other materials provided with the distribution.
12 *
13 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
14 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
17 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23 * SUCH DAMAGE.
24 */
25
26/*
27 * This implements a hash-based lookup scheme for UFS directories.
28 */
29
30#include <sys/cdefs.h>
31__FBSDID("$FreeBSD: head/sys/ufs/ufs/ufs_dirhash.c 183080 2008-09-16 16:23:56Z jhb $");
32
33#include "opt_ufs.h"
34
35#ifdef UFS_DIRHASH
36
37#include <sys/param.h>
38#include <sys/systm.h>
39#include <sys/kernel.h>
40#include <sys/lock.h>
41#include <sys/mutex.h>
42#include <sys/malloc.h>
43#include <sys/fnv_hash.h>
44#include <sys/proc.h>
45#include <sys/bio.h>
46#include <sys/buf.h>
47#include <sys/vnode.h>
48#include <sys/mount.h>
49#include <sys/refcount.h>
50#include <sys/sysctl.h>
51#include <sys/sx.h>
52#include <vm/uma.h>
53
54#include <ufs/ufs/quota.h>
55#include <ufs/ufs/inode.h>
56#include <ufs/ufs/dir.h>
57#include <ufs/ufs/dirhash.h>
58#include <ufs/ufs/extattr.h>
59#include <ufs/ufs/ufsmount.h>
60#include <ufs/ufs/ufs_extern.h>
61
62#define WRAPINCR(val, limit)	(((val) + 1 == (limit)) ? 0 : ((val) + 1))
63#define WRAPDECR(val, limit)	(((val) == 0) ? ((limit) - 1) : ((val) - 1))
64#define OFSFMT(vp)		((vp)->v_mount->mnt_maxsymlinklen <= 0)
65#define BLKFREE2IDX(n)		((n) > DH_NFSTATS ? DH_NFSTATS : (n))
66
67static MALLOC_DEFINE(M_DIRHASH, "ufs_dirhash", "UFS directory hash tables");
68
69static SYSCTL_NODE(_vfs, OID_AUTO, ufs, CTLFLAG_RD, 0, "UFS filesystem");
70
71static int ufs_mindirhashsize = DIRBLKSIZ * 5;
72SYSCTL_INT(_vfs_ufs, OID_AUTO, dirhash_minsize, CTLFLAG_RW,
73    &ufs_mindirhashsize,
74    0, "minimum directory size in bytes for which to use hashed lookup");
75static int ufs_dirhashmaxmem = 2 * 1024 * 1024;
76SYSCTL_INT(_vfs_ufs, OID_AUTO, dirhash_maxmem, CTLFLAG_RW, &ufs_dirhashmaxmem,
77    0, "maximum allowed dirhash memory usage");
78static int ufs_dirhashmem;
79SYSCTL_INT(_vfs_ufs, OID_AUTO, dirhash_mem, CTLFLAG_RD, &ufs_dirhashmem,
80    0, "current dirhash memory usage");
81static int ufs_dirhashcheck = 0;
82SYSCTL_INT(_vfs_ufs, OID_AUTO, dirhash_docheck, CTLFLAG_RW, &ufs_dirhashcheck,
83    0, "enable extra sanity tests");
84
85
86static int ufsdirhash_hash(struct dirhash *dh, char *name, int namelen);
87static void ufsdirhash_adjfree(struct dirhash *dh, doff_t offset, int diff);
88static void ufsdirhash_delslot(struct dirhash *dh, int slot);
89static int ufsdirhash_findslot(struct dirhash *dh, char *name, int namelen,
90	   doff_t offset);
91static doff_t ufsdirhash_getprev(struct direct *dp, doff_t offset);
92static int ufsdirhash_recycle(int wanted);
93static void ufsdirhash_free_locked(struct inode *ip);
94
95static uma_zone_t	ufsdirhash_zone;
96
97#define DIRHASHLIST_LOCK() 		mtx_lock(&ufsdirhash_mtx)
98#define DIRHASHLIST_UNLOCK() 		mtx_unlock(&ufsdirhash_mtx)
99#define DIRHASH_BLKALLOC_WAITOK() 	uma_zalloc(ufsdirhash_zone, M_WAITOK)
100#define DIRHASH_BLKFREE(ptr) 		uma_zfree(ufsdirhash_zone, (ptr))
101#define	DIRHASH_ASSERT_LOCKED(dh)					\
102    sx_assert(&(dh)->dh_lock, SA_LOCKED)
103
104/* Dirhash list; recently-used entries are near the tail. */
105static TAILQ_HEAD(, dirhash) ufsdirhash_list;
106
107/* Protects: ufsdirhash_list, `dh_list' field, ufs_dirhashmem. */
108static struct mtx	ufsdirhash_mtx;
109
110/*
111 * Locking:
112 *
113 * The relationship between inode and dirhash is protected either by an
114 * exclusive vnode lock or the vnode interlock where a shared vnode lock
115 * may be used.  The dirhash_mtx is acquired after the dirhash lock.  To
116 * handle teardown races, code wishing to lock the dirhash for an inode
117 * when using a shared vnode lock must obtain a private reference on the
118 * dirhash while holding the vnode interlock.  They can drop it once they
119 * have obtained the dirhash lock and verified that the dirhash wasn't
120 * recycled while they waited for the dirhash lock.
121 *
122 * ufsdirhash_build() acquires a shared lock on the dirhash when it is
123 * successful.  This lock is released after a call to ufsdirhash_lookup().
124 *
125 * Functions requiring exclusive access use ufsdirhash_acquire() which may
126 * free a dirhash structure that was recycled by ufsdirhash_recycle().
127 *
128 * The dirhash lock may be held across io operations.
129 */
130
131static void
132ufsdirhash_hold(struct dirhash *dh)
133{
134
135	refcount_acquire(&dh->dh_refcount);
136}
137
138static void
139ufsdirhash_drop(struct dirhash *dh)
140{
141
142	if (refcount_release(&dh->dh_refcount)) {
143		sx_destroy(&dh->dh_lock);
144		free(dh, M_DIRHASH);
145	}
146}
147
148/*
149 * Release the lock on a dirhash.
150 */
151static void
152ufsdirhash_release(struct dirhash *dh)
153{
154
155	sx_unlock(&dh->dh_lock);
156}
157
158/*
159 * Either acquire an existing hash locked shared or create a new hash and
160 * return it exclusively locked.  May return NULL if the allocation fails.
161 *
162 * The vnode interlock is used to protect the i_dirhash pointer from
163 * simultaneous access while only a shared vnode lock is held.
164 */
165static struct dirhash *
166ufsdirhash_create(struct inode *ip)
167{
168	struct dirhash *ndh;
169	struct dirhash *dh;
170	struct vnode *vp;
171	int error;
172
173	error = 0;
174	ndh = dh = NULL;
175	vp = ip->i_vnode;
176	for (;;) {
177		/* Racy check for i_dirhash to prefetch an dirhash structure. */
178		if (ip->i_dirhash == NULL && ndh == NULL) {
179			MALLOC(ndh, struct dirhash *, sizeof *dh, M_DIRHASH,
180			    M_NOWAIT | M_ZERO);
181			if (ndh == NULL)
182				return (NULL);
183			refcount_init(&ndh->dh_refcount, 1);
184			sx_init(&ndh->dh_lock, "dirhash");
185			sx_xlock(&ndh->dh_lock);
186		}
187		/*
188		 * Check i_dirhash.  If it's NULL just try to use a
189		 * preallocated structure.  If none exists loop and try again.
190		 */
191		VI_LOCK(vp);
192		dh = ip->i_dirhash;
193		if (dh == NULL) {
194			ip->i_dirhash = ndh;
195			VI_UNLOCK(vp);
196			if (ndh == NULL)
197				continue;
198			return (ndh);
199		}
200		ufsdirhash_hold(dh);
201		VI_UNLOCK(vp);
202
203		/* Acquire a shared lock on existing hashes. */
204		sx_slock(&dh->dh_lock);
205
206		/* The hash could've been recycled while we were waiting. */
207		VI_LOCK(vp);
208		if (ip->i_dirhash != dh) {
209			VI_UNLOCK(vp);
210			ufsdirhash_release(dh);
211			ufsdirhash_drop(dh);
212			continue;
213		}
214		VI_UNLOCK(vp);
215		ufsdirhash_drop(dh);
216
217		/* If the hash is still valid we've succeeded. */
218		if (dh->dh_hash != NULL)
219			break;
220		/*
221		 * If the hash is NULL it has been recycled.  Try to upgrade
222		 * so we can recreate it.  If we fail the upgrade, drop our
223		 * lock and try again.
224		 */
225		if (sx_try_upgrade(&dh->dh_lock))
226			break;
227		sx_sunlock(&dh->dh_lock);
228	}
229	/* Free the preallocated structure if it was not necessary. */
230	if (ndh) {
231		ufsdirhash_release(ndh);
232		ufsdirhash_drop(ndh);
233	}
234	return (dh);
235}
236
237/*
238 * Acquire an exclusive lock on an existing hash.  Requires an exclusive
239 * vnode lock to protect the i_dirhash pointer.  hashes that have been
240 * recycled are reclaimed here and NULL is returned.
241 */
242static struct dirhash *
243ufsdirhash_acquire(struct inode *ip)
244{
245	struct dirhash *dh;
246	struct vnode *vp;
247
248	ASSERT_VOP_ELOCKED(ip->i_vnode, __FUNCTION__);
249
250	vp = ip->i_vnode;
251	dh = ip->i_dirhash;
252	if (dh == NULL)
253		return (NULL);
254	sx_xlock(&dh->dh_lock);
255	if (dh->dh_hash != NULL)
256		return (dh);
257	ufsdirhash_free_locked(ip);
258	return (NULL);
259}
260
261/*
262 * Acquire exclusively and free the hash pointed to by ip.  Works with a
263 * shared or exclusive vnode lock.
264 */
265void
266ufsdirhash_free(struct inode *ip)
267{
268	struct dirhash *dh;
269	struct vnode *vp;
270
271	vp = ip->i_vnode;
272	for (;;) {
273		/* Grab a reference on this inode's dirhash if it has one. */
274		VI_LOCK(vp);
275		dh = ip->i_dirhash;
276		if (dh == NULL) {
277			VI_UNLOCK(vp);
278			return;
279		}
280		ufsdirhash_hold(dh);
281		VI_UNLOCK(vp);
282
283		/* Exclusively lock the dirhash. */
284		sx_xlock(&dh->dh_lock);
285
286		/* If this dirhash still belongs to this inode, then free it. */
287		VI_LOCK(vp);
288		if (ip->i_dirhash == dh) {
289			VI_UNLOCK(vp);
290			ufsdirhash_drop(dh);
291			break;
292		}
293		VI_UNLOCK(vp);
294
295		/*
296		 * This inode's dirhash has changed while we were
297		 * waiting for the dirhash lock, so try again.
298		 */
299		ufsdirhash_release(dh);
300		ufsdirhash_drop(dh);
301	}
302	ufsdirhash_free_locked(ip);
303}
304
305/*
306 * Attempt to build up a hash table for the directory contents in
307 * inode 'ip'. Returns 0 on success, or -1 of the operation failed.
308 */
309int
310ufsdirhash_build(struct inode *ip)
311{
312	struct dirhash *dh;
313	struct buf *bp = NULL;
314	struct direct *ep;
315	struct vnode *vp;
316	doff_t bmask, pos;
317	int dirblocks, i, j, memreqd, nblocks, narrays, nslots, slot;
318
319	/* Take care of a decreased sysctl value. */
320	while (ufs_dirhashmem > ufs_dirhashmaxmem)
321		if (ufsdirhash_recycle(0) != 0)
322			return (-1);
323
324	/* Check if we can/should use dirhash. */
325	if (ip->i_size < ufs_mindirhashsize || OFSFMT(ip->i_vnode) ||
326	    ip->i_effnlink == 0) {
327		if (ip->i_dirhash)
328			ufsdirhash_free(ip);
329		return (-1);
330	}
331	dh = ufsdirhash_create(ip);
332	if (dh == NULL)
333		return (-1);
334	if (dh->dh_hash != NULL)
335		return (0);
336
337	vp = ip->i_vnode;
338	/* Allocate 50% more entries than this dir size could ever need. */
339	KASSERT(ip->i_size >= DIRBLKSIZ, ("ufsdirhash_build size"));
340	nslots = ip->i_size / DIRECTSIZ(1);
341	nslots = (nslots * 3 + 1) / 2;
342	narrays = howmany(nslots, DH_NBLKOFF);
343	nslots = narrays * DH_NBLKOFF;
344	dirblocks = howmany(ip->i_size, DIRBLKSIZ);
345	nblocks = (dirblocks * 3 + 1) / 2;
346	memreqd = sizeof(*dh) + narrays * sizeof(*dh->dh_hash) +
347	    narrays * DH_NBLKOFF * sizeof(**dh->dh_hash) +
348	    nblocks * sizeof(*dh->dh_blkfree);
349	DIRHASHLIST_LOCK();
350	if (memreqd + ufs_dirhashmem > ufs_dirhashmaxmem) {
351		DIRHASHLIST_UNLOCK();
352		if (memreqd > ufs_dirhashmaxmem / 2)
353			goto fail;
354		/* Try to free some space. */
355		if (ufsdirhash_recycle(memreqd) != 0)
356			goto fail;
357		/* Enough was freed, and list has been locked. */
358	}
359	ufs_dirhashmem += memreqd;
360	DIRHASHLIST_UNLOCK();
361
362	/* Initialise the hash table and block statistics. */
363	dh->dh_memreq = memreqd;
364	dh->dh_narrays = narrays;
365	dh->dh_hlen = nslots;
366	dh->dh_nblk = nblocks;
367	dh->dh_dirblks = dirblocks;
368	for (i = 0; i < DH_NFSTATS; i++)
369		dh->dh_firstfree[i] = -1;
370	dh->dh_firstfree[DH_NFSTATS] = 0;
371	dh->dh_hused = 0;
372	dh->dh_seqopt = 0;
373	dh->dh_seqoff = 0;
374	dh->dh_score = DH_SCOREINIT;
375
376	/*
377	 * Use non-blocking mallocs so that we will revert to a linear
378	 * lookup on failure rather than potentially blocking forever.
379	 */
380	MALLOC(dh->dh_hash, doff_t **, narrays * sizeof(dh->dh_hash[0]),
381	    M_DIRHASH, M_NOWAIT | M_ZERO);
382	if (dh->dh_hash == NULL)
383		goto fail;
384	MALLOC(dh->dh_blkfree, u_int8_t *, nblocks * sizeof(dh->dh_blkfree[0]),
385	    M_DIRHASH, M_NOWAIT);
386	if (dh->dh_blkfree == NULL)
387		goto fail;
388	for (i = 0; i < narrays; i++) {
389		if ((dh->dh_hash[i] = DIRHASH_BLKALLOC_WAITOK()) == NULL)
390			goto fail;
391		for (j = 0; j < DH_NBLKOFF; j++)
392			dh->dh_hash[i][j] = DIRHASH_EMPTY;
393	}
394	for (i = 0; i < dirblocks; i++)
395		dh->dh_blkfree[i] = DIRBLKSIZ / DIRALIGN;
396	bmask = VFSTOUFS(vp->v_mount)->um_mountp->mnt_stat.f_iosize - 1;
397	pos = 0;
398	while (pos < ip->i_size) {
399		/* If necessary, get the next directory block. */
400		if ((pos & bmask) == 0) {
401			if (bp != NULL)
402				brelse(bp);
403			if (UFS_BLKATOFF(vp, (off_t)pos, NULL, &bp) != 0)
404				goto fail;
405		}
406
407		/* Add this entry to the hash. */
408		ep = (struct direct *)((char *)bp->b_data + (pos & bmask));
409		if (ep->d_reclen == 0 || ep->d_reclen >
410		    DIRBLKSIZ - (pos & (DIRBLKSIZ - 1))) {
411			/* Corrupted directory. */
412			brelse(bp);
413			goto fail;
414		}
415		if (ep->d_ino != 0) {
416			/* Add the entry (simplified ufsdirhash_add). */
417			slot = ufsdirhash_hash(dh, ep->d_name, ep->d_namlen);
418			while (DH_ENTRY(dh, slot) != DIRHASH_EMPTY)
419				slot = WRAPINCR(slot, dh->dh_hlen);
420			dh->dh_hused++;
421			DH_ENTRY(dh, slot) = pos;
422			ufsdirhash_adjfree(dh, pos, -DIRSIZ(0, ep));
423		}
424		pos += ep->d_reclen;
425	}
426
427	if (bp != NULL)
428		brelse(bp);
429	DIRHASHLIST_LOCK();
430	TAILQ_INSERT_TAIL(&ufsdirhash_list, dh, dh_list);
431	dh->dh_onlist = 1;
432	DIRHASHLIST_UNLOCK();
433	sx_downgrade(&dh->dh_lock);
434	return (0);
435
436fail:
437	ufsdirhash_free_locked(ip);
438	return (-1);
439}
440
441/*
442 * Free any hash table associated with inode 'ip'.
443 */
444static void
445ufsdirhash_free_locked(struct inode *ip)
446{
447	struct dirhash *dh;
448	struct vnode *vp;
449	int i;
450
451	DIRHASH_ASSERT_LOCKED(ip->i_dirhash);
452
453	/*
454	 * Clear the pointer in the inode to prevent new threads from
455	 * finding the dead structure.
456	 */
457	vp = ip->i_vnode;
458	VI_LOCK(vp);
459	dh = ip->i_dirhash;
460	ip->i_dirhash = NULL;
461	VI_UNLOCK(vp);
462
463	/*
464	 * At this point, any waiters for the lock should hold their
465	 * own reference on the dirhash structure.  They will drop
466	 * that reference once they grab the vnode interlock and see
467	 * that ip->i_dirhash is NULL.
468	 */
469	sx_xunlock(&dh->dh_lock);
470
471	/*
472	 * Handle partially recycled as well as fully constructed hashes.
473	 */
474	if (dh->dh_hash != NULL) {
475		for (i = 0; i < dh->dh_narrays; i++)
476			if (dh->dh_hash[i] != NULL)
477				DIRHASH_BLKFREE(dh->dh_hash[i]);
478		FREE(dh->dh_hash, M_DIRHASH);
479		if (dh->dh_blkfree != NULL)
480			FREE(dh->dh_blkfree, M_DIRHASH);
481	}
482	DIRHASHLIST_LOCK();
483	if (dh->dh_onlist)
484		TAILQ_REMOVE(&ufsdirhash_list, dh, dh_list);
485	ufs_dirhashmem -= dh->dh_memreq;
486	DIRHASHLIST_UNLOCK();
487
488	/*
489	 * Drop the inode's reference to the data structure.
490	 */
491	ufsdirhash_drop(dh);
492}
493
494/*
495 * Find the offset of the specified name within the given inode.
496 * Returns 0 on success, ENOENT if the entry does not exist, or
497 * EJUSTRETURN if the caller should revert to a linear search.
498 *
499 * If successful, the directory offset is stored in *offp, and a
500 * pointer to a struct buf containing the entry is stored in *bpp. If
501 * prevoffp is non-NULL, the offset of the previous entry within
502 * the DIRBLKSIZ-sized block is stored in *prevoffp (if the entry
503 * is the first in a block, the start of the block is used).
504 *
505 * Must be called with the hash locked.  Returns with the hash unlocked.
506 */
507int
508ufsdirhash_lookup(struct inode *ip, char *name, int namelen, doff_t *offp,
509    struct buf **bpp, doff_t *prevoffp)
510{
511	struct dirhash *dh, *dh_next;
512	struct direct *dp;
513	struct vnode *vp;
514	struct buf *bp;
515	doff_t blkoff, bmask, offset, prevoff;
516	int i, slot;
517	int error;
518
519	dh = ip->i_dirhash;
520	KASSERT(dh != NULL && dh->dh_hash != NULL,
521	    ("ufsdirhash_lookup: Invalid dirhash %p\n", dh));
522	DIRHASH_ASSERT_LOCKED(dh);
523	/*
524	 * Move this dirhash towards the end of the list if it has a
525	 * score higher than the next entry, and acquire the dh_lock.
526	 */
527	DIRHASHLIST_LOCK();
528	if (TAILQ_NEXT(dh, dh_list) != NULL) {
529		/*
530		 * If the new score will be greater than that of the next
531		 * entry, then move this entry past it. With both mutexes
532		 * held, dh_next won't go away, but its dh_score could
533		 * change; that's not important since it is just a hint.
534		 */
535		if ((dh_next = TAILQ_NEXT(dh, dh_list)) != NULL &&
536		    dh->dh_score >= dh_next->dh_score) {
537			KASSERT(dh->dh_onlist, ("dirhash: not on list"));
538			TAILQ_REMOVE(&ufsdirhash_list, dh, dh_list);
539			TAILQ_INSERT_AFTER(&ufsdirhash_list, dh_next, dh,
540			    dh_list);
541		}
542	}
543	/* Update the score. */
544	if (dh->dh_score < DH_SCOREMAX)
545		dh->dh_score++;
546	DIRHASHLIST_UNLOCK();
547
548	vp = ip->i_vnode;
549	bmask = VFSTOUFS(vp->v_mount)->um_mountp->mnt_stat.f_iosize - 1;
550	blkoff = -1;
551	bp = NULL;
552restart:
553	slot = ufsdirhash_hash(dh, name, namelen);
554
555	if (dh->dh_seqopt) {
556		/*
557		 * Sequential access optimisation. dh_seqoff contains the
558		 * offset of the directory entry immediately following
559		 * the last entry that was looked up. Check if this offset
560		 * appears in the hash chain for the name we are looking for.
561		 */
562		for (i = slot; (offset = DH_ENTRY(dh, i)) != DIRHASH_EMPTY;
563		    i = WRAPINCR(i, dh->dh_hlen))
564			if (offset == dh->dh_seqoff)
565				break;
566		if (offset == dh->dh_seqoff) {
567			/*
568			 * We found an entry with the expected offset. This
569			 * is probably the entry we want, but if not, the
570			 * code below will turn off seqopt and retry.
571			 */
572			slot = i;
573		} else
574			dh->dh_seqopt = 0;
575	}
576
577	for (; (offset = DH_ENTRY(dh, slot)) != DIRHASH_EMPTY;
578	    slot = WRAPINCR(slot, dh->dh_hlen)) {
579		if (offset == DIRHASH_DEL)
580			continue;
581		if (offset < 0 || offset >= ip->i_size)
582			panic("ufsdirhash_lookup: bad offset in hash array");
583		if ((offset & ~bmask) != blkoff) {
584			if (bp != NULL)
585				brelse(bp);
586			blkoff = offset & ~bmask;
587			if (UFS_BLKATOFF(vp, (off_t)blkoff, NULL, &bp) != 0) {
588				error = EJUSTRETURN;
589				goto fail;
590			}
591		}
592		dp = (struct direct *)(bp->b_data + (offset & bmask));
593		if (dp->d_reclen == 0 || dp->d_reclen >
594		    DIRBLKSIZ - (offset & (DIRBLKSIZ - 1))) {
595			/* Corrupted directory. */
596			error = EJUSTRETURN;
597			goto fail;
598		}
599		if (dp->d_namlen == namelen &&
600		    bcmp(dp->d_name, name, namelen) == 0) {
601			/* Found. Get the prev offset if needed. */
602			if (prevoffp != NULL) {
603				if (offset & (DIRBLKSIZ - 1)) {
604					prevoff = ufsdirhash_getprev(dp,
605					    offset);
606					if (prevoff == -1) {
607						error = EJUSTRETURN;
608						goto fail;
609					}
610				} else
611					prevoff = offset;
612				*prevoffp = prevoff;
613			}
614
615			/* Check for sequential access, and update offset. */
616			if (dh->dh_seqopt == 0 && dh->dh_seqoff == offset)
617				dh->dh_seqopt = 1;
618			dh->dh_seqoff = offset + DIRSIZ(0, dp);
619			*bpp = bp;
620			*offp = offset;
621			ufsdirhash_release(dh);
622			return (0);
623		}
624
625		/*
626		 * When the name doesn't match in the seqopt case, go back
627		 * and search normally.
628		 */
629		if (dh->dh_seqopt) {
630			dh->dh_seqopt = 0;
631			goto restart;
632		}
633	}
634	error = ENOENT;
635fail:
636	ufsdirhash_release(dh);
637	if (bp != NULL)
638		brelse(bp);
639	return (error);
640}
641
642/*
643 * Find a directory block with room for 'slotneeded' bytes. Returns
644 * the offset of the directory entry that begins the free space.
645 * This will either be the offset of an existing entry that has free
646 * space at the end, or the offset of an entry with d_ino == 0 at
647 * the start of a DIRBLKSIZ block.
648 *
649 * To use the space, the caller may need to compact existing entries in
650 * the directory. The total number of bytes in all of the entries involved
651 * in the compaction is stored in *slotsize. In other words, all of
652 * the entries that must be compacted are exactly contained in the
653 * region beginning at the returned offset and spanning *slotsize bytes.
654 *
655 * Returns -1 if no space was found, indicating that the directory
656 * must be extended.
657 */
658doff_t
659ufsdirhash_findfree(struct inode *ip, int slotneeded, int *slotsize)
660{
661	struct direct *dp;
662	struct dirhash *dh;
663	struct buf *bp;
664	doff_t pos, slotstart;
665	int dirblock, error, freebytes, i;
666
667	dh = ip->i_dirhash;
668	KASSERT(dh != NULL && dh->dh_hash != NULL,
669	    ("ufsdirhash_findfree: Invalid dirhash %p\n", dh));
670	DIRHASH_ASSERT_LOCKED(dh);
671
672	/* Find a directory block with the desired free space. */
673	dirblock = -1;
674	for (i = howmany(slotneeded, DIRALIGN); i <= DH_NFSTATS; i++)
675		if ((dirblock = dh->dh_firstfree[i]) != -1)
676			break;
677	if (dirblock == -1)
678		return (-1);
679
680	KASSERT(dirblock < dh->dh_nblk &&
681	    dh->dh_blkfree[dirblock] >= howmany(slotneeded, DIRALIGN),
682	    ("ufsdirhash_findfree: bad stats"));
683	pos = dirblock * DIRBLKSIZ;
684	error = UFS_BLKATOFF(ip->i_vnode, (off_t)pos, (char **)&dp, &bp);
685	if (error)
686		return (-1);
687
688	/* Find the first entry with free space. */
689	for (i = 0; i < DIRBLKSIZ; ) {
690		if (dp->d_reclen == 0) {
691			brelse(bp);
692			return (-1);
693		}
694		if (dp->d_ino == 0 || dp->d_reclen > DIRSIZ(0, dp))
695			break;
696		i += dp->d_reclen;
697		dp = (struct direct *)((char *)dp + dp->d_reclen);
698	}
699	if (i > DIRBLKSIZ) {
700		brelse(bp);
701		return (-1);
702	}
703	slotstart = pos + i;
704
705	/* Find the range of entries needed to get enough space */
706	freebytes = 0;
707	while (i < DIRBLKSIZ && freebytes < slotneeded) {
708		freebytes += dp->d_reclen;
709		if (dp->d_ino != 0)
710			freebytes -= DIRSIZ(0, dp);
711		if (dp->d_reclen == 0) {
712			brelse(bp);
713			return (-1);
714		}
715		i += dp->d_reclen;
716		dp = (struct direct *)((char *)dp + dp->d_reclen);
717	}
718	if (i > DIRBLKSIZ) {
719		brelse(bp);
720		return (-1);
721	}
722	if (freebytes < slotneeded)
723		panic("ufsdirhash_findfree: free mismatch");
724	brelse(bp);
725	*slotsize = pos + i - slotstart;
726	return (slotstart);
727}
728
729/*
730 * Return the start of the unused space at the end of a directory, or
731 * -1 if there are no trailing unused blocks.
732 */
733doff_t
734ufsdirhash_enduseful(struct inode *ip)
735{
736
737	struct dirhash *dh;
738	int i;
739
740	dh = ip->i_dirhash;
741	DIRHASH_ASSERT_LOCKED(dh);
742	KASSERT(dh != NULL && dh->dh_hash != NULL,
743	    ("ufsdirhash_enduseful: Invalid dirhash %p\n", dh));
744
745	if (dh->dh_blkfree[dh->dh_dirblks - 1] != DIRBLKSIZ / DIRALIGN)
746		return (-1);
747
748	for (i = dh->dh_dirblks - 1; i >= 0; i--)
749		if (dh->dh_blkfree[i] != DIRBLKSIZ / DIRALIGN)
750			break;
751
752	return ((doff_t)(i + 1) * DIRBLKSIZ);
753}
754
755/*
756 * Insert information into the hash about a new directory entry. dirp
757 * points to a struct direct containing the entry, and offset specifies
758 * the offset of this entry.
759 */
760void
761ufsdirhash_add(struct inode *ip, struct direct *dirp, doff_t offset)
762{
763	struct dirhash *dh;
764	int slot;
765
766	if ((dh = ufsdirhash_acquire(ip)) == NULL)
767		return;
768
769	KASSERT(offset < dh->dh_dirblks * DIRBLKSIZ,
770	    ("ufsdirhash_add: bad offset"));
771	/*
772	 * Normal hash usage is < 66%. If the usage gets too high then
773	 * remove the hash entirely and let it be rebuilt later.
774	 */
775	if (dh->dh_hused >= (dh->dh_hlen * 3) / 4) {
776		ufsdirhash_free_locked(ip);
777		return;
778	}
779
780	/* Find a free hash slot (empty or deleted), and add the entry. */
781	slot = ufsdirhash_hash(dh, dirp->d_name, dirp->d_namlen);
782	while (DH_ENTRY(dh, slot) >= 0)
783		slot = WRAPINCR(slot, dh->dh_hlen);
784	if (DH_ENTRY(dh, slot) == DIRHASH_EMPTY)
785		dh->dh_hused++;
786	DH_ENTRY(dh, slot) = offset;
787
788	/* Update the per-block summary info. */
789	ufsdirhash_adjfree(dh, offset, -DIRSIZ(0, dirp));
790	ufsdirhash_release(dh);
791}
792
793/*
794 * Remove the specified directory entry from the hash. The entry to remove
795 * is defined by the name in `dirp', which must exist at the specified
796 * `offset' within the directory.
797 */
798void
799ufsdirhash_remove(struct inode *ip, struct direct *dirp, doff_t offset)
800{
801	struct dirhash *dh;
802	int slot;
803
804	if ((dh = ufsdirhash_acquire(ip)) == NULL)
805		return;
806
807	KASSERT(offset < dh->dh_dirblks * DIRBLKSIZ,
808	    ("ufsdirhash_remove: bad offset"));
809	/* Find the entry */
810	slot = ufsdirhash_findslot(dh, dirp->d_name, dirp->d_namlen, offset);
811
812	/* Remove the hash entry. */
813	ufsdirhash_delslot(dh, slot);
814
815	/* Update the per-block summary info. */
816	ufsdirhash_adjfree(dh, offset, DIRSIZ(0, dirp));
817	ufsdirhash_release(dh);
818}
819
820/*
821 * Change the offset associated with a directory entry in the hash. Used
822 * when compacting directory blocks.
823 */
824void
825ufsdirhash_move(struct inode *ip, struct direct *dirp, doff_t oldoff,
826    doff_t newoff)
827{
828	struct dirhash *dh;
829	int slot;
830
831	if ((dh = ufsdirhash_acquire(ip)) == NULL)
832		return;
833
834	KASSERT(oldoff < dh->dh_dirblks * DIRBLKSIZ &&
835	    newoff < dh->dh_dirblks * DIRBLKSIZ,
836	    ("ufsdirhash_move: bad offset"));
837	/* Find the entry, and update the offset. */
838	slot = ufsdirhash_findslot(dh, dirp->d_name, dirp->d_namlen, oldoff);
839	DH_ENTRY(dh, slot) = newoff;
840	ufsdirhash_release(dh);
841}
842
843/*
844 * Inform dirhash that the directory has grown by one block that
845 * begins at offset (i.e. the new length is offset + DIRBLKSIZ).
846 */
847void
848ufsdirhash_newblk(struct inode *ip, doff_t offset)
849{
850	struct dirhash *dh;
851	int block;
852
853	if ((dh = ufsdirhash_acquire(ip)) == NULL)
854		return;
855
856	KASSERT(offset == dh->dh_dirblks * DIRBLKSIZ,
857	    ("ufsdirhash_newblk: bad offset"));
858	block = offset / DIRBLKSIZ;
859	if (block >= dh->dh_nblk) {
860		/* Out of space; must rebuild. */
861		ufsdirhash_free_locked(ip);
862		return;
863	}
864	dh->dh_dirblks = block + 1;
865
866	/* Account for the new free block. */
867	dh->dh_blkfree[block] = DIRBLKSIZ / DIRALIGN;
868	if (dh->dh_firstfree[DH_NFSTATS] == -1)
869		dh->dh_firstfree[DH_NFSTATS] = block;
870	ufsdirhash_release(dh);
871}
872
873/*
874 * Inform dirhash that the directory is being truncated.
875 */
876void
877ufsdirhash_dirtrunc(struct inode *ip, doff_t offset)
878{
879	struct dirhash *dh;
880	int block, i;
881
882	if ((dh = ufsdirhash_acquire(ip)) == NULL)
883		return;
884
885	KASSERT(offset <= dh->dh_dirblks * DIRBLKSIZ,
886	    ("ufsdirhash_dirtrunc: bad offset"));
887	block = howmany(offset, DIRBLKSIZ);
888	/*
889	 * If the directory shrinks to less than 1/8 of dh_nblk blocks
890	 * (about 20% of its original size due to the 50% extra added in
891	 * ufsdirhash_build) then free it, and let the caller rebuild
892	 * if necessary.
893	 */
894	if (block < dh->dh_nblk / 8 && dh->dh_narrays > 1) {
895		ufsdirhash_free_locked(ip);
896		return;
897	}
898
899	/*
900	 * Remove any `first free' information pertaining to the
901	 * truncated blocks. All blocks we're removing should be
902	 * completely unused.
903	 */
904	if (dh->dh_firstfree[DH_NFSTATS] >= block)
905		dh->dh_firstfree[DH_NFSTATS] = -1;
906	for (i = block; i < dh->dh_dirblks; i++)
907		if (dh->dh_blkfree[i] != DIRBLKSIZ / DIRALIGN)
908			panic("ufsdirhash_dirtrunc: blocks in use");
909	for (i = 0; i < DH_NFSTATS; i++)
910		if (dh->dh_firstfree[i] >= block)
911			panic("ufsdirhash_dirtrunc: first free corrupt");
912	dh->dh_dirblks = block;
913	ufsdirhash_release(dh);
914}
915
916/*
917 * Debugging function to check that the dirhash information about
918 * a directory block matches its actual contents. Panics if a mismatch
919 * is detected.
920 *
921 * On entry, `buf' should point to the start of an in-core
922 * DIRBLKSIZ-sized directory block, and `offset' should contain the
923 * offset from the start of the directory of that block.
924 */
925void
926ufsdirhash_checkblock(struct inode *ip, char *buf, doff_t offset)
927{
928	struct dirhash *dh;
929	struct direct *dp;
930	int block, ffslot, i, nfree;
931
932	if (!ufs_dirhashcheck)
933		return;
934	if ((dh = ufsdirhash_acquire(ip)) == NULL)
935		return;
936
937	block = offset / DIRBLKSIZ;
938	if ((offset & (DIRBLKSIZ - 1)) != 0 || block >= dh->dh_dirblks)
939		panic("ufsdirhash_checkblock: bad offset");
940
941	nfree = 0;
942	for (i = 0; i < DIRBLKSIZ; i += dp->d_reclen) {
943		dp = (struct direct *)(buf + i);
944		if (dp->d_reclen == 0 || i + dp->d_reclen > DIRBLKSIZ)
945			panic("ufsdirhash_checkblock: bad dir");
946
947		if (dp->d_ino == 0) {
948#if 0
949			/*
950			 * XXX entries with d_ino == 0 should only occur
951			 * at the start of a DIRBLKSIZ block. However the
952			 * ufs code is tolerant of such entries at other
953			 * offsets, and fsck does not fix them.
954			 */
955			if (i != 0)
956				panic("ufsdirhash_checkblock: bad dir inode");
957#endif
958			nfree += dp->d_reclen;
959			continue;
960		}
961
962		/* Check that the entry	exists (will panic if it doesn't). */
963		ufsdirhash_findslot(dh, dp->d_name, dp->d_namlen, offset + i);
964
965		nfree += dp->d_reclen - DIRSIZ(0, dp);
966	}
967	if (i != DIRBLKSIZ)
968		panic("ufsdirhash_checkblock: bad dir end");
969
970	if (dh->dh_blkfree[block] * DIRALIGN != nfree)
971		panic("ufsdirhash_checkblock: bad free count");
972
973	ffslot = BLKFREE2IDX(nfree / DIRALIGN);
974	for (i = 0; i <= DH_NFSTATS; i++)
975		if (dh->dh_firstfree[i] == block && i != ffslot)
976			panic("ufsdirhash_checkblock: bad first-free");
977	if (dh->dh_firstfree[ffslot] == -1)
978		panic("ufsdirhash_checkblock: missing first-free entry");
979	ufsdirhash_release(dh);
980}
981
982/*
983 * Hash the specified filename into a dirhash slot.
984 */
985static int
986ufsdirhash_hash(struct dirhash *dh, char *name, int namelen)
987{
988	u_int32_t hash;
989
990	/*
991	 * We hash the name and then some other bit of data that is
992	 * invariant over the dirhash's lifetime. Otherwise names
993	 * differing only in the last byte are placed close to one
994	 * another in the table, which is bad for linear probing.
995	 */
996	hash = fnv_32_buf(name, namelen, FNV1_32_INIT);
997	hash = fnv_32_buf(&dh, sizeof(dh), hash);
998	return (hash % dh->dh_hlen);
999}
1000
1001/*
1002 * Adjust the number of free bytes in the block containing `offset'
1003 * by the value specified by `diff'.
1004 *
1005 * The caller must ensure we have exclusive access to `dh'; normally
1006 * that means that dh_lock should be held, but this is also called
1007 * from ufsdirhash_build() where exclusive access can be assumed.
1008 */
1009static void
1010ufsdirhash_adjfree(struct dirhash *dh, doff_t offset, int diff)
1011{
1012	int block, i, nfidx, ofidx;
1013
1014	/* Update the per-block summary info. */
1015	block = offset / DIRBLKSIZ;
1016	KASSERT(block < dh->dh_nblk && block < dh->dh_dirblks,
1017	     ("dirhash bad offset"));
1018	ofidx = BLKFREE2IDX(dh->dh_blkfree[block]);
1019	dh->dh_blkfree[block] = (int)dh->dh_blkfree[block] + (diff / DIRALIGN);
1020	nfidx = BLKFREE2IDX(dh->dh_blkfree[block]);
1021
1022	/* Update the `first free' list if necessary. */
1023	if (ofidx != nfidx) {
1024		/* If removing, scan forward for the next block. */
1025		if (dh->dh_firstfree[ofidx] == block) {
1026			for (i = block + 1; i < dh->dh_dirblks; i++)
1027				if (BLKFREE2IDX(dh->dh_blkfree[i]) == ofidx)
1028					break;
1029			dh->dh_firstfree[ofidx] = (i < dh->dh_dirblks) ? i : -1;
1030		}
1031
1032		/* Make this the new `first free' if necessary */
1033		if (dh->dh_firstfree[nfidx] > block ||
1034		    dh->dh_firstfree[nfidx] == -1)
1035			dh->dh_firstfree[nfidx] = block;
1036	}
1037}
1038
1039/*
1040 * Find the specified name which should have the specified offset.
1041 * Returns a slot number, and panics on failure.
1042 *
1043 * `dh' must be locked on entry and remains so on return.
1044 */
1045static int
1046ufsdirhash_findslot(struct dirhash *dh, char *name, int namelen, doff_t offset)
1047{
1048	int slot;
1049
1050	DIRHASH_ASSERT_LOCKED(dh);
1051
1052	/* Find the entry. */
1053	KASSERT(dh->dh_hused < dh->dh_hlen, ("dirhash find full"));
1054	slot = ufsdirhash_hash(dh, name, namelen);
1055	while (DH_ENTRY(dh, slot) != offset &&
1056	    DH_ENTRY(dh, slot) != DIRHASH_EMPTY)
1057		slot = WRAPINCR(slot, dh->dh_hlen);
1058	if (DH_ENTRY(dh, slot) != offset)
1059		panic("ufsdirhash_findslot: '%.*s' not found", namelen, name);
1060
1061	return (slot);
1062}
1063
1064/*
1065 * Remove the entry corresponding to the specified slot from the hash array.
1066 *
1067 * `dh' must be locked on entry and remains so on return.
1068 */
1069static void
1070ufsdirhash_delslot(struct dirhash *dh, int slot)
1071{
1072	int i;
1073
1074	DIRHASH_ASSERT_LOCKED(dh);
1075
1076	/* Mark the entry as deleted. */
1077	DH_ENTRY(dh, slot) = DIRHASH_DEL;
1078
1079	/* If this is the end of a chain of DIRHASH_DEL slots, remove them. */
1080	for (i = slot; DH_ENTRY(dh, i) == DIRHASH_DEL; )
1081		i = WRAPINCR(i, dh->dh_hlen);
1082	if (DH_ENTRY(dh, i) == DIRHASH_EMPTY) {
1083		i = WRAPDECR(i, dh->dh_hlen);
1084		while (DH_ENTRY(dh, i) == DIRHASH_DEL) {
1085			DH_ENTRY(dh, i) = DIRHASH_EMPTY;
1086			dh->dh_hused--;
1087			i = WRAPDECR(i, dh->dh_hlen);
1088		}
1089		KASSERT(dh->dh_hused >= 0, ("ufsdirhash_delslot neg hlen"));
1090	}
1091}
1092
1093/*
1094 * Given a directory entry and its offset, find the offset of the
1095 * previous entry in the same DIRBLKSIZ-sized block. Returns an
1096 * offset, or -1 if there is no previous entry in the block or some
1097 * other problem occurred.
1098 */
1099static doff_t
1100ufsdirhash_getprev(struct direct *dirp, doff_t offset)
1101{
1102	struct direct *dp;
1103	char *blkbuf;
1104	doff_t blkoff, prevoff;
1105	int entrypos, i;
1106
1107	blkoff = offset & ~(DIRBLKSIZ - 1);	/* offset of start of block */
1108	entrypos = offset & (DIRBLKSIZ - 1);	/* entry relative to block */
1109	blkbuf = (char *)dirp - entrypos;
1110	prevoff = blkoff;
1111
1112	/* If `offset' is the start of a block, there is no previous entry. */
1113	if (entrypos == 0)
1114		return (-1);
1115
1116	/* Scan from the start of the block until we get to the entry. */
1117	for (i = 0; i < entrypos; i += dp->d_reclen) {
1118		dp = (struct direct *)(blkbuf + i);
1119		if (dp->d_reclen == 0 || i + dp->d_reclen > entrypos)
1120			return (-1);	/* Corrupted directory. */
1121		prevoff = blkoff + i;
1122	}
1123	return (prevoff);
1124}
1125
1126/*
1127 * Try to free up `wanted' bytes by stealing memory from existing
1128 * dirhashes. Returns zero with list locked if successful.
1129 */
1130static int
1131ufsdirhash_recycle(int wanted)
1132{
1133	struct dirhash *dh;
1134	doff_t **hash;
1135	u_int8_t *blkfree;
1136	int i, mem, narrays;
1137
1138	DIRHASHLIST_LOCK();
1139	dh = TAILQ_FIRST(&ufsdirhash_list);
1140	while (wanted + ufs_dirhashmem > ufs_dirhashmaxmem) {
1141		/* Decrement the score; only recycle if it becomes zero. */
1142		if (dh == NULL || --dh->dh_score > 0) {
1143			DIRHASHLIST_UNLOCK();
1144			return (-1);
1145		}
1146		/*
1147		 * If we can't lock it it's in use and we don't want to
1148		 * recycle it anyway.
1149		 */
1150		if (!sx_try_xlock(&dh->dh_lock)) {
1151			dh = TAILQ_NEXT(dh, dh_list);
1152			continue;
1153		}
1154		KASSERT(dh->dh_hash != NULL, ("dirhash: NULL hash on list"));
1155
1156		/* Remove it from the list and detach its memory. */
1157		TAILQ_REMOVE(&ufsdirhash_list, dh, dh_list);
1158		dh->dh_onlist = 0;
1159		hash = dh->dh_hash;
1160		dh->dh_hash = NULL;
1161		blkfree = dh->dh_blkfree;
1162		dh->dh_blkfree = NULL;
1163		narrays = dh->dh_narrays;
1164		mem = dh->dh_memreq;
1165		dh->dh_memreq = 0;
1166
1167		/* Unlock everything, free the detached memory. */
1168		ufsdirhash_release(dh);
1169		DIRHASHLIST_UNLOCK();
1170		for (i = 0; i < narrays; i++)
1171			DIRHASH_BLKFREE(hash[i]);
1172		FREE(hash, M_DIRHASH);
1173		FREE(blkfree, M_DIRHASH);
1174
1175		/* Account for the returned memory, and repeat if necessary. */
1176		DIRHASHLIST_LOCK();
1177		ufs_dirhashmem -= mem;
1178		dh = TAILQ_FIRST(&ufsdirhash_list);
1179	}
1180	/* Success; return with list locked. */
1181	return (0);
1182}
1183
1184
1185void
1186ufsdirhash_init()
1187{
1188	ufsdirhash_zone = uma_zcreate("DIRHASH", DH_NBLKOFF * sizeof(doff_t),
1189	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1190	mtx_init(&ufsdirhash_mtx, "dirhash list", NULL, MTX_DEF);
1191	TAILQ_INIT(&ufsdirhash_list);
1192}
1193
1194void
1195ufsdirhash_uninit()
1196{
1197	KASSERT(TAILQ_EMPTY(&ufsdirhash_list), ("ufsdirhash_uninit"));
1198	uma_zdestroy(ufsdirhash_zone);
1199	mtx_destroy(&ufsdirhash_mtx);
1200}
1201
1202#endif /* UFS_DIRHASH */
1203