kref.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. /**
  16. * kref_set - initialize object and set refcount to requested number.
  17. * @kref: object in question.
  18. * @num: initial reference counter
  19. */
  20. void kref_set(struct kref *kref, int num)
  21. {
  22. atomic_set(&kref->refcount, num);
  23. smp_mb();
  24. }
  25. /**
  26. * kref_init - initialize object.
  27. * @kref: object in question.
  28. */
  29. void kref_init(struct kref *kref)
  30. {
  31. kref_set(kref, 1);
  32. }
  33. /**
  34. * kref_get - increment refcount for object.
  35. * @kref: object.
  36. */
  37. void kref_get(struct kref *kref)
  38. {
  39. WARN_ON(!atomic_read(&kref->refcount));
  40. atomic_inc(&kref->refcount);
  41. smp_mb__after_atomic_inc();
  42. }
  43. /**
  44. * kref_put - decrement refcount for object.
  45. * @kref: object.
  46. * @release: pointer to the function that will clean up the object when the
  47. * last reference to the object is released.
  48. * This pointer is required, and it is not acceptable to pass kfree
  49. * in as this function.
  50. *
  51. * Decrement the refcount, and if 0, call release().
  52. * Return 1 if the object was removed, otherwise return 0. Beware, if this
  53. * function returns 0, you still can not count on the kref from remaining in
  54. * memory. Only use the return value if you want to see if the kref is now
  55. * gone, not present.
  56. */
  57. int kref_put(struct kref *kref, void (*release)(struct kref *kref))
  58. {
  59. WARN_ON(release == NULL);
  60. WARN_ON(release == (void (*)(struct kref *))kfree);
  61. if (atomic_dec_and_test(&kref->refcount)) {
  62. release(kref);
  63. return 1;
  64. }
  65. return 0;
  66. }
  67. EXPORT_SYMBOL(kref_set);
  68. EXPORT_SYMBOL(kref_init);
  69. EXPORT_SYMBOL(kref_get);
  70. EXPORT_SYMBOL(kref_put);