aboutsummaryrefslogtreecommitdiff
path: root/src/Ryujinx.HLE/HOS/Kernel/Process/KContextIdManager.cs
blob: 32a751325899024c010dab8e8cfefaf119b9d4a1 (plain) (blame)
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
using System;
using System.Numerics;

namespace Ryujinx.HLE.HOS.Kernel.Process
{
    class KContextIdManager
    {
        private const int IdMasksCount = 8;

        private readonly int[] _idMasks;

        private int _nextFreeBitHint;

        public KContextIdManager()
        {
            _idMasks = new int[IdMasksCount];
        }

        public int GetId()
        {
            lock (_idMasks)
            {
                int id = 0;

                if (!TestBit(_nextFreeBitHint))
                {
                    id = _nextFreeBitHint;
                }
                else
                {
                    for (int index = 0; index < IdMasksCount; index++)
                    {
                        int mask = _idMasks[index];

                        int firstFreeBit = BitOperations.LeadingZeroCount((uint)((mask + 1) & ~mask));

                        if (firstFreeBit < 32)
                        {
                            int baseBit = index * 32 + 31;

                            id = baseBit - firstFreeBit;

                            break;
                        }
                        else if (index == IdMasksCount - 1)
                        {
                            throw new InvalidOperationException("Maximum number of Ids reached!");
                        }
                    }
                }

                _nextFreeBitHint = id + 1;

                SetBit(id);

                return id;
            }
        }

        public void PutId(int id)
        {
            lock (_idMasks)
            {
                ClearBit(id);
            }
        }

        private bool TestBit(int bit)
        {
            return (_idMasks[bit / 32] & (1 << (bit & 31))) != 0;
        }

        private void SetBit(int bit)
        {
            _idMasks[bit / 32] |= (1 << (bit & 31));
        }

        private void ClearBit(int bit)
        {
            _idMasks[bit / 32] &= ~(1 << (bit & 31));
        }
    }
}