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