ladybird/Kernel/Lock.cpp

77 lines
2.3 KiB
C++
Raw Normal View History

2019-07-29 10:00:14 +00:00
#include <Kernel/Lock.h>
#include <Kernel/Thread.h>
2019-07-29 10:00:14 +00:00
void Lock::lock()
{
ASSERT(!Scheduler::is_active());
2019-07-29 10:00:14 +00:00
if (!are_interrupts_enabled()) {
kprintf("Interrupts disabled when trying to take Lock{%s}\n", m_name);
dump_backtrace();
hang();
}
for (;;) {
bool expected = false;
if (m_lock.compare_exchange_strong(expected, true, AK::memory_order_acq_rel)) {
2019-07-29 10:00:14 +00:00
if (!m_holder || m_holder == current) {
m_holder = current;
++m_level;
m_lock.store(false, AK::memory_order_release);
2019-07-29 10:00:14 +00:00
return;
}
m_lock.store(false, AK::memory_order_release);
(void)current->donate_remaining_timeslice_and_block<Thread::WaitQueueBlocker>(m_holder, m_name, m_queue);
2019-07-29 10:00:14 +00:00
}
}
}
void Lock::unlock()
{
for (;;) {
bool expected = false;
if (m_lock.compare_exchange_strong(expected, true, AK::memory_order_acq_rel)) {
2019-07-29 10:00:14 +00:00
ASSERT(m_holder == current);
ASSERT(m_level);
--m_level;
if (m_level) {
m_lock.store(false, AK::memory_order_release);
2019-07-29 10:00:14 +00:00
return;
}
m_holder = nullptr;
m_queue.wake_one();
m_lock.store(false, AK::memory_order_release);
2019-07-29 10:00:14 +00:00
return;
}
// I don't know *who* is using "m_lock", so just yield.
Scheduler::yield();
2019-07-29 10:00:14 +00:00
}
}
bool Lock::unlock_if_locked()
{
for (;;) {
bool expected = false;
if (m_lock.compare_exchange_strong(expected, true, AK::memory_order_acq_rel)) {
2019-07-29 10:00:14 +00:00
if (m_level == 0) {
m_lock.store(false, AK::memory_order_release);
2019-07-29 10:00:14 +00:00
return false;
}
if (m_holder != current) {
m_lock.store(false, AK::memory_order_release);
return false;
}
2019-07-29 10:00:14 +00:00
ASSERT(m_level);
--m_level;
if (m_level) {
m_lock.store(false, AK::memory_order_release);
2019-07-29 10:00:14 +00:00
return false;
}
m_holder = nullptr;
m_lock.store(false, AK::memory_order_release);
m_queue.wake_one();
2019-07-29 10:00:14 +00:00
return true;
}
// I don't know *who* is using "m_lock", so just yield.
Scheduler::yield();
2019-07-29 10:00:14 +00:00
}
}