Linux-libre 4.9.135-gnu
[librecmc/linux-libre.git] / drivers / staging / lustre / lnet / 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, 2012, 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 "../../include/linux/libcfs/libcfs.h"
109
110 #if CFS_HASH_DEBUG_LEVEL >= CFS_HASH_DEBUG_1
111 static unsigned int warn_on_depth = 8;
112 module_param(warn_on_depth, uint, 0644);
113 MODULE_PARM_DESC(warn_on_depth, "warning when hash depth is high.");
114 #endif
115
116 struct cfs_wi_sched *cfs_sched_rehash;
117
118 static inline void
119 cfs_hash_nl_lock(union cfs_hash_lock *lock, int exclusive) {}
120
121 static inline void
122 cfs_hash_nl_unlock(union cfs_hash_lock *lock, int exclusive) {}
123
124 static inline void
125 cfs_hash_spin_lock(union cfs_hash_lock *lock, int exclusive)
126         __acquires(&lock->spin)
127 {
128         spin_lock(&lock->spin);
129 }
130
131 static inline void
132 cfs_hash_spin_unlock(union cfs_hash_lock *lock, int exclusive)
133         __releases(&lock->spin)
134 {
135         spin_unlock(&lock->spin);
136 }
137
138 static inline void
139 cfs_hash_rw_lock(union cfs_hash_lock *lock, int exclusive)
140         __acquires(&lock->rw)
141 {
142         if (!exclusive)
143                 read_lock(&lock->rw);
144         else
145                 write_lock(&lock->rw);
146 }
147
148 static inline void
149 cfs_hash_rw_unlock(union cfs_hash_lock *lock, int exclusive)
150         __releases(&lock->rw)
151 {
152         if (!exclusive)
153                 read_unlock(&lock->rw);
154         else
155                 write_unlock(&lock->rw);
156 }
157
158 /** No lock hash */
159 static struct cfs_hash_lock_ops cfs_hash_nl_lops = {
160         .hs_lock        = cfs_hash_nl_lock,
161         .hs_unlock      = cfs_hash_nl_unlock,
162         .hs_bkt_lock    = cfs_hash_nl_lock,
163         .hs_bkt_unlock  = cfs_hash_nl_unlock,
164 };
165
166 /** no bucket lock, one spinlock to protect everything */
167 static struct cfs_hash_lock_ops cfs_hash_nbl_lops = {
168         .hs_lock        = cfs_hash_spin_lock,
169         .hs_unlock      = cfs_hash_spin_unlock,
170         .hs_bkt_lock    = cfs_hash_nl_lock,
171         .hs_bkt_unlock  = cfs_hash_nl_unlock,
172 };
173
174 /** spin bucket lock, rehash is enabled */
175 static struct cfs_hash_lock_ops cfs_hash_bkt_spin_lops = {
176         .hs_lock        = cfs_hash_rw_lock,
177         .hs_unlock      = cfs_hash_rw_unlock,
178         .hs_bkt_lock    = cfs_hash_spin_lock,
179         .hs_bkt_unlock  = cfs_hash_spin_unlock,
180 };
181
182 /** rw bucket lock, rehash is enabled */
183 static struct cfs_hash_lock_ops cfs_hash_bkt_rw_lops = {
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 struct cfs_hash_lock_ops cfs_hash_nr_bkt_spin_lops = {
192         .hs_lock        = cfs_hash_nl_lock,
193         .hs_unlock      = cfs_hash_nl_unlock,
194         .hs_bkt_lock    = cfs_hash_spin_lock,
195         .hs_bkt_unlock  = cfs_hash_spin_unlock,
196 };
197
198 /** rw bucket lock, rehash is disabled */
199 static struct cfs_hash_lock_ops cfs_hash_nr_bkt_rw_lops = {
200         .hs_lock        = cfs_hash_nl_lock,
201         .hs_unlock      = cfs_hash_nl_unlock,
202         .hs_bkt_lock    = cfs_hash_rw_lock,
203         .hs_bkt_unlock  = cfs_hash_rw_unlock,
204 };
205
206 static void
207 cfs_hash_lock_setup(struct cfs_hash *hs)
208 {
209         if (cfs_hash_with_no_lock(hs)) {
210                 hs->hs_lops = &cfs_hash_nl_lops;
211
212         } else if (cfs_hash_with_no_bktlock(hs)) {
213                 hs->hs_lops = &cfs_hash_nbl_lops;
214                 spin_lock_init(&hs->hs_lock.spin);
215
216         } else if (cfs_hash_with_rehash(hs)) {
217                 rwlock_init(&hs->hs_lock.rw);
218
219                 if (cfs_hash_with_rw_bktlock(hs))
220                         hs->hs_lops = &cfs_hash_bkt_rw_lops;
221                 else if (cfs_hash_with_spin_bktlock(hs))
222                         hs->hs_lops = &cfs_hash_bkt_spin_lops;
223                 else
224                         LBUG();
225         } else {
226                 if (cfs_hash_with_rw_bktlock(hs))
227                         hs->hs_lops = &cfs_hash_nr_bkt_rw_lops;
228                 else if (cfs_hash_with_spin_bktlock(hs))
229                         hs->hs_lops = &cfs_hash_nr_bkt_spin_lops;
230                 else
231                         LBUG();
232         }
233 }
234
235 /**
236  * Simple hash head without depth tracking
237  * new element is always added to head of hlist
238  */
239 struct cfs_hash_head {
240         struct hlist_head       hh_head;        /**< entries list */
241 };
242
243 static int
244 cfs_hash_hh_hhead_size(struct cfs_hash *hs)
245 {
246         return sizeof(struct cfs_hash_head);
247 }
248
249 static struct hlist_head *
250 cfs_hash_hh_hhead(struct cfs_hash *hs, struct cfs_hash_bd *bd)
251 {
252         struct cfs_hash_head *head;
253
254         head = (struct cfs_hash_head *)&bd->bd_bucket->hsb_head[0];
255         return &head[bd->bd_offset].hh_head;
256 }
257
258 static int
259 cfs_hash_hh_hnode_add(struct cfs_hash *hs, struct cfs_hash_bd *bd,
260                       struct hlist_node *hnode)
261 {
262         hlist_add_head(hnode, cfs_hash_hh_hhead(hs, bd));
263         return -1; /* unknown depth */
264 }
265
266 static int
267 cfs_hash_hh_hnode_del(struct cfs_hash *hs, struct cfs_hash_bd *bd,
268                       struct hlist_node *hnode)
269 {
270         hlist_del_init(hnode);
271         return -1; /* unknown depth */
272 }
273
274 /**
275  * Simple hash head with depth tracking
276  * new element is always added to head of hlist
277  */
278 struct cfs_hash_head_dep {
279         struct hlist_head       hd_head;        /**< entries list */
280         unsigned int            hd_depth;       /**< list length */
281 };
282
283 static int
284 cfs_hash_hd_hhead_size(struct cfs_hash *hs)
285 {
286         return sizeof(struct cfs_hash_head_dep);
287 }
288
289 static struct hlist_head *
290 cfs_hash_hd_hhead(struct cfs_hash *hs, struct cfs_hash_bd *bd)
291 {
292         struct cfs_hash_head_dep   *head;
293
294         head = (struct cfs_hash_head_dep *)&bd->bd_bucket->hsb_head[0];
295         return &head[bd->bd_offset].hd_head;
296 }
297
298 static int
299 cfs_hash_hd_hnode_add(struct cfs_hash *hs, struct cfs_hash_bd *bd,
300                       struct hlist_node *hnode)
301 {
302         struct cfs_hash_head_dep *hh;
303
304         hh = container_of(cfs_hash_hd_hhead(hs, bd),
305                           struct cfs_hash_head_dep, hd_head);
306         hlist_add_head(hnode, &hh->hd_head);
307         return ++hh->hd_depth;
308 }
309
310 static int
311 cfs_hash_hd_hnode_del(struct cfs_hash *hs, struct cfs_hash_bd *bd,
312                       struct hlist_node *hnode)
313 {
314         struct cfs_hash_head_dep *hh;
315
316         hh = container_of(cfs_hash_hd_hhead(hs, bd),
317                           struct cfs_hash_head_dep, hd_head);
318         hlist_del_init(hnode);
319         return --hh->hd_depth;
320 }
321
322 /**
323  * double links hash head without depth tracking
324  * new element is always added to tail of hlist
325  */
326 struct cfs_hash_dhead {
327         struct hlist_head       dh_head;        /**< entries list */
328         struct hlist_node       *dh_tail;       /**< the last entry */
329 };
330
331 static int
332 cfs_hash_dh_hhead_size(struct cfs_hash *hs)
333 {
334         return sizeof(struct cfs_hash_dhead);
335 }
336
337 static struct hlist_head *
338 cfs_hash_dh_hhead(struct cfs_hash *hs, struct cfs_hash_bd *bd)
339 {
340         struct cfs_hash_dhead *head;
341
342         head = (struct cfs_hash_dhead *)&bd->bd_bucket->hsb_head[0];
343         return &head[bd->bd_offset].dh_head;
344 }
345
346 static int
347 cfs_hash_dh_hnode_add(struct cfs_hash *hs, struct cfs_hash_bd *bd,
348                       struct hlist_node *hnode)
349 {
350         struct cfs_hash_dhead *dh;
351
352         dh = container_of(cfs_hash_dh_hhead(hs, bd),
353                           struct cfs_hash_dhead, dh_head);
354         if (dh->dh_tail) /* not empty */
355                 hlist_add_behind(hnode, dh->dh_tail);
356         else /* empty list */
357                 hlist_add_head(hnode, &dh->dh_head);
358         dh->dh_tail = hnode;
359         return -1; /* unknown depth */
360 }
361
362 static int
363 cfs_hash_dh_hnode_del(struct cfs_hash *hs, struct cfs_hash_bd *bd,
364                       struct hlist_node *hnd)
365 {
366         struct cfs_hash_dhead *dh;
367
368         dh = container_of(cfs_hash_dh_hhead(hs, bd),
369                           struct cfs_hash_dhead, dh_head);
370         if (!hnd->next) { /* it's the tail */
371                 dh->dh_tail = (hnd->pprev == &dh->dh_head.first) ? NULL :
372                               container_of(hnd->pprev, struct hlist_node, next);
373         }
374         hlist_del_init(hnd);
375         return -1; /* unknown depth */
376 }
377
378 /**
379  * double links hash head with depth tracking
380  * new element is always added to tail of hlist
381  */
382 struct cfs_hash_dhead_dep {
383         struct hlist_head       dd_head;        /**< entries list */
384         struct hlist_node       *dd_tail;       /**< the last entry */
385         unsigned int            dd_depth;       /**< list length */
386 };
387
388 static int
389 cfs_hash_dd_hhead_size(struct cfs_hash *hs)
390 {
391         return sizeof(struct cfs_hash_dhead_dep);
392 }
393
394 static struct hlist_head *
395 cfs_hash_dd_hhead(struct cfs_hash *hs, struct cfs_hash_bd *bd)
396 {
397         struct cfs_hash_dhead_dep *head;
398
399         head = (struct cfs_hash_dhead_dep *)&bd->bd_bucket->hsb_head[0];
400         return &head[bd->bd_offset].dd_head;
401 }
402
403 static int
404 cfs_hash_dd_hnode_add(struct cfs_hash *hs, struct cfs_hash_bd *bd,
405                       struct hlist_node *hnode)
406 {
407         struct cfs_hash_dhead_dep *dh;
408
409         dh = container_of(cfs_hash_dd_hhead(hs, bd),
410                           struct cfs_hash_dhead_dep, dd_head);
411         if (dh->dd_tail) /* not empty */
412                 hlist_add_behind(hnode, dh->dd_tail);
413         else /* empty list */
414                 hlist_add_head(hnode, &dh->dd_head);
415         dh->dd_tail = hnode;
416         return ++dh->dd_depth;
417 }
418
419 static int
420 cfs_hash_dd_hnode_del(struct cfs_hash *hs, struct cfs_hash_bd *bd,
421                       struct hlist_node *hnd)
422 {
423         struct cfs_hash_dhead_dep *dh;
424
425         dh = container_of(cfs_hash_dd_hhead(hs, bd),
426                           struct cfs_hash_dhead_dep, dd_head);
427         if (!hnd->next) { /* it's the tail */
428                 dh->dd_tail = (hnd->pprev == &dh->dd_head.first) ? NULL :
429                               container_of(hnd->pprev, struct hlist_node, next);
430         }
431         hlist_del_init(hnd);
432         return --dh->dd_depth;
433 }
434
435 static struct cfs_hash_hlist_ops cfs_hash_hh_hops = {
436         .hop_hhead      = cfs_hash_hh_hhead,
437         .hop_hhead_size = cfs_hash_hh_hhead_size,
438         .hop_hnode_add  = cfs_hash_hh_hnode_add,
439         .hop_hnode_del  = cfs_hash_hh_hnode_del,
440 };
441
442 static struct cfs_hash_hlist_ops cfs_hash_hd_hops = {
443         .hop_hhead      = cfs_hash_hd_hhead,
444         .hop_hhead_size = cfs_hash_hd_hhead_size,
445         .hop_hnode_add  = cfs_hash_hd_hnode_add,
446         .hop_hnode_del  = cfs_hash_hd_hnode_del,
447 };
448
449 static struct cfs_hash_hlist_ops cfs_hash_dh_hops = {
450         .hop_hhead      = cfs_hash_dh_hhead,
451         .hop_hhead_size = cfs_hash_dh_hhead_size,
452         .hop_hnode_add  = cfs_hash_dh_hnode_add,
453         .hop_hnode_del  = cfs_hash_dh_hnode_del,
454 };
455
456 static struct cfs_hash_hlist_ops cfs_hash_dd_hops = {
457         .hop_hhead      = cfs_hash_dd_hhead,
458         .hop_hhead_size = cfs_hash_dd_hhead_size,
459         .hop_hnode_add  = cfs_hash_dd_hnode_add,
460         .hop_hnode_del  = cfs_hash_dd_hnode_del,
461 };
462
463 static void
464 cfs_hash_hlist_setup(struct cfs_hash *hs)
465 {
466         if (cfs_hash_with_add_tail(hs)) {
467                 hs->hs_hops = cfs_hash_with_depth(hs) ?
468                               &cfs_hash_dd_hops : &cfs_hash_dh_hops;
469         } else {
470                 hs->hs_hops = cfs_hash_with_depth(hs) ?
471                               &cfs_hash_hd_hops : &cfs_hash_hh_hops;
472         }
473 }
474
475 static void
476 cfs_hash_bd_from_key(struct cfs_hash *hs, struct cfs_hash_bucket **bkts,
477                      unsigned int bits, const void *key, struct cfs_hash_bd *bd)
478 {
479         unsigned int index = cfs_hash_id(hs, key, (1U << bits) - 1);
480
481         LASSERT(bits == hs->hs_cur_bits || bits == hs->hs_rehash_bits);
482
483         bd->bd_bucket = bkts[index & ((1U << (bits - hs->hs_bkt_bits)) - 1)];
484         bd->bd_offset = index >> (bits - hs->hs_bkt_bits);
485 }
486
487 void
488 cfs_hash_bd_get(struct cfs_hash *hs, const void *key, struct cfs_hash_bd *bd)
489 {
490         /* NB: caller should hold hs->hs_rwlock if REHASH is set */
491         if (likely(!hs->hs_rehash_buckets)) {
492                 cfs_hash_bd_from_key(hs, hs->hs_buckets,
493                                      hs->hs_cur_bits, key, bd);
494         } else {
495                 LASSERT(hs->hs_rehash_bits != 0);
496                 cfs_hash_bd_from_key(hs, hs->hs_rehash_buckets,
497                                      hs->hs_rehash_bits, key, bd);
498         }
499 }
500 EXPORT_SYMBOL(cfs_hash_bd_get);
501
502 static inline void
503 cfs_hash_bd_dep_record(struct cfs_hash *hs, struct cfs_hash_bd *bd, int dep_cur)
504 {
505         if (likely(dep_cur <= bd->bd_bucket->hsb_depmax))
506                 return;
507
508         bd->bd_bucket->hsb_depmax = dep_cur;
509 # if CFS_HASH_DEBUG_LEVEL >= CFS_HASH_DEBUG_1
510         if (likely(warn_on_depth == 0 ||
511                    max(warn_on_depth, hs->hs_dep_max) >= dep_cur))
512                 return;
513
514         spin_lock(&hs->hs_dep_lock);
515         hs->hs_dep_max  = dep_cur;
516         hs->hs_dep_bkt  = bd->bd_bucket->hsb_index;
517         hs->hs_dep_off  = bd->bd_offset;
518         hs->hs_dep_bits = hs->hs_cur_bits;
519         spin_unlock(&hs->hs_dep_lock);
520
521         cfs_wi_schedule(cfs_sched_rehash, &hs->hs_dep_wi);
522 # endif
523 }
524
525 void
526 cfs_hash_bd_add_locked(struct cfs_hash *hs, struct cfs_hash_bd *bd,
527                        struct hlist_node *hnode)
528 {
529         int rc;
530
531         rc = hs->hs_hops->hop_hnode_add(hs, bd, hnode);
532         cfs_hash_bd_dep_record(hs, bd, rc);
533         bd->bd_bucket->hsb_version++;
534         if (unlikely(bd->bd_bucket->hsb_version == 0))
535                 bd->bd_bucket->hsb_version++;
536         bd->bd_bucket->hsb_count++;
537
538         if (cfs_hash_with_counter(hs))
539                 atomic_inc(&hs->hs_count);
540         if (!cfs_hash_with_no_itemref(hs))
541                 cfs_hash_get(hs, hnode);
542 }
543 EXPORT_SYMBOL(cfs_hash_bd_add_locked);
544
545 void
546 cfs_hash_bd_del_locked(struct cfs_hash *hs, struct cfs_hash_bd *bd,
547                        struct hlist_node *hnode)
548 {
549         hs->hs_hops->hop_hnode_del(hs, bd, hnode);
550
551         LASSERT(bd->bd_bucket->hsb_count > 0);
552         bd->bd_bucket->hsb_count--;
553         bd->bd_bucket->hsb_version++;
554         if (unlikely(bd->bd_bucket->hsb_version == 0))
555                 bd->bd_bucket->hsb_version++;
556
557         if (cfs_hash_with_counter(hs)) {
558                 LASSERT(atomic_read(&hs->hs_count) > 0);
559                 atomic_dec(&hs->hs_count);
560         }
561         if (!cfs_hash_with_no_itemref(hs))
562                 cfs_hash_put_locked(hs, hnode);
563 }
564 EXPORT_SYMBOL(cfs_hash_bd_del_locked);
565
566 void
567 cfs_hash_bd_move_locked(struct cfs_hash *hs, struct cfs_hash_bd *bd_old,
568                         struct cfs_hash_bd *bd_new, struct hlist_node *hnode)
569 {
570         struct cfs_hash_bucket *obkt = bd_old->bd_bucket;
571         struct cfs_hash_bucket *nbkt = bd_new->bd_bucket;
572         int rc;
573
574         if (cfs_hash_bd_compare(bd_old, bd_new) == 0)
575                 return;
576
577         /* use cfs_hash_bd_hnode_add/del, to avoid atomic & refcount ops
578          * in cfs_hash_bd_del/add_locked
579          */
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 = BIT(0),
598         /** return entry with a ref */
599         CFS_HS_LOOKUP_MASK_REF  = BIT(1),
600         /** add entry if not existing */
601         CFS_HS_LOOKUP_MASK_ADD  = BIT(2),
602         /** delete entry, ignore other masks */
603         CFS_HS_LOOKUP_MASK_DEL  = BIT(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          */
637         match = intent_add ? NULL : hnode;
638         hlist_for_each(ehnode, hhead) {
639                 if (!cfs_hash_keycmp(hs, key, ehnode))
640                         continue;
641
642                 if (match && match != ehnode) /* can't match */
643                         continue;
644
645                 /* match and ... */
646                 if ((intent & CFS_HS_LOOKUP_MASK_DEL) != 0) {
647                         cfs_hash_bd_del_locked(hs, bd, ehnode);
648                         return ehnode;
649                 }
650
651                 /* caller wants refcount? */
652                 if ((intent & CFS_HS_LOOKUP_MASK_REF) != 0)
653                         cfs_hash_get(hs, ehnode);
654                 return ehnode;
655         }
656         /* no match item */
657         if (!intent_add)
658                 return NULL;
659
660         LASSERT(hnode);
661         cfs_hash_bd_add_locked(hs, bd, hnode);
662         return hnode;
663 }
664
665 struct hlist_node *
666 cfs_hash_bd_lookup_locked(struct cfs_hash *hs, struct cfs_hash_bd *bd,
667                           const void *key)
668 {
669         return cfs_hash_bd_lookup_intent(hs, bd, key, NULL,
670                                          CFS_HS_LOOKUP_IT_FIND);
671 }
672 EXPORT_SYMBOL(cfs_hash_bd_lookup_locked);
673
674 struct hlist_node *
675 cfs_hash_bd_peek_locked(struct cfs_hash *hs, struct cfs_hash_bd *bd,
676                         const void *key)
677 {
678         return cfs_hash_bd_lookup_intent(hs, bd, key, NULL,
679                                          CFS_HS_LOOKUP_IT_PEEK);
680 }
681 EXPORT_SYMBOL(cfs_hash_bd_peek_locked);
682
683 static void
684 cfs_hash_multi_bd_lock(struct cfs_hash *hs, struct cfs_hash_bd *bds,
685                        unsigned n, int excl)
686 {
687         struct cfs_hash_bucket *prev = NULL;
688         int i;
689
690         /**
691          * bds must be ascendantly ordered by bd->bd_bucket->hsb_index.
692          * NB: it's possible that several bds point to the same bucket but
693          * have different bd::bd_offset, so need take care of deadlock.
694          */
695         cfs_hash_for_each_bd(bds, n, i) {
696                 if (prev == bds[i].bd_bucket)
697                         continue;
698
699                 LASSERT(!prev || 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)
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);
746         intent = (!noref * CFS_HS_LOOKUP_MASK_REF) | CFS_HS_LOOKUP_IT_PEEK;
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)
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 int 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)
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)
790                 return;
791
792         if (!bd1->bd_bucket) {
793                 *bd1 = *bd2;
794                 bd2->bd_bucket = NULL;
795                 return;
796         }
797
798         rc = cfs_hash_bd_compare(bd1, bd2);
799         if (!rc)
800                 bd2->bd_bucket = NULL;
801         else if (rc > 0)
802                 swap(*bd1, *bd2); /* swap bd1 and bd2 */
803 }
804
805 void
806 cfs_hash_dual_bd_get(struct cfs_hash *hs, const void *key,
807                      struct cfs_hash_bd *bds)
808 {
809         /* NB: caller should hold hs_lock.rw if REHASH is set */
810         cfs_hash_bd_from_key(hs, hs->hs_buckets,
811                              hs->hs_cur_bits, key, &bds[0]);
812         if (likely(!hs->hs_rehash_buckets)) {
813                 /* no rehash or not rehashing */
814                 bds[1].bd_bucket = NULL;
815                 return;
816         }
817
818         LASSERT(hs->hs_rehash_bits != 0);
819         cfs_hash_bd_from_key(hs, hs->hs_rehash_buckets,
820                              hs->hs_rehash_bits, key, &bds[1]);
821
822         cfs_hash_bd_order(&bds[0], &bds[1]);
823 }
824
825 void
826 cfs_hash_dual_bd_lock(struct cfs_hash *hs, struct cfs_hash_bd *bds, int excl)
827 {
828         cfs_hash_multi_bd_lock(hs, bds, 2, excl);
829 }
830
831 void
832 cfs_hash_dual_bd_unlock(struct cfs_hash *hs, struct cfs_hash_bd *bds, int excl)
833 {
834         cfs_hash_multi_bd_unlock(hs, bds, 2, excl);
835 }
836
837 struct hlist_node *
838 cfs_hash_dual_bd_lookup_locked(struct cfs_hash *hs, struct cfs_hash_bd *bds,
839                                const void *key)
840 {
841         return cfs_hash_multi_bd_lookup_locked(hs, bds, 2, key);
842 }
843
844 struct hlist_node *
845 cfs_hash_dual_bd_findadd_locked(struct cfs_hash *hs, struct cfs_hash_bd *bds,
846                                 const void *key, struct hlist_node *hnode,
847                                 int noref)
848 {
849         return cfs_hash_multi_bd_findadd_locked(hs, bds, 2, key,
850                                                 hnode, noref);
851 }
852
853 struct hlist_node *
854 cfs_hash_dual_bd_finddel_locked(struct cfs_hash *hs, struct cfs_hash_bd *bds,
855                                 const void *key, struct hlist_node *hnode)
856 {
857         return cfs_hash_multi_bd_finddel_locked(hs, bds, 2, key, hnode);
858 }
859
860 static void
861 cfs_hash_buckets_free(struct cfs_hash_bucket **buckets,
862                       int bkt_size, int prev_size, int size)
863 {
864         int i;
865
866         for (i = prev_size; i < size; i++) {
867                 if (buckets[i])
868                         LIBCFS_FREE(buckets[i], bkt_size);
869         }
870
871         LIBCFS_FREE(buckets, sizeof(buckets[0]) * size);
872 }
873
874 /*
875  * Create or grow bucket memory. Return old_buckets if no allocation was
876  * needed, the newly allocated buckets if allocation was needed and
877  * successful, and NULL on error.
878  */
879 static struct cfs_hash_bucket **
880 cfs_hash_buckets_realloc(struct cfs_hash *hs, struct cfs_hash_bucket **old_bkts,
881                          unsigned int old_size, unsigned int new_size)
882 {
883         struct cfs_hash_bucket **new_bkts;
884         int i;
885
886         LASSERT(old_size == 0 || old_bkts);
887
888         if (old_bkts && old_size == new_size)
889                 return old_bkts;
890
891         LIBCFS_ALLOC(new_bkts, sizeof(new_bkts[0]) * new_size);
892         if (!new_bkts)
893                 return NULL;
894
895         if (old_bkts) {
896                 memcpy(new_bkts, old_bkts,
897                        min(old_size, new_size) * sizeof(*old_bkts));
898         }
899
900         for (i = old_size; i < new_size; i++) {
901                 struct hlist_head *hhead;
902                 struct cfs_hash_bd bd;
903
904                 LIBCFS_ALLOC(new_bkts[i], cfs_hash_bkt_size(hs));
905                 if (!new_bkts[i]) {
906                         cfs_hash_buckets_free(new_bkts, cfs_hash_bkt_size(hs),
907                                               old_size, new_size);
908                         return NULL;
909                 }
910
911                 new_bkts[i]->hsb_index   = i;
912                 new_bkts[i]->hsb_version = 1;  /* shouldn't be zero */
913                 new_bkts[i]->hsb_depmax  = -1; /* unknown */
914                 bd.bd_bucket = new_bkts[i];
915                 cfs_hash_bd_for_each_hlist(hs, &bd, hhead)
916                         INIT_HLIST_HEAD(hhead);
917
918                 if (cfs_hash_with_no_lock(hs) ||
919                     cfs_hash_with_no_bktlock(hs))
920                         continue;
921
922                 if (cfs_hash_with_rw_bktlock(hs))
923                         rwlock_init(&new_bkts[i]->hsb_lock.rw);
924                 else if (cfs_hash_with_spin_bktlock(hs))
925                         spin_lock_init(&new_bkts[i]->hsb_lock.spin);
926                 else
927                         LBUG(); /* invalid use-case */
928         }
929         return new_bkts;
930 }
931
932 /**
933  * Initialize new libcfs hash, where:
934  * @name     - Descriptive hash name
935  * @cur_bits - Initial hash table size, in bits
936  * @max_bits - Maximum allowed hash table resize, in bits
937  * @ops      - Registered hash table operations
938  * @flags    - CFS_HASH_REHASH enable synamic hash resizing
939  *           - CFS_HASH_SORT enable chained hash sort
940  */
941 static int cfs_hash_rehash_worker(struct cfs_workitem *wi);
942
943 #if CFS_HASH_DEBUG_LEVEL >= CFS_HASH_DEBUG_1
944 static int cfs_hash_dep_print(struct cfs_workitem *wi)
945 {
946         struct cfs_hash *hs = container_of(wi, struct cfs_hash, hs_dep_wi);
947         int dep;
948         int bkt;
949         int off;
950         int bits;
951
952         spin_lock(&hs->hs_dep_lock);
953         dep  = hs->hs_dep_max;
954         bkt  = hs->hs_dep_bkt;
955         off  = hs->hs_dep_off;
956         bits = hs->hs_dep_bits;
957         spin_unlock(&hs->hs_dep_lock);
958
959         LCONSOLE_WARN("#### HASH %s (bits: %d): max depth %d at bucket %d/%d\n",
960                       hs->hs_name, bits, dep, bkt, off);
961         spin_lock(&hs->hs_dep_lock);
962         hs->hs_dep_bits = 0; /* mark as workitem done */
963         spin_unlock(&hs->hs_dep_lock);
964         return 0;
965 }
966
967 static void cfs_hash_depth_wi_init(struct cfs_hash *hs)
968 {
969         spin_lock_init(&hs->hs_dep_lock);
970         cfs_wi_init(&hs->hs_dep_wi, hs, cfs_hash_dep_print);
971 }
972
973 static void cfs_hash_depth_wi_cancel(struct cfs_hash *hs)
974 {
975         if (cfs_wi_deschedule(cfs_sched_rehash, &hs->hs_dep_wi))
976                 return;
977
978         spin_lock(&hs->hs_dep_lock);
979         while (hs->hs_dep_bits != 0) {
980                 spin_unlock(&hs->hs_dep_lock);
981                 cond_resched();
982                 spin_lock(&hs->hs_dep_lock);
983         }
984         spin_unlock(&hs->hs_dep_lock);
985 }
986
987 #else /* CFS_HASH_DEBUG_LEVEL < CFS_HASH_DEBUG_1 */
988
989 static inline void cfs_hash_depth_wi_init(struct cfs_hash *hs) {}
990 static inline void cfs_hash_depth_wi_cancel(struct cfs_hash *hs) {}
991
992 #endif /* CFS_HASH_DEBUG_LEVEL >= CFS_HASH_DEBUG_1 */
993
994 struct cfs_hash *
995 cfs_hash_create(char *name, unsigned cur_bits, unsigned max_bits,
996                 unsigned bkt_bits, unsigned extra_bytes,
997                 unsigned min_theta, unsigned max_theta,
998                 struct cfs_hash_ops *ops, unsigned flags)
999 {
1000         struct cfs_hash *hs;
1001         int len;
1002
1003         CLASSERT(CFS_HASH_THETA_BITS < 15);
1004
1005         LASSERT(name);
1006         LASSERT(ops->hs_key);
1007         LASSERT(ops->hs_hash);
1008         LASSERT(ops->hs_object);
1009         LASSERT(ops->hs_keycmp);
1010         LASSERT(ops->hs_get);
1011         LASSERT(ops->hs_put_locked);
1012
1013         if ((flags & CFS_HASH_REHASH) != 0)
1014                 flags |= CFS_HASH_COUNTER; /* must have counter */
1015
1016         LASSERT(cur_bits > 0);
1017         LASSERT(cur_bits >= bkt_bits);
1018         LASSERT(max_bits >= cur_bits && max_bits < 31);
1019         LASSERT(ergo((flags & CFS_HASH_REHASH) == 0, cur_bits == max_bits));
1020         LASSERT(ergo((flags & CFS_HASH_REHASH) != 0,
1021                      (flags & CFS_HASH_NO_LOCK) == 0));
1022         LASSERT(ergo((flags & CFS_HASH_REHASH_KEY) != 0, ops->hs_keycpy));
1023
1024         len = (flags & CFS_HASH_BIGNAME) == 0 ?
1025               CFS_HASH_NAME_LEN : CFS_HASH_BIGNAME_LEN;
1026         LIBCFS_ALLOC(hs, offsetof(struct cfs_hash, hs_name[len]));
1027         if (!hs)
1028                 return NULL;
1029
1030         strlcpy(hs->hs_name, name, len);
1031         hs->hs_flags = flags;
1032
1033         atomic_set(&hs->hs_refcount, 1);
1034         atomic_set(&hs->hs_count, 0);
1035
1036         cfs_hash_lock_setup(hs);
1037         cfs_hash_hlist_setup(hs);
1038
1039         hs->hs_cur_bits = (__u8)cur_bits;
1040         hs->hs_min_bits = (__u8)cur_bits;
1041         hs->hs_max_bits = (__u8)max_bits;
1042         hs->hs_bkt_bits = (__u8)bkt_bits;
1043
1044         hs->hs_ops         = ops;
1045         hs->hs_extra_bytes = extra_bytes;
1046         hs->hs_rehash_bits = 0;
1047         cfs_wi_init(&hs->hs_rehash_wi, hs, cfs_hash_rehash_worker);
1048         cfs_hash_depth_wi_init(hs);
1049
1050         if (cfs_hash_with_rehash(hs))
1051                 __cfs_hash_set_theta(hs, min_theta, max_theta);
1052
1053         hs->hs_buckets = cfs_hash_buckets_realloc(hs, NULL, 0,
1054                                                   CFS_HASH_NBKT(hs));
1055         if (hs->hs_buckets)
1056                 return hs;
1057
1058         LIBCFS_FREE(hs, offsetof(struct cfs_hash, hs_name[len]));
1059         return NULL;
1060 }
1061 EXPORT_SYMBOL(cfs_hash_create);
1062
1063 /**
1064  * Cleanup libcfs hash @hs.
1065  */
1066 static void
1067 cfs_hash_destroy(struct cfs_hash *hs)
1068 {
1069         struct hlist_node *hnode;
1070         struct hlist_node *pos;
1071         struct cfs_hash_bd bd;
1072         int i;
1073
1074         LASSERT(hs);
1075         LASSERT(!cfs_hash_is_exiting(hs) &&
1076                 !cfs_hash_is_iterating(hs));
1077
1078         /**
1079          * prohibit further rehashes, don't need any lock because
1080          * I'm the only (last) one can change it.
1081          */
1082         hs->hs_exiting = 1;
1083         if (cfs_hash_with_rehash(hs))
1084                 cfs_hash_rehash_cancel(hs);
1085
1086         cfs_hash_depth_wi_cancel(hs);
1087         /* rehash should be done/canceled */
1088         LASSERT(hs->hs_buckets && !hs->hs_rehash_buckets);
1089
1090         cfs_hash_for_each_bucket(hs, &bd, i) {
1091                 struct hlist_head *hhead;
1092
1093                 LASSERT(bd.bd_bucket);
1094                 /* no need to take this lock, just for consistent code */
1095                 cfs_hash_bd_lock(hs, &bd, 1);
1096
1097                 cfs_hash_bd_for_each_hlist(hs, &bd, hhead) {
1098                         hlist_for_each_safe(hnode, pos, hhead) {
1099                                 LASSERTF(!cfs_hash_with_assert_empty(hs),
1100                                          "hash %s bucket %u(%u) is not 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                                  */
1106                                 cfs_hash_bd_del_locked(hs, &bd, hnode);
1107                                 cfs_hash_exit(hs, hnode);
1108                         }
1109                 }
1110                 LASSERT(bd.bd_bucket->hsb_count == 0);
1111                 cfs_hash_bd_unlock(hs, &bd, 1);
1112                 cond_resched();
1113         }
1114
1115         LASSERT(atomic_read(&hs->hs_count) == 0);
1116
1117         cfs_hash_buckets_free(hs->hs_buckets, cfs_hash_bkt_size(hs),
1118                               0, CFS_HASH_NBKT(hs));
1119         i = cfs_hash_with_bigname(hs) ?
1120             CFS_HASH_BIGNAME_LEN : CFS_HASH_NAME_LEN;
1121         LIBCFS_FREE(hs, offsetof(struct cfs_hash, hs_name[i]));
1122 }
1123
1124 struct cfs_hash *cfs_hash_getref(struct cfs_hash *hs)
1125 {
1126         if (atomic_inc_not_zero(&hs->hs_refcount))
1127                 return hs;
1128         return NULL;
1129 }
1130 EXPORT_SYMBOL(cfs_hash_getref);
1131
1132 void cfs_hash_putref(struct cfs_hash *hs)
1133 {
1134         if (atomic_dec_and_test(&hs->hs_refcount))
1135                 cfs_hash_destroy(hs);
1136 }
1137 EXPORT_SYMBOL(cfs_hash_putref);
1138
1139 static inline int
1140 cfs_hash_rehash_bits(struct cfs_hash *hs)
1141 {
1142         if (cfs_hash_with_no_lock(hs) ||
1143             !cfs_hash_with_rehash(hs))
1144                 return -EOPNOTSUPP;
1145
1146         if (unlikely(cfs_hash_is_exiting(hs)))
1147                 return -ESRCH;
1148
1149         if (unlikely(cfs_hash_is_rehashing(hs)))
1150                 return -EALREADY;
1151
1152         if (unlikely(cfs_hash_is_iterating(hs)))
1153                 return -EAGAIN;
1154
1155         /* XXX: need to handle case with max_theta != 2.0
1156          *      and the case with min_theta != 0.5
1157          */
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         LASSERT(hlist_unhashed(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 || !hlist_unhashed(hnode)) {
1287                 if (!bds[1].bd_bucket && hnode) {
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) {
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)
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
1368         /* NB: iteration is mostly called by service thread,
1369          * we tend to cancel pending rehash-request, instead of
1370          * blocking service thread, we will relaunch rehash request
1371          * after iteration
1372          */
1373         if (cfs_hash_is_rehashing(hs))
1374                 cfs_hash_rehash_cancel_locked(hs);
1375         cfs_hash_unlock(hs, 1);
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
1421         cfs_hash_for_each_enter(hs);
1422
1423         cfs_hash_lock(hs, 0);
1424         LASSERT(!cfs_hash_is_rehashing(hs));
1425
1426         cfs_hash_for_each_bucket(hs, &bd, i) {
1427                 struct hlist_head *hhead;
1428
1429                 cfs_hash_bd_lock(hs, &bd, excl);
1430                 if (!func) { /* only glimpse size */
1431                         count += bd.bd_bucket->hsb_count;
1432                         cfs_hash_bd_unlock(hs, &bd, excl);
1433                         continue;
1434                 }
1435
1436                 cfs_hash_bd_for_each_hlist(hs, &bd, hhead) {
1437                         hlist_for_each_safe(hnode, pos, hhead) {
1438                                 cfs_hash_bucket_validate(hs, &bd, hnode);
1439                                 count++;
1440                                 loop++;
1441                                 if (func(hs, &bd, hnode, data)) {
1442                                         cfs_hash_bd_unlock(hs, &bd, excl);
1443                                         goto out;
1444                                 }
1445                         }
1446                 }
1447                 cfs_hash_bd_unlock(hs, &bd, excl);
1448                 if (loop < CFS_HASH_LOOP_HOG)
1449                         continue;
1450                 loop = 0;
1451                 cfs_hash_unlock(hs, 0);
1452                 cond_resched();
1453                 cfs_hash_lock(hs, 0);
1454         }
1455  out:
1456         cfs_hash_unlock(hs, 0);
1457
1458         cfs_hash_for_each_exit(hs);
1459         return count;
1460 }
1461
1462 struct cfs_hash_cond_arg {
1463         cfs_hash_cond_opt_cb_t  func;
1464         void                    *arg;
1465 };
1466
1467 static int
1468 cfs_hash_cond_del_locked(struct cfs_hash *hs, struct cfs_hash_bd *bd,
1469                          struct hlist_node *hnode, void *data)
1470 {
1471         struct cfs_hash_cond_arg *cond = data;
1472
1473         if (cond->func(cfs_hash_object(hs, hnode), cond->arg))
1474                 cfs_hash_bd_del_locked(hs, bd, hnode);
1475         return 0;
1476 }
1477
1478 /**
1479  * Delete item from the libcfs hash @hs when @func return true.
1480  * The write lock being hold during loop for each bucket to avoid
1481  * any object be reference.
1482  */
1483 void
1484 cfs_hash_cond_del(struct cfs_hash *hs, cfs_hash_cond_opt_cb_t func, void *data)
1485 {
1486         struct cfs_hash_cond_arg arg = {
1487                 .func   = func,
1488                 .arg    = data,
1489         };
1490
1491         cfs_hash_for_each_tight(hs, cfs_hash_cond_del_locked, &arg, 1);
1492 }
1493 EXPORT_SYMBOL(cfs_hash_cond_del);
1494
1495 void
1496 cfs_hash_for_each(struct cfs_hash *hs, cfs_hash_for_each_cb_t func,
1497                   void *data)
1498 {
1499         cfs_hash_for_each_tight(hs, func, data, 0);
1500 }
1501 EXPORT_SYMBOL(cfs_hash_for_each);
1502
1503 void
1504 cfs_hash_for_each_safe(struct cfs_hash *hs, cfs_hash_for_each_cb_t func,
1505                        void *data)
1506 {
1507         cfs_hash_for_each_tight(hs, func, data, 1);
1508 }
1509 EXPORT_SYMBOL(cfs_hash_for_each_safe);
1510
1511 static int
1512 cfs_hash_peek(struct cfs_hash *hs, struct cfs_hash_bd *bd,
1513               struct hlist_node *hnode, void *data)
1514 {
1515         *(int *)data = 0;
1516         return 1; /* return 1 to break the loop */
1517 }
1518
1519 int
1520 cfs_hash_is_empty(struct cfs_hash *hs)
1521 {
1522         int empty = 1;
1523
1524         cfs_hash_for_each_tight(hs, cfs_hash_peek, &empty, 0);
1525         return empty;
1526 }
1527 EXPORT_SYMBOL(cfs_hash_is_empty);
1528
1529 __u64
1530 cfs_hash_size_get(struct cfs_hash *hs)
1531 {
1532         return cfs_hash_with_counter(hs) ?
1533                atomic_read(&hs->hs_count) :
1534                cfs_hash_for_each_tight(hs, NULL, NULL, 0);
1535 }
1536 EXPORT_SYMBOL(cfs_hash_size_get);
1537
1538 /*
1539  * cfs_hash_for_each_relax:
1540  * Iterate the hash table and call @func on each item without
1541  * any lock. This function can't guarantee to finish iteration
1542  * if these features are enabled:
1543  *
1544  *  a. if rehash_key is enabled, an item can be moved from
1545  *     one bucket to another bucket
1546  *  b. user can remove non-zero-ref item from hash-table,
1547  *     so the item can be removed from hash-table, even worse,
1548  *     it's possible that user changed key and insert to another
1549  *     hash bucket.
1550  * there's no way for us to finish iteration correctly on previous
1551  * two cases, so iteration has to be stopped on change.
1552  */
1553 static int
1554 cfs_hash_for_each_relax(struct cfs_hash *hs, cfs_hash_for_each_cb_t func,
1555                         void *data)
1556 {
1557         struct hlist_node *hnode;
1558         struct hlist_node *tmp;
1559         struct cfs_hash_bd bd;
1560         __u32 version;
1561         int count = 0;
1562         int stop_on_change;
1563         int rc;
1564         int i;
1565
1566         stop_on_change = cfs_hash_with_rehash_key(hs) ||
1567                          !cfs_hash_with_no_itemref(hs) ||
1568                          !hs->hs_ops->hs_put_locked;
1569         cfs_hash_lock(hs, 0);
1570         LASSERT(!cfs_hash_is_rehashing(hs));
1571
1572         cfs_hash_for_each_bucket(hs, &bd, i) {
1573                 struct hlist_head *hhead;
1574
1575                 cfs_hash_bd_lock(hs, &bd, 0);
1576                 version = cfs_hash_bd_version_get(&bd);
1577
1578                 cfs_hash_bd_for_each_hlist(hs, &bd, hhead) {
1579                         for (hnode = hhead->first; hnode;) {
1580                                 cfs_hash_bucket_validate(hs, &bd, hnode);
1581                                 cfs_hash_get(hs, hnode);
1582                                 cfs_hash_bd_unlock(hs, &bd, 0);
1583                                 cfs_hash_unlock(hs, 0);
1584
1585                                 rc = func(hs, &bd, hnode, data);
1586                                 if (stop_on_change)
1587                                         cfs_hash_put(hs, hnode);
1588                                 cond_resched();
1589                                 count++;
1590
1591                                 cfs_hash_lock(hs, 0);
1592                                 cfs_hash_bd_lock(hs, &bd, 0);
1593                                 if (!stop_on_change) {
1594                                         tmp = hnode->next;
1595                                         cfs_hash_put_locked(hs, hnode);
1596                                         hnode = tmp;
1597                                 } else { /* bucket changed? */
1598                                         if (version !=
1599                                             cfs_hash_bd_version_get(&bd))
1600                                                 break;
1601                                         /* safe to continue because no change */
1602                                         hnode = hnode->next;
1603                                 }
1604                                 if (rc) /* callback wants to break iteration */
1605                                         break;
1606                         }
1607                         if (rc) /* callback wants to break iteration */
1608                                 break;
1609                 }
1610                 cfs_hash_bd_unlock(hs, &bd, 0);
1611                 if (rc) /* callback wants to break iteration */
1612                         break;
1613         }
1614         cfs_hash_unlock(hs, 0);
1615
1616         return count;
1617 }
1618
1619 int
1620 cfs_hash_for_each_nolock(struct cfs_hash *hs, cfs_hash_for_each_cb_t func,
1621                          void *data)
1622 {
1623         if (cfs_hash_with_no_lock(hs) ||
1624             cfs_hash_with_rehash_key(hs) ||
1625             !cfs_hash_with_no_itemref(hs))
1626                 return -EOPNOTSUPP;
1627
1628         if (!hs->hs_ops->hs_get ||
1629             (!hs->hs_ops->hs_put && !hs->hs_ops->hs_put_locked))
1630                 return -EOPNOTSUPP;
1631
1632         cfs_hash_for_each_enter(hs);
1633         cfs_hash_for_each_relax(hs, func, data);
1634         cfs_hash_for_each_exit(hs);
1635
1636         return 0;
1637 }
1638 EXPORT_SYMBOL(cfs_hash_for_each_nolock);
1639
1640 /**
1641  * For each hash bucket in the libcfs hash @hs call the passed callback
1642  * @func until all the hash buckets are empty.  The passed callback @func
1643  * or the previously registered callback hs->hs_put must remove the item
1644  * from the hash.  You may either use the cfs_hash_del() or hlist_del()
1645  * functions.  No rwlocks will be held during the callback @func it is
1646  * safe to sleep if needed.  This function will not terminate until the
1647  * hash is empty.  Note it is still possible to concurrently add new
1648  * items in to the hash.  It is the callers responsibility to ensure
1649  * the required locking is in place to prevent concurrent insertions.
1650  */
1651 int
1652 cfs_hash_for_each_empty(struct cfs_hash *hs, cfs_hash_for_each_cb_t func,
1653                         void *data)
1654 {
1655         unsigned i = 0;
1656
1657         if (cfs_hash_with_no_lock(hs))
1658                 return -EOPNOTSUPP;
1659
1660         if (!hs->hs_ops->hs_get ||
1661             (!hs->hs_ops->hs_put && !hs->hs_ops->hs_put_locked))
1662                 return -EOPNOTSUPP;
1663
1664         cfs_hash_for_each_enter(hs);
1665         while (cfs_hash_for_each_relax(hs, func, data)) {
1666                 CDEBUG(D_INFO, "Try to empty hash: %s, loop: %u\n",
1667                        hs->hs_name, i++);
1668         }
1669         cfs_hash_for_each_exit(hs);
1670         return 0;
1671 }
1672 EXPORT_SYMBOL(cfs_hash_for_each_empty);
1673
1674 void
1675 cfs_hash_hlist_for_each(struct cfs_hash *hs, unsigned hindex,
1676                         cfs_hash_for_each_cb_t func, void *data)
1677 {
1678         struct hlist_head *hhead;
1679         struct hlist_node *hnode;
1680         struct cfs_hash_bd bd;
1681
1682         cfs_hash_for_each_enter(hs);
1683         cfs_hash_lock(hs, 0);
1684         if (hindex >= CFS_HASH_NHLIST(hs))
1685                 goto out;
1686
1687         cfs_hash_bd_index_set(hs, hindex, &bd);
1688
1689         cfs_hash_bd_lock(hs, &bd, 0);
1690         hhead = cfs_hash_bd_hhead(hs, &bd);
1691         hlist_for_each(hnode, hhead) {
1692                 if (func(hs, &bd, hnode, data))
1693                         break;
1694         }
1695         cfs_hash_bd_unlock(hs, &bd, 0);
1696 out:
1697         cfs_hash_unlock(hs, 0);
1698         cfs_hash_for_each_exit(hs);
1699 }
1700 EXPORT_SYMBOL(cfs_hash_hlist_for_each);
1701
1702 /*
1703  * For each item in the libcfs hash @hs which matches the @key call
1704  * the passed callback @func and pass to it as an argument each hash
1705  * item and the private @data. During the callback the bucket lock
1706  * is held so the callback must never sleep.
1707    */
1708 void
1709 cfs_hash_for_each_key(struct cfs_hash *hs, const void *key,
1710                       cfs_hash_for_each_cb_t func, void *data)
1711 {
1712         struct hlist_node *hnode;
1713         struct cfs_hash_bd bds[2];
1714         unsigned int i;
1715
1716         cfs_hash_lock(hs, 0);
1717
1718         cfs_hash_dual_bd_get_and_lock(hs, key, bds, 0);
1719
1720         cfs_hash_for_each_bd(bds, 2, i) {
1721                 struct hlist_head *hlist = cfs_hash_bd_hhead(hs, &bds[i]);
1722
1723                 hlist_for_each(hnode, hlist) {
1724                         cfs_hash_bucket_validate(hs, &bds[i], hnode);
1725
1726                         if (cfs_hash_keycmp(hs, key, hnode)) {
1727                                 if (func(hs, &bds[i], hnode, data))
1728                                         break;
1729                         }
1730                 }
1731         }
1732
1733         cfs_hash_dual_bd_unlock(hs, bds, 0);
1734         cfs_hash_unlock(hs, 0);
1735 }
1736 EXPORT_SYMBOL(cfs_hash_for_each_key);
1737
1738 /**
1739  * Rehash the libcfs hash @hs to the given @bits.  This can be used
1740  * to grow the hash size when excessive chaining is detected, or to
1741  * shrink the hash when it is larger than needed.  When the CFS_HASH_REHASH
1742  * flag is set in @hs the libcfs hash may be dynamically rehashed
1743  * during addition or removal if the hash's theta value exceeds
1744  * either the hs->hs_min_theta or hs->max_theta values.  By default
1745  * these values are tuned to keep the chained hash depth small, and
1746  * this approach assumes a reasonably uniform hashing function.  The
1747  * theta thresholds for @hs are tunable via cfs_hash_set_theta().
1748  */
1749 void
1750 cfs_hash_rehash_cancel_locked(struct cfs_hash *hs)
1751 {
1752         int i;
1753
1754         /* need hold cfs_hash_lock(hs, 1) */
1755         LASSERT(cfs_hash_with_rehash(hs) &&
1756                 !cfs_hash_with_no_lock(hs));
1757
1758         if (!cfs_hash_is_rehashing(hs))
1759                 return;
1760
1761         if (cfs_wi_deschedule(cfs_sched_rehash, &hs->hs_rehash_wi)) {
1762                 hs->hs_rehash_bits = 0;
1763                 return;
1764         }
1765
1766         for (i = 2; cfs_hash_is_rehashing(hs); i++) {
1767                 cfs_hash_unlock(hs, 1);
1768                 /* raise console warning while waiting too long */
1769                 CDEBUG(is_power_of_2(i >> 3) ? D_WARNING : D_INFO,
1770                        "hash %s is still rehashing, rescheded %d\n",
1771                        hs->hs_name, i - 1);
1772                 cond_resched();
1773                 cfs_hash_lock(hs, 1);
1774         }
1775 }
1776
1777 void
1778 cfs_hash_rehash_cancel(struct cfs_hash *hs)
1779 {
1780         cfs_hash_lock(hs, 1);
1781         cfs_hash_rehash_cancel_locked(hs);
1782         cfs_hash_unlock(hs, 1);
1783 }
1784
1785 int
1786 cfs_hash_rehash(struct cfs_hash *hs, int do_rehash)
1787 {
1788         int rc;
1789
1790         LASSERT(cfs_hash_with_rehash(hs) && !cfs_hash_with_no_lock(hs));
1791
1792         cfs_hash_lock(hs, 1);
1793
1794         rc = cfs_hash_rehash_bits(hs);
1795         if (rc <= 0) {
1796                 cfs_hash_unlock(hs, 1);
1797                 return rc;
1798         }
1799
1800         hs->hs_rehash_bits = rc;
1801         if (!do_rehash) {
1802                 /* launch and return */
1803                 cfs_wi_schedule(cfs_sched_rehash, &hs->hs_rehash_wi);
1804                 cfs_hash_unlock(hs, 1);
1805                 return 0;
1806         }
1807
1808         /* rehash right now */
1809         cfs_hash_unlock(hs, 1);
1810
1811         return cfs_hash_rehash_worker(&hs->hs_rehash_wi);
1812 }
1813
1814 static int
1815 cfs_hash_rehash_bd(struct cfs_hash *hs, struct cfs_hash_bd *old)
1816 {
1817         struct cfs_hash_bd new;
1818         struct hlist_head *hhead;
1819         struct hlist_node *hnode;
1820         struct hlist_node *pos;
1821         void *key;
1822         int c = 0;
1823
1824         /* hold cfs_hash_lock(hs, 1), so don't need any bucket lock */
1825         cfs_hash_bd_for_each_hlist(hs, old, hhead) {
1826                 hlist_for_each_safe(hnode, pos, hhead) {
1827                         key = cfs_hash_key(hs, hnode);
1828                         LASSERT(key);
1829                         /* Validate hnode is in the correct bucket. */
1830                         cfs_hash_bucket_validate(hs, old, hnode);
1831                         /*
1832                          * Delete from old hash bucket; move to new bucket.
1833                          * ops->hs_key must be defined.
1834                          */
1835                         cfs_hash_bd_from_key(hs, hs->hs_rehash_buckets,
1836                                              hs->hs_rehash_bits, key, &new);
1837                         cfs_hash_bd_move_locked(hs, old, &new, hnode);
1838                         c++;
1839                 }
1840         }
1841
1842         return c;
1843 }
1844
1845 static int
1846 cfs_hash_rehash_worker(struct cfs_workitem *wi)
1847 {
1848         struct cfs_hash *hs = container_of(wi, struct cfs_hash, hs_rehash_wi);
1849         struct cfs_hash_bucket **bkts;
1850         struct cfs_hash_bd bd;
1851         unsigned int old_size;
1852         unsigned int new_size;
1853         int bsize;
1854         int count = 0;
1855         int rc = 0;
1856         int i;
1857
1858         LASSERT(hs && cfs_hash_with_rehash(hs));
1859
1860         cfs_hash_lock(hs, 0);
1861         LASSERT(cfs_hash_is_rehashing(hs));
1862
1863         old_size = CFS_HASH_NBKT(hs);
1864         new_size = CFS_HASH_RH_NBKT(hs);
1865
1866         cfs_hash_unlock(hs, 0);
1867
1868         /*
1869          * don't need hs::hs_rwlock for hs::hs_buckets,
1870          * because nobody can change bkt-table except me.
1871          */
1872         bkts = cfs_hash_buckets_realloc(hs, hs->hs_buckets,
1873                                         old_size, new_size);
1874         cfs_hash_lock(hs, 1);
1875         if (!bkts) {
1876                 rc = -ENOMEM;
1877                 goto out;
1878         }
1879
1880         if (bkts == hs->hs_buckets) {
1881                 bkts = NULL; /* do nothing */
1882                 goto out;
1883         }
1884
1885         rc = __cfs_hash_theta(hs);
1886         if ((rc >= hs->hs_min_theta) && (rc <= hs->hs_max_theta)) {
1887                 /* free the new allocated bkt-table */
1888                 old_size = new_size;
1889                 new_size = CFS_HASH_NBKT(hs);
1890                 rc = -EALREADY;
1891                 goto out;
1892         }
1893
1894         LASSERT(!hs->hs_rehash_buckets);
1895         hs->hs_rehash_buckets = bkts;
1896
1897         rc = 0;
1898         cfs_hash_for_each_bucket(hs, &bd, i) {
1899                 if (cfs_hash_is_exiting(hs)) {
1900                         rc = -ESRCH;
1901                         /* someone wants to destroy the hash, abort now */
1902                         if (old_size < new_size) /* OK to free old bkt-table */
1903                                 break;
1904                         /* it's shrinking, need free new bkt-table */
1905                         hs->hs_rehash_buckets = NULL;
1906                         old_size = new_size;
1907                         new_size = CFS_HASH_NBKT(hs);
1908                         goto out;
1909                 }
1910
1911                 count += cfs_hash_rehash_bd(hs, &bd);
1912                 if (count < CFS_HASH_LOOP_HOG ||
1913                     cfs_hash_is_iterating(hs)) { /* need to finish ASAP */
1914                         continue;
1915                 }
1916
1917                 count = 0;
1918                 cfs_hash_unlock(hs, 1);
1919                 cond_resched();
1920                 cfs_hash_lock(hs, 1);
1921         }
1922
1923         hs->hs_rehash_count++;
1924
1925         bkts = hs->hs_buckets;
1926         hs->hs_buckets = hs->hs_rehash_buckets;
1927         hs->hs_rehash_buckets = NULL;
1928
1929         hs->hs_cur_bits = hs->hs_rehash_bits;
1930 out:
1931         hs->hs_rehash_bits = 0;
1932         if (rc == -ESRCH) /* never be scheduled again */
1933                 cfs_wi_exit(cfs_sched_rehash, wi);
1934         bsize = cfs_hash_bkt_size(hs);
1935         cfs_hash_unlock(hs, 1);
1936         /* can't refer to @hs anymore because it could be destroyed */
1937         if (bkts)
1938                 cfs_hash_buckets_free(bkts, bsize, new_size, old_size);
1939         if (rc != 0)
1940                 CDEBUG(D_INFO, "early quit of rehashing: %d\n", rc);
1941         /* return 1 only if cfs_wi_exit is called */
1942         return rc == -ESRCH;
1943 }
1944
1945 /**
1946  * Rehash the object referenced by @hnode in the libcfs hash @hs.  The
1947  * @old_key must be provided to locate the objects previous location
1948  * in the hash, and the @new_key will be used to reinsert the object.
1949  * Use this function instead of a cfs_hash_add() + cfs_hash_del()
1950  * combo when it is critical that there is no window in time where the
1951  * object is missing from the hash.  When an object is being rehashed
1952  * the registered cfs_hash_get() and cfs_hash_put() functions will
1953  * not be called.
1954  */
1955 void cfs_hash_rehash_key(struct cfs_hash *hs, const void *old_key,
1956                          void *new_key, struct hlist_node *hnode)
1957 {
1958         struct cfs_hash_bd bds[3];
1959         struct cfs_hash_bd old_bds[2];
1960         struct cfs_hash_bd new_bd;
1961
1962         LASSERT(!hlist_unhashed(hnode));
1963
1964         cfs_hash_lock(hs, 0);
1965
1966         cfs_hash_dual_bd_get(hs, old_key, old_bds);
1967         cfs_hash_bd_get(hs, new_key, &new_bd);
1968
1969         bds[0] = old_bds[0];
1970         bds[1] = old_bds[1];
1971         bds[2] = new_bd;
1972
1973         /* NB: bds[0] and bds[1] are ordered already */
1974         cfs_hash_bd_order(&bds[1], &bds[2]);
1975         cfs_hash_bd_order(&bds[0], &bds[1]);
1976
1977         cfs_hash_multi_bd_lock(hs, bds, 3, 1);
1978         if (likely(!old_bds[1].bd_bucket)) {
1979                 cfs_hash_bd_move_locked(hs, &old_bds[0], &new_bd, hnode);
1980         } else {
1981                 cfs_hash_dual_bd_finddel_locked(hs, old_bds, old_key, hnode);
1982                 cfs_hash_bd_add_locked(hs, &new_bd, hnode);
1983         }
1984         /* overwrite key inside locks, otherwise may screw up with
1985          * other operations, i.e: rehash
1986          */
1987         cfs_hash_keycpy(hs, hnode, new_key);
1988
1989         cfs_hash_multi_bd_unlock(hs, bds, 3, 1);
1990         cfs_hash_unlock(hs, 0);
1991 }
1992 EXPORT_SYMBOL(cfs_hash_rehash_key);
1993
1994 void cfs_hash_debug_header(struct seq_file *m)
1995 {
1996         seq_printf(m, "%-*s   cur   min   max theta t-min t-max flags rehash   count  maxdep maxdepb distribution\n",
1997                    CFS_HASH_BIGNAME_LEN, "name");
1998 }
1999 EXPORT_SYMBOL(cfs_hash_debug_header);
2000
2001 static struct cfs_hash_bucket **
2002 cfs_hash_full_bkts(struct cfs_hash *hs)
2003 {
2004         /* NB: caller should hold hs->hs_rwlock if REHASH is set */
2005         if (!hs->hs_rehash_buckets)
2006                 return hs->hs_buckets;
2007
2008         LASSERT(hs->hs_rehash_bits != 0);
2009         return hs->hs_rehash_bits > hs->hs_cur_bits ?
2010                hs->hs_rehash_buckets : hs->hs_buckets;
2011 }
2012
2013 static unsigned int
2014 cfs_hash_full_nbkt(struct cfs_hash *hs)
2015 {
2016         /* NB: caller should hold hs->hs_rwlock if REHASH is set */
2017         if (!hs->hs_rehash_buckets)
2018                 return CFS_HASH_NBKT(hs);
2019
2020         LASSERT(hs->hs_rehash_bits != 0);
2021         return hs->hs_rehash_bits > hs->hs_cur_bits ?
2022                CFS_HASH_RH_NBKT(hs) : CFS_HASH_NBKT(hs);
2023 }
2024
2025 void cfs_hash_debug_str(struct cfs_hash *hs, struct seq_file *m)
2026 {
2027         int dist[8] = { 0, };
2028         int maxdep = -1;
2029         int maxdepb = -1;
2030         int total = 0;
2031         int theta;
2032         int i;
2033
2034         cfs_hash_lock(hs, 0);
2035         theta = __cfs_hash_theta(hs);
2036
2037         seq_printf(m, "%-*s %5d %5d %5d %d.%03d %d.%03d %d.%03d  0x%02x %6d ",
2038                    CFS_HASH_BIGNAME_LEN, hs->hs_name,
2039                    1 << hs->hs_cur_bits, 1 << hs->hs_min_bits,
2040                    1 << hs->hs_max_bits,
2041                    __cfs_hash_theta_int(theta), __cfs_hash_theta_frac(theta),
2042                    __cfs_hash_theta_int(hs->hs_min_theta),
2043                    __cfs_hash_theta_frac(hs->hs_min_theta),
2044                    __cfs_hash_theta_int(hs->hs_max_theta),
2045                    __cfs_hash_theta_frac(hs->hs_max_theta),
2046                    hs->hs_flags, hs->hs_rehash_count);
2047
2048         /*
2049          * The distribution is a summary of the chained hash depth in
2050          * each of the libcfs hash buckets.  Each buckets hsb_count is
2051          * divided by the hash theta value and used to generate a
2052          * histogram of the hash distribution.  A uniform hash will
2053          * result in all hash buckets being close to the average thus
2054          * only the first few entries in the histogram will be non-zero.
2055          * If you hash function results in a non-uniform hash the will
2056          * be observable by outlier bucks in the distribution histogram.
2057          *
2058          * Uniform hash distribution:           128/128/0/0/0/0/0/0
2059          * Non-Uniform hash distribution:       128/125/0/0/0/0/2/1
2060          */
2061         for (i = 0; i < cfs_hash_full_nbkt(hs); i++) {
2062                 struct cfs_hash_bd bd;
2063
2064                 bd.bd_bucket = cfs_hash_full_bkts(hs)[i];
2065                 cfs_hash_bd_lock(hs, &bd, 0);
2066                 if (maxdep < bd.bd_bucket->hsb_depmax) {
2067                         maxdep  = bd.bd_bucket->hsb_depmax;
2068                         maxdepb = ffz(~maxdep);
2069                 }
2070                 total += bd.bd_bucket->hsb_count;
2071                 dist[min(fls(bd.bd_bucket->hsb_count / max(theta, 1)), 7)]++;
2072                 cfs_hash_bd_unlock(hs, &bd, 0);
2073         }
2074
2075         seq_printf(m, "%7d %7d %7d ", total, maxdep, maxdepb);
2076         for (i = 0; i < 8; i++)
2077                 seq_printf(m, "%d%c",  dist[i], (i == 7) ? '\n' : '/');
2078
2079         cfs_hash_unlock(hs, 0);
2080 }
2081 EXPORT_SYMBOL(cfs_hash_debug_str);