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