ufs_dirhash.c revision 183280
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 183280 2008-09-22 20:53:22Z 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	 * Remove the hash from the list since we are going to free its
465	 * memory.
466	 */
467	DIRHASHLIST_LOCK();
468	if (dh->dh_onlist)
469		TAILQ_REMOVE(&ufsdirhash_list, dh, dh_list);
470	ufs_dirhashmem -= dh->dh_memreq;
471	DIRHASHLIST_UNLOCK();
472
473	/*
474	 * At this point, any waiters for the lock should hold their
475	 * own reference on the dirhash structure.  They will drop
476	 * that reference once they grab the vnode interlock and see
477	 * that ip->i_dirhash is NULL.
478	 */
479	sx_xunlock(&dh->dh_lock);
480
481	/*
482	 * Handle partially recycled as well as fully constructed hashes.
483	 */
484	if (dh->dh_hash != NULL) {
485		for (i = 0; i < dh->dh_narrays; i++)
486			if (dh->dh_hash[i] != NULL)
487				DIRHASH_BLKFREE(dh->dh_hash[i]);
488		FREE(dh->dh_hash, M_DIRHASH);
489		if (dh->dh_blkfree != NULL)
490			FREE(dh->dh_blkfree, M_DIRHASH);
491	}
492
493	/*
494	 * Drop the inode's reference to the data structure.
495	 */
496	ufsdirhash_drop(dh);
497}
498
499/*
500 * Find the offset of the specified name within the given inode.
501 * Returns 0 on success, ENOENT if the entry does not exist, or
502 * EJUSTRETURN if the caller should revert to a linear search.
503 *
504 * If successful, the directory offset is stored in *offp, and a
505 * pointer to a struct buf containing the entry is stored in *bpp. If
506 * prevoffp is non-NULL, the offset of the previous entry within
507 * the DIRBLKSIZ-sized block is stored in *prevoffp (if the entry
508 * is the first in a block, the start of the block is used).
509 *
510 * Must be called with the hash locked.  Returns with the hash unlocked.
511 */
512int
513ufsdirhash_lookup(struct inode *ip, char *name, int namelen, doff_t *offp,
514    struct buf **bpp, doff_t *prevoffp)
515{
516	struct dirhash *dh, *dh_next;
517	struct direct *dp;
518	struct vnode *vp;
519	struct buf *bp;
520	doff_t blkoff, bmask, offset, prevoff;
521	int i, slot;
522	int error;
523
524	dh = ip->i_dirhash;
525	KASSERT(dh != NULL && dh->dh_hash != NULL,
526	    ("ufsdirhash_lookup: Invalid dirhash %p\n", dh));
527	DIRHASH_ASSERT_LOCKED(dh);
528	/*
529	 * Move this dirhash towards the end of the list if it has a
530	 * score higher than the next entry, and acquire the dh_lock.
531	 */
532	DIRHASHLIST_LOCK();
533	if (TAILQ_NEXT(dh, dh_list) != NULL) {
534		/*
535		 * If the new score will be greater than that of the next
536		 * entry, then move this entry past it. With both mutexes
537		 * held, dh_next won't go away, but its dh_score could
538		 * change; that's not important since it is just a hint.
539		 */
540		if ((dh_next = TAILQ_NEXT(dh, dh_list)) != NULL &&
541		    dh->dh_score >= dh_next->dh_score) {
542			KASSERT(dh->dh_onlist, ("dirhash: not on list"));
543			TAILQ_REMOVE(&ufsdirhash_list, dh, dh_list);
544			TAILQ_INSERT_AFTER(&ufsdirhash_list, dh_next, dh,
545			    dh_list);
546		}
547	}
548	/* Update the score. */
549	if (dh->dh_score < DH_SCOREMAX)
550		dh->dh_score++;
551	DIRHASHLIST_UNLOCK();
552
553	vp = ip->i_vnode;
554	bmask = VFSTOUFS(vp->v_mount)->um_mountp->mnt_stat.f_iosize - 1;
555	blkoff = -1;
556	bp = NULL;
557restart:
558	slot = ufsdirhash_hash(dh, name, namelen);
559
560	if (dh->dh_seqopt) {
561		/*
562		 * Sequential access optimisation. dh_seqoff contains the
563		 * offset of the directory entry immediately following
564		 * the last entry that was looked up. Check if this offset
565		 * appears in the hash chain for the name we are looking for.
566		 */
567		for (i = slot; (offset = DH_ENTRY(dh, i)) != DIRHASH_EMPTY;
568		    i = WRAPINCR(i, dh->dh_hlen))
569			if (offset == dh->dh_seqoff)
570				break;
571		if (offset == dh->dh_seqoff) {
572			/*
573			 * We found an entry with the expected offset. This
574			 * is probably the entry we want, but if not, the
575			 * code below will turn off seqopt and retry.
576			 */
577			slot = i;
578		} else
579			dh->dh_seqopt = 0;
580	}
581
582	for (; (offset = DH_ENTRY(dh, slot)) != DIRHASH_EMPTY;
583	    slot = WRAPINCR(slot, dh->dh_hlen)) {
584		if (offset == DIRHASH_DEL)
585			continue;
586		if (offset < 0 || offset >= ip->i_size)
587			panic("ufsdirhash_lookup: bad offset in hash array");
588		if ((offset & ~bmask) != blkoff) {
589			if (bp != NULL)
590				brelse(bp);
591			blkoff = offset & ~bmask;
592			if (UFS_BLKATOFF(vp, (off_t)blkoff, NULL, &bp) != 0) {
593				error = EJUSTRETURN;
594				goto fail;
595			}
596		}
597		dp = (struct direct *)(bp->b_data + (offset & bmask));
598		if (dp->d_reclen == 0 || dp->d_reclen >
599		    DIRBLKSIZ - (offset & (DIRBLKSIZ - 1))) {
600			/* Corrupted directory. */
601			error = EJUSTRETURN;
602			goto fail;
603		}
604		if (dp->d_namlen == namelen &&
605		    bcmp(dp->d_name, name, namelen) == 0) {
606			/* Found. Get the prev offset if needed. */
607			if (prevoffp != NULL) {
608				if (offset & (DIRBLKSIZ - 1)) {
609					prevoff = ufsdirhash_getprev(dp,
610					    offset);
611					if (prevoff == -1) {
612						error = EJUSTRETURN;
613						goto fail;
614					}
615				} else
616					prevoff = offset;
617				*prevoffp = prevoff;
618			}
619
620			/* Check for sequential access, and update offset. */
621			if (dh->dh_seqopt == 0 && dh->dh_seqoff == offset)
622				dh->dh_seqopt = 1;
623			dh->dh_seqoff = offset + DIRSIZ(0, dp);
624			*bpp = bp;
625			*offp = offset;
626			ufsdirhash_release(dh);
627			return (0);
628		}
629
630		/*
631		 * When the name doesn't match in the seqopt case, go back
632		 * and search normally.
633		 */
634		if (dh->dh_seqopt) {
635			dh->dh_seqopt = 0;
636			goto restart;
637		}
638	}
639	error = ENOENT;
640fail:
641	ufsdirhash_release(dh);
642	if (bp != NULL)
643		brelse(bp);
644	return (error);
645}
646
647/*
648 * Find a directory block with room for 'slotneeded' bytes. Returns
649 * the offset of the directory entry that begins the free space.
650 * This will either be the offset of an existing entry that has free
651 * space at the end, or the offset of an entry with d_ino == 0 at
652 * the start of a DIRBLKSIZ block.
653 *
654 * To use the space, the caller may need to compact existing entries in
655 * the directory. The total number of bytes in all of the entries involved
656 * in the compaction is stored in *slotsize. In other words, all of
657 * the entries that must be compacted are exactly contained in the
658 * region beginning at the returned offset and spanning *slotsize bytes.
659 *
660 * Returns -1 if no space was found, indicating that the directory
661 * must be extended.
662 */
663doff_t
664ufsdirhash_findfree(struct inode *ip, int slotneeded, int *slotsize)
665{
666	struct direct *dp;
667	struct dirhash *dh;
668	struct buf *bp;
669	doff_t pos, slotstart;
670	int dirblock, error, freebytes, i;
671
672	dh = ip->i_dirhash;
673	KASSERT(dh != NULL && dh->dh_hash != NULL,
674	    ("ufsdirhash_findfree: Invalid dirhash %p\n", dh));
675	DIRHASH_ASSERT_LOCKED(dh);
676
677	/* Find a directory block with the desired free space. */
678	dirblock = -1;
679	for (i = howmany(slotneeded, DIRALIGN); i <= DH_NFSTATS; i++)
680		if ((dirblock = dh->dh_firstfree[i]) != -1)
681			break;
682	if (dirblock == -1)
683		return (-1);
684
685	KASSERT(dirblock < dh->dh_nblk &&
686	    dh->dh_blkfree[dirblock] >= howmany(slotneeded, DIRALIGN),
687	    ("ufsdirhash_findfree: bad stats"));
688	pos = dirblock * DIRBLKSIZ;
689	error = UFS_BLKATOFF(ip->i_vnode, (off_t)pos, (char **)&dp, &bp);
690	if (error)
691		return (-1);
692
693	/* Find the first entry with free space. */
694	for (i = 0; i < DIRBLKSIZ; ) {
695		if (dp->d_reclen == 0) {
696			brelse(bp);
697			return (-1);
698		}
699		if (dp->d_ino == 0 || dp->d_reclen > DIRSIZ(0, dp))
700			break;
701		i += dp->d_reclen;
702		dp = (struct direct *)((char *)dp + dp->d_reclen);
703	}
704	if (i > DIRBLKSIZ) {
705		brelse(bp);
706		return (-1);
707	}
708	slotstart = pos + i;
709
710	/* Find the range of entries needed to get enough space */
711	freebytes = 0;
712	while (i < DIRBLKSIZ && freebytes < slotneeded) {
713		freebytes += dp->d_reclen;
714		if (dp->d_ino != 0)
715			freebytes -= DIRSIZ(0, dp);
716		if (dp->d_reclen == 0) {
717			brelse(bp);
718			return (-1);
719		}
720		i += dp->d_reclen;
721		dp = (struct direct *)((char *)dp + dp->d_reclen);
722	}
723	if (i > DIRBLKSIZ) {
724		brelse(bp);
725		return (-1);
726	}
727	if (freebytes < slotneeded)
728		panic("ufsdirhash_findfree: free mismatch");
729	brelse(bp);
730	*slotsize = pos + i - slotstart;
731	return (slotstart);
732}
733
734/*
735 * Return the start of the unused space at the end of a directory, or
736 * -1 if there are no trailing unused blocks.
737 */
738doff_t
739ufsdirhash_enduseful(struct inode *ip)
740{
741
742	struct dirhash *dh;
743	int i;
744
745	dh = ip->i_dirhash;
746	DIRHASH_ASSERT_LOCKED(dh);
747	KASSERT(dh != NULL && dh->dh_hash != NULL,
748	    ("ufsdirhash_enduseful: Invalid dirhash %p\n", dh));
749
750	if (dh->dh_blkfree[dh->dh_dirblks - 1] != DIRBLKSIZ / DIRALIGN)
751		return (-1);
752
753	for (i = dh->dh_dirblks - 1; i >= 0; i--)
754		if (dh->dh_blkfree[i] != DIRBLKSIZ / DIRALIGN)
755			break;
756
757	return ((doff_t)(i + 1) * DIRBLKSIZ);
758}
759
760/*
761 * Insert information into the hash about a new directory entry. dirp
762 * points to a struct direct containing the entry, and offset specifies
763 * the offset of this entry.
764 */
765void
766ufsdirhash_add(struct inode *ip, struct direct *dirp, doff_t offset)
767{
768	struct dirhash *dh;
769	int slot;
770
771	if ((dh = ufsdirhash_acquire(ip)) == NULL)
772		return;
773
774	KASSERT(offset < dh->dh_dirblks * DIRBLKSIZ,
775	    ("ufsdirhash_add: bad offset"));
776	/*
777	 * Normal hash usage is < 66%. If the usage gets too high then
778	 * remove the hash entirely and let it be rebuilt later.
779	 */
780	if (dh->dh_hused >= (dh->dh_hlen * 3) / 4) {
781		ufsdirhash_free_locked(ip);
782		return;
783	}
784
785	/* Find a free hash slot (empty or deleted), and add the entry. */
786	slot = ufsdirhash_hash(dh, dirp->d_name, dirp->d_namlen);
787	while (DH_ENTRY(dh, slot) >= 0)
788		slot = WRAPINCR(slot, dh->dh_hlen);
789	if (DH_ENTRY(dh, slot) == DIRHASH_EMPTY)
790		dh->dh_hused++;
791	DH_ENTRY(dh, slot) = offset;
792
793	/* Update the per-block summary info. */
794	ufsdirhash_adjfree(dh, offset, -DIRSIZ(0, dirp));
795	ufsdirhash_release(dh);
796}
797
798/*
799 * Remove the specified directory entry from the hash. The entry to remove
800 * is defined by the name in `dirp', which must exist at the specified
801 * `offset' within the directory.
802 */
803void
804ufsdirhash_remove(struct inode *ip, struct direct *dirp, doff_t offset)
805{
806	struct dirhash *dh;
807	int slot;
808
809	if ((dh = ufsdirhash_acquire(ip)) == NULL)
810		return;
811
812	KASSERT(offset < dh->dh_dirblks * DIRBLKSIZ,
813	    ("ufsdirhash_remove: bad offset"));
814	/* Find the entry */
815	slot = ufsdirhash_findslot(dh, dirp->d_name, dirp->d_namlen, offset);
816
817	/* Remove the hash entry. */
818	ufsdirhash_delslot(dh, slot);
819
820	/* Update the per-block summary info. */
821	ufsdirhash_adjfree(dh, offset, DIRSIZ(0, dirp));
822	ufsdirhash_release(dh);
823}
824
825/*
826 * Change the offset associated with a directory entry in the hash. Used
827 * when compacting directory blocks.
828 */
829void
830ufsdirhash_move(struct inode *ip, struct direct *dirp, doff_t oldoff,
831    doff_t newoff)
832{
833	struct dirhash *dh;
834	int slot;
835
836	if ((dh = ufsdirhash_acquire(ip)) == NULL)
837		return;
838
839	KASSERT(oldoff < dh->dh_dirblks * DIRBLKSIZ &&
840	    newoff < dh->dh_dirblks * DIRBLKSIZ,
841	    ("ufsdirhash_move: bad offset"));
842	/* Find the entry, and update the offset. */
843	slot = ufsdirhash_findslot(dh, dirp->d_name, dirp->d_namlen, oldoff);
844	DH_ENTRY(dh, slot) = newoff;
845	ufsdirhash_release(dh);
846}
847
848/*
849 * Inform dirhash that the directory has grown by one block that
850 * begins at offset (i.e. the new length is offset + DIRBLKSIZ).
851 */
852void
853ufsdirhash_newblk(struct inode *ip, doff_t offset)
854{
855	struct dirhash *dh;
856	int block;
857
858	if ((dh = ufsdirhash_acquire(ip)) == NULL)
859		return;
860
861	KASSERT(offset == dh->dh_dirblks * DIRBLKSIZ,
862	    ("ufsdirhash_newblk: bad offset"));
863	block = offset / DIRBLKSIZ;
864	if (block >= dh->dh_nblk) {
865		/* Out of space; must rebuild. */
866		ufsdirhash_free_locked(ip);
867		return;
868	}
869	dh->dh_dirblks = block + 1;
870
871	/* Account for the new free block. */
872	dh->dh_blkfree[block] = DIRBLKSIZ / DIRALIGN;
873	if (dh->dh_firstfree[DH_NFSTATS] == -1)
874		dh->dh_firstfree[DH_NFSTATS] = block;
875	ufsdirhash_release(dh);
876}
877
878/*
879 * Inform dirhash that the directory is being truncated.
880 */
881void
882ufsdirhash_dirtrunc(struct inode *ip, doff_t offset)
883{
884	struct dirhash *dh;
885	int block, i;
886
887	if ((dh = ufsdirhash_acquire(ip)) == NULL)
888		return;
889
890	KASSERT(offset <= dh->dh_dirblks * DIRBLKSIZ,
891	    ("ufsdirhash_dirtrunc: bad offset"));
892	block = howmany(offset, DIRBLKSIZ);
893	/*
894	 * If the directory shrinks to less than 1/8 of dh_nblk blocks
895	 * (about 20% of its original size due to the 50% extra added in
896	 * ufsdirhash_build) then free it, and let the caller rebuild
897	 * if necessary.
898	 */
899	if (block < dh->dh_nblk / 8 && dh->dh_narrays > 1) {
900		ufsdirhash_free_locked(ip);
901		return;
902	}
903
904	/*
905	 * Remove any `first free' information pertaining to the
906	 * truncated blocks. All blocks we're removing should be
907	 * completely unused.
908	 */
909	if (dh->dh_firstfree[DH_NFSTATS] >= block)
910		dh->dh_firstfree[DH_NFSTATS] = -1;
911	for (i = block; i < dh->dh_dirblks; i++)
912		if (dh->dh_blkfree[i] != DIRBLKSIZ / DIRALIGN)
913			panic("ufsdirhash_dirtrunc: blocks in use");
914	for (i = 0; i < DH_NFSTATS; i++)
915		if (dh->dh_firstfree[i] >= block)
916			panic("ufsdirhash_dirtrunc: first free corrupt");
917	dh->dh_dirblks = block;
918	ufsdirhash_release(dh);
919}
920
921/*
922 * Debugging function to check that the dirhash information about
923 * a directory block matches its actual contents. Panics if a mismatch
924 * is detected.
925 *
926 * On entry, `buf' should point to the start of an in-core
927 * DIRBLKSIZ-sized directory block, and `offset' should contain the
928 * offset from the start of the directory of that block.
929 */
930void
931ufsdirhash_checkblock(struct inode *ip, char *buf, doff_t offset)
932{
933	struct dirhash *dh;
934	struct direct *dp;
935	int block, ffslot, i, nfree;
936
937	if (!ufs_dirhashcheck)
938		return;
939	if ((dh = ufsdirhash_acquire(ip)) == NULL)
940		return;
941
942	block = offset / DIRBLKSIZ;
943	if ((offset & (DIRBLKSIZ - 1)) != 0 || block >= dh->dh_dirblks)
944		panic("ufsdirhash_checkblock: bad offset");
945
946	nfree = 0;
947	for (i = 0; i < DIRBLKSIZ; i += dp->d_reclen) {
948		dp = (struct direct *)(buf + i);
949		if (dp->d_reclen == 0 || i + dp->d_reclen > DIRBLKSIZ)
950			panic("ufsdirhash_checkblock: bad dir");
951
952		if (dp->d_ino == 0) {
953#if 0
954			/*
955			 * XXX entries with d_ino == 0 should only occur
956			 * at the start of a DIRBLKSIZ block. However the
957			 * ufs code is tolerant of such entries at other
958			 * offsets, and fsck does not fix them.
959			 */
960			if (i != 0)
961				panic("ufsdirhash_checkblock: bad dir inode");
962#endif
963			nfree += dp->d_reclen;
964			continue;
965		}
966
967		/* Check that the entry	exists (will panic if it doesn't). */
968		ufsdirhash_findslot(dh, dp->d_name, dp->d_namlen, offset + i);
969
970		nfree += dp->d_reclen - DIRSIZ(0, dp);
971	}
972	if (i != DIRBLKSIZ)
973		panic("ufsdirhash_checkblock: bad dir end");
974
975	if (dh->dh_blkfree[block] * DIRALIGN != nfree)
976		panic("ufsdirhash_checkblock: bad free count");
977
978	ffslot = BLKFREE2IDX(nfree / DIRALIGN);
979	for (i = 0; i <= DH_NFSTATS; i++)
980		if (dh->dh_firstfree[i] == block && i != ffslot)
981			panic("ufsdirhash_checkblock: bad first-free");
982	if (dh->dh_firstfree[ffslot] == -1)
983		panic("ufsdirhash_checkblock: missing first-free entry");
984	ufsdirhash_release(dh);
985}
986
987/*
988 * Hash the specified filename into a dirhash slot.
989 */
990static int
991ufsdirhash_hash(struct dirhash *dh, char *name, int namelen)
992{
993	u_int32_t hash;
994
995	/*
996	 * We hash the name and then some other bit of data that is
997	 * invariant over the dirhash's lifetime. Otherwise names
998	 * differing only in the last byte are placed close to one
999	 * another in the table, which is bad for linear probing.
1000	 */
1001	hash = fnv_32_buf(name, namelen, FNV1_32_INIT);
1002	hash = fnv_32_buf(&dh, sizeof(dh), hash);
1003	return (hash % dh->dh_hlen);
1004}
1005
1006/*
1007 * Adjust the number of free bytes in the block containing `offset'
1008 * by the value specified by `diff'.
1009 *
1010 * The caller must ensure we have exclusive access to `dh'; normally
1011 * that means that dh_lock should be held, but this is also called
1012 * from ufsdirhash_build() where exclusive access can be assumed.
1013 */
1014static void
1015ufsdirhash_adjfree(struct dirhash *dh, doff_t offset, int diff)
1016{
1017	int block, i, nfidx, ofidx;
1018
1019	/* Update the per-block summary info. */
1020	block = offset / DIRBLKSIZ;
1021	KASSERT(block < dh->dh_nblk && block < dh->dh_dirblks,
1022	     ("dirhash bad offset"));
1023	ofidx = BLKFREE2IDX(dh->dh_blkfree[block]);
1024	dh->dh_blkfree[block] = (int)dh->dh_blkfree[block] + (diff / DIRALIGN);
1025	nfidx = BLKFREE2IDX(dh->dh_blkfree[block]);
1026
1027	/* Update the `first free' list if necessary. */
1028	if (ofidx != nfidx) {
1029		/* If removing, scan forward for the next block. */
1030		if (dh->dh_firstfree[ofidx] == block) {
1031			for (i = block + 1; i < dh->dh_dirblks; i++)
1032				if (BLKFREE2IDX(dh->dh_blkfree[i]) == ofidx)
1033					break;
1034			dh->dh_firstfree[ofidx] = (i < dh->dh_dirblks) ? i : -1;
1035		}
1036
1037		/* Make this the new `first free' if necessary */
1038		if (dh->dh_firstfree[nfidx] > block ||
1039		    dh->dh_firstfree[nfidx] == -1)
1040			dh->dh_firstfree[nfidx] = block;
1041	}
1042}
1043
1044/*
1045 * Find the specified name which should have the specified offset.
1046 * Returns a slot number, and panics on failure.
1047 *
1048 * `dh' must be locked on entry and remains so on return.
1049 */
1050static int
1051ufsdirhash_findslot(struct dirhash *dh, char *name, int namelen, doff_t offset)
1052{
1053	int slot;
1054
1055	DIRHASH_ASSERT_LOCKED(dh);
1056
1057	/* Find the entry. */
1058	KASSERT(dh->dh_hused < dh->dh_hlen, ("dirhash find full"));
1059	slot = ufsdirhash_hash(dh, name, namelen);
1060	while (DH_ENTRY(dh, slot) != offset &&
1061	    DH_ENTRY(dh, slot) != DIRHASH_EMPTY)
1062		slot = WRAPINCR(slot, dh->dh_hlen);
1063	if (DH_ENTRY(dh, slot) != offset)
1064		panic("ufsdirhash_findslot: '%.*s' not found", namelen, name);
1065
1066	return (slot);
1067}
1068
1069/*
1070 * Remove the entry corresponding to the specified slot from the hash array.
1071 *
1072 * `dh' must be locked on entry and remains so on return.
1073 */
1074static void
1075ufsdirhash_delslot(struct dirhash *dh, int slot)
1076{
1077	int i;
1078
1079	DIRHASH_ASSERT_LOCKED(dh);
1080
1081	/* Mark the entry as deleted. */
1082	DH_ENTRY(dh, slot) = DIRHASH_DEL;
1083
1084	/* If this is the end of a chain of DIRHASH_DEL slots, remove them. */
1085	for (i = slot; DH_ENTRY(dh, i) == DIRHASH_DEL; )
1086		i = WRAPINCR(i, dh->dh_hlen);
1087	if (DH_ENTRY(dh, i) == DIRHASH_EMPTY) {
1088		i = WRAPDECR(i, dh->dh_hlen);
1089		while (DH_ENTRY(dh, i) == DIRHASH_DEL) {
1090			DH_ENTRY(dh, i) = DIRHASH_EMPTY;
1091			dh->dh_hused--;
1092			i = WRAPDECR(i, dh->dh_hlen);
1093		}
1094		KASSERT(dh->dh_hused >= 0, ("ufsdirhash_delslot neg hlen"));
1095	}
1096}
1097
1098/*
1099 * Given a directory entry and its offset, find the offset of the
1100 * previous entry in the same DIRBLKSIZ-sized block. Returns an
1101 * offset, or -1 if there is no previous entry in the block or some
1102 * other problem occurred.
1103 */
1104static doff_t
1105ufsdirhash_getprev(struct direct *dirp, doff_t offset)
1106{
1107	struct direct *dp;
1108	char *blkbuf;
1109	doff_t blkoff, prevoff;
1110	int entrypos, i;
1111
1112	blkoff = offset & ~(DIRBLKSIZ - 1);	/* offset of start of block */
1113	entrypos = offset & (DIRBLKSIZ - 1);	/* entry relative to block */
1114	blkbuf = (char *)dirp - entrypos;
1115	prevoff = blkoff;
1116
1117	/* If `offset' is the start of a block, there is no previous entry. */
1118	if (entrypos == 0)
1119		return (-1);
1120
1121	/* Scan from the start of the block until we get to the entry. */
1122	for (i = 0; i < entrypos; i += dp->d_reclen) {
1123		dp = (struct direct *)(blkbuf + i);
1124		if (dp->d_reclen == 0 || i + dp->d_reclen > entrypos)
1125			return (-1);	/* Corrupted directory. */
1126		prevoff = blkoff + i;
1127	}
1128	return (prevoff);
1129}
1130
1131/*
1132 * Try to free up `wanted' bytes by stealing memory from existing
1133 * dirhashes. Returns zero with list locked if successful.
1134 */
1135static int
1136ufsdirhash_recycle(int wanted)
1137{
1138	struct dirhash *dh;
1139	doff_t **hash;
1140	u_int8_t *blkfree;
1141	int i, mem, narrays;
1142
1143	DIRHASHLIST_LOCK();
1144	dh = TAILQ_FIRST(&ufsdirhash_list);
1145	while (wanted + ufs_dirhashmem > ufs_dirhashmaxmem) {
1146		/* Decrement the score; only recycle if it becomes zero. */
1147		if (dh == NULL || --dh->dh_score > 0) {
1148			DIRHASHLIST_UNLOCK();
1149			return (-1);
1150		}
1151		/*
1152		 * If we can't lock it it's in use and we don't want to
1153		 * recycle it anyway.
1154		 */
1155		if (!sx_try_xlock(&dh->dh_lock)) {
1156			dh = TAILQ_NEXT(dh, dh_list);
1157			continue;
1158		}
1159		KASSERT(dh->dh_hash != NULL, ("dirhash: NULL hash on list"));
1160
1161		/* Remove it from the list and detach its memory. */
1162		TAILQ_REMOVE(&ufsdirhash_list, dh, dh_list);
1163		dh->dh_onlist = 0;
1164		hash = dh->dh_hash;
1165		dh->dh_hash = NULL;
1166		blkfree = dh->dh_blkfree;
1167		dh->dh_blkfree = NULL;
1168		narrays = dh->dh_narrays;
1169		mem = dh->dh_memreq;
1170		dh->dh_memreq = 0;
1171
1172		/* Unlock everything, free the detached memory. */
1173		ufsdirhash_release(dh);
1174		DIRHASHLIST_UNLOCK();
1175		for (i = 0; i < narrays; i++)
1176			DIRHASH_BLKFREE(hash[i]);
1177		FREE(hash, M_DIRHASH);
1178		FREE(blkfree, M_DIRHASH);
1179
1180		/* Account for the returned memory, and repeat if necessary. */
1181		DIRHASHLIST_LOCK();
1182		ufs_dirhashmem -= mem;
1183		dh = TAILQ_FIRST(&ufsdirhash_list);
1184	}
1185	/* Success; return with list locked. */
1186	return (0);
1187}
1188
1189
1190void
1191ufsdirhash_init()
1192{
1193	ufsdirhash_zone = uma_zcreate("DIRHASH", DH_NBLKOFF * sizeof(doff_t),
1194	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1195	mtx_init(&ufsdirhash_mtx, "dirhash list", NULL, MTX_DEF);
1196	TAILQ_INIT(&ufsdirhash_list);
1197}
1198
1199void
1200ufsdirhash_uninit()
1201{
1202	KASSERT(TAILQ_EMPTY(&ufsdirhash_list), ("ufsdirhash_uninit"));
1203	uma_zdestroy(ufsdirhash_zone);
1204	mtx_destroy(&ufsdirhash_mtx);
1205}
1206
1207#endif /* UFS_DIRHASH */
1208