ufs_dirhash.c revision 139825
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 139825 2005-01-07 02:29:27Z imp $");
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/sysctl.h>
50#include <vm/uma.h>
51
52#include <ufs/ufs/quota.h>
53#include <ufs/ufs/inode.h>
54#include <ufs/ufs/dir.h>
55#include <ufs/ufs/dirhash.h>
56#include <ufs/ufs/extattr.h>
57#include <ufs/ufs/ufsmount.h>
58#include <ufs/ufs/ufs_extern.h>
59
60#define WRAPINCR(val, limit)	(((val) + 1 == (limit)) ? 0 : ((val) + 1))
61#define WRAPDECR(val, limit)	(((val) == 0) ? ((limit) - 1) : ((val) - 1))
62#define OFSFMT(vp)		((vp)->v_mount->mnt_maxsymlinklen <= 0)
63#define BLKFREE2IDX(n)		((n) > DH_NFSTATS ? DH_NFSTATS : (n))
64
65static MALLOC_DEFINE(M_DIRHASH, "UFS dirhash", "UFS directory hash tables");
66
67SYSCTL_NODE(_vfs, OID_AUTO, ufs, CTLFLAG_RD, 0, "UFS filesystem");
68
69static int ufs_mindirhashsize = DIRBLKSIZ * 5;
70SYSCTL_INT(_vfs_ufs, OID_AUTO, dirhash_minsize, CTLFLAG_RW,
71    &ufs_mindirhashsize,
72    0, "minimum directory size in bytes for which to use hashed lookup");
73static int ufs_dirhashmaxmem = 2 * 1024 * 1024;
74SYSCTL_INT(_vfs_ufs, OID_AUTO, dirhash_maxmem, CTLFLAG_RW, &ufs_dirhashmaxmem,
75    0, "maximum allowed dirhash memory usage");
76static int ufs_dirhashmem;
77SYSCTL_INT(_vfs_ufs, OID_AUTO, dirhash_mem, CTLFLAG_RD, &ufs_dirhashmem,
78    0, "current dirhash memory usage");
79static int ufs_dirhashcheck = 0;
80SYSCTL_INT(_vfs_ufs, OID_AUTO, dirhash_docheck, CTLFLAG_RW, &ufs_dirhashcheck,
81    0, "enable extra sanity tests");
82
83
84static int ufsdirhash_hash(struct dirhash *dh, char *name, int namelen);
85static void ufsdirhash_adjfree(struct dirhash *dh, doff_t offset, int diff);
86static void ufsdirhash_delslot(struct dirhash *dh, int slot);
87static int ufsdirhash_findslot(struct dirhash *dh, char *name, int namelen,
88	   doff_t offset);
89static doff_t ufsdirhash_getprev(struct direct *dp, doff_t offset);
90static int ufsdirhash_recycle(int wanted);
91
92static uma_zone_t	ufsdirhash_zone;
93
94#define DIRHASHLIST_LOCK() 		mtx_lock(&ufsdirhash_mtx)
95#define DIRHASHLIST_UNLOCK() 		mtx_unlock(&ufsdirhash_mtx)
96#define DIRHASH_LOCK(dh)		mtx_lock(&(dh)->dh_mtx)
97#define DIRHASH_UNLOCK(dh) 		mtx_unlock(&(dh)->dh_mtx)
98#define DIRHASH_BLKALLOC_WAITOK() 	uma_zalloc(ufsdirhash_zone, M_WAITOK)
99#define DIRHASH_BLKFREE(ptr) 		uma_zfree(ufsdirhash_zone, (ptr))
100
101/* Dirhash list; recently-used entries are near the tail. */
102static TAILQ_HEAD(, dirhash) ufsdirhash_list;
103
104/* Protects: ufsdirhash_list, `dh_list' field, ufs_dirhashmem. */
105static struct mtx	ufsdirhash_mtx;
106
107/*
108 * Locking order:
109 *	ufsdirhash_mtx
110 *	dh_mtx
111 *
112 * The dh_mtx mutex should be acquired either via the inode lock, or via
113 * ufsdirhash_mtx. Only the owner of the inode may free the associated
114 * dirhash, but anything can steal its memory and set dh_hash to NULL.
115 */
116
117/*
118 * Attempt to build up a hash table for the directory contents in
119 * inode 'ip'. Returns 0 on success, or -1 of the operation failed.
120 */
121int
122ufsdirhash_build(struct inode *ip)
123{
124	struct dirhash *dh;
125	struct buf *bp = NULL;
126	struct direct *ep;
127	struct vnode *vp;
128	doff_t bmask, pos;
129	int dirblocks, i, j, memreqd, nblocks, narrays, nslots, slot;
130
131	/* Check if we can/should use dirhash. */
132	if (ip->i_dirhash == NULL) {
133		if (ip->i_size < ufs_mindirhashsize || OFSFMT(ip->i_vnode))
134			return (-1);
135	} else {
136		/* Hash exists, but sysctls could have changed. */
137		if (ip->i_size < ufs_mindirhashsize ||
138		    ufs_dirhashmem > ufs_dirhashmaxmem) {
139			ufsdirhash_free(ip);
140			return (-1);
141		}
142		/* Check if hash exists and is intact (note: unlocked read). */
143		if (ip->i_dirhash->dh_hash != NULL)
144			return (0);
145		/* Free the old, recycled hash and build a new one. */
146		ufsdirhash_free(ip);
147	}
148
149	/* Don't hash removed directories. */
150	if (ip->i_effnlink == 0)
151		return (-1);
152
153	vp = ip->i_vnode;
154	/* Allocate 50% more entries than this dir size could ever need. */
155	KASSERT(ip->i_size >= DIRBLKSIZ, ("ufsdirhash_build size"));
156	nslots = ip->i_size / DIRECTSIZ(1);
157	nslots = (nslots * 3 + 1) / 2;
158	narrays = howmany(nslots, DH_NBLKOFF);
159	nslots = narrays * DH_NBLKOFF;
160	dirblocks = howmany(ip->i_size, DIRBLKSIZ);
161	nblocks = (dirblocks * 3 + 1) / 2;
162
163	memreqd = sizeof(*dh) + narrays * sizeof(*dh->dh_hash) +
164	    narrays * DH_NBLKOFF * sizeof(**dh->dh_hash) +
165	    nblocks * sizeof(*dh->dh_blkfree);
166	DIRHASHLIST_LOCK();
167	if (memreqd + ufs_dirhashmem > ufs_dirhashmaxmem) {
168		DIRHASHLIST_UNLOCK();
169		if (memreqd > ufs_dirhashmaxmem / 2)
170			return (-1);
171
172		/* Try to free some space. */
173		if (ufsdirhash_recycle(memreqd) != 0)
174			return (-1);
175		/* Enough was freed, and list has been locked. */
176	}
177	ufs_dirhashmem += memreqd;
178	DIRHASHLIST_UNLOCK();
179
180	/*
181	 * Use non-blocking mallocs so that we will revert to a linear
182	 * lookup on failure rather than potentially blocking forever.
183	 */
184	MALLOC(dh, struct dirhash *, sizeof *dh, M_DIRHASH, M_NOWAIT | M_ZERO);
185	if (dh == NULL) {
186		DIRHASHLIST_LOCK();
187		ufs_dirhashmem -= memreqd;
188		DIRHASHLIST_UNLOCK();
189		return (-1);
190	}
191	MALLOC(dh->dh_hash, doff_t **, narrays * sizeof(dh->dh_hash[0]),
192	    M_DIRHASH, M_NOWAIT | M_ZERO);
193	MALLOC(dh->dh_blkfree, u_int8_t *, nblocks * sizeof(dh->dh_blkfree[0]),
194	    M_DIRHASH, M_NOWAIT);
195	if (dh->dh_hash == NULL || dh->dh_blkfree == NULL)
196		goto fail;
197	for (i = 0; i < narrays; i++) {
198		if ((dh->dh_hash[i] = DIRHASH_BLKALLOC_WAITOK()) == NULL)
199			goto fail;
200		for (j = 0; j < DH_NBLKOFF; j++)
201			dh->dh_hash[i][j] = DIRHASH_EMPTY;
202	}
203
204	/* Initialise the hash table and block statistics. */
205	mtx_init(&dh->dh_mtx, "dirhash", NULL, MTX_DEF);
206	dh->dh_narrays = narrays;
207	dh->dh_hlen = nslots;
208	dh->dh_nblk = nblocks;
209	dh->dh_dirblks = dirblocks;
210	for (i = 0; i < dirblocks; i++)
211		dh->dh_blkfree[i] = DIRBLKSIZ / DIRALIGN;
212	for (i = 0; i < DH_NFSTATS; i++)
213		dh->dh_firstfree[i] = -1;
214	dh->dh_firstfree[DH_NFSTATS] = 0;
215	dh->dh_seqopt = 0;
216	dh->dh_seqoff = 0;
217	dh->dh_score = DH_SCOREINIT;
218	ip->i_dirhash = dh;
219
220	bmask = VFSTOUFS(vp->v_mount)->um_mountp->mnt_stat.f_iosize - 1;
221	pos = 0;
222	while (pos < ip->i_size) {
223		/* If necessary, get the next directory block. */
224		if ((pos & bmask) == 0) {
225			if (bp != NULL)
226				brelse(bp);
227			if (UFS_BLKATOFF(vp, (off_t)pos, NULL, &bp) != 0)
228				goto fail;
229		}
230
231		/* Add this entry to the hash. */
232		ep = (struct direct *)((char *)bp->b_data + (pos & bmask));
233		if (ep->d_reclen == 0 || ep->d_reclen >
234		    DIRBLKSIZ - (pos & (DIRBLKSIZ - 1))) {
235			/* Corrupted directory. */
236			brelse(bp);
237			goto fail;
238		}
239		if (ep->d_ino != 0) {
240			/* Add the entry (simplified ufsdirhash_add). */
241			slot = ufsdirhash_hash(dh, ep->d_name, ep->d_namlen);
242			while (DH_ENTRY(dh, slot) != DIRHASH_EMPTY)
243				slot = WRAPINCR(slot, dh->dh_hlen);
244			dh->dh_hused++;
245			DH_ENTRY(dh, slot) = pos;
246			ufsdirhash_adjfree(dh, pos, -DIRSIZ(0, ep));
247		}
248		pos += ep->d_reclen;
249	}
250
251	if (bp != NULL)
252		brelse(bp);
253	DIRHASHLIST_LOCK();
254	TAILQ_INSERT_TAIL(&ufsdirhash_list, dh, dh_list);
255	dh->dh_onlist = 1;
256	DIRHASHLIST_UNLOCK();
257	return (0);
258
259fail:
260	if (dh->dh_hash != NULL) {
261		for (i = 0; i < narrays; i++)
262			if (dh->dh_hash[i] != NULL)
263				DIRHASH_BLKFREE(dh->dh_hash[i]);
264		FREE(dh->dh_hash, M_DIRHASH);
265	}
266	if (dh->dh_blkfree != NULL)
267		FREE(dh->dh_blkfree, M_DIRHASH);
268	FREE(dh, M_DIRHASH);
269	ip->i_dirhash = NULL;
270	DIRHASHLIST_LOCK();
271	ufs_dirhashmem -= memreqd;
272	DIRHASHLIST_UNLOCK();
273	return (-1);
274}
275
276/*
277 * Free any hash table associated with inode 'ip'.
278 */
279void
280ufsdirhash_free(struct inode *ip)
281{
282	struct dirhash *dh;
283	int i, mem;
284
285	if ((dh = ip->i_dirhash) == NULL)
286		return;
287	DIRHASHLIST_LOCK();
288	DIRHASH_LOCK(dh);
289	if (dh->dh_onlist)
290		TAILQ_REMOVE(&ufsdirhash_list, dh, dh_list);
291	DIRHASH_UNLOCK(dh);
292	DIRHASHLIST_UNLOCK();
293
294	/* The dirhash pointed to by 'dh' is exclusively ours now. */
295
296	mem = sizeof(*dh);
297	if (dh->dh_hash != NULL) {
298		for (i = 0; i < dh->dh_narrays; i++)
299			DIRHASH_BLKFREE(dh->dh_hash[i]);
300		FREE(dh->dh_hash, M_DIRHASH);
301		FREE(dh->dh_blkfree, M_DIRHASH);
302		mem += dh->dh_narrays * sizeof(*dh->dh_hash) +
303		    dh->dh_narrays * DH_NBLKOFF * sizeof(**dh->dh_hash) +
304		    dh->dh_nblk * sizeof(*dh->dh_blkfree);
305	}
306	mtx_destroy(&dh->dh_mtx);
307	FREE(dh, M_DIRHASH);
308	ip->i_dirhash = NULL;
309
310	DIRHASHLIST_LOCK();
311	ufs_dirhashmem -= mem;
312	DIRHASHLIST_UNLOCK();
313}
314
315/*
316 * Find the offset of the specified name within the given inode.
317 * Returns 0 on success, ENOENT if the entry does not exist, or
318 * EJUSTRETURN if the caller should revert to a linear search.
319 *
320 * If successful, the directory offset is stored in *offp, and a
321 * pointer to a struct buf containing the entry is stored in *bpp. If
322 * prevoffp is non-NULL, the offset of the previous entry within
323 * the DIRBLKSIZ-sized block is stored in *prevoffp (if the entry
324 * is the first in a block, the start of the block is used).
325 */
326int
327ufsdirhash_lookup(struct inode *ip, char *name, int namelen, doff_t *offp,
328    struct buf **bpp, doff_t *prevoffp)
329{
330	struct dirhash *dh, *dh_next;
331	struct direct *dp;
332	struct vnode *vp;
333	struct buf *bp;
334	doff_t blkoff, bmask, offset, prevoff;
335	int i, slot;
336
337	if ((dh = ip->i_dirhash) == NULL)
338		return (EJUSTRETURN);
339	/*
340	 * Move this dirhash towards the end of the list if it has a
341	 * score higher than the next entry, and acquire the dh_mtx.
342	 * Optimise the case where it's already the last by performing
343	 * an unlocked read of the TAILQ_NEXT pointer.
344	 *
345	 * In both cases, end up holding just dh_mtx.
346	 */
347	if (TAILQ_NEXT(dh, dh_list) != NULL) {
348		DIRHASHLIST_LOCK();
349		DIRHASH_LOCK(dh);
350		/*
351		 * If the new score will be greater than that of the next
352		 * entry, then move this entry past it. With both mutexes
353		 * held, dh_next won't go away, but its dh_score could
354		 * change; that's not important since it is just a hint.
355		 */
356		if (dh->dh_hash != NULL &&
357		    (dh_next = TAILQ_NEXT(dh, dh_list)) != NULL &&
358		    dh->dh_score >= dh_next->dh_score) {
359			KASSERT(dh->dh_onlist, ("dirhash: not on list"));
360			TAILQ_REMOVE(&ufsdirhash_list, dh, dh_list);
361			TAILQ_INSERT_AFTER(&ufsdirhash_list, dh_next, dh,
362			    dh_list);
363		}
364		DIRHASHLIST_UNLOCK();
365	} else {
366		/* Already the last, though that could change as we wait. */
367		DIRHASH_LOCK(dh);
368	}
369	if (dh->dh_hash == NULL) {
370		DIRHASH_UNLOCK(dh);
371		ufsdirhash_free(ip);
372		return (EJUSTRETURN);
373	}
374
375	/* Update the score. */
376	if (dh->dh_score < DH_SCOREMAX)
377		dh->dh_score++;
378
379	vp = ip->i_vnode;
380	bmask = VFSTOUFS(vp->v_mount)->um_mountp->mnt_stat.f_iosize - 1;
381	blkoff = -1;
382	bp = NULL;
383restart:
384	slot = ufsdirhash_hash(dh, name, namelen);
385
386	if (dh->dh_seqopt) {
387		/*
388		 * Sequential access optimisation. dh_seqoff contains the
389		 * offset of the directory entry immediately following
390		 * the last entry that was looked up. Check if this offset
391		 * appears in the hash chain for the name we are looking for.
392		 */
393		for (i = slot; (offset = DH_ENTRY(dh, i)) != DIRHASH_EMPTY;
394		    i = WRAPINCR(i, dh->dh_hlen))
395			if (offset == dh->dh_seqoff)
396				break;
397		if (offset == dh->dh_seqoff) {
398			/*
399			 * We found an entry with the expected offset. This
400			 * is probably the entry we want, but if not, the
401			 * code below will turn off seqoff and retry.
402			 */
403			slot = i;
404		} else
405			dh->dh_seqopt = 0;
406	}
407
408	for (; (offset = DH_ENTRY(dh, slot)) != DIRHASH_EMPTY;
409	    slot = WRAPINCR(slot, dh->dh_hlen)) {
410		if (offset == DIRHASH_DEL)
411			continue;
412		DIRHASH_UNLOCK(dh);
413
414		if (offset < 0 || offset >= ip->i_size)
415			panic("ufsdirhash_lookup: bad offset in hash array");
416		if ((offset & ~bmask) != blkoff) {
417			if (bp != NULL)
418				brelse(bp);
419			blkoff = offset & ~bmask;
420			if (UFS_BLKATOFF(vp, (off_t)blkoff, NULL, &bp) != 0)
421				return (EJUSTRETURN);
422		}
423		dp = (struct direct *)(bp->b_data + (offset & bmask));
424		if (dp->d_reclen == 0 || dp->d_reclen >
425		    DIRBLKSIZ - (offset & (DIRBLKSIZ - 1))) {
426			/* Corrupted directory. */
427			brelse(bp);
428			return (EJUSTRETURN);
429		}
430		if (dp->d_namlen == namelen &&
431		    bcmp(dp->d_name, name, namelen) == 0) {
432			/* Found. Get the prev offset if needed. */
433			if (prevoffp != NULL) {
434				if (offset & (DIRBLKSIZ - 1)) {
435					prevoff = ufsdirhash_getprev(dp,
436					    offset);
437					if (prevoff == -1) {
438						brelse(bp);
439						return (EJUSTRETURN);
440					}
441				} else
442					prevoff = offset;
443				*prevoffp = prevoff;
444			}
445
446			/* Check for sequential access, and update offset. */
447			if (dh->dh_seqopt == 0 && dh->dh_seqoff == offset)
448				dh->dh_seqopt = 1;
449			dh->dh_seqoff = offset + DIRSIZ(0, dp);
450
451			*bpp = bp;
452			*offp = offset;
453			return (0);
454		}
455
456		DIRHASH_LOCK(dh);
457		if (dh->dh_hash == NULL) {
458			DIRHASH_UNLOCK(dh);
459			if (bp != NULL)
460				brelse(bp);
461			ufsdirhash_free(ip);
462			return (EJUSTRETURN);
463		}
464		/*
465		 * When the name doesn't match in the seqopt case, go back
466		 * and search normally.
467		 */
468		if (dh->dh_seqopt) {
469			dh->dh_seqopt = 0;
470			goto restart;
471		}
472	}
473	DIRHASH_UNLOCK(dh);
474	if (bp != NULL)
475		brelse(bp);
476	return (ENOENT);
477}
478
479/*
480 * Find a directory block with room for 'slotneeded' bytes. Returns
481 * the offset of the directory entry that begins the free space.
482 * This will either be the offset of an existing entry that has free
483 * space at the end, or the offset of an entry with d_ino == 0 at
484 * the start of a DIRBLKSIZ block.
485 *
486 * To use the space, the caller may need to compact existing entries in
487 * the directory. The total number of bytes in all of the entries involved
488 * in the compaction is stored in *slotsize. In other words, all of
489 * the entries that must be compacted are exactly contained in the
490 * region beginning at the returned offset and spanning *slotsize bytes.
491 *
492 * Returns -1 if no space was found, indicating that the directory
493 * must be extended.
494 */
495doff_t
496ufsdirhash_findfree(struct inode *ip, int slotneeded, int *slotsize)
497{
498	struct direct *dp;
499	struct dirhash *dh;
500	struct buf *bp;
501	doff_t pos, slotstart;
502	int dirblock, error, freebytes, i;
503
504	if ((dh = ip->i_dirhash) == NULL)
505		return (-1);
506	DIRHASH_LOCK(dh);
507	if (dh->dh_hash == NULL) {
508		DIRHASH_UNLOCK(dh);
509		ufsdirhash_free(ip);
510		return (-1);
511	}
512
513	/* Find a directory block with the desired free space. */
514	dirblock = -1;
515	for (i = howmany(slotneeded, DIRALIGN); i <= DH_NFSTATS; i++)
516		if ((dirblock = dh->dh_firstfree[i]) != -1)
517			break;
518	if (dirblock == -1) {
519		DIRHASH_UNLOCK(dh);
520		return (-1);
521	}
522
523	KASSERT(dirblock < dh->dh_nblk &&
524	    dh->dh_blkfree[dirblock] >= howmany(slotneeded, DIRALIGN),
525	    ("ufsdirhash_findfree: bad stats"));
526	DIRHASH_UNLOCK(dh);
527	pos = dirblock * DIRBLKSIZ;
528	error = UFS_BLKATOFF(ip->i_vnode, (off_t)pos, (char **)&dp, &bp);
529	if (error)
530		return (-1);
531
532	/* Find the first entry with free space. */
533	for (i = 0; i < DIRBLKSIZ; ) {
534		if (dp->d_reclen == 0) {
535			brelse(bp);
536			return (-1);
537		}
538		if (dp->d_ino == 0 || dp->d_reclen > DIRSIZ(0, dp))
539			break;
540		i += dp->d_reclen;
541		dp = (struct direct *)((char *)dp + dp->d_reclen);
542	}
543	if (i > DIRBLKSIZ) {
544		brelse(bp);
545		return (-1);
546	}
547	slotstart = pos + i;
548
549	/* Find the range of entries needed to get enough space */
550	freebytes = 0;
551	while (i < DIRBLKSIZ && freebytes < slotneeded) {
552		freebytes += dp->d_reclen;
553		if (dp->d_ino != 0)
554			freebytes -= DIRSIZ(0, dp);
555		if (dp->d_reclen == 0) {
556			brelse(bp);
557			return (-1);
558		}
559		i += dp->d_reclen;
560		dp = (struct direct *)((char *)dp + dp->d_reclen);
561	}
562	if (i > DIRBLKSIZ) {
563		brelse(bp);
564		return (-1);
565	}
566	if (freebytes < slotneeded)
567		panic("ufsdirhash_findfree: free mismatch");
568	brelse(bp);
569	*slotsize = pos + i - slotstart;
570	return (slotstart);
571}
572
573/*
574 * Return the start of the unused space at the end of a directory, or
575 * -1 if there are no trailing unused blocks.
576 */
577doff_t
578ufsdirhash_enduseful(struct inode *ip)
579{
580
581	struct dirhash *dh;
582	int i;
583
584	if ((dh = ip->i_dirhash) == NULL)
585		return (-1);
586	DIRHASH_LOCK(dh);
587	if (dh->dh_hash == NULL) {
588		DIRHASH_UNLOCK(dh);
589		ufsdirhash_free(ip);
590		return (-1);
591	}
592
593	if (dh->dh_blkfree[dh->dh_dirblks - 1] != DIRBLKSIZ / DIRALIGN) {
594		DIRHASH_UNLOCK(dh);
595		return (-1);
596	}
597
598	for (i = dh->dh_dirblks - 1; i >= 0; i--)
599		if (dh->dh_blkfree[i] != DIRBLKSIZ / DIRALIGN)
600			break;
601	DIRHASH_UNLOCK(dh);
602	return ((doff_t)(i + 1) * DIRBLKSIZ);
603}
604
605/*
606 * Insert information into the hash about a new directory entry. dirp
607 * points to a struct direct containing the entry, and offset specifies
608 * the offset of this entry.
609 */
610void
611ufsdirhash_add(struct inode *ip, struct direct *dirp, doff_t offset)
612{
613	struct dirhash *dh;
614	int slot;
615
616	if ((dh = ip->i_dirhash) == NULL)
617		return;
618	DIRHASH_LOCK(dh);
619	if (dh->dh_hash == NULL) {
620		DIRHASH_UNLOCK(dh);
621		ufsdirhash_free(ip);
622		return;
623	}
624
625	KASSERT(offset < dh->dh_dirblks * DIRBLKSIZ,
626	    ("ufsdirhash_add: bad offset"));
627	/*
628	 * Normal hash usage is < 66%. If the usage gets too high then
629	 * remove the hash entirely and let it be rebuilt later.
630	 */
631	if (dh->dh_hused >= (dh->dh_hlen * 3) / 4) {
632		DIRHASH_UNLOCK(dh);
633		ufsdirhash_free(ip);
634		return;
635	}
636
637	/* Find a free hash slot (empty or deleted), and add the entry. */
638	slot = ufsdirhash_hash(dh, dirp->d_name, dirp->d_namlen);
639	while (DH_ENTRY(dh, slot) >= 0)
640		slot = WRAPINCR(slot, dh->dh_hlen);
641	if (DH_ENTRY(dh, slot) == DIRHASH_EMPTY)
642		dh->dh_hused++;
643	DH_ENTRY(dh, slot) = offset;
644
645	/* Update the per-block summary info. */
646	ufsdirhash_adjfree(dh, offset, -DIRSIZ(0, dirp));
647	DIRHASH_UNLOCK(dh);
648}
649
650/*
651 * Remove the specified directory entry from the hash. The entry to remove
652 * is defined by the name in `dirp', which must exist at the specified
653 * `offset' within the directory.
654 */
655void
656ufsdirhash_remove(struct inode *ip, struct direct *dirp, doff_t offset)
657{
658	struct dirhash *dh;
659	int slot;
660
661	if ((dh = ip->i_dirhash) == NULL)
662		return;
663	DIRHASH_LOCK(dh);
664	if (dh->dh_hash == NULL) {
665		DIRHASH_UNLOCK(dh);
666		ufsdirhash_free(ip);
667		return;
668	}
669
670	KASSERT(offset < dh->dh_dirblks * DIRBLKSIZ,
671	    ("ufsdirhash_remove: bad offset"));
672	/* Find the entry */
673	slot = ufsdirhash_findslot(dh, dirp->d_name, dirp->d_namlen, offset);
674
675	/* Remove the hash entry. */
676	ufsdirhash_delslot(dh, slot);
677
678	/* Update the per-block summary info. */
679	ufsdirhash_adjfree(dh, offset, DIRSIZ(0, dirp));
680	DIRHASH_UNLOCK(dh);
681}
682
683/*
684 * Change the offset associated with a directory entry in the hash. Used
685 * when compacting directory blocks.
686 */
687void
688ufsdirhash_move(struct inode *ip, struct direct *dirp, doff_t oldoff,
689    doff_t newoff)
690{
691	struct dirhash *dh;
692	int slot;
693
694	if ((dh = ip->i_dirhash) == NULL)
695		return;
696	DIRHASH_LOCK(dh);
697	if (dh->dh_hash == NULL) {
698		DIRHASH_UNLOCK(dh);
699		ufsdirhash_free(ip);
700		return;
701	}
702
703	KASSERT(oldoff < dh->dh_dirblks * DIRBLKSIZ &&
704	    newoff < dh->dh_dirblks * DIRBLKSIZ,
705	    ("ufsdirhash_move: bad offset"));
706	/* Find the entry, and update the offset. */
707	slot = ufsdirhash_findslot(dh, dirp->d_name, dirp->d_namlen, oldoff);
708	DH_ENTRY(dh, slot) = newoff;
709	DIRHASH_UNLOCK(dh);
710}
711
712/*
713 * Inform dirhash that the directory has grown by one block that
714 * begins at offset (i.e. the new length is offset + DIRBLKSIZ).
715 */
716void
717ufsdirhash_newblk(struct inode *ip, doff_t offset)
718{
719	struct dirhash *dh;
720	int block;
721
722	if ((dh = ip->i_dirhash) == NULL)
723		return;
724	DIRHASH_LOCK(dh);
725	if (dh->dh_hash == NULL) {
726		DIRHASH_UNLOCK(dh);
727		ufsdirhash_free(ip);
728		return;
729	}
730
731	KASSERT(offset == dh->dh_dirblks * DIRBLKSIZ,
732	    ("ufsdirhash_newblk: bad offset"));
733	block = offset / DIRBLKSIZ;
734	if (block >= dh->dh_nblk) {
735		/* Out of space; must rebuild. */
736		DIRHASH_UNLOCK(dh);
737		ufsdirhash_free(ip);
738		return;
739	}
740	dh->dh_dirblks = block + 1;
741
742	/* Account for the new free block. */
743	dh->dh_blkfree[block] = DIRBLKSIZ / DIRALIGN;
744	if (dh->dh_firstfree[DH_NFSTATS] == -1)
745		dh->dh_firstfree[DH_NFSTATS] = block;
746	DIRHASH_UNLOCK(dh);
747}
748
749/*
750 * Inform dirhash that the directory is being truncated.
751 */
752void
753ufsdirhash_dirtrunc(struct inode *ip, doff_t offset)
754{
755	struct dirhash *dh;
756	int block, i;
757
758	if ((dh = ip->i_dirhash) == NULL)
759		return;
760	DIRHASH_LOCK(dh);
761	if (dh->dh_hash == NULL) {
762		DIRHASH_UNLOCK(dh);
763		ufsdirhash_free(ip);
764		return;
765	}
766
767	KASSERT(offset <= dh->dh_dirblks * DIRBLKSIZ,
768	    ("ufsdirhash_dirtrunc: bad offset"));
769	block = howmany(offset, DIRBLKSIZ);
770	/*
771	 * If the directory shrinks to less than 1/8 of dh_nblk blocks
772	 * (about 20% of its original size due to the 50% extra added in
773	 * ufsdirhash_build) then free it, and let the caller rebuild
774	 * if necessary.
775	 */
776	if (block < dh->dh_nblk / 8 && dh->dh_narrays > 1) {
777		DIRHASH_UNLOCK(dh);
778		ufsdirhash_free(ip);
779		return;
780	}
781
782	/*
783	 * Remove any `first free' information pertaining to the
784	 * truncated blocks. All blocks we're removing should be
785	 * completely unused.
786	 */
787	if (dh->dh_firstfree[DH_NFSTATS] >= block)
788		dh->dh_firstfree[DH_NFSTATS] = -1;
789	for (i = block; i < dh->dh_dirblks; i++)
790		if (dh->dh_blkfree[i] != DIRBLKSIZ / DIRALIGN)
791			panic("ufsdirhash_dirtrunc: blocks in use");
792	for (i = 0; i < DH_NFSTATS; i++)
793		if (dh->dh_firstfree[i] >= block)
794			panic("ufsdirhash_dirtrunc: first free corrupt");
795	dh->dh_dirblks = block;
796	DIRHASH_UNLOCK(dh);
797}
798
799/*
800 * Debugging function to check that the dirhash information about
801 * a directory block matches its actual contents. Panics if a mismatch
802 * is detected.
803 *
804 * On entry, `buf' should point to the start of an in-core
805 * DIRBLKSIZ-sized directory block, and `offset' should contain the
806 * offset from the start of the directory of that block.
807 */
808void
809ufsdirhash_checkblock(struct inode *ip, char *buf, doff_t offset)
810{
811	struct dirhash *dh;
812	struct direct *dp;
813	int block, ffslot, i, nfree;
814
815	if (!ufs_dirhashcheck)
816		return;
817	if ((dh = ip->i_dirhash) == NULL)
818		return;
819	DIRHASH_LOCK(dh);
820	if (dh->dh_hash == NULL) {
821		DIRHASH_UNLOCK(dh);
822		ufsdirhash_free(ip);
823		return;
824	}
825
826	block = offset / DIRBLKSIZ;
827	if ((offset & (DIRBLKSIZ - 1)) != 0 || block >= dh->dh_dirblks)
828		panic("ufsdirhash_checkblock: bad offset");
829
830	nfree = 0;
831	for (i = 0; i < DIRBLKSIZ; i += dp->d_reclen) {
832		dp = (struct direct *)(buf + i);
833		if (dp->d_reclen == 0 || i + dp->d_reclen > DIRBLKSIZ)
834			panic("ufsdirhash_checkblock: bad dir");
835
836		if (dp->d_ino == 0) {
837#if 0
838			/*
839			 * XXX entries with d_ino == 0 should only occur
840			 * at the start of a DIRBLKSIZ block. However the
841			 * ufs code is tolerant of such entries at other
842			 * offsets, and fsck does not fix them.
843			 */
844			if (i != 0)
845				panic("ufsdirhash_checkblock: bad dir inode");
846#endif
847			nfree += dp->d_reclen;
848			continue;
849		}
850
851		/* Check that the entry	exists (will panic if it doesn't). */
852		ufsdirhash_findslot(dh, dp->d_name, dp->d_namlen, offset + i);
853
854		nfree += dp->d_reclen - DIRSIZ(0, dp);
855	}
856	if (i != DIRBLKSIZ)
857		panic("ufsdirhash_checkblock: bad dir end");
858
859	if (dh->dh_blkfree[block] * DIRALIGN != nfree)
860		panic("ufsdirhash_checkblock: bad free count");
861
862	ffslot = BLKFREE2IDX(nfree / DIRALIGN);
863	for (i = 0; i <= DH_NFSTATS; i++)
864		if (dh->dh_firstfree[i] == block && i != ffslot)
865			panic("ufsdirhash_checkblock: bad first-free");
866	if (dh->dh_firstfree[ffslot] == -1)
867		panic("ufsdirhash_checkblock: missing first-free entry");
868	DIRHASH_UNLOCK(dh);
869}
870
871/*
872 * Hash the specified filename into a dirhash slot.
873 */
874static int
875ufsdirhash_hash(struct dirhash *dh, char *name, int namelen)
876{
877	u_int32_t hash;
878
879	/*
880	 * We hash the name and then some other bit of data that is
881	 * invariant over the dirhash's lifetime. Otherwise names
882	 * differing only in the last byte are placed close to one
883	 * another in the table, which is bad for linear probing.
884	 */
885	hash = fnv_32_buf(name, namelen, FNV1_32_INIT);
886	hash = fnv_32_buf(&dh, sizeof(dh), hash);
887	return (hash % dh->dh_hlen);
888}
889
890/*
891 * Adjust the number of free bytes in the block containing `offset'
892 * by the value specified by `diff'.
893 *
894 * The caller must ensure we have exclusive access to `dh'; normally
895 * that means that dh_mtx should be held, but this is also called
896 * from ufsdirhash_build() where exclusive access can be assumed.
897 */
898static void
899ufsdirhash_adjfree(struct dirhash *dh, doff_t offset, int diff)
900{
901	int block, i, nfidx, ofidx;
902
903	/* Update the per-block summary info. */
904	block = offset / DIRBLKSIZ;
905	KASSERT(block < dh->dh_nblk && block < dh->dh_dirblks,
906	     ("dirhash bad offset"));
907	ofidx = BLKFREE2IDX(dh->dh_blkfree[block]);
908	dh->dh_blkfree[block] = (int)dh->dh_blkfree[block] + (diff / DIRALIGN);
909	nfidx = BLKFREE2IDX(dh->dh_blkfree[block]);
910
911	/* Update the `first free' list if necessary. */
912	if (ofidx != nfidx) {
913		/* If removing, scan forward for the next block. */
914		if (dh->dh_firstfree[ofidx] == block) {
915			for (i = block + 1; i < dh->dh_dirblks; i++)
916				if (BLKFREE2IDX(dh->dh_blkfree[i]) == ofidx)
917					break;
918			dh->dh_firstfree[ofidx] = (i < dh->dh_dirblks) ? i : -1;
919		}
920
921		/* Make this the new `first free' if necessary */
922		if (dh->dh_firstfree[nfidx] > block ||
923		    dh->dh_firstfree[nfidx] == -1)
924			dh->dh_firstfree[nfidx] = block;
925	}
926}
927
928/*
929 * Find the specified name which should have the specified offset.
930 * Returns a slot number, and panics on failure.
931 *
932 * `dh' must be locked on entry and remains so on return.
933 */
934static int
935ufsdirhash_findslot(struct dirhash *dh, char *name, int namelen, doff_t offset)
936{
937	int slot;
938
939	mtx_assert(&dh->dh_mtx, MA_OWNED);
940
941	/* Find the entry. */
942	KASSERT(dh->dh_hused < dh->dh_hlen, ("dirhash find full"));
943	slot = ufsdirhash_hash(dh, name, namelen);
944	while (DH_ENTRY(dh, slot) != offset &&
945	    DH_ENTRY(dh, slot) != DIRHASH_EMPTY)
946		slot = WRAPINCR(slot, dh->dh_hlen);
947	if (DH_ENTRY(dh, slot) != offset)
948		panic("ufsdirhash_findslot: '%.*s' not found", namelen, name);
949
950	return (slot);
951}
952
953/*
954 * Remove the entry corresponding to the specified slot from the hash array.
955 *
956 * `dh' must be locked on entry and remains so on return.
957 */
958static void
959ufsdirhash_delslot(struct dirhash *dh, int slot)
960{
961	int i;
962
963	mtx_assert(&dh->dh_mtx, MA_OWNED);
964
965	/* Mark the entry as deleted. */
966	DH_ENTRY(dh, slot) = DIRHASH_DEL;
967
968	/* If this is the end of a chain of DIRHASH_DEL slots, remove them. */
969	for (i = slot; DH_ENTRY(dh, i) == DIRHASH_DEL; )
970		i = WRAPINCR(i, dh->dh_hlen);
971	if (DH_ENTRY(dh, i) == DIRHASH_EMPTY) {
972		i = WRAPDECR(i, dh->dh_hlen);
973		while (DH_ENTRY(dh, i) == DIRHASH_DEL) {
974			DH_ENTRY(dh, i) = DIRHASH_EMPTY;
975			dh->dh_hused--;
976			i = WRAPDECR(i, dh->dh_hlen);
977		}
978		KASSERT(dh->dh_hused >= 0, ("ufsdirhash_delslot neg hlen"));
979	}
980}
981
982/*
983 * Given a directory entry and its offset, find the offset of the
984 * previous entry in the same DIRBLKSIZ-sized block. Returns an
985 * offset, or -1 if there is no previous entry in the block or some
986 * other problem occurred.
987 */
988static doff_t
989ufsdirhash_getprev(struct direct *dirp, doff_t offset)
990{
991	struct direct *dp;
992	char *blkbuf;
993	doff_t blkoff, prevoff;
994	int entrypos, i;
995
996	blkoff = offset & ~(DIRBLKSIZ - 1);	/* offset of start of block */
997	entrypos = offset & (DIRBLKSIZ - 1);	/* entry relative to block */
998	blkbuf = (char *)dirp - entrypos;
999	prevoff = blkoff;
1000
1001	/* If `offset' is the start of a block, there is no previous entry. */
1002	if (entrypos == 0)
1003		return (-1);
1004
1005	/* Scan from the start of the block until we get to the entry. */
1006	for (i = 0; i < entrypos; i += dp->d_reclen) {
1007		dp = (struct direct *)(blkbuf + i);
1008		if (dp->d_reclen == 0 || i + dp->d_reclen > entrypos)
1009			return (-1);	/* Corrupted directory. */
1010		prevoff = blkoff + i;
1011	}
1012	return (prevoff);
1013}
1014
1015/*
1016 * Try to free up `wanted' bytes by stealing memory from existing
1017 * dirhashes. Returns zero with list locked if successful.
1018 */
1019static int
1020ufsdirhash_recycle(int wanted)
1021{
1022	struct dirhash *dh;
1023	doff_t **hash;
1024	u_int8_t *blkfree;
1025	int i, mem, narrays;
1026
1027	DIRHASHLIST_LOCK();
1028	while (wanted + ufs_dirhashmem > ufs_dirhashmaxmem) {
1029		/* Find a dirhash, and lock it. */
1030		if ((dh = TAILQ_FIRST(&ufsdirhash_list)) == NULL) {
1031			DIRHASHLIST_UNLOCK();
1032			return (-1);
1033		}
1034		DIRHASH_LOCK(dh);
1035		KASSERT(dh->dh_hash != NULL, ("dirhash: NULL hash on list"));
1036
1037		/* Decrement the score; only recycle if it becomes zero. */
1038		if (--dh->dh_score > 0) {
1039			DIRHASH_UNLOCK(dh);
1040			DIRHASHLIST_UNLOCK();
1041			return (-1);
1042		}
1043
1044		/* Remove it from the list and detach its memory. */
1045		TAILQ_REMOVE(&ufsdirhash_list, dh, dh_list);
1046		dh->dh_onlist = 0;
1047		hash = dh->dh_hash;
1048		dh->dh_hash = NULL;
1049		blkfree = dh->dh_blkfree;
1050		dh->dh_blkfree = NULL;
1051		narrays = dh->dh_narrays;
1052		mem = narrays * sizeof(*dh->dh_hash) +
1053		    narrays * DH_NBLKOFF * sizeof(**dh->dh_hash) +
1054		    dh->dh_nblk * sizeof(*dh->dh_blkfree);
1055
1056		/* Unlock everything, free the detached memory. */
1057		DIRHASH_UNLOCK(dh);
1058		DIRHASHLIST_UNLOCK();
1059		for (i = 0; i < narrays; i++)
1060			DIRHASH_BLKFREE(hash[i]);
1061		FREE(hash, M_DIRHASH);
1062		FREE(blkfree, M_DIRHASH);
1063
1064		/* Account for the returned memory, and repeat if necessary. */
1065		DIRHASHLIST_LOCK();
1066		ufs_dirhashmem -= mem;
1067	}
1068	/* Success; return with list locked. */
1069	return (0);
1070}
1071
1072
1073void
1074ufsdirhash_init()
1075{
1076	ufsdirhash_zone = uma_zcreate("DIRHASH", DH_NBLKOFF * sizeof(doff_t),
1077	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1078	mtx_init(&ufsdirhash_mtx, "dirhash list", NULL, MTX_DEF);
1079	TAILQ_INIT(&ufsdirhash_list);
1080}
1081
1082void
1083ufsdirhash_uninit()
1084{
1085	KASSERT(TAILQ_EMPTY(&ufsdirhash_list), ("ufsdirhash_uninit"));
1086	uma_zdestroy(ufsdirhash_zone);
1087	mtx_destroy(&ufsdirhash_mtx);
1088}
1089
1090#endif /* UFS_DIRHASH */
1091