refs.h 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /* SPDX-License-Identifier: GPL-2.0 */
  2. #ifndef IOU_REQ_REF_H
  3. #define IOU_REQ_REF_H
  4. #include <linux/atomic.h>
  5. #include <linux/io_uring_types.h>
  6. /*
  7. * Shamelessly stolen from the mm implementation of page reference checking,
  8. * see commit f958d7b528b1 for details.
  9. */
  10. #define req_ref_zero_or_close_to_overflow(req) \
  11. ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
  12. static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
  13. {
  14. WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
  15. return atomic_inc_not_zero(&req->refs);
  16. }
  17. static inline bool req_ref_put_and_test_atomic(struct io_kiocb *req)
  18. {
  19. WARN_ON_ONCE(!(data_race(req->flags) & REQ_F_REFCOUNT));
  20. WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
  21. return atomic_dec_and_test(&req->refs);
  22. }
  23. static inline bool req_ref_put_and_test(struct io_kiocb *req)
  24. {
  25. if (likely(!(req->flags & REQ_F_REFCOUNT)))
  26. return true;
  27. WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
  28. return atomic_dec_and_test(&req->refs);
  29. }
  30. static inline void req_ref_get(struct io_kiocb *req)
  31. {
  32. WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
  33. WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
  34. atomic_inc(&req->refs);
  35. }
  36. static inline void req_ref_put(struct io_kiocb *req)
  37. {
  38. WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
  39. WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
  40. atomic_dec(&req->refs);
  41. }
  42. static inline void __io_req_set_refcount(struct io_kiocb *req, int nr)
  43. {
  44. if (!(req->flags & REQ_F_REFCOUNT)) {
  45. req->flags |= REQ_F_REFCOUNT;
  46. atomic_set(&req->refs, nr);
  47. }
  48. }
  49. static inline void io_req_set_refcount(struct io_kiocb *req)
  50. {
  51. __io_req_set_refcount(req, 1);
  52. }
  53. #endif