string_table.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. // SPDX-License-Identifier: GPL-2.0
  2. #include <linux/slab.h>
  3. #include <linux/gfp.h>
  4. #include <linux/string.h>
  5. #include <linux/spinlock.h>
  6. #include <linux/ceph/string_table.h>
  7. static DEFINE_SPINLOCK(string_tree_lock);
  8. static struct rb_root string_tree = RB_ROOT;
  9. struct ceph_string *ceph_find_or_create_string(const char* str, size_t len)
  10. {
  11. struct ceph_string *cs, *exist;
  12. struct rb_node **p, *parent;
  13. int ret;
  14. exist = NULL;
  15. spin_lock(&string_tree_lock);
  16. p = &string_tree.rb_node;
  17. while (*p) {
  18. exist = rb_entry(*p, struct ceph_string, node);
  19. ret = ceph_compare_string(exist, str, len);
  20. if (ret > 0)
  21. p = &(*p)->rb_left;
  22. else if (ret < 0)
  23. p = &(*p)->rb_right;
  24. else
  25. break;
  26. exist = NULL;
  27. }
  28. if (exist && !kref_get_unless_zero(&exist->kref)) {
  29. rb_erase(&exist->node, &string_tree);
  30. RB_CLEAR_NODE(&exist->node);
  31. exist = NULL;
  32. }
  33. spin_unlock(&string_tree_lock);
  34. if (exist)
  35. return exist;
  36. cs = kmalloc(sizeof(*cs) + len + 1, GFP_NOFS);
  37. if (!cs)
  38. return NULL;
  39. kref_init(&cs->kref);
  40. cs->len = len;
  41. memcpy(cs->str, str, len);
  42. cs->str[len] = 0;
  43. retry:
  44. exist = NULL;
  45. parent = NULL;
  46. p = &string_tree.rb_node;
  47. spin_lock(&string_tree_lock);
  48. while (*p) {
  49. parent = *p;
  50. exist = rb_entry(*p, struct ceph_string, node);
  51. ret = ceph_compare_string(exist, str, len);
  52. if (ret > 0)
  53. p = &(*p)->rb_left;
  54. else if (ret < 0)
  55. p = &(*p)->rb_right;
  56. else
  57. break;
  58. exist = NULL;
  59. }
  60. ret = 0;
  61. if (!exist) {
  62. rb_link_node(&cs->node, parent, p);
  63. rb_insert_color(&cs->node, &string_tree);
  64. } else if (!kref_get_unless_zero(&exist->kref)) {
  65. rb_erase(&exist->node, &string_tree);
  66. RB_CLEAR_NODE(&exist->node);
  67. ret = -EAGAIN;
  68. }
  69. spin_unlock(&string_tree_lock);
  70. if (ret == -EAGAIN)
  71. goto retry;
  72. if (exist) {
  73. kfree(cs);
  74. cs = exist;
  75. }
  76. return cs;
  77. }
  78. EXPORT_SYMBOL(ceph_find_or_create_string);
  79. void ceph_release_string(struct kref *ref)
  80. {
  81. struct ceph_string *cs = container_of(ref, struct ceph_string, kref);
  82. spin_lock(&string_tree_lock);
  83. if (!RB_EMPTY_NODE(&cs->node)) {
  84. rb_erase(&cs->node, &string_tree);
  85. RB_CLEAR_NODE(&cs->node);
  86. }
  87. spin_unlock(&string_tree_lock);
  88. kfree_rcu(cs, rcu);
  89. }
  90. EXPORT_SYMBOL(ceph_release_string);
  91. bool ceph_strings_empty(void)
  92. {
  93. return RB_EMPTY_ROOT(&string_tree);
  94. }