k_scheduler_lock.h 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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/kernel.h"
  11. namespace Kernel {
  12. class KernelCore;
  13. template <typename SchedulerType>
  14. class KAbstractSchedulerLock {
  15. public:
  16. explicit KAbstractSchedulerLock(KernelCore& kernel_) : kernel{kernel_} {}
  17. bool IsLockedByCurrentThread() const {
  18. return this->owner_thread == kernel.GetCurrentEmuThreadID();
  19. }
  20. void Lock() {
  21. if (this->IsLockedByCurrentThread()) {
  22. // If we already own the lock, we can just increment the count.
  23. ASSERT(this->lock_count > 0);
  24. this->lock_count++;
  25. } else {
  26. // Otherwise, we want to disable scheduling and acquire the spinlock.
  27. SchedulerType::DisableScheduling(kernel);
  28. this->spin_lock.lock();
  29. // For debug, ensure that our state is valid.
  30. ASSERT(this->lock_count == 0);
  31. ASSERT(this->owner_thread == EmuThreadHandleInvalid);
  32. // Increment count, take ownership.
  33. this->lock_count = 1;
  34. this->owner_thread = kernel.GetCurrentEmuThreadID();
  35. }
  36. }
  37. void Unlock() {
  38. ASSERT(this->IsLockedByCurrentThread());
  39. ASSERT(this->lock_count > 0);
  40. // Release an instance of the lock.
  41. if ((--this->lock_count) == 0) {
  42. // We're no longer going to hold the lock. Take note of what cores need scheduling.
  43. const u64 cores_needing_scheduling =
  44. SchedulerType::UpdateHighestPriorityThreads(kernel);
  45. // Note that we no longer hold the lock, and unlock the spinlock.
  46. this->owner_thread = EmuThreadHandleInvalid;
  47. this->spin_lock.unlock();
  48. // Enable scheduling, and perform a rescheduling operation.
  49. SchedulerType::EnableScheduling(kernel, cores_needing_scheduling);
  50. }
  51. }
  52. private:
  53. KernelCore& kernel;
  54. Common::SpinLock spin_lock{};
  55. s32 lock_count{};
  56. EmuThreadHandle owner_thread{EmuThreadHandleInvalid};
  57. };
  58. } // namespace Kernel