summaryrefslogtreecommitdiff
path: root/arm9/lib/NitroSDK/src/OS_vramExclusive.c
blob: 5ce10f4acbd2be35ea70542a3dcb81e09fd6c660 (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
#include "OS_vramExclusive.h"
#include "function_target.h"
#include "OS_system.h"

static u32 OSi_vramExclusive;
static u16 OSi_vramLockId[9];

static u32 OsCountZeroBits(register u32 bitmap);

ARM_FUNC static asm u32 OsCountZeroBits(register u32 bitmap)
{
    clz r0, r0
    bx lr
}

ARM_FUNC void OSi_InitVramExclusive(void)
{
    OSi_vramExclusive = 0x0000;

    for (s32 i = 0; i < 9; i++)
    {
        OSi_vramLockId[i] = 0;
    }
}

ARM_FUNC BOOL OSi_TryLockVram(u16 bank, u16 lockId)
{
    u32 workMap;
    s32 zeroBits;
    OSIntrMode enabled = OS_DisableInterrupts();

    workMap = (u32)(bank & OSi_vramExclusive);
    while (TRUE)
    {
        zeroBits = (s32)(31 - OsCountZeroBits(workMap));
        if (zeroBits < 0)
        {
            break;
        }
        workMap &= ~(0x00000001 << zeroBits);
        if (OSi_vramLockId[zeroBits] != lockId)
        {
            (void)OS_RestoreInterrupts(enabled);
            return FALSE;
        }
    }

    workMap = (u32)(bank & 0x01ff);
    while (TRUE)
    {
        zeroBits = (s32)(31 - OsCountZeroBits(workMap));
        if (zeroBits < 0)
        {
            break;
        }
        workMap &= ~(0x00000001 << zeroBits);
        OSi_vramLockId[zeroBits] = lockId;
        OSi_vramExclusive |= (0x00000001 << zeroBits);
    }

    (void)OS_RestoreInterrupts(enabled);
    return TRUE;
}

ARM_FUNC void OSi_UnlockVram(u16 bank, u16 lockId)
{
    u32 workMap;
    s32 zeroBits;
    OSIntrMode enabled = OS_DisableInterrupts();

    workMap = (u32)(bank & OSi_vramExclusive & 0x01ff);
    while (TRUE)
    {
        zeroBits = (s32)(31- OsCountZeroBits((u32)workMap));
        if (zeroBits < 0)
        {
            break;
        }
        workMap &= ~(0x00000001 << zeroBits);
        if (OSi_vramLockId[zeroBits] == lockId)
        {
            OSi_vramLockId[zeroBits] = 0;
            OSi_vramExclusive &= ~(0x00000001 << zeroBits);
        }
    }

    (void)OS_RestoreInterrupts(enabled);
}