hash.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // SPDX-License-Identifier: GPL-2.0
  2. /* Copyright (C) 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_obj(*hash, GFP_ATOMIC);
  41. if (!hash)
  42. return NULL;
  43. hash->table = kmalloc_objs(*hash->table, size, GFP_ATOMIC);
  44. if (!hash->table)
  45. goto free_hash;
  46. hash->list_locks = kmalloc_objs(*hash->list_locks, size, GFP_ATOMIC);
  47. if (!hash->list_locks)
  48. goto free_table;
  49. hash->size = size;
  50. batadv_hash_init(hash);
  51. return hash;
  52. free_table:
  53. kfree(hash->table);
  54. free_hash:
  55. kfree(hash);
  56. return NULL;
  57. }
  58. /**
  59. * batadv_hash_set_lock_class() - Set specific lockdep class for hash spinlocks
  60. * @hash: hash object to modify
  61. * @key: lockdep class key address
  62. */
  63. void batadv_hash_set_lock_class(struct batadv_hashtable *hash,
  64. struct lock_class_key *key)
  65. {
  66. u32 i;
  67. for (i = 0; i < hash->size; i++)
  68. lockdep_set_class(&hash->list_locks[i], key);
  69. }