object.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * Landlock LSM - Object management
  4. *
  5. * Copyright © 2016-2020 Mickaël Salaün <[email protected]>
  6. * Copyright © 2018-2020 ANSSI
  7. */
  8. #include <linux/bug.h>
  9. #include <linux/compiler_types.h>
  10. #include <linux/err.h>
  11. #include <linux/kernel.h>
  12. #include <linux/rcupdate.h>
  13. #include <linux/refcount.h>
  14. #include <linux/slab.h>
  15. #include <linux/spinlock.h>
  16. #include "object.h"
  17. struct landlock_object *
  18. landlock_create_object(const struct landlock_object_underops *const underops,
  19. void *const underobj)
  20. {
  21. struct landlock_object *new_object;
  22. if (WARN_ON_ONCE(!underops || !underobj))
  23. return ERR_PTR(-ENOENT);
  24. new_object = kzalloc(sizeof(*new_object), GFP_KERNEL_ACCOUNT);
  25. if (!new_object)
  26. return ERR_PTR(-ENOMEM);
  27. refcount_set(&new_object->usage, 1);
  28. spin_lock_init(&new_object->lock);
  29. new_object->underops = underops;
  30. new_object->underobj = underobj;
  31. return new_object;
  32. }
  33. /*
  34. * The caller must own the object (i.e. thanks to object->usage) to safely put
  35. * it.
  36. */
  37. void landlock_put_object(struct landlock_object *const object)
  38. {
  39. /*
  40. * The call to @object->underops->release(object) might sleep, e.g.
  41. * because of iput().
  42. */
  43. might_sleep();
  44. if (!object)
  45. return;
  46. /*
  47. * If the @object's refcount cannot drop to zero, we can just decrement
  48. * the refcount without holding a lock. Otherwise, the decrement must
  49. * happen under @object->lock for synchronization with things like
  50. * get_inode_object().
  51. */
  52. if (refcount_dec_and_lock(&object->usage, &object->lock)) {
  53. __acquire(&object->lock);
  54. /*
  55. * With @object->lock initially held, remove the reference from
  56. * @object->underobj to @object (if it still exists).
  57. */
  58. object->underops->release(object);
  59. kfree_rcu(object, rcu_free);
  60. }
  61. }