2019-07-29 10:00:14 +00:00
|
|
|
#include <Kernel/Lock.h>
|
|
|
|
|
|
|
|
void Lock::lock()
|
|
|
|
{
|
2019-08-22 07:22:30 +00:00
|
|
|
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 (;;) {
|
|
|
|
if (CAS(&m_lock, 1, 0) == 0) {
|
|
|
|
if (!m_holder || m_holder == current) {
|
|
|
|
m_holder = current;
|
|
|
|
++m_level;
|
|
|
|
memory_barrier();
|
|
|
|
m_lock = 0;
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
m_lock = 0;
|
|
|
|
}
|
|
|
|
Scheduler::donate_to(m_holder, m_name);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void Lock::unlock()
|
|
|
|
{
|
|
|
|
for (;;) {
|
|
|
|
if (CAS(&m_lock, 1, 0) == 0) {
|
|
|
|
ASSERT(m_holder == current);
|
|
|
|
ASSERT(m_level);
|
|
|
|
--m_level;
|
|
|
|
if (m_level) {
|
|
|
|
memory_barrier();
|
|
|
|
m_lock = 0;
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
m_holder = nullptr;
|
|
|
|
memory_barrier();
|
|
|
|
m_lock = 0;
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
Scheduler::donate_to(m_holder, m_name);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
bool Lock::unlock_if_locked()
|
|
|
|
{
|
|
|
|
for (;;) {
|
|
|
|
if (CAS(&m_lock, 1, 0) == 0) {
|
|
|
|
if (m_level == 0) {
|
|
|
|
m_lock = 0;
|
|
|
|
return false;
|
|
|
|
}
|
2019-09-14 17:35:07 +00:00
|
|
|
if (m_holder != current) {
|
|
|
|
m_lock = 0;
|
|
|
|
return false;
|
|
|
|
}
|
2019-07-29 10:00:14 +00:00
|
|
|
ASSERT(m_level);
|
|
|
|
--m_level;
|
|
|
|
if (m_level) {
|
|
|
|
memory_barrier();
|
|
|
|
m_lock = 0;
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
m_holder = nullptr;
|
|
|
|
memory_barrier();
|
|
|
|
m_lock = 0;
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|