string_table.c 2.2 KB

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