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