summaryrefslogtreecommitdiff
path: root/include/kernel/spinlock.h
blob: 15111995a91efd092244bbb78c28c4019ddca3f5 (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
// SPDX-License-Identifier: GPL-2.0-or-later
/*
 * Copyright (C) 2026 Richard QIn
 */

#pragma once
#include "common/types.h"

struct cpu;

// Spinlock
// Features: Non-interruptible, busy-wait loop, extremely short hold time.
// Scenario: Protecting core data such as scheduler, interrupt handling, PMM, etc.
class Spinlock
{
public:
    volatile uint32 locked;     // Whether it is locked (0: unlocked, 1: locked)
    const char *name;      // Lock Name (for debugging)
    struct cpu *cpu; // The CPU holding the lock

    // Constructor
    Spinlock() : locked(0), name("uninit"), cpu(nullptr) {}

    // Initialize lock name
    void init(const char *name);

    // Acquire lock
    void acquire();

    // Release lock
    void release();

    // Check if the current CPU holds the lock
    bool holding();
};

// Mutex
// Features: Allows interruption, allows sleeping (yield CPU), can hold for a long time.
// Scenarios: File system IO, device driver waiting, long-term buffering operations.
class Mutex
{
public:
    uint32 locked;    // Whether it is locked
    const char *name; // Lock Name
    int pid;          // PID of the process holding the lock (for debugging)

    Spinlock lk; // Internal spin lock, protects the state of the Mutex itself

    void init(const char *name);
    void acquire();
    void release();
    bool holding();
};