summaryrefslogtreecommitdiff
path: root/src/kernel/spinlock.cc
blob: 210e0b9a27e3bdf7415102228a6c435f7fdef47f (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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include "kernel/spinlock.h"
#include "kernel/riscv.h"
#include "kernel/proc.h"
#include "drivers/uart.h"
#include "common/types.h"

#define NCPU 8

namespace Spinlock
{
    int g_noff[NCPU];

    int g_intena[NCPU];

    int cpuid()
    {
        return r_tp();
    }

    void init(struct spinlock *lk, char* name)
    {
        lk->name = name;
        lk->locked = 0;
        lk->cpu_id = -1;
    }

    void push_off()
    {
        int old = intr_get();
        intr_off();

        int id = cpuid();
        if (g_noff[id] == 0)
        {
            g_intena[id] = old;
        }
        g_noff[id] += 1;
    }

    void pop_off()
    {
        int id = cpuid();
        if (intr_get())
            Drivers::uart_puts("pop_off - interruptible\n");

        if (g_noff[id] < 1)
            Drivers::uart_puts("pop_off - count error\n");

        g_noff[id] -= 1;

        if (g_noff[id] == 0 && g_intena[id])
        {
            intr_on();
        }
    }

    int holding(struct spinlock *lk)
    {
        int r;
        push_off();
        r = (lk->locked && lk->cpu_id == cpuid());
        pop_off();
        return r;
    }

    void acquire(struct spinlock *lk)
    {
        push_off();

        if(holding(lk))
        {
            Drivers::uart_puts("acquire: panic - recursive lock ");
            Drivers::uart_puts(lk->name);
            Drivers::uart_puts("\n");
            while (1)
                ;
        }

        while (__sync_lock_test_and_set(&lk->locked, 1) != 0)
        {
            // 自旋等待
        }

        __sync_synchronize();

        lk->cpu_id = cpuid();
    }

    void release(struct spinlock *lk)
    {
        if (!holding(lk))
        {
            Drivers::uart_puts("release: panic - not holding\n");
            while (1)
                ;
        }

        lk->cpu_id = -1;

        __sync_synchronize();

        __sync_lock_release(&lk->locked);

        pop_off();
    }

} // namespace Spinlock