k_scheduler_lock.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright 2020 yuzu Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. // This file references various implementation details from Atmosphere, an open-source firmware for
  5. // the Nintendo Switch. Copyright 2018-2020 Atmosphere-NX.
  6. #pragma once
  7. #include "common/assert.h"
  8. #include "common/spin_lock.h"
  9. #include "core/hardware_properties.h"
  10. #include "core/hle/kernel/k_thread.h"
  11. #include "core/hle/kernel/kernel.h"
  12. namespace Kernel {
  13. class KernelCore;
  14. template <typename SchedulerType>
  15. class KAbstractSchedulerLock {
  16. public:
  17. explicit KAbstractSchedulerLock(KernelCore& kernel_) : kernel{kernel_} {}
  18. bool IsLockedByCurrentThread() const {
  19. return owner_thread == GetCurrentThreadPointer(kernel);
  20. }
  21. void Lock() {
  22. if (IsLockedByCurrentThread()) {
  23. // If we already own the lock, we can just increment the count.
  24. ASSERT(lock_count > 0);
  25. lock_count++;
  26. } else {
  27. // Otherwise, we want to disable scheduling and acquire the spinlock.
  28. SchedulerType::DisableScheduling(kernel);
  29. spin_lock.lock();
  30. // For debug, ensure that our state is valid.
  31. ASSERT(lock_count == 0);
  32. ASSERT(owner_thread == nullptr);
  33. // Increment count, take ownership.
  34. lock_count = 1;
  35. owner_thread = GetCurrentThreadPointer(kernel);
  36. }
  37. }
  38. void Unlock() {
  39. ASSERT(IsLockedByCurrentThread());
  40. ASSERT(lock_count > 0);
  41. // Release an instance of the lock.
  42. if ((--lock_count) == 0) {
  43. // We're no longer going to hold the lock. Take note of what cores need scheduling.
  44. const u64 cores_needing_scheduling =
  45. SchedulerType::UpdateHighestPriorityThreads(kernel);
  46. // Note that we no longer hold the lock, and unlock the spinlock.
  47. owner_thread = nullptr;
  48. spin_lock.unlock();
  49. // Enable scheduling, and perform a rescheduling operation.
  50. SchedulerType::EnableScheduling(kernel, cores_needing_scheduling);
  51. }
  52. }
  53. private:
  54. KernelCore& kernel;
  55. Common::SpinLock spin_lock{};
  56. s32 lock_count{};
  57. KThread* owner_thread{};
  58. };
  59. } // namespace Kernel