summaryrefslogtreecommitdiff
path: root/common/JackAtomicState.h
blob: 69c8316e02a2f00f0c5ff0ea05506882fdd3383e (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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
/*
Copyright (C) 2004-2008 Grame

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with this program; if not, write to the Free Software 
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

*/

#ifndef __JackAtomicState__
#define __JackAtomicState__

#include "JackAtomic.h"
#include "JackCompilerDeps.h"
#include <string.h> // for memcpy
#include <cstddef>

namespace Jack
{

/*!
\brief Counter for CAS
*/

PRE_PACKED_STRUCTURE
struct AtomicCounter
{
    union {
        struct {
            UInt16 fShortVal1;	// Cur
            UInt16 fShortVal2;	// Next
        }
        scounter;
        UInt32 fLongVal;
    }info;

	AtomicCounter()
	{
        info.fLongVal = 0;
    }

	AtomicCounter(volatile const AtomicCounter& obj)
	{
		info.fLongVal = obj.info.fLongVal;
	}

	AtomicCounter(volatile AtomicCounter& obj)
	{
		info.fLongVal = obj.info.fLongVal;
	}

 	AtomicCounter& operator=(AtomicCounter& obj)
    {
        info.fLongVal = obj.info.fLongVal;
        return *this;
    }

	AtomicCounter& operator=(volatile AtomicCounter& obj)
	{
        info.fLongVal = obj.info.fLongVal;
        return *this;
    }

} POST_PACKED_STRUCTURE;

#define Counter(e) (e).info.fLongVal
#define CurIndex(e) (e).info.scounter.fShortVal1
#define NextIndex(e) (e).info.scounter.fShortVal2

#define CurArrayIndex(e) (CurIndex(e) & 0x0001)
#define NextArrayIndex(e) ((CurIndex(e) + 1) & 0x0001)

/*!
\brief A class to handle two states (switching from one to the other) in a lock-free manner
*/

// CHECK livelock

PRE_PACKED_STRUCTURE
template <class T>
class JackAtomicState
{

    protected:

        T fState[2];
        alignas(UInt32) alignas(AtomicCounter) volatile AtomicCounter fCounter;
        SInt32 fCallWriteCounter;

        UInt32 WriteNextStateStartAux()
        {
            AtomicCounter old_val;
            AtomicCounter new_val;
            UInt32 cur_index;
            UInt32 next_index;
            bool need_copy;
            do {
                old_val = fCounter;
                new_val = old_val;
                cur_index = CurArrayIndex(new_val);
                next_index = NextArrayIndex(new_val);
                need_copy = (CurIndex(new_val) == NextIndex(new_val));
                NextIndex(new_val) = CurIndex(new_val); // Invalidate next index
            } while (!CAS(Counter(old_val), Counter(new_val), (UInt32*)&fCounter));
            if (need_copy)
                memcpy(&fState[next_index], &fState[cur_index], sizeof(T));
            return next_index;
        }

        void WriteNextStateStopAux()
        {
            AtomicCounter old_val;
            AtomicCounter new_val;
            do {
                old_val = fCounter;
                new_val = old_val;
                NextIndex(new_val)++; // Set next index
            } while (!CAS(Counter(old_val), Counter(new_val), (UInt32*)&fCounter));
        }

    public:

        JackAtomicState()
        {
            static_assert(offsetof(JackAtomicState, fCounter) % sizeof(fCounter) == 0,
                          "fCounter must be aligned within JackAtomicState");
            Counter(fCounter) = 0;
            fCallWriteCounter = 0;
        }

        ~JackAtomicState() // Not virtual ??
        {}

        /*!
        \brief Returns the current state : only valid in the RT reader thread
        */
        T* ReadCurrentState()
        {
            return &fState[CurArrayIndex(fCounter)];
        }

        /*!
        \brief Returns the current state index
        */
        UInt16 GetCurrentIndex()
        {
            return CurIndex(fCounter);
        }

        /*!
        \brief Tries to switch to the next state and returns the new current state (either the same as before if case of switch failure or the new one)
        */
        T* TrySwitchState()
        {
            AtomicCounter old_val;
            AtomicCounter new_val;
            do {
                old_val = fCounter;
                new_val = old_val;
                CurIndex(new_val) = NextIndex(new_val);	// Prepare switch
            } while (!CAS(Counter(old_val), Counter(new_val), (UInt32*)&fCounter));
            return &fState[CurArrayIndex(fCounter)];	// Read the counter again
        }

        /*!
        \brief Tries to switch to the next state and returns the new current state (either the same as before if case of switch failure or the new one)
        */
        T* TrySwitchState(bool* result)
        {
            AtomicCounter old_val;
            AtomicCounter new_val;
            do {
                old_val = fCounter;
                new_val = old_val;
                *result = (CurIndex(new_val) != NextIndex(new_val));
                CurIndex(new_val) = NextIndex(new_val);  // Prepare switch
            } while (!CAS(Counter(old_val), Counter(new_val), (UInt32*)&fCounter));
            return &fState[CurArrayIndex(fCounter)];	// Read the counter again
        }

        /*!
        \brief Start write operation : setup and returns the next state to update, check for recursive write calls.
        */
        T* WriteNextStateStart()
        {
            UInt32 next_index = (fCallWriteCounter++ == 0)
                                ? WriteNextStateStartAux()
                                : NextArrayIndex(fCounter); // We are inside a wrapping WriteNextStateStart call, NextArrayIndex can be read safely
            return &fState[next_index];
        }

        /*!
        \brief Stop write operation : make the next state ready to be used by the RT thread
        */
        void WriteNextStateStop()
        {
            if (--fCallWriteCounter == 0)
                WriteNextStateStopAux();
        }

        bool IsPendingChange()
        {
            return CurIndex(fCounter) != NextIndex(fCounter);
        }

        /*
              // Single writer : write methods get the *next* state to be updated
        void TestWriteMethod()
        {
        	T* state = WriteNextStateStart();
        	......
        	......
        	WriteNextStateStop(); 
        }

              // First RT call possibly switch state
        void TestReadRTMethod1()
        {
        	T* state = TrySwitchState();
        	......
        	......
        }

              // Other RT methods can safely use the current state during the *same* RT cycle
        void TestReadRTMethod2() 
        {
        	T* state = ReadCurrentState();
        	......
        	......
        }

              // Non RT read methods : must check state coherency
        void TestReadMethod()
        {
        	T* state;
        	UInt16 cur_index;
            UInt16 next_index = GetCurrentIndex();
        	do {
                cur_index = next_index;
        		state = ReadCurrentState();
        		
        		......
        		......

                next_index = GetCurrentIndex();
        	} while (cur_index != next_index);
        }
        */

} POST_PACKED_STRUCTURE;

} // end of namespace

#endif