cookie.h 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /* SPDX-License-Identifier: GPL-2.0 */
  2. #ifndef __LINUX_COOKIE_H
  3. #define __LINUX_COOKIE_H
  4. #include <linux/atomic.h>
  5. #include <linux/percpu.h>
  6. #include <asm/local.h>
  7. struct pcpu_gen_cookie {
  8. local_t nesting;
  9. u64 last;
  10. } __aligned(16);
  11. struct gen_cookie {
  12. struct pcpu_gen_cookie __percpu *local;
  13. atomic64_t forward_last ____cacheline_aligned_in_smp;
  14. atomic64_t reverse_last;
  15. };
  16. #define COOKIE_LOCAL_BATCH 4096
  17. #define DEFINE_COOKIE(name) \
  18. static DEFINE_PER_CPU(struct pcpu_gen_cookie, __##name); \
  19. static struct gen_cookie name = { \
  20. .local = &__##name, \
  21. .forward_last = ATOMIC64_INIT(0), \
  22. .reverse_last = ATOMIC64_INIT(0), \
  23. }
  24. static __always_inline u64 gen_cookie_next(struct gen_cookie *gc)
  25. {
  26. struct pcpu_gen_cookie *local = this_cpu_ptr(gc->local);
  27. u64 val;
  28. if (likely(local_inc_return(&local->nesting) == 1)) {
  29. val = local->last;
  30. if (__is_defined(CONFIG_SMP) &&
  31. unlikely((val & (COOKIE_LOCAL_BATCH - 1)) == 0)) {
  32. s64 next = atomic64_add_return(COOKIE_LOCAL_BATCH,
  33. &gc->forward_last);
  34. val = next - COOKIE_LOCAL_BATCH;
  35. }
  36. local->last = ++val;
  37. } else {
  38. val = atomic64_dec_return(&gc->reverse_last);
  39. }
  40. local_dec(&local->nesting);
  41. return val;
  42. }
  43. #endif /* __LINUX_COOKIE_H */