lock.hpp 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #pragma once
  2. #include <cstddef>
  3. #include <stdint.h>
  4. namespace kernel::async {
  5. using spinlock_t = unsigned long volatile;
  6. using lock_context_t = unsigned long;
  7. using preempt_count_t = ssize_t;
  8. void preempt_disable();
  9. void preempt_enable();
  10. preempt_count_t preempt_count();
  11. void init_spinlock(spinlock_t& lock);
  12. void spin_lock(spinlock_t& lock);
  13. void spin_unlock(spinlock_t& lock);
  14. lock_context_t spin_lock_irqsave(spinlock_t& lock);
  15. void spin_unlock_irqrestore(spinlock_t& lock, lock_context_t context);
  16. class mutex {
  17. private:
  18. spinlock_t m_lock;
  19. public:
  20. constexpr mutex() : m_lock{0} {}
  21. mutex(const mutex&) = delete;
  22. ~mutex();
  23. void lock();
  24. void unlock();
  25. lock_context_t lock_irq();
  26. void unlock_irq(lock_context_t state);
  27. };
  28. class lock_guard {
  29. private:
  30. mutex& m_mtx;
  31. public:
  32. explicit inline lock_guard(mutex& mtx) : m_mtx{mtx} { m_mtx.lock(); }
  33. lock_guard(const lock_guard&) = delete;
  34. inline ~lock_guard() { m_mtx.unlock(); }
  35. };
  36. class lock_guard_irq {
  37. private:
  38. mutex& m_mtx;
  39. lock_context_t state;
  40. public:
  41. explicit inline lock_guard_irq(mutex& mtx) : m_mtx{mtx} {
  42. state = m_mtx.lock_irq();
  43. }
  44. lock_guard_irq(const lock_guard_irq&) = delete;
  45. inline ~lock_guard_irq() { m_mtx.unlock_irq(state); }
  46. };
  47. } // namespace kernel::async