hash.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // SPDX-License-Identifier: GPL-2.0
  2. /* Copyright (C) 2006-2020 B.A.T.M.A.N. contributors:
  3. *
  4. * Simon Wunderlich, Marek Lindner
  5. */
  6. #include "hash.h"
  7. #include "main.h"
  8. #include <linux/gfp.h>
  9. #include <linux/lockdep.h>
  10. #include <linux/slab.h>
  11. /* clears the hash */
  12. static void batadv_hash_init(struct batadv_hashtable *hash)
  13. {
  14. u32 i;
  15. for (i = 0; i < hash->size; i++) {
  16. INIT_HLIST_HEAD(&hash->table[i]);
  17. spin_lock_init(&hash->list_locks[i]);
  18. }
  19. atomic_set(&hash->generation, 0);
  20. }
  21. /**
  22. * batadv_hash_destroy() - Free only the hashtable and the hash itself
  23. * @hash: hash object to destroy
  24. */
  25. void batadv_hash_destroy(struct batadv_hashtable *hash)
  26. {
  27. kfree(hash->list_locks);
  28. kfree(hash->table);
  29. kfree(hash);
  30. }
  31. /**
  32. * batadv_hash_new() - Allocates and clears the hashtable
  33. * @size: number of hash buckets to allocate
  34. *
  35. * Return: newly allocated hashtable, NULL on errors
  36. */
  37. struct batadv_hashtable *batadv_hash_new(u32 size)
  38. {
  39. struct batadv_hashtable *hash;
  40. hash = kmalloc(sizeof(*hash), GFP_ATOMIC);
  41. if (!hash)
  42. return NULL;
  43. hash->table = kmalloc_array(size, sizeof(*hash->table), GFP_ATOMIC);
  44. if (!hash->table)
  45. goto free_hash;
  46. hash->list_locks = kmalloc_array(size, sizeof(*hash->list_locks),
  47. GFP_ATOMIC);
  48. if (!hash->list_locks)
  49. goto free_table;
  50. hash->size = size;
  51. batadv_hash_init(hash);
  52. return hash;
  53. free_table:
  54. kfree(hash->table);
  55. free_hash:
  56. kfree(hash);
  57. return NULL;
  58. }
  59. /**
  60. * batadv_hash_set_lock_class() - Set specific lockdep class for hash spinlocks
  61. * @hash: hash object to modify
  62. * @key: lockdep class key address
  63. */
  64. void batadv_hash_set_lock_class(struct batadv_hashtable *hash,
  65. struct lock_class_key *key)
  66. {
  67. u32 i;
  68. for (i = 0; i < hash->size; i++)
  69. lockdep_set_class(&hash->list_locks[i], key);
  70. }