kref.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. * kref.c - library routines for handling generic reference counted objects
  3. *
  4. * Copyright (C) 2004 Greg Kroah-Hartman <greg@kroah.com>
  5. * Copyright (C) 2004 IBM Corp.
  6. *
  7. * based on lib/kobject.c which was:
  8. * Copyright (C) 2002-2003 Patrick Mochel <mochel@osdl.org>
  9. *
  10. * This file is released under the GPLv2.
  11. *
  12. */
  13. #include <linux/kref.h>
  14. #include <linux/module.h>
  15. #include <linux/slab.h>
  16. /**
  17. * kref_set - initialize object and set refcount to requested number.
  18. * @kref: object in question.
  19. * @num: initial reference counter
  20. */
  21. void kref_set(struct kref *kref, int num)
  22. {
  23. atomic_set(&kref->refcount, num);
  24. smp_mb();
  25. }
  26. /**
  27. * kref_init - initialize object.
  28. * @kref: object in question.
  29. */
  30. void kref_init(struct kref *kref)
  31. {
  32. kref_set(kref, 1);
  33. }
  34. /**
  35. * kref_get - increment refcount for object.
  36. * @kref: object.
  37. */
  38. void kref_get(struct kref *kref)
  39. {
  40. WARN_ON(!atomic_read(&kref->refcount));
  41. atomic_inc(&kref->refcount);
  42. smp_mb__after_atomic_inc();
  43. }
  44. /**
  45. * kref_put - decrement refcount for object.
  46. * @kref: object.
  47. * @release: pointer to the function that will clean up the object when the
  48. * last reference to the object is released.
  49. * This pointer is required, and it is not acceptable to pass kfree
  50. * in as this function.
  51. *
  52. * Decrement the refcount, and if 0, call release().
  53. * Return 1 if the object was removed, otherwise return 0. Beware, if this
  54. * function returns 0, you still can not count on the kref from remaining in
  55. * memory. Only use the return value if you want to see if the kref is now
  56. * gone, not present.
  57. */
  58. int kref_put(struct kref *kref, void (*release)(struct kref *kref))
  59. {
  60. WARN_ON(release == NULL);
  61. WARN_ON(release == (void (*)(struct kref *))kfree);
  62. if (atomic_dec_and_test(&kref->refcount)) {
  63. release(kref);
  64. return 1;
  65. }
  66. return 0;
  67. }
  68. EXPORT_SYMBOL(kref_set);
  69. EXPORT_SYMBOL(kref_init);
  70. EXPORT_SYMBOL(kref_get);
  71. EXPORT_SYMBOL(kref_put);