kref.c 1.6 KB

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