Whamcloud - gitweb
d676005a5738ef3dc1d114c56c1c3ef31c4958c6
[fs/lustre-release.git] / libcfs / libcfs / hash.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  * GPL HEADER START
5  *
6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 only,
10  * as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License version 2 for more details (a copy is included
16  * in the LICENSE file that accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License
19  * version 2 along with this program; If not, see
20  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
21  *
22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
23  * CA 95054 USA or visit www.sun.com if you need additional information or
24  * have any questions.
25  *
26  * GPL HEADER END
27  */
28 /*
29  * Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
30  * Use is subject to license terms.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * libcfs/libcfs/hash.c
37  *
38  * Implement a hash class for hash process in lustre system.
39  *
40  * Author: YuZhangyong <yzy@clusterfs.com>
41  *
42  * 2008-08-15: Brian Behlendorf <behlendorf1@llnl.gov>
43  * - Simplified API and improved documentation
44  * - Added per-hash feature flags:
45  *   * CFS_HASH_DEBUG additional validation
46  *   * CFS_HASH_REHASH dynamic rehashing
47  * - Added per-hash statistics
48  * - General performance enhancements
49  *
50  * 2009-07-31: Liang Zhen <zhen.liang@sun.com>
51  * - move all stuff to libcfs
52  * - don't allow cur_bits != max_bits without setting of CFS_HASH_REHASH
53  * - ignore hs_rwlock if without CFS_HASH_REHASH setting
54  * - buckets are allocated one by one(intead of contiguous memory),
55  *   to avoid unnecessary cacheline conflict
56  *
57  * 2010-03-01: Liang Zhen <zhen.liang@sun.com>
58  * - "bucket" is a group of hlist_head now, user can speicify bucket size
59  *   by bkt_bits of cfs_hash_create(), all hlist_heads in a bucket share
60  *   one lock for reducing memory overhead.
61  *
62  * - support lockless hash, caller will take care of locks:
63  *   avoid lock overhead for hash tables that are already protected
64  *   by locking in the caller for another reason
65  *
66  * - support both spin_lock/rwlock for bucket:
67  *   overhead of spinlock contention is lower than read/write
68  *   contention of rwlock, so using spinlock to serialize operations on
69  *   bucket is more reasonable for those frequently changed hash tables
70  *
71  * - support one-single lock mode:
72  *   one lock to protect all hash operations to avoid overhead of
73  *   multiple locks if hash table is always small
74  *
75  * - removed a lot of unnecessary addref & decref on hash element:
76  *   addref & decref are atomic operations in many use-cases which
77  *   are expensive.
78  *
79  * - support non-blocking cfs_hash_add() and cfs_hash_findadd():
80  *   some lustre use-cases require these functions to be strictly
81  *   non-blocking, we need to schedule required rehash on a different
82  *   thread on those cases.
83  *
84  * - safer rehash on large hash table
85  *   In old implementation, rehash function will exclusively lock the
86  *   hash table and finish rehash in one batch, it's dangerous on SMP
87  *   system because rehash millions of elements could take long time.
88  *   New implemented rehash can release lock and relax CPU in middle
89  *   of rehash, it's safe for another thread to search/change on the
90  *   hash table even it's in rehasing.
91  *
92  * - support two different refcount modes
93  *   . hash table has refcount on element
94  *   . hash table doesn't change refcount on adding/removing element
95  *
96  * - support long name hash table (for param-tree)
97  *
98  * - fix a bug for cfs_hash_rehash_key:
99  *   in old implementation, cfs_hash_rehash_key could screw up the
100  *   hash-table because @key is overwritten without any protection.
101  *   Now we need user to define hs_keycpy for those rehash enabled
102  *   hash tables, cfs_hash_rehash_key will overwrite hash-key
103  *   inside lock by calling hs_keycpy.
104  *
105  * - better hash iteration:
106  *   Now we support both locked iteration & lockless iteration of hash
107  *   table. Also, user can break the iteration by return 1 in callback.
108  */
109
110 #include <libcfs/libcfs.h>
111
112 #if CFS_HASH_DEBUG_LEVEL >= CFS_HASH_DEBUG_1
113 static unsigned int warn_on_depth = 0;
114 CFS_MODULE_PARM(warn_on_depth, "i", uint, 0644,
115                 "warning when hash depth is high.");
116 #endif
117
118 static inline void
119 cfs_hash_nl_lock(cfs_hash_lock_t *lock, int exclusive) {}
120
121 static inline void
122 cfs_hash_nl_unlock(cfs_hash_lock_t *lock, int exclusive) {}
123
124 static inline void
125 cfs_hash_spin_lock(cfs_hash_lock_t *lock, int exclusive)
126 {
127         cfs_spin_lock(&lock->spin);
128 }
129
130 static inline void
131 cfs_hash_spin_unlock(cfs_hash_lock_t *lock, int exclusive)
132 {
133         cfs_spin_unlock(&lock->spin);
134 }
135
136 static inline void
137 cfs_hash_rw_lock(cfs_hash_lock_t *lock, int exclusive)
138 {
139         if (!exclusive)
140                 cfs_read_lock(&lock->rw);
141         else
142                 cfs_write_lock(&lock->rw);
143 }
144
145 static inline void
146 cfs_hash_rw_unlock(cfs_hash_lock_t *lock, int exclusive)
147 {
148         if (!exclusive)
149                 cfs_read_unlock(&lock->rw);
150         else
151                 cfs_write_unlock(&lock->rw);
152 }
153
154 /** No lock hash */
155 static cfs_hash_lock_ops_t cfs_hash_nl_lops =
156 {
157         .hs_lock        = cfs_hash_nl_lock,
158         .hs_unlock      = cfs_hash_nl_unlock,
159         .hs_bkt_lock    = cfs_hash_nl_lock,
160         .hs_bkt_unlock  = cfs_hash_nl_unlock,
161 };
162
163 /** no bucket lock, one spinlock to protect everything */
164 static cfs_hash_lock_ops_t cfs_hash_nbl_lops =
165 {
166         .hs_lock        = cfs_hash_spin_lock,
167         .hs_unlock      = cfs_hash_spin_unlock,
168         .hs_bkt_lock    = cfs_hash_nl_lock,
169         .hs_bkt_unlock  = cfs_hash_nl_unlock,
170 };
171
172 /** spin bucket lock, rehash is enabled */
173 static cfs_hash_lock_ops_t cfs_hash_bkt_spin_lops =
174 {
175         .hs_lock        = cfs_hash_rw_lock,
176         .hs_unlock      = cfs_hash_rw_unlock,
177         .hs_bkt_lock    = cfs_hash_spin_lock,
178         .hs_bkt_unlock  = cfs_hash_spin_unlock,
179 };
180
181 /** rw bucket lock, rehash is enabled */
182 static cfs_hash_lock_ops_t cfs_hash_bkt_rw_lops =
183 {
184         .hs_lock        = cfs_hash_rw_lock,
185         .hs_unlock      = cfs_hash_rw_unlock,
186         .hs_bkt_lock    = cfs_hash_rw_lock,
187         .hs_bkt_unlock  = cfs_hash_rw_unlock,
188 };
189
190 /** spin bucket lock, rehash is disabled */
191 static cfs_hash_lock_ops_t cfs_hash_nr_bkt_spin_lops =
192 {
193         .hs_lock        = cfs_hash_nl_lock,
194         .hs_unlock      = cfs_hash_nl_unlock,
195         .hs_bkt_lock    = cfs_hash_spin_lock,
196         .hs_bkt_unlock  = cfs_hash_spin_unlock,
197 };
198
199 /** rw bucket lock, rehash is disabled */
200 static cfs_hash_lock_ops_t cfs_hash_nr_bkt_rw_lops =
201 {
202         .hs_lock        = cfs_hash_nl_lock,
203         .hs_unlock      = cfs_hash_nl_unlock,
204         .hs_bkt_lock    = cfs_hash_rw_lock,
205         .hs_bkt_unlock  = cfs_hash_rw_unlock,
206 };
207
208 static void
209 cfs_hash_lock_setup(cfs_hash_t *hs)
210 {
211         if (cfs_hash_with_no_lock(hs)) {
212                 hs->hs_lops = &cfs_hash_nl_lops;
213
214         } else if (cfs_hash_with_no_bktlock(hs)) {
215                 hs->hs_lops = &cfs_hash_nbl_lops;
216                 cfs_spin_lock_init(&hs->hs_lock.spin);
217
218         } else if (cfs_hash_with_rehash(hs)) {
219                 cfs_rwlock_init(&hs->hs_lock.rw);
220
221                 if (cfs_hash_with_rw_bktlock(hs))
222                         hs->hs_lops = &cfs_hash_bkt_rw_lops;
223                 else if (cfs_hash_with_spin_bktlock(hs))
224                         hs->hs_lops = &cfs_hash_bkt_spin_lops;
225                 else
226                         LBUG();
227         } else {
228                 if (cfs_hash_with_rw_bktlock(hs))
229                         hs->hs_lops = &cfs_hash_nr_bkt_rw_lops;
230                 else if (cfs_hash_with_spin_bktlock(hs))
231                         hs->hs_lops = &cfs_hash_nr_bkt_spin_lops;
232                 else
233                         LBUG();
234         }
235 }
236
237 /**
238  * Simple hash head without depth tracking
239  * new element is always added to head of hlist
240  */
241 typedef struct {
242         cfs_hlist_head_t        hh_head;        /**< entries list */
243 } cfs_hash_head_t;
244
245 static int
246 cfs_hash_hh_hhead_size(cfs_hash_t *hs)
247 {
248         return sizeof(cfs_hash_head_t);
249 }
250
251 static cfs_hlist_head_t *
252 cfs_hash_hh_hhead(cfs_hash_t *hs, cfs_hash_bd_t *bd)
253 {
254         cfs_hash_head_t *head = (cfs_hash_head_t *)&bd->bd_bucket->hsb_head[0];
255
256         return &head[bd->bd_offset].hh_head;
257 }
258
259 static int
260 cfs_hash_hh_hnode_add(cfs_hash_t *hs, cfs_hash_bd_t *bd,
261                       cfs_hlist_node_t *hnode)
262 {
263         cfs_hlist_add_head(hnode, cfs_hash_hh_hhead(hs, bd));
264         return -1; /* unknown depth */
265 }
266
267 static int
268 cfs_hash_hh_hnode_del(cfs_hash_t *hs, cfs_hash_bd_t *bd,
269                       cfs_hlist_node_t *hnode)
270 {
271         cfs_hlist_del_init(hnode);
272         return -1; /* unknown depth */
273 }
274
275 /**
276  * Simple hash head with depth tracking
277  * new element is always added to head of hlist
278  */
279 typedef struct {
280         cfs_hlist_head_t        hd_head;        /**< entries list */
281         unsigned int            hd_depth;       /**< list length */
282 } cfs_hash_head_dep_t;
283
284 static int
285 cfs_hash_hd_hhead_size(cfs_hash_t *hs)
286 {
287         return sizeof(cfs_hash_head_dep_t);
288 }
289
290 static cfs_hlist_head_t *
291 cfs_hash_hd_hhead(cfs_hash_t *hs, cfs_hash_bd_t *bd)
292 {
293         cfs_hash_head_dep_t   *head;
294
295         head = (cfs_hash_head_dep_t *)&bd->bd_bucket->hsb_head[0];
296         return &head[bd->bd_offset].hd_head;
297 }
298
299 static int
300 cfs_hash_hd_hnode_add(cfs_hash_t *hs, cfs_hash_bd_t *bd,
301                       cfs_hlist_node_t *hnode)
302 {
303         cfs_hash_head_dep_t *hh = container_of(cfs_hash_hd_hhead(hs, bd),
304                                                cfs_hash_head_dep_t, hd_head);
305         cfs_hlist_add_head(hnode, &hh->hd_head);
306         return ++hh->hd_depth;
307 }
308
309 static int
310 cfs_hash_hd_hnode_del(cfs_hash_t *hs, cfs_hash_bd_t *bd,
311                       cfs_hlist_node_t *hnode)
312 {
313         cfs_hash_head_dep_t *hh = container_of(cfs_hash_hd_hhead(hs, bd),
314                                                cfs_hash_head_dep_t, hd_head);
315         cfs_hlist_del_init(hnode);
316         return --hh->hd_depth;
317 }
318
319 /**
320  * double links hash head without depth tracking
321  * new element is always added to tail of hlist
322  */
323 typedef struct {
324         cfs_hlist_head_t        dh_head;        /**< entries list */
325         cfs_hlist_node_t       *dh_tail;        /**< the last entry */
326 } cfs_hash_dhead_t;
327
328 static int
329 cfs_hash_dh_hhead_size(cfs_hash_t *hs)
330 {
331         return sizeof(cfs_hash_dhead_t);
332 }
333
334 static cfs_hlist_head_t *
335 cfs_hash_dh_hhead(cfs_hash_t *hs, cfs_hash_bd_t *bd)
336 {
337         cfs_hash_dhead_t *head;
338
339         head = (cfs_hash_dhead_t *)&bd->bd_bucket->hsb_head[0];
340         return &head[bd->bd_offset].dh_head;
341 }
342
343 static int
344 cfs_hash_dh_hnode_add(cfs_hash_t *hs, cfs_hash_bd_t *bd,
345                       cfs_hlist_node_t *hnode)
346 {
347         cfs_hash_dhead_t *dh = container_of(cfs_hash_dh_hhead(hs, bd),
348                                             cfs_hash_dhead_t, dh_head);
349
350         if (dh->dh_tail != NULL) /* not empty */
351                 cfs_hlist_add_after(dh->dh_tail, hnode);
352         else /* empty list */
353                 cfs_hlist_add_head(hnode, &dh->dh_head);
354         dh->dh_tail = hnode;
355         return -1; /* unknown depth */
356 }
357
358 static int
359 cfs_hash_dh_hnode_del(cfs_hash_t *hs, cfs_hash_bd_t *bd,
360                       cfs_hlist_node_t *hnd)
361 {
362         cfs_hash_dhead_t *dh = container_of(cfs_hash_dh_hhead(hs, bd),
363                                             cfs_hash_dhead_t, dh_head);
364
365         if (hnd->next == NULL) { /* it's the tail */
366                 dh->dh_tail = (hnd->pprev == &dh->dh_head.first) ? NULL :
367                               container_of(hnd->pprev, cfs_hlist_node_t, next);
368         }
369         cfs_hlist_del_init(hnd);
370         return -1; /* unknown depth */
371 }
372
373 /**
374  * double links hash head with depth tracking
375  * new element is always added to tail of hlist
376  */
377 typedef struct {
378         cfs_hlist_head_t        dd_head;        /**< entries list */
379         cfs_hlist_node_t       *dd_tail;        /**< the last entry */
380         unsigned int            dd_depth;       /**< list length */
381 } cfs_hash_dhead_dep_t;
382
383 static int
384 cfs_hash_dd_hhead_size(cfs_hash_t *hs)
385 {
386         return sizeof(cfs_hash_dhead_dep_t);
387 }
388
389 static cfs_hlist_head_t *
390 cfs_hash_dd_hhead(cfs_hash_t *hs, cfs_hash_bd_t *bd)
391 {
392         cfs_hash_dhead_dep_t *head;
393
394         head = (cfs_hash_dhead_dep_t *)&bd->bd_bucket->hsb_head[0];
395         return &head[bd->bd_offset].dd_head;
396 }
397
398 static int
399 cfs_hash_dd_hnode_add(cfs_hash_t *hs, cfs_hash_bd_t *bd,
400                       cfs_hlist_node_t *hnode)
401 {
402         cfs_hash_dhead_dep_t *dh = container_of(cfs_hash_dd_hhead(hs, bd),
403                                                 cfs_hash_dhead_dep_t, dd_head);
404
405         if (dh->dd_tail != NULL) /* not empty */
406                 cfs_hlist_add_after(dh->dd_tail, hnode);
407         else /* empty list */
408                 cfs_hlist_add_head(hnode, &dh->dd_head);
409         dh->dd_tail = hnode;
410         return ++dh->dd_depth;
411 }
412
413 static int
414 cfs_hash_dd_hnode_del(cfs_hash_t *hs, cfs_hash_bd_t *bd,
415                       cfs_hlist_node_t *hnd)
416 {
417         cfs_hash_dhead_dep_t *dh = container_of(cfs_hash_dd_hhead(hs, bd),
418                                                 cfs_hash_dhead_dep_t, dd_head);
419
420         if (hnd->next == NULL) { /* it's the tail */
421                 dh->dd_tail = (hnd->pprev == &dh->dd_head.first) ? NULL :
422                               container_of(hnd->pprev, cfs_hlist_node_t, next);
423         }
424         cfs_hlist_del_init(hnd);
425         return --dh->dd_depth;
426 }
427
428 static cfs_hash_hlist_ops_t cfs_hash_hh_hops = {
429        .hop_hhead      = cfs_hash_hh_hhead,
430        .hop_hhead_size = cfs_hash_hh_hhead_size,
431        .hop_hnode_add  = cfs_hash_hh_hnode_add,
432        .hop_hnode_del  = cfs_hash_hh_hnode_del,
433 };
434
435 static cfs_hash_hlist_ops_t cfs_hash_hd_hops = {
436        .hop_hhead      = cfs_hash_hd_hhead,
437        .hop_hhead_size = cfs_hash_hd_hhead_size,
438        .hop_hnode_add  = cfs_hash_hd_hnode_add,
439        .hop_hnode_del  = cfs_hash_hd_hnode_del,
440 };
441
442 static cfs_hash_hlist_ops_t cfs_hash_dh_hops = {
443        .hop_hhead      = cfs_hash_dh_hhead,
444        .hop_hhead_size = cfs_hash_dh_hhead_size,
445        .hop_hnode_add  = cfs_hash_dh_hnode_add,
446        .hop_hnode_del  = cfs_hash_dh_hnode_del,
447 };
448
449 static cfs_hash_hlist_ops_t cfs_hash_dd_hops = {
450        .hop_hhead      = cfs_hash_dd_hhead,
451        .hop_hhead_size = cfs_hash_dd_hhead_size,
452        .hop_hnode_add  = cfs_hash_dd_hnode_add,
453        .hop_hnode_del  = cfs_hash_dd_hnode_del,
454 };
455
456 static void
457 cfs_hash_hlist_setup(cfs_hash_t *hs)
458 {
459         if (cfs_hash_with_add_tail(hs)) {
460                 hs->hs_hops = cfs_hash_with_depth(hs) ?
461                               &cfs_hash_dd_hops : &cfs_hash_dh_hops;
462         } else {
463                 hs->hs_hops = cfs_hash_with_depth(hs) ?
464                               &cfs_hash_hd_hops : &cfs_hash_hh_hops;
465         }
466 }
467
468 static void
469 cfs_hash_bd_from_key(cfs_hash_t *hs, cfs_hash_bucket_t **bkts,
470                      unsigned int bits, void *key, cfs_hash_bd_t *bd)
471 {
472         unsigned int index = cfs_hash_id(hs, key, (1U << bits) - 1);
473
474         LASSERT(bits == hs->hs_cur_bits || bits == hs->hs_rehash_bits);
475
476         bd->bd_bucket = bkts[index & ((1U << (bits - hs->hs_bkt_bits)) - 1)];
477         bd->bd_offset = index >> (bits - hs->hs_bkt_bits);
478 }
479
480 void
481 cfs_hash_bd_get(cfs_hash_t *hs, void *key, cfs_hash_bd_t *bd)
482 {
483         /* NB: caller should hold hs->hs_rwlock if REHASH is set */
484         if (likely(hs->hs_rehash_buckets == NULL)) {
485                 cfs_hash_bd_from_key(hs, hs->hs_buckets,
486                                      hs->hs_cur_bits, key, bd);
487         } else {
488                 LASSERT(hs->hs_rehash_bits != 0);
489                 cfs_hash_bd_from_key(hs, hs->hs_rehash_buckets,
490                                      hs->hs_rehash_bits, key, bd);
491         }
492 }
493 CFS_EXPORT_SYMBOL(cfs_hash_bd_get);
494
495 static inline void
496 cfs_hash_bd_dep_record(cfs_hash_t *hs, cfs_hash_bd_t *bd, int dep_cur)
497 {
498         if (likely(dep_cur <= bd->bd_bucket->hsb_depmax))
499                 return;
500
501         bd->bd_bucket->hsb_depmax = dep_cur;
502 # if CFS_HASH_DEBUG_LEVEL >= CFS_HASH_DEBUG_1
503         if (likely(warn_on_depth == 0 ||
504                    max(warn_on_depth, hs->hs_dep_max) >= dep_cur))
505                 return;
506
507         cfs_spin_lock(&hs->hs_dep_lock);
508         hs->hs_dep_max  = dep_cur;
509         hs->hs_dep_bkt  = bd->bd_bucket->hsb_index;
510         hs->hs_dep_off  = bd->bd_offset;
511         hs->hs_dep_bits = hs->hs_cur_bits;
512         cfs_spin_unlock(&hs->hs_dep_lock);
513
514         cfs_wi_schedule(&hs->hs_dep_wi);
515 # endif
516 }
517
518 void
519 cfs_hash_bd_add_locked(cfs_hash_t *hs, cfs_hash_bd_t *bd,
520                        cfs_hlist_node_t *hnode)
521 {
522         int                rc;
523
524         rc = hs->hs_hops->hop_hnode_add(hs, bd, hnode);
525         cfs_hash_bd_dep_record(hs, bd, rc);
526         bd->bd_bucket->hsb_version++;
527         if (unlikely(bd->bd_bucket->hsb_version == 0))
528                 bd->bd_bucket->hsb_version++;
529         bd->bd_bucket->hsb_count++;
530
531         if (cfs_hash_with_counter(hs))
532                 cfs_atomic_inc(&hs->hs_count);
533         if (!cfs_hash_with_no_itemref(hs))
534                 cfs_hash_get(hs, hnode);
535 }
536 CFS_EXPORT_SYMBOL(cfs_hash_bd_add_locked);
537
538 void
539 cfs_hash_bd_del_locked(cfs_hash_t *hs, cfs_hash_bd_t *bd,
540                        cfs_hlist_node_t *hnode)
541 {
542         hs->hs_hops->hop_hnode_del(hs, bd, hnode);
543
544         LASSERT(bd->bd_bucket->hsb_count > 0);
545         bd->bd_bucket->hsb_count--;
546         bd->bd_bucket->hsb_version++;
547         if (unlikely(bd->bd_bucket->hsb_version == 0))
548                 bd->bd_bucket->hsb_version++;
549
550         if (cfs_hash_with_counter(hs)) {
551                 LASSERT(cfs_atomic_read(&hs->hs_count) > 0);
552                 cfs_atomic_dec(&hs->hs_count);
553         }
554         if (!cfs_hash_with_no_itemref(hs))
555                 cfs_hash_put_locked(hs, hnode);
556 }
557 CFS_EXPORT_SYMBOL(cfs_hash_bd_del_locked);
558
559 void
560 cfs_hash_bd_move_locked(cfs_hash_t *hs, cfs_hash_bd_t *bd_old,
561                         cfs_hash_bd_t *bd_new, cfs_hlist_node_t *hnode)
562 {
563         cfs_hash_bucket_t *obkt = bd_old->bd_bucket;
564         cfs_hash_bucket_t *nbkt = bd_new->bd_bucket;
565         int                rc;
566
567         if (cfs_hash_bd_compare(bd_old, bd_new) == 0)
568                 return;
569
570         /* use cfs_hash_bd_hnode_add/del, to avoid atomic & refcount ops
571          * in cfs_hash_bd_del/add_locked */
572         hs->hs_hops->hop_hnode_del(hs, bd_old, hnode);
573         rc = hs->hs_hops->hop_hnode_add(hs, bd_new, hnode);
574         cfs_hash_bd_dep_record(hs, bd_new, rc);
575
576         LASSERT(obkt->hsb_count > 0);
577         obkt->hsb_count--;
578         obkt->hsb_version++;
579         if (unlikely(obkt->hsb_version == 0))
580                 obkt->hsb_version++;
581         nbkt->hsb_count++;
582         nbkt->hsb_version++;
583         if (unlikely(nbkt->hsb_version == 0))
584                 nbkt->hsb_version++;
585 }
586 CFS_EXPORT_SYMBOL(cfs_hash_bd_move_locked);
587
588 enum {
589         /** always set, for sanity (avoid ZERO intent) */
590         CFS_HS_LOOKUP_MASK_FIND     = 1 << 0,
591         /** return entry with a ref */
592         CFS_HS_LOOKUP_MASK_REF      = 1 << 1,
593         /** add entry if not existing */
594         CFS_HS_LOOKUP_MASK_ADD      = 1 << 2,
595         /** delete entry, ignore other masks */
596         CFS_HS_LOOKUP_MASK_DEL      = 1 << 3,
597 };
598
599 typedef enum cfs_hash_lookup_intent {
600         /** return item w/o refcount */
601         CFS_HS_LOOKUP_IT_PEEK       = CFS_HS_LOOKUP_MASK_FIND,
602         /** return item with refcount */
603         CFS_HS_LOOKUP_IT_FIND       = (CFS_HS_LOOKUP_MASK_FIND |
604                                        CFS_HS_LOOKUP_MASK_REF),
605         /** return item w/o refcount if existed, otherwise add */
606         CFS_HS_LOOKUP_IT_ADD        = (CFS_HS_LOOKUP_MASK_FIND |
607                                        CFS_HS_LOOKUP_MASK_ADD),
608         /** return item with refcount if existed, otherwise add */
609         CFS_HS_LOOKUP_IT_FINDADD    = (CFS_HS_LOOKUP_IT_FIND |
610                                        CFS_HS_LOOKUP_MASK_ADD),
611         /** delete if existed */
612         CFS_HS_LOOKUP_IT_FINDDEL    = (CFS_HS_LOOKUP_MASK_FIND |
613                                        CFS_HS_LOOKUP_MASK_DEL)
614 } cfs_hash_lookup_intent_t;
615
616 static cfs_hlist_node_t *
617 cfs_hash_bd_lookup_intent(cfs_hash_t *hs, cfs_hash_bd_t *bd,
618                           void *key, cfs_hlist_node_t *hnode,
619                           cfs_hash_lookup_intent_t intent)
620
621 {
622         cfs_hlist_head_t  *hhead = cfs_hash_bd_hhead(hs, bd);
623         cfs_hlist_node_t  *ehnode;
624         cfs_hlist_node_t  *match;
625         int  intent_add = (intent & CFS_HS_LOOKUP_MASK_ADD) != 0;
626
627         /* with this function, we can avoid a lot of useless refcount ops,
628          * which are expensive atomic operations most time. */
629         match = intent_add ? NULL : hnode;
630         cfs_hlist_for_each(ehnode, hhead) {
631                 if (!cfs_hash_keycmp(hs, key, ehnode))
632                         continue;
633
634                 if (match != NULL && match != ehnode) /* can't match */
635                         continue;
636
637                 /* match and ... */
638                 if ((intent & CFS_HS_LOOKUP_MASK_DEL) != 0) {
639                         cfs_hash_bd_del_locked(hs, bd, ehnode);
640                         return ehnode;
641                 }
642
643                 /* caller wants refcount? */
644                 if ((intent & CFS_HS_LOOKUP_MASK_REF) != 0)
645                         cfs_hash_get(hs, ehnode);
646                 return ehnode;
647         }
648         /* no match item */
649         if (!intent_add)
650                 return NULL;
651
652         LASSERT(hnode != NULL);
653         cfs_hash_bd_add_locked(hs, bd, hnode);
654         return hnode;
655 }
656
657 cfs_hlist_node_t *
658 cfs_hash_bd_lookup_locked(cfs_hash_t *hs, cfs_hash_bd_t *bd, void *key)
659 {
660         return cfs_hash_bd_lookup_intent(hs, bd, key, NULL,
661                                          CFS_HS_LOOKUP_IT_FIND);
662 }
663 CFS_EXPORT_SYMBOL(cfs_hash_bd_lookup_locked);
664
665 cfs_hlist_node_t *
666 cfs_hash_bd_findadd_locked(cfs_hash_t *hs, cfs_hash_bd_t *bd,
667                            void *key, cfs_hlist_node_t *hnode,
668                            int noref)
669 {
670         return cfs_hash_bd_lookup_intent(hs, bd, key, hnode,
671                                          CFS_HS_LOOKUP_IT_ADD |
672                                          (!noref * CFS_HS_LOOKUP_MASK_REF));
673 }
674 CFS_EXPORT_SYMBOL(cfs_hash_bd_findadd_locked);
675
676 cfs_hlist_node_t *
677 cfs_hash_bd_finddel_locked(cfs_hash_t *hs, cfs_hash_bd_t *bd,
678                            void *key, cfs_hlist_node_t *hnode)
679 {
680         /* hnode can be NULL, we find the first item with @key */
681         return cfs_hash_bd_lookup_intent(hs, bd, key, hnode,
682                                          CFS_HS_LOOKUP_IT_FINDDEL);
683 }
684 CFS_EXPORT_SYMBOL(cfs_hash_bd_finddel_locked);
685
686 static void
687 cfs_hash_multi_bd_lock(cfs_hash_t *hs, cfs_hash_bd_t *bds,
688                        unsigned n, int excl)
689 {
690         cfs_hash_bucket_t *prev = NULL;
691         int                i;
692
693         /**
694          * bds must be ascendantly ordered by bd->bd_bucket->hsb_index.
695          * NB: it's possible that several bds point to the same bucket but
696          * have different bd::bd_offset, so need take care of deadlock.
697          */
698         cfs_hash_for_each_bd(bds, n, i) {
699                 if (prev == bds[i].bd_bucket)
700                         continue;
701
702                 LASSERT(prev == NULL ||
703                         prev->hsb_index < bds[i].bd_bucket->hsb_index);
704                 cfs_hash_bd_lock(hs, &bds[i], excl);
705                 prev = bds[i].bd_bucket;
706         }
707 }
708
709 static void
710 cfs_hash_multi_bd_unlock(cfs_hash_t *hs, cfs_hash_bd_t *bds,
711                          unsigned n, int excl)
712 {
713         cfs_hash_bucket_t *prev = NULL;
714         int                i;
715
716         cfs_hash_for_each_bd(bds, n, i) {
717                 if (prev != bds[i].bd_bucket) {
718                         cfs_hash_bd_unlock(hs, &bds[i], excl);
719                         prev = bds[i].bd_bucket;
720                 }
721         }
722 }
723
724 static cfs_hlist_node_t *
725 cfs_hash_multi_bd_lookup_locked(cfs_hash_t *hs, cfs_hash_bd_t *bds,
726                                 unsigned n, void *key)
727 {
728         cfs_hlist_node_t  *ehnode;
729         unsigned           i;
730
731         cfs_hash_for_each_bd(bds, n, i) {
732                 ehnode = cfs_hash_bd_lookup_intent(hs, &bds[i], key, NULL,
733                                                    CFS_HS_LOOKUP_IT_FIND);
734                 if (ehnode != NULL)
735                         return ehnode;
736         }
737         return NULL;
738 }
739
740 static cfs_hlist_node_t *
741 cfs_hash_multi_bd_findadd_locked(cfs_hash_t *hs,
742                                  cfs_hash_bd_t *bds, unsigned n, void *key,
743                                  cfs_hlist_node_t *hnode, int noref)
744 {
745         cfs_hlist_node_t  *ehnode;
746         int                intent;
747         unsigned           i;
748
749         LASSERT(hnode != NULL);
750         intent = CFS_HS_LOOKUP_IT_PEEK | (!noref * CFS_HS_LOOKUP_MASK_REF);
751
752         cfs_hash_for_each_bd(bds, n, i) {
753                 ehnode = cfs_hash_bd_lookup_intent(hs, &bds[i], key,
754                                                    NULL, intent);
755                 if (ehnode != NULL)
756                         return ehnode;
757         }
758
759         if (i == 1) { /* only one bucket */
760                 cfs_hash_bd_add_locked(hs, &bds[0], hnode);
761         } else {
762                 cfs_hash_bd_t      mybd;
763
764                 cfs_hash_bd_get(hs, key, &mybd);
765                 cfs_hash_bd_add_locked(hs, &mybd, hnode);
766         }
767
768         return hnode;
769 }
770
771 static cfs_hlist_node_t *
772 cfs_hash_multi_bd_finddel_locked(cfs_hash_t *hs, cfs_hash_bd_t *bds,
773                                  unsigned n, void *key, cfs_hlist_node_t *hnode)
774 {
775         cfs_hlist_node_t  *ehnode;
776         unsigned           i;
777
778         cfs_hash_for_each_bd(bds, n, i) {
779                 ehnode = cfs_hash_bd_lookup_intent(hs, &bds[i], key, hnode,
780                                                    CFS_HS_LOOKUP_IT_FINDDEL);
781                 if (ehnode != NULL)
782                         return ehnode;
783         }
784         return NULL;
785 }
786
787 static void
788 cfs_hash_bd_order(cfs_hash_bd_t *bd1, cfs_hash_bd_t *bd2)
789 {
790         int     rc;
791
792         if (bd2->bd_bucket == NULL)
793                 return;
794
795         if (bd1->bd_bucket == NULL) {
796                 *bd1 = *bd2;
797                 bd2->bd_bucket = NULL;
798                 return;
799         }
800
801         rc = cfs_hash_bd_compare(bd1, bd2);
802         if (rc == 0) {
803                 bd2->bd_bucket = NULL;
804
805         } else if (rc > 0) { /* swab bd1 and bd2 */
806                 cfs_hash_bd_t tmp;
807
808                 tmp = *bd2;
809                 *bd2 = *bd1;
810                 *bd1 = tmp;
811         }
812 }
813
814 void
815 cfs_hash_dual_bd_get(cfs_hash_t *hs, void *key, cfs_hash_bd_t *bds)
816 {
817         /* NB: caller should hold hs_lock.rw if REHASH is set */
818         cfs_hash_bd_from_key(hs, hs->hs_buckets,
819                              hs->hs_cur_bits, key, &bds[0]);
820         if (likely(hs->hs_rehash_buckets == NULL)) {
821                 /* no rehash or not rehashing */
822                 bds[1].bd_bucket = NULL;
823                 return;
824         }
825
826         LASSERT(hs->hs_rehash_bits != 0);
827         cfs_hash_bd_from_key(hs, hs->hs_rehash_buckets,
828                              hs->hs_rehash_bits, key, &bds[1]);
829
830         cfs_hash_bd_order(&bds[0], &bds[1]);
831 }
832 CFS_EXPORT_SYMBOL(cfs_hash_dual_bd_get);
833
834 void
835 cfs_hash_dual_bd_lock(cfs_hash_t *hs, cfs_hash_bd_t *bds, int excl)
836 {
837         cfs_hash_multi_bd_lock(hs, bds, 2, excl);
838 }
839 CFS_EXPORT_SYMBOL(cfs_hash_dual_bd_lock);
840
841 void
842 cfs_hash_dual_bd_unlock(cfs_hash_t *hs, cfs_hash_bd_t *bds, int excl)
843 {
844         cfs_hash_multi_bd_unlock(hs, bds, 2, excl);
845 }
846 CFS_EXPORT_SYMBOL(cfs_hash_dual_bd_unlock);
847
848 cfs_hlist_node_t *
849 cfs_hash_dual_bd_lookup_locked(cfs_hash_t *hs, cfs_hash_bd_t *bds, void *key)
850 {
851         return cfs_hash_multi_bd_lookup_locked(hs, bds, 2, key);
852 }
853 CFS_EXPORT_SYMBOL(cfs_hash_dual_bd_lookup_locked);
854
855 cfs_hlist_node_t *
856 cfs_hash_dual_bd_findadd_locked(cfs_hash_t *hs, cfs_hash_bd_t *bds,
857                                 void *key, cfs_hlist_node_t *hnode,
858                                 int noref)
859 {
860         return cfs_hash_multi_bd_findadd_locked(hs, bds, 2, key,
861                                                 hnode, noref);
862 }
863 CFS_EXPORT_SYMBOL(cfs_hash_dual_bd_findadd_locked);
864
865 cfs_hlist_node_t *
866 cfs_hash_dual_bd_finddel_locked(cfs_hash_t *hs, cfs_hash_bd_t *bds,
867                                 void *key, cfs_hlist_node_t *hnode)
868 {
869         return cfs_hash_multi_bd_finddel_locked(hs, bds, 2, key, hnode);
870 }
871 CFS_EXPORT_SYMBOL(cfs_hash_dual_bd_finddel_locked);
872
873 static void
874 cfs_hash_buckets_free(cfs_hash_bucket_t **buckets,
875                       int bkt_size, int prev_size, int size)
876 {
877         int     i;
878
879         for (i = prev_size; i < size; i++) {
880                 if (buckets[i] != NULL)
881                         LIBCFS_FREE(buckets[i], bkt_size);
882         }
883
884         LIBCFS_FREE(buckets, sizeof(buckets[0]) * size);
885 }
886
887 /*
888  * Create or grow bucket memory. Return old_buckets if no allocation was
889  * needed, the newly allocated buckets if allocation was needed and
890  * successful, and NULL on error.
891  */
892 static cfs_hash_bucket_t **
893 cfs_hash_buckets_realloc(cfs_hash_t *hs, cfs_hash_bucket_t **old_bkts,
894                          unsigned int old_size, unsigned int new_size)
895 {
896         cfs_hash_bucket_t **new_bkts;
897         int                 i;
898
899         LASSERT(old_size == 0 || old_bkts != NULL);
900
901         if (old_bkts != NULL && old_size == new_size)
902                 return old_bkts;
903
904         LIBCFS_ALLOC(new_bkts, sizeof(new_bkts[0]) * new_size);
905         if (new_bkts == NULL)
906                 return NULL;
907
908         if (old_bkts != NULL) {
909                 memcpy(new_bkts, old_bkts,
910                        min(old_size, new_size) * sizeof(*old_bkts));
911         }
912
913         for (i = old_size; i < new_size; i++) {
914                 cfs_hlist_head_t *hhead;
915                 cfs_hash_bd_t     bd;
916
917                 LIBCFS_ALLOC(new_bkts[i], cfs_hash_bkt_size(hs));
918                 if (new_bkts[i] == NULL) {
919                         cfs_hash_buckets_free(new_bkts, cfs_hash_bkt_size(hs),
920                                               old_size, new_size);
921                         return NULL;
922                 }
923
924                 new_bkts[i]->hsb_index   = i;
925                 new_bkts[i]->hsb_version = 1;  /* shouldn't be zero */
926                 new_bkts[i]->hsb_depmax  = -1; /* unknown */
927                 bd.bd_bucket = new_bkts[i];
928                 cfs_hash_bd_for_each_hlist(hs, &bd, hhead)
929                         CFS_INIT_HLIST_HEAD(hhead);
930
931                 if (cfs_hash_with_no_lock(hs) ||
932                     cfs_hash_with_no_bktlock(hs))
933                         continue;
934
935                 if (cfs_hash_with_rw_bktlock(hs))
936                         cfs_rwlock_init(&new_bkts[i]->hsb_lock.rw);
937                 else if (cfs_hash_with_spin_bktlock(hs))
938                         cfs_spin_lock_init(&new_bkts[i]->hsb_lock.spin);
939                 else
940                         LBUG(); /* invalid use-case */
941         }
942         return new_bkts;
943 }
944
945 /**
946  * Initialize new libcfs hash, where:
947  * @name     - Descriptive hash name
948  * @cur_bits - Initial hash table size, in bits
949  * @max_bits - Maximum allowed hash table resize, in bits
950  * @ops      - Registered hash table operations
951  * @flags    - CFS_HASH_REHASH enable synamic hash resizing
952  *           - CFS_HASH_SORT enable chained hash sort
953  */
954 static int cfs_hash_rehash_worker(cfs_workitem_t *wi);
955
956 #if CFS_HASH_DEBUG_LEVEL >= CFS_HASH_DEBUG_1
957 static int cfs_hash_dep_print(cfs_workitem_t *wi)
958 {
959         cfs_hash_t *hs = container_of(wi, cfs_hash_t, hs_dep_wi);
960         int         dep;
961         int         bkt;
962         int         off;
963         int         bits;
964
965         cfs_spin_lock(&hs->hs_dep_lock);
966         dep  = hs->hs_dep_max;
967         bkt  = hs->hs_dep_bkt;
968         off  = hs->hs_dep_off;
969         bits = hs->hs_dep_bits;
970         cfs_spin_unlock(&hs->hs_dep_lock);
971
972         LCONSOLE_WARN("#### HASH %s (bits: %d): max depth %d at bucket %d/%d\n",
973                       hs->hs_name, bits, dep, bkt, off);
974         cfs_spin_lock(&hs->hs_dep_lock);
975         hs->hs_dep_bits = 0; /* mark as workitem done */
976         cfs_spin_unlock(&hs->hs_dep_lock);
977         return 0;
978 }
979
980 static void cfs_hash_depth_wi_init(cfs_hash_t *hs)
981 {
982         cfs_spin_lock_init(&hs->hs_dep_lock);
983         cfs_wi_init(&hs->hs_dep_wi, hs,
984                     cfs_hash_dep_print, CFS_WI_SCHED_ANY);
985 }
986
987 static void cfs_hash_depth_wi_cancel(cfs_hash_t *hs)
988 {
989         if (cfs_wi_cancel(&hs->hs_dep_wi))
990                 return;
991
992         cfs_spin_lock(&hs->hs_dep_lock);
993         while (hs->hs_dep_bits != 0) {
994                 cfs_spin_unlock(&hs->hs_dep_lock);
995                 cfs_cond_resched();
996                 cfs_spin_lock(&hs->hs_dep_lock);
997         }
998         cfs_spin_unlock(&hs->hs_dep_lock);
999 }
1000
1001 #else /* CFS_HASH_DEBUG_LEVEL < CFS_HASH_DEBUG_1 */
1002
1003 static inline void cfs_hash_depth_wi_init(cfs_hash_t *hs) {}
1004 static inline void cfs_hash_depth_wi_cancel(cfs_hash_t *hs) {}
1005
1006 #endif /* CFS_HASH_DEBUG_LEVEL >= CFS_HASH_DEBUG_1 */
1007
1008 cfs_hash_t *
1009 cfs_hash_create(char *name, unsigned cur_bits, unsigned max_bits,
1010                 unsigned bkt_bits, unsigned extra_bytes,
1011                 unsigned min_theta, unsigned max_theta,
1012                 cfs_hash_ops_t *ops, unsigned flags)
1013 {
1014         cfs_hash_t *hs;
1015         int         len;
1016
1017         ENTRY;
1018
1019         CLASSERT(CFS_HASH_THETA_BITS < 15);
1020
1021         LASSERT(name != NULL);
1022         LASSERT(ops != NULL);
1023         LASSERT(ops->hs_key);
1024         LASSERT(ops->hs_hash);
1025         LASSERT(ops->hs_object);
1026         LASSERT(ops->hs_keycmp);
1027         LASSERT(ops->hs_get != NULL);
1028         LASSERT(ops->hs_put_locked != NULL);
1029
1030         if ((flags & CFS_HASH_REHASH) != 0)
1031                 flags |= CFS_HASH_COUNTER; /* must have counter */
1032
1033         LASSERT(cur_bits > 0);
1034         LASSERT(cur_bits >= bkt_bits);
1035         LASSERT(max_bits >= cur_bits && max_bits < 31);
1036         LASSERT(ergo((flags & CFS_HASH_REHASH) == 0, cur_bits == max_bits));
1037         LASSERT(ergo((flags & CFS_HASH_REHASH) != 0,
1038                      (flags & CFS_HASH_NO_LOCK) == 0));
1039         LASSERT(ergo((flags & CFS_HASH_REHASH_KEY) != 0,
1040                       ops->hs_keycpy != NULL));
1041
1042         len = (flags & CFS_HASH_BIGNAME) == 0 ?
1043               CFS_HASH_NAME_LEN : CFS_HASH_BIGNAME_LEN;
1044         LIBCFS_ALLOC(hs, offsetof(cfs_hash_t, hs_name[len]));
1045         if (hs == NULL)
1046                 RETURN(NULL);
1047
1048         strncpy(hs->hs_name, name, len);
1049         hs->hs_name[len - 1] = '\0';
1050         hs->hs_flags = flags;
1051
1052         cfs_atomic_set(&hs->hs_refcount, 1);
1053         cfs_atomic_set(&hs->hs_count, 0);
1054
1055         cfs_hash_lock_setup(hs);
1056         cfs_hash_hlist_setup(hs);
1057
1058         hs->hs_cur_bits = (__u8)cur_bits;
1059         hs->hs_min_bits = (__u8)cur_bits;
1060         hs->hs_max_bits = (__u8)max_bits;
1061         hs->hs_bkt_bits = (__u8)bkt_bits;
1062
1063         hs->hs_ops         = ops;
1064         hs->hs_extra_bytes = extra_bytes;
1065         hs->hs_rehash_bits = 0;
1066         cfs_wi_init(&hs->hs_rehash_wi, hs,
1067                     cfs_hash_rehash_worker, CFS_WI_SCHED_ANY);
1068         cfs_hash_depth_wi_init(hs);
1069
1070         if (cfs_hash_with_rehash(hs))
1071                 __cfs_hash_set_theta(hs, min_theta, max_theta);
1072
1073         hs->hs_buckets = cfs_hash_buckets_realloc(hs, NULL, 0,
1074                                                   CFS_HASH_NBKT(hs));
1075         if (hs->hs_buckets != NULL)
1076                 return hs;
1077
1078         LIBCFS_FREE(hs, offsetof(cfs_hash_t, hs_name[len]));
1079         RETURN(NULL);
1080 }
1081 CFS_EXPORT_SYMBOL(cfs_hash_create);
1082
1083 /**
1084  * Cleanup libcfs hash @hs.
1085  */
1086 static void
1087 cfs_hash_destroy(cfs_hash_t *hs)
1088 {
1089         cfs_hlist_node_t     *hnode;
1090         cfs_hlist_node_t     *pos;
1091         cfs_hash_bd_t         bd;
1092         int                   i;
1093         ENTRY;
1094
1095         LASSERT(hs != NULL);
1096         LASSERT(!cfs_hash_is_exiting(hs) &&
1097                 !cfs_hash_is_iterating(hs));
1098
1099         /**
1100          * prohibit further rehashes, don't need any lock because
1101          * I'm the only (last) one can change it.
1102          */
1103         hs->hs_exiting = 1;
1104         if (cfs_hash_with_rehash(hs))
1105                 cfs_hash_rehash_cancel(hs);
1106
1107         cfs_hash_depth_wi_cancel(hs);
1108         /* rehash should be done/canceled */
1109         LASSERT(hs->hs_buckets != NULL &&
1110                 hs->hs_rehash_buckets == NULL);
1111
1112         cfs_hash_for_each_bucket(hs, &bd, i) {
1113                 cfs_hlist_head_t *hhead;
1114
1115                 LASSERT(bd.bd_bucket != NULL);
1116                 /* no need to take this lock, just for consistent code */
1117                 cfs_hash_bd_lock(hs, &bd, 1);
1118
1119                 cfs_hash_bd_for_each_hlist(hs, &bd, hhead) {
1120                         cfs_hlist_for_each_safe(hnode, pos, hhead) {
1121                                 LASSERTF(!cfs_hash_with_assert_empty(hs),
1122                                          "hash %s bucket %u(%u) is not "
1123                                          " empty: %u items left\n",
1124                                          hs->hs_name, bd.bd_bucket->hsb_index,
1125                                          bd.bd_offset, bd.bd_bucket->hsb_count);
1126                                 /* can't assert key valicate, because we
1127                                  * can interrupt rehash */
1128                                 cfs_hash_bd_del_locked(hs, &bd, hnode);
1129                                 cfs_hash_exit(hs, hnode);
1130                         }
1131                 }
1132                 LASSERT(bd.bd_bucket->hsb_count == 0);
1133                 cfs_hash_bd_unlock(hs, &bd, 1);
1134                 cfs_cond_resched();
1135         }
1136
1137         LASSERT(cfs_atomic_read(&hs->hs_count) == 0);
1138
1139         cfs_hash_buckets_free(hs->hs_buckets, cfs_hash_bkt_size(hs),
1140                               0, CFS_HASH_NBKT(hs));
1141         i = cfs_hash_with_bigname(hs) ?
1142             CFS_HASH_BIGNAME_LEN : CFS_HASH_NAME_LEN;
1143         LIBCFS_FREE(hs, offsetof(cfs_hash_t, hs_name[i]));
1144
1145         EXIT;
1146 }
1147
1148 cfs_hash_t *cfs_hash_getref(cfs_hash_t *hs)
1149 {
1150         if (cfs_atomic_inc_not_zero(&hs->hs_refcount))
1151                 return hs;
1152         return NULL;
1153 }
1154 CFS_EXPORT_SYMBOL(cfs_hash_getref);
1155
1156 void cfs_hash_putref(cfs_hash_t *hs)
1157 {
1158         if (cfs_atomic_dec_and_test(&hs->hs_refcount))
1159                 cfs_hash_destroy(hs);
1160 }
1161 CFS_EXPORT_SYMBOL(cfs_hash_putref);
1162
1163 static inline int
1164 cfs_hash_rehash_bits(cfs_hash_t *hs)
1165 {
1166         if (cfs_hash_with_no_lock(hs) ||
1167             !cfs_hash_with_rehash(hs))
1168                 return -EOPNOTSUPP;
1169
1170         if (unlikely(cfs_hash_is_exiting(hs)))
1171                 return -ESRCH;
1172
1173         if (unlikely(cfs_hash_is_rehashing(hs)))
1174                 return -EALREADY;
1175
1176         if (unlikely(cfs_hash_is_iterating(hs)))
1177                 return -EAGAIN;
1178
1179         /* XXX: need to handle case with max_theta != 2.0
1180          *      and the case with min_theta != 0.5 */
1181         if ((hs->hs_cur_bits < hs->hs_max_bits) &&
1182             (__cfs_hash_theta(hs) > hs->hs_max_theta))
1183                 return hs->hs_cur_bits + 1;
1184
1185         if (!cfs_hash_with_shrink(hs))
1186                 return 0;
1187
1188         if ((hs->hs_cur_bits > hs->hs_min_bits) &&
1189             (__cfs_hash_theta(hs) < hs->hs_min_theta))
1190                 return hs->hs_cur_bits - 1;
1191
1192         return 0;
1193 }
1194
1195 /**
1196  * don't allow inline rehash if:
1197  * - user wants non-blocking change (add/del) on hash table
1198  * - too many elements
1199  */
1200 static inline int
1201 cfs_hash_rehash_inline(cfs_hash_t *hs)
1202 {
1203         return !cfs_hash_with_nblk_change(hs) &&
1204                cfs_atomic_read(&hs->hs_count) < CFS_HASH_LOOP_HOG;
1205 }
1206
1207 /**
1208  * Add item @hnode to libcfs hash @hs using @key.  The registered
1209  * ops->hs_get function will be called when the item is added.
1210  */
1211 void
1212 cfs_hash_add(cfs_hash_t *hs, void *key, cfs_hlist_node_t *hnode)
1213 {
1214         cfs_hash_bd_t   bd;
1215         int             bits;
1216
1217         LASSERT(cfs_hlist_unhashed(hnode));
1218
1219         cfs_hash_lock(hs, 0);
1220         cfs_hash_bd_get_and_lock(hs, key, &bd, 1);
1221
1222         cfs_hash_key_validate(hs, key, hnode);
1223         cfs_hash_bd_add_locked(hs, &bd, hnode);
1224
1225         cfs_hash_bd_unlock(hs, &bd, 1);
1226
1227         bits = cfs_hash_rehash_bits(hs);
1228         cfs_hash_unlock(hs, 0);
1229         if (bits > 0)
1230                 cfs_hash_rehash(hs, cfs_hash_rehash_inline(hs));
1231 }
1232 CFS_EXPORT_SYMBOL(cfs_hash_add);
1233
1234 static cfs_hlist_node_t *
1235 cfs_hash_find_or_add(cfs_hash_t *hs, void *key,
1236                      cfs_hlist_node_t *hnode, int noref)
1237 {
1238         cfs_hlist_node_t *ehnode;
1239         cfs_hash_bd_t     bds[2];
1240         int               bits = 0;
1241
1242         LASSERT(cfs_hlist_unhashed(hnode));
1243
1244         cfs_hash_lock(hs, 0);
1245         cfs_hash_dual_bd_get_and_lock(hs, key, bds, 1);
1246
1247         cfs_hash_key_validate(hs, key, hnode);
1248         ehnode = cfs_hash_dual_bd_findadd_locked(hs, bds, key,
1249                                                  hnode, noref);
1250         cfs_hash_dual_bd_unlock(hs, bds, 1);
1251
1252         if (ehnode == hnode) /* new item added */
1253                 bits = cfs_hash_rehash_bits(hs);
1254         cfs_hash_unlock(hs, 0);
1255         if (bits > 0)
1256                 cfs_hash_rehash(hs, cfs_hash_rehash_inline(hs));
1257
1258         return ehnode;
1259 }
1260
1261 /**
1262  * Add item @hnode to libcfs hash @hs using @key.  The registered
1263  * ops->hs_get function will be called if the item was added.
1264  * Returns 0 on success or -EALREADY on key collisions.
1265  */
1266 int
1267 cfs_hash_add_unique(cfs_hash_t *hs, void *key, cfs_hlist_node_t *hnode)
1268 {
1269         RETURN(cfs_hash_find_or_add(hs, key, hnode, 1) != hnode ?
1270                -EALREADY : 0);
1271 }
1272 CFS_EXPORT_SYMBOL(cfs_hash_add_unique);
1273
1274 /**
1275  * Add item @hnode to libcfs hash @hs using @key.  If this @key
1276  * already exists in the hash then ops->hs_get will be called on the
1277  * conflicting entry and that entry will be returned to the caller.
1278  * Otherwise ops->hs_get is called on the item which was added.
1279  */
1280 void *
1281 cfs_hash_findadd_unique(cfs_hash_t *hs, void *key,
1282                         cfs_hlist_node_t *hnode)
1283 {
1284         hnode = cfs_hash_find_or_add(hs, key, hnode, 0);
1285
1286         return cfs_hash_object(hs, hnode);
1287 }
1288 CFS_EXPORT_SYMBOL(cfs_hash_findadd_unique);
1289
1290 /**
1291  * Delete item @hnode from the libcfs hash @hs using @key.  The @key
1292  * is required to ensure the correct hash bucket is locked since there
1293  * is no direct linkage from the item to the bucket.  The object
1294  * removed from the hash will be returned and obs->hs_put is called
1295  * on the removed object.
1296  */
1297 void *
1298 cfs_hash_del(cfs_hash_t *hs, void *key, cfs_hlist_node_t *hnode)
1299 {
1300         void           *obj  = NULL;
1301         int             bits = 0;
1302         cfs_hash_bd_t   bds[2];
1303
1304         cfs_hash_lock(hs, 0);
1305         cfs_hash_dual_bd_get_and_lock(hs, key, bds, 1);
1306
1307         if (bds[1].bd_bucket == NULL && hnode != NULL)
1308                 cfs_hash_bd_del_locked(hs, &bds[0], hnode);
1309         else
1310                 hnode = cfs_hash_dual_bd_finddel_locked(hs, bds, key, hnode);
1311
1312         if (hnode != NULL) {
1313                 obj  = cfs_hash_object(hs, hnode);
1314                 bits = cfs_hash_rehash_bits(hs);
1315         }
1316
1317         cfs_hash_dual_bd_unlock(hs, bds, 1);
1318         cfs_hash_unlock(hs, 0);
1319         if (bits > 0)
1320                 cfs_hash_rehash(hs, cfs_hash_rehash_inline(hs));
1321
1322         return obj;
1323 }
1324 CFS_EXPORT_SYMBOL(cfs_hash_del);
1325
1326 /**
1327  * Delete item given @key in libcfs hash @hs.  The first @key found in
1328  * the hash will be removed, if the key exists multiple times in the hash
1329  * @hs this function must be called once per key.  The removed object
1330  * will be returned and ops->hs_put is called on the removed object.
1331  */
1332 void *
1333 cfs_hash_del_key(cfs_hash_t *hs, void *key)
1334 {
1335         return cfs_hash_del(hs, key, NULL);
1336 }
1337 CFS_EXPORT_SYMBOL(cfs_hash_del_key);
1338
1339 /**
1340  * Lookup an item using @key in the libcfs hash @hs and return it.
1341  * If the @key is found in the hash hs->hs_get() is called and the
1342  * matching objects is returned.  It is the callers responsibility
1343  * to call the counterpart ops->hs_put using the cfs_hash_put() macro
1344  * when when finished with the object.  If the @key was not found
1345  * in the hash @hs NULL is returned.
1346  */
1347 void *
1348 cfs_hash_lookup(cfs_hash_t *hs, void *key)
1349 {
1350         void                 *obj = NULL;
1351         cfs_hlist_node_t     *hnode;
1352         cfs_hash_bd_t         bds[2];
1353
1354         cfs_hash_lock(hs, 0);
1355         cfs_hash_dual_bd_get_and_lock(hs, key, bds, 0);
1356
1357         hnode = cfs_hash_dual_bd_lookup_locked(hs, bds, key);
1358         if (hnode != NULL)
1359                 obj = cfs_hash_object(hs, hnode);
1360
1361         cfs_hash_dual_bd_unlock(hs, bds, 0);
1362         cfs_hash_unlock(hs, 0);
1363
1364         return obj;
1365 }
1366 CFS_EXPORT_SYMBOL(cfs_hash_lookup);
1367
1368 static void
1369 cfs_hash_for_each_enter(cfs_hash_t *hs)
1370 {
1371         LASSERT(!cfs_hash_is_exiting(hs));
1372
1373         if (!cfs_hash_with_rehash(hs))
1374                 return;
1375         /*
1376          * NB: it's race on cfs_has_t::hs_iterating, but doesn't matter
1377          * because it's just an unreliable signal to rehash-thread,
1378          * rehash-thread will try to finsih rehash ASAP when seeing this.
1379          */
1380         hs->hs_iterating = 1;
1381
1382         cfs_hash_lock(hs, 1);
1383         hs->hs_iterators++;
1384
1385         /* NB: iteration is mostly called by service thread,
1386          * we tend to cancel pending rehash-requst, instead of
1387          * blocking service thread, we will relaunch rehash request
1388          * after iteration */
1389         if (cfs_hash_is_rehashing(hs))
1390                 cfs_hash_rehash_cancel_locked(hs);
1391         cfs_hash_unlock(hs, 1);
1392 }
1393
1394 static void
1395 cfs_hash_for_each_exit(cfs_hash_t *hs)
1396 {
1397         int remained;
1398         int bits;
1399
1400         if (!cfs_hash_with_rehash(hs))
1401                 return;
1402         cfs_hash_lock(hs, 1);
1403         remained = --hs->hs_iterators;
1404         bits = cfs_hash_rehash_bits(hs);
1405         cfs_hash_unlock(hs, 1);
1406         /* NB: it's race on cfs_has_t::hs_iterating, see above */
1407         if (remained == 0)
1408                 hs->hs_iterating = 0;
1409         if (bits > 0) {
1410                 cfs_hash_rehash(hs, cfs_atomic_read(&hs->hs_count) <
1411                                     CFS_HASH_LOOP_HOG);
1412         }
1413 }
1414
1415 /**
1416  * For each item in the libcfs hash @hs call the passed callback @func
1417  * and pass to it as an argument each hash item and the private @data.
1418  *
1419  * a) the function may sleep!
1420  * b) during the callback:
1421  *    . the bucket lock is held so the callback must never sleep.
1422  *    . if @removal_safe is true, use can remove current item by
1423  *      cfs_hash_bd_del_locked
1424  */
1425 static __u64
1426 cfs_hash_for_each_tight(cfs_hash_t *hs, cfs_hash_for_each_cb_t func,
1427                         void *data, int remove_safe)
1428 {
1429         cfs_hlist_node_t     *hnode;
1430         cfs_hlist_node_t     *pos;
1431         cfs_hash_bd_t         bd;
1432         __u64                 count = 0;
1433         int                   excl  = !!remove_safe;
1434         int                   loop  = 0;
1435         int                   i;
1436         ENTRY;
1437
1438         cfs_hash_for_each_enter(hs);
1439
1440         cfs_hash_lock(hs, 0);
1441         LASSERT(!cfs_hash_is_rehashing(hs));
1442
1443         cfs_hash_for_each_bucket(hs, &bd, i) {
1444                 cfs_hlist_head_t *hhead;
1445
1446                 cfs_hash_bd_lock(hs, &bd, excl);
1447                 if (func == NULL) { /* only glimpse size */
1448                         count += bd.bd_bucket->hsb_count;
1449                         cfs_hash_bd_unlock(hs, &bd, excl);
1450                         continue;
1451                 }
1452
1453                 cfs_hash_bd_for_each_hlist(hs, &bd, hhead) {
1454                         cfs_hlist_for_each_safe(hnode, pos, hhead) {
1455                                 cfs_hash_bucket_validate(hs, &bd, hnode);
1456                                 count++;
1457                                 loop++;
1458                                 if (func(hs, &bd, hnode, data)) {
1459                                         cfs_hash_bd_unlock(hs, &bd, excl);
1460                                         goto out;
1461                                 }
1462                         }
1463                 }
1464                 cfs_hash_bd_unlock(hs, &bd, excl);
1465                 if (loop < CFS_HASH_LOOP_HOG)
1466                         continue;
1467                 loop = 0;
1468                 cfs_hash_unlock(hs, 0);
1469                 cfs_cond_resched();
1470                 cfs_hash_lock(hs, 0);
1471         }
1472  out:
1473         cfs_hash_unlock(hs, 0);
1474
1475         cfs_hash_for_each_exit(hs);
1476         RETURN(count);
1477 }
1478
1479 typedef struct {
1480         cfs_hash_cond_opt_cb_t  func;
1481         void                   *arg;
1482 } cfs_hash_cond_arg_t;
1483
1484 static int
1485 cfs_hash_cond_del_locked(cfs_hash_t *hs, cfs_hash_bd_t *bd,
1486                          cfs_hlist_node_t *hnode, void *data)
1487 {
1488         cfs_hash_cond_arg_t *cond = data;
1489
1490         if (cond->func(cfs_hash_object(hs, hnode), cond->arg))
1491                 cfs_hash_bd_del_locked(hs, bd, hnode);
1492         return 0;
1493 }
1494
1495 /**
1496  * Delete item from the libcfs hash @hs when @func return true.
1497  * The write lock being hold during loop for each bucket to avoid
1498  * any object be reference.
1499  */
1500 void
1501 cfs_hash_cond_del(cfs_hash_t *hs, cfs_hash_cond_opt_cb_t func, void *data)
1502 {
1503         cfs_hash_cond_arg_t arg = {
1504                 .func   = func,
1505                 .arg    = data,
1506         };
1507
1508         cfs_hash_for_each_tight(hs, cfs_hash_cond_del_locked, &arg, 1);
1509 }
1510 CFS_EXPORT_SYMBOL(cfs_hash_cond_del);
1511
1512 void
1513 cfs_hash_for_each(cfs_hash_t *hs,
1514                   cfs_hash_for_each_cb_t func, void *data)
1515 {
1516         cfs_hash_for_each_tight(hs, func, data, 0);
1517 }
1518 CFS_EXPORT_SYMBOL(cfs_hash_for_each);
1519
1520 void
1521 cfs_hash_for_each_safe(cfs_hash_t *hs,
1522                        cfs_hash_for_each_cb_t func, void *data)
1523 {
1524         cfs_hash_for_each_tight(hs, func, data, 1);
1525 }
1526 CFS_EXPORT_SYMBOL(cfs_hash_for_each_safe);
1527
1528 static int
1529 cfs_hash_peek(cfs_hash_t *hs, cfs_hash_bd_t *bd,
1530               cfs_hlist_node_t *hnode, void *data)
1531 {
1532         *(int *)data = 0;
1533         return 1; /* return 1 to break the loop */
1534 }
1535
1536 int
1537 cfs_hash_is_empty(cfs_hash_t *hs)
1538 {
1539         int empty = 1;
1540
1541         cfs_hash_for_each_tight(hs, cfs_hash_peek, &empty, 0);
1542         return empty;
1543 }
1544 CFS_EXPORT_SYMBOL(cfs_hash_is_empty);
1545
1546 __u64
1547 cfs_hash_size_get(cfs_hash_t *hs)
1548 {
1549         return cfs_hash_for_each_tight(hs, NULL, NULL, 0);
1550 }
1551 CFS_EXPORT_SYMBOL(cfs_hash_size_get);
1552
1553 /*
1554  * cfs_hash_for_each_relax:
1555  * Iterate the hash table and call @func on each item without
1556  * any lock. This function can't guarantee to finish iteration
1557  * if these features are enabled:
1558  *
1559  *  a. if rehash_key is enabled, an item can be moved from
1560  *     one bucket to another bucket
1561  *  b. user can remove non-zero-ref item from hash-table,
1562  *     so the item can be removed from hash-table, even worse,
1563  *     it's possible that user changed key and insert to another
1564  *     hash bucket.
1565  * there's no way for us to finish iteration correctly on previous
1566  * two cases, so iteration has to be stopped on change.
1567  */
1568 static int
1569 cfs_hash_for_each_relax(cfs_hash_t *hs, cfs_hash_for_each_cb_t func, void *data)
1570 {
1571         cfs_hlist_node_t *hnode;
1572         cfs_hlist_node_t *tmp;
1573         void             *obj;
1574         cfs_hash_bd_t     bd;
1575         __u32             version;
1576         int               count = 0;
1577         int               stop_on_change;
1578         int               rc;
1579         int               i;
1580         ENTRY;
1581
1582         stop_on_change = cfs_hash_with_rehash_key(hs) ||
1583                          !cfs_hash_with_no_itemref(hs) ||
1584                          CFS_HOP(hs, put_locked) == NULL;
1585         cfs_hash_lock(hs, 0);
1586         LASSERT(!cfs_hash_is_rehashing(hs));
1587
1588         cfs_hash_for_each_bucket(hs, &bd, i) {
1589                 cfs_hlist_head_t *hhead;
1590
1591                 cfs_hash_bd_lock(hs, &bd, 0);
1592                 version = cfs_hash_bd_version_get(&bd);
1593
1594                 cfs_hash_bd_for_each_hlist(hs, &bd, hhead) {
1595                         for (hnode = hhead->first; hnode != NULL;) {
1596                                 cfs_hash_bucket_validate(hs, &bd, hnode);
1597                                 obj = cfs_hash_get(hs, hnode);
1598                                 cfs_hash_bd_unlock(hs, &bd, 0);
1599                                 cfs_hash_unlock(hs, 0);
1600
1601                                 rc = func(hs, &bd, hnode, data);
1602                                 if (stop_on_change)
1603                                         (void)cfs_hash_put(hs, hnode);
1604                                 cfs_cond_resched();
1605                                 count++;
1606
1607                                 cfs_hash_lock(hs, 0);
1608                                 cfs_hash_bd_lock(hs, &bd, 0);
1609                                 if (!stop_on_change) {
1610                                         tmp = hnode->next;
1611                                         cfs_hash_put_locked(hs, hnode);
1612                                         hnode = tmp;
1613                                 } else { /* bucket changed? */
1614                                         if (version !=
1615                                             cfs_hash_bd_version_get(&bd))
1616                                                 break;
1617                                         /* safe to continue because no change */
1618                                         hnode = hnode->next;
1619                                 }
1620                                 if (rc) /* callback wants to break iteration */
1621                                         break;
1622                         }
1623                 }
1624                 cfs_hash_bd_unlock(hs, &bd, 0);
1625         }
1626         cfs_hash_unlock(hs, 0);
1627
1628         return count;
1629 }
1630
1631 int
1632 cfs_hash_for_each_nolock(cfs_hash_t *hs,
1633                          cfs_hash_for_each_cb_t func, void *data)
1634 {
1635         ENTRY;
1636
1637         if (cfs_hash_with_no_lock(hs) ||
1638             cfs_hash_with_rehash_key(hs) ||
1639             !cfs_hash_with_no_itemref(hs))
1640                 RETURN(-EOPNOTSUPP);
1641
1642         if (CFS_HOP(hs, get) == NULL ||
1643             (CFS_HOP(hs, put) == NULL &&
1644              CFS_HOP(hs, put_locked) == NULL))
1645                 RETURN(-EOPNOTSUPP);
1646
1647         cfs_hash_for_each_enter(hs);
1648         cfs_hash_for_each_relax(hs, func, data);
1649         cfs_hash_for_each_exit(hs);
1650
1651         RETURN(0);
1652 }
1653 CFS_EXPORT_SYMBOL(cfs_hash_for_each_nolock);
1654
1655 /**
1656  * For each hash bucket in the libcfs hash @hs call the passed callback
1657  * @func until all the hash buckets are empty.  The passed callback @func
1658  * or the previously registered callback hs->hs_put must remove the item
1659  * from the hash.  You may either use the cfs_hash_del() or hlist_del()
1660  * functions.  No rwlocks will be held during the callback @func it is
1661  * safe to sleep if needed.  This function will not terminate until the
1662  * hash is empty.  Note it is still possible to concurrently add new
1663  * items in to the hash.  It is the callers responsibility to ensure
1664  * the required locking is in place to prevent concurrent insertions.
1665  */
1666 int
1667 cfs_hash_for_each_empty(cfs_hash_t *hs,
1668                         cfs_hash_for_each_cb_t func, void *data)
1669 {
1670         unsigned  i = 0;
1671         ENTRY;
1672
1673         if (cfs_hash_with_no_lock(hs))
1674                 return -EOPNOTSUPP;
1675
1676         if (CFS_HOP(hs, get) == NULL ||
1677             (CFS_HOP(hs, put) == NULL &&
1678              CFS_HOP(hs, put_locked) == NULL))
1679                 return -EOPNOTSUPP;
1680
1681         cfs_hash_for_each_enter(hs);
1682         while (cfs_hash_for_each_relax(hs, func, data)) {
1683                 CDEBUG(D_INFO, "Try to empty hash: %s, loop: %u\n",
1684                        hs->hs_name, i++);
1685         }
1686         cfs_hash_for_each_exit(hs);
1687         RETURN(0);
1688 }
1689 CFS_EXPORT_SYMBOL(cfs_hash_for_each_empty);
1690
1691 void
1692 cfs_hash_hlist_for_each(cfs_hash_t *hs, unsigned hindex,
1693                         cfs_hash_for_each_cb_t func, void *data)
1694 {
1695         cfs_hlist_head_t   *hhead;
1696         cfs_hlist_node_t   *hnode;
1697         cfs_hash_bd_t       bd;
1698         ENTRY;
1699
1700         cfs_hash_for_each_enter(hs);
1701         cfs_hash_lock(hs, 0);
1702         if (hindex >= CFS_HASH_NHLIST(hs))
1703                 goto out;
1704
1705         bd.bd_bucket = hs->hs_buckets[hindex >> hs->hs_bkt_bits];
1706         bd.bd_offset = hindex & (CFS_HASH_BKT_NHLIST(hs) - 1);
1707
1708         cfs_hash_bd_lock(hs, &bd, 0);
1709         hhead = cfs_hash_bd_hhead(hs, &bd);
1710         cfs_hlist_for_each(hnode, hhead) {
1711                 if (func(hs, &bd, hnode, data))
1712                         break;
1713         }
1714         cfs_hash_bd_unlock(hs, &bd, 0);
1715  out:
1716         cfs_hash_unlock(hs, 0);
1717         cfs_hash_for_each_exit(hs);
1718         EXIT;
1719 }
1720
1721 CFS_EXPORT_SYMBOL(cfs_hash_hlist_for_each);
1722
1723 /*
1724  * For each item in the libcfs hash @hs which matches the @key call
1725  * the passed callback @func and pass to it as an argument each hash
1726  * item and the private @data. During the callback the bucket lock
1727  * is held so the callback must never sleep.
1728    */
1729 void
1730 cfs_hash_for_each_key(cfs_hash_t *hs, void *key,
1731                       cfs_hash_for_each_cb_t func, void *data)
1732 {
1733         cfs_hlist_node_t   *hnode;
1734         cfs_hash_bd_t       bds[2];
1735         unsigned            i;
1736         ENTRY;
1737
1738         cfs_hash_lock(hs, 0);
1739
1740         cfs_hash_dual_bd_get_and_lock(hs, key, bds, 0);
1741
1742         cfs_hash_for_each_bd(bds, 2, i) {
1743                 cfs_hlist_head_t *hlist = cfs_hash_bd_hhead(hs, &bds[i]);
1744
1745                 cfs_hlist_for_each(hnode, hlist) {
1746                         cfs_hash_bucket_validate(hs, &bds[i], hnode);
1747
1748                         if (cfs_hash_keycmp(hs, key, hnode)) {
1749                                 if (func(hs, &bds[i], hnode, data))
1750                                         break;
1751                         }
1752                 }
1753         }
1754
1755         cfs_hash_dual_bd_unlock(hs, bds, 0);
1756         cfs_hash_unlock(hs, 0);
1757
1758         EXIT;
1759 }
1760 CFS_EXPORT_SYMBOL(cfs_hash_for_each_key);
1761
1762 /**
1763  * Rehash the libcfs hash @hs to the given @bits.  This can be used
1764  * to grow the hash size when excessive chaining is detected, or to
1765  * shrink the hash when it is larger than needed.  When the CFS_HASH_REHASH
1766  * flag is set in @hs the libcfs hash may be dynamically rehashed
1767  * during addition or removal if the hash's theta value exceeds
1768  * either the hs->hs_min_theta or hs->max_theta values.  By default
1769  * these values are tuned to keep the chained hash depth small, and
1770  * this approach assumes a reasonably uniform hashing function.  The
1771  * theta thresholds for @hs are tunable via cfs_hash_set_theta().
1772  */
1773 void
1774 cfs_hash_rehash_cancel_locked(cfs_hash_t *hs)
1775 {
1776         int     i;
1777
1778         /* need hold cfs_hash_lock(hs, 1) */
1779         LASSERT(cfs_hash_with_rehash(hs) &&
1780                 !cfs_hash_with_no_lock(hs));
1781
1782         if (!cfs_hash_is_rehashing(hs))
1783                 return;
1784
1785         if (cfs_wi_cancel(&hs->hs_rehash_wi)) {
1786                 hs->hs_rehash_bits = 0;
1787                 return;
1788         }
1789
1790         for (i = 2; cfs_hash_is_rehashing(hs); i++) {
1791                 cfs_hash_unlock(hs, 1);
1792                 /* raise console warning while waiting too long */
1793                 CDEBUG(IS_PO2(i >> 3) ? D_WARNING : D_INFO,
1794                        "hash %s is still rehashing, rescheded %d\n",
1795                        hs->hs_name, i - 1);
1796                 cfs_cond_resched();
1797                 cfs_hash_lock(hs, 1);
1798         }
1799 }
1800 CFS_EXPORT_SYMBOL(cfs_hash_rehash_cancel_locked);
1801
1802 void
1803 cfs_hash_rehash_cancel(cfs_hash_t *hs)
1804 {
1805         cfs_hash_lock(hs, 1);
1806         cfs_hash_rehash_cancel_locked(hs);
1807         cfs_hash_unlock(hs, 1);
1808 }
1809 CFS_EXPORT_SYMBOL(cfs_hash_rehash_cancel);
1810
1811 int
1812 cfs_hash_rehash(cfs_hash_t *hs, int do_rehash)
1813 {
1814         int     rc;
1815         ENTRY;
1816
1817         LASSERT(cfs_hash_with_rehash(hs) && !cfs_hash_with_no_lock(hs));
1818
1819         cfs_hash_lock(hs, 1);
1820
1821         rc = cfs_hash_rehash_bits(hs);
1822         if (rc <= 0) {
1823                 cfs_hash_unlock(hs, 1);
1824                 return rc;
1825         }
1826
1827         hs->hs_rehash_bits = rc;
1828         if (!do_rehash) {
1829                 /* launch and return */
1830                 cfs_wi_schedule(&hs->hs_rehash_wi);
1831                 cfs_hash_unlock(hs, 1);
1832                 return 0;
1833         }
1834
1835         /* rehash right now */
1836         cfs_hash_unlock(hs, 1);
1837
1838         return cfs_hash_rehash_worker(&hs->hs_rehash_wi);
1839 }
1840 CFS_EXPORT_SYMBOL(cfs_hash_rehash);
1841
1842 static int
1843 cfs_hash_rehash_bd(cfs_hash_t *hs, cfs_hash_bd_t *old)
1844 {
1845         cfs_hash_bd_t      new;
1846         cfs_hlist_head_t  *hhead;
1847         cfs_hlist_node_t  *hnode;
1848         cfs_hlist_node_t  *pos;
1849         void              *key;
1850         int                c = 0;
1851
1852         /* hold cfs_hash_lock(hs, 1), so don't need any bucket lock */
1853         cfs_hash_bd_for_each_hlist(hs, old, hhead) {
1854                 cfs_hlist_for_each_safe(hnode, pos, hhead) {
1855                         key = cfs_hash_key(hs, hnode);
1856                         LASSERT(key != NULL);
1857                         /* Validate hnode is in the correct bucket. */
1858                         cfs_hash_bucket_validate(hs, old, hnode);
1859                         /*
1860                          * Delete from old hash bucket; move to new bucket.
1861                          * ops->hs_key must be defined.
1862                          */
1863                         cfs_hash_bd_from_key(hs, hs->hs_rehash_buckets,
1864                                              hs->hs_rehash_bits, key, &new);
1865                         cfs_hash_bd_move_locked(hs, old, &new, hnode);
1866                         c++;
1867                 }
1868         }
1869
1870         return c;
1871 }
1872
1873 static int
1874 cfs_hash_rehash_worker(cfs_workitem_t *wi)
1875 {
1876         cfs_hash_t         *hs = container_of(wi, cfs_hash_t, hs_rehash_wi);
1877         cfs_hash_bucket_t **bkts;
1878         cfs_hash_bd_t       bd;
1879         unsigned int        old_size;
1880         unsigned int        new_size;
1881         int                 bsize;
1882         int                 count = 0;
1883         int                 rc = 0;
1884         int                 i;
1885         ENTRY;
1886
1887         LASSERT (hs != NULL && cfs_hash_with_rehash(hs));
1888
1889         cfs_hash_lock(hs, 0);
1890         LASSERT(cfs_hash_is_rehashing(hs));
1891
1892         old_size = CFS_HASH_NBKT(hs);
1893         new_size = CFS_HASH_RH_NBKT(hs);
1894
1895         cfs_hash_unlock(hs, 0);
1896
1897         /*
1898          * don't need hs::hs_rwlock for hs::hs_buckets,
1899          * because nobody can change bkt-table except me.
1900          */
1901         bkts = cfs_hash_buckets_realloc(hs, hs->hs_buckets,
1902                                         old_size, new_size);
1903         cfs_hash_lock(hs, 1);
1904         if (bkts == NULL) {
1905                 rc = -ENOMEM;
1906                 goto out;
1907         }
1908
1909         if (bkts == hs->hs_buckets) {
1910                 bkts = NULL; /* do nothing */
1911                 goto out;
1912         }
1913
1914         rc = __cfs_hash_theta(hs);
1915         if ((rc >= hs->hs_min_theta) && (rc <= hs->hs_max_theta)) {
1916                 /* free the new allocated bkt-table */
1917                 old_size = new_size;
1918                 new_size = CFS_HASH_NBKT(hs);
1919                 rc = -EALREADY;
1920                 goto out;
1921         }
1922
1923         LASSERT(hs->hs_rehash_buckets == NULL);
1924         hs->hs_rehash_buckets = bkts;
1925
1926         rc = 0;
1927         cfs_hash_for_each_bucket(hs, &bd, i) {
1928                 if (cfs_hash_is_exiting(hs)) {
1929                         rc = -ESRCH;
1930                         /* someone wants to destroy the hash, abort now */
1931                         if (old_size < new_size) /* OK to free old bkt-table */
1932                                 break;
1933                         /* it's shrinking, need free new bkt-table */
1934                         hs->hs_rehash_buckets = NULL;
1935                         old_size = new_size;
1936                         new_size = CFS_HASH_NBKT(hs);
1937                         goto out;
1938                 }
1939
1940                 count += cfs_hash_rehash_bd(hs, &bd);
1941                 if (count < CFS_HASH_LOOP_HOG ||
1942                     cfs_hash_is_iterating(hs)) { /* need to finish ASAP */
1943                         continue;
1944                 }
1945
1946                 count = 0;
1947                 cfs_hash_unlock(hs, 1);
1948                 cfs_cond_resched();
1949                 cfs_hash_lock(hs, 1);
1950         }
1951
1952         hs->hs_rehash_count++;
1953
1954         bkts = hs->hs_buckets;
1955         hs->hs_buckets = hs->hs_rehash_buckets;
1956         hs->hs_rehash_buckets = NULL;
1957
1958         hs->hs_cur_bits = hs->hs_rehash_bits;
1959  out:
1960         hs->hs_rehash_bits = 0;
1961         if (rc == -ESRCH)
1962                 cfs_wi_exit(wi); /* never be scheduled again */
1963         bsize = cfs_hash_bkt_size(hs);
1964         cfs_hash_unlock(hs, 1);
1965         /* can't refer to @hs anymore because it could be destroyed */
1966         if (bkts != NULL)
1967                 cfs_hash_buckets_free(bkts, bsize, new_size, old_size);
1968         if (rc != 0)
1969                 CDEBUG(D_INFO, "early quit of of rehashing: %d\n", rc);
1970         /* cfs_workitem require us to always return 0 */
1971         RETURN(0);
1972 }
1973
1974 /**
1975  * Rehash the object referenced by @hnode in the libcfs hash @hs.  The
1976  * @old_key must be provided to locate the objects previous location
1977  * in the hash, and the @new_key will be used to reinsert the object.
1978  * Use this function instead of a cfs_hash_add() + cfs_hash_del()
1979  * combo when it is critical that there is no window in time where the
1980  * object is missing from the hash.  When an object is being rehashed
1981  * the registered cfs_hash_get() and cfs_hash_put() functions will
1982  * not be called.
1983  */
1984 void cfs_hash_rehash_key(cfs_hash_t *hs, void *old_key,
1985                          void *new_key, cfs_hlist_node_t *hnode)
1986 {
1987         cfs_hash_bd_t        bds[3];
1988         cfs_hash_bd_t        old_bds[2];
1989         cfs_hash_bd_t        new_bd;
1990
1991         LASSERT(!cfs_hlist_unhashed(hnode));
1992
1993         cfs_hash_lock(hs, 0);
1994
1995         cfs_hash_dual_bd_get(hs, old_key, old_bds);
1996         cfs_hash_bd_get(hs, new_key, &new_bd);
1997
1998         bds[0] = old_bds[0];
1999         bds[1] = old_bds[1];
2000         bds[2] = new_bd;
2001
2002         /* NB: bds[0] and bds[1] are ordered already */
2003         cfs_hash_bd_order(&bds[1], &bds[2]);
2004         cfs_hash_bd_order(&bds[0], &bds[1]);
2005
2006         cfs_hash_multi_bd_lock(hs, bds, 3, 1);
2007         if (likely(old_bds[1].bd_bucket == NULL)) {
2008                 cfs_hash_bd_move_locked(hs, &old_bds[0], &new_bd, hnode);
2009         } else {
2010                 cfs_hash_dual_bd_finddel_locked(hs, old_bds, old_key, hnode);
2011                 cfs_hash_bd_add_locked(hs, &new_bd, hnode);
2012         }
2013         /* overwrite key inside locks, otherwise may screw up with
2014          * other operations, i.e: rehash */
2015         cfs_hash_keycpy(hs, new_key, hnode);
2016
2017         cfs_hash_multi_bd_unlock(hs, bds, 3, 1);
2018         cfs_hash_unlock(hs, 0);
2019 }
2020 CFS_EXPORT_SYMBOL(cfs_hash_rehash_key);
2021
2022 int cfs_hash_debug_header(char *str, int size)
2023 {
2024         return snprintf(str, size, "%-*s%6s%6s%6s%6s%6s%6s%6s%7s%8s%8s%8s%s\n",
2025                  CFS_HASH_BIGNAME_LEN,
2026                  "name", "cur", "min", "max", "theta", "t-min", "t-max",
2027                  "flags", "rehash", "count", "maxdep", "maxdepb",
2028                  " distribution");
2029 }
2030 CFS_EXPORT_SYMBOL(cfs_hash_debug_header);
2031
2032 static cfs_hash_bucket_t **
2033 cfs_hash_full_bkts(cfs_hash_t *hs)
2034 {
2035         /* NB: caller should hold hs->hs_rwlock if REHASH is set */
2036         if (hs->hs_rehash_buckets == NULL)
2037                 return hs->hs_buckets;
2038
2039         LASSERT(hs->hs_rehash_bits != 0);
2040         return hs->hs_rehash_bits > hs->hs_cur_bits ?
2041                hs->hs_rehash_buckets : hs->hs_buckets;
2042 }
2043
2044 static unsigned int
2045 cfs_hash_full_nbkt(cfs_hash_t *hs)
2046 {
2047         /* NB: caller should hold hs->hs_rwlock if REHASH is set */
2048         if (hs->hs_rehash_buckets == NULL)
2049                 return CFS_HASH_NBKT(hs);
2050
2051         LASSERT(hs->hs_rehash_bits != 0);
2052         return hs->hs_rehash_bits > hs->hs_cur_bits ?
2053                CFS_HASH_RH_NBKT(hs) : CFS_HASH_NBKT(hs);
2054 }
2055
2056 int cfs_hash_debug_str(cfs_hash_t *hs, char *str, int size)
2057 {
2058         int                    dist[8] = { 0, };
2059         int                    maxdep  = -1;
2060         int                    maxdepb = -1;
2061         int                    total   = 0;
2062         int                    c       = 0;
2063         int                    theta;
2064         int                    i;
2065
2066         if (str == NULL || size == 0)
2067                 return 0;
2068
2069         cfs_hash_lock(hs, 0);
2070         theta = __cfs_hash_theta(hs);
2071
2072         c += snprintf(str + c, size - c, "%-*s ",
2073                       CFS_HASH_BIGNAME_LEN, hs->hs_name);
2074         c += snprintf(str + c, size - c, "%5d ",  1 << hs->hs_cur_bits);
2075         c += snprintf(str + c, size - c, "%5d ",  1 << hs->hs_min_bits);
2076         c += snprintf(str + c, size - c, "%5d ",  1 << hs->hs_max_bits);
2077         c += snprintf(str + c, size - c, "%d.%03d ",
2078                       __cfs_hash_theta_int(theta),
2079                       __cfs_hash_theta_frac(theta));
2080         c += snprintf(str + c, size - c, "%d.%03d ",
2081                       __cfs_hash_theta_int(hs->hs_min_theta),
2082                       __cfs_hash_theta_frac(hs->hs_min_theta));
2083         c += snprintf(str + c, size - c, "%d.%03d ",
2084                       __cfs_hash_theta_int(hs->hs_max_theta),
2085                       __cfs_hash_theta_frac(hs->hs_max_theta));
2086         c += snprintf(str + c, size - c, " 0x%02x ", hs->hs_flags);
2087         c += snprintf(str + c, size - c, "%6d ", hs->hs_rehash_count);
2088
2089         /*
2090          * The distribution is a summary of the chained hash depth in
2091          * each of the libcfs hash buckets.  Each buckets hsb_count is
2092          * divided by the hash theta value and used to generate a
2093          * histogram of the hash distribution.  A uniform hash will
2094          * result in all hash buckets being close to the average thus
2095          * only the first few entries in the histogram will be non-zero.
2096          * If you hash function results in a non-uniform hash the will
2097          * be observable by outlier bucks in the distribution histogram.
2098          *
2099          * Uniform hash distribution:      128/128/0/0/0/0/0/0
2100          * Non-Uniform hash distribution:  128/125/0/0/0/0/2/1
2101          */
2102         for (i = 0; i < cfs_hash_full_nbkt(hs); i++) {
2103                 cfs_hash_bd_t  bd;
2104
2105                 bd.bd_bucket = cfs_hash_full_bkts(hs)[i];
2106                 cfs_hash_bd_lock(hs, &bd, 0);
2107                 if (maxdep < bd.bd_bucket->hsb_depmax) {
2108                         maxdep  = bd.bd_bucket->hsb_depmax;
2109 #ifdef __KERNEL__
2110                         maxdepb = cfs_ffz(~maxdep);
2111 #endif
2112                 }
2113                 total += bd.bd_bucket->hsb_count;
2114                 dist[min(__cfs_fls(bd.bd_bucket->hsb_count/max(theta,1)),7)]++;
2115                 cfs_hash_bd_unlock(hs, &bd, 0);
2116         }
2117
2118         c += snprintf(str + c, size - c, "%7d ", total);
2119         c += snprintf(str + c, size - c, "%7d ", maxdep);
2120         c += snprintf(str + c, size - c, "%7d ", maxdepb);
2121         for (i = 0; i < 8; i++)
2122                 c += snprintf(str + c, size - c, "%d%c",  dist[i],
2123                               (i == 7) ? '\n' : '/');
2124
2125         cfs_hash_unlock(hs, 0);
2126
2127         return c;
2128 }
2129 CFS_EXPORT_SYMBOL(cfs_hash_debug_str);