summaryrefslogtreecommitdiff
path: root/Kernel/Lock.cpp
blob: 511d4b3e727b0d401f2bd2d372a24beecc6a7889 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <Kernel/Lock.h>

void Lock::lock()
{
    ASSERT(!Scheduler::is_active());
    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)) {
            if (!m_holder || m_holder == current) {
                m_holder = current;
                ++m_level;
                m_lock.store(false, AK::memory_order_release);
                return;
            }
            m_lock.store(false, AK::memory_order_release);
        }
        Scheduler::donate_to(m_holder, m_name);
    }
}

void Lock::unlock()
{
    for (;;) {
        bool expected = false;
        if (m_lock.compare_exchange_strong(expected, true, AK::memory_order_acq_rel)) {
            ASSERT(m_holder == current);
            ASSERT(m_level);
            --m_level;
            if (m_level) {
                m_lock.store(false, AK::memory_order_release);
                return;
            }
            m_holder = nullptr;
            m_lock.store(false, AK::memory_order_release);
            return;
        }
        Scheduler::donate_to(m_holder, m_name);
    }
}

bool Lock::unlock_if_locked()
{
    for (;;) {
        bool expected = false;
        if (m_lock.compare_exchange_strong(expected, true, AK::memory_order_acq_rel)) {
            if (m_level == 0) {
                m_lock.store(false, AK::memory_order_release);
                return false;
            }
            if (m_holder != current) {
                m_lock.store(false, AK::memory_order_release);
                return false;
            }
            ASSERT(m_level);
            --m_level;
            if (m_level) {
                m_lock.store(false, AK::memory_order_release);
                return false;
            }
            m_holder = nullptr;
            m_lock.store(false, AK::memory_order_release);
            return true;
        }
    }
}