Merge pull request #1 from richardkogelnig/patch-1
[junction.git] / junction / ConcurrentMap_Linear.h
1 /*------------------------------------------------------------------------
2   Junction: Concurrent data structures in C++
3   Copyright (c) 2016 Jeff Preshing
4
5   Distributed under the Simplified BSD License.
6   Original location: https://github.com/preshing/junction
7
8   This software is distributed WITHOUT ANY WARRANTY; without even the
9   implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10   See the LICENSE file for more information.
11 ------------------------------------------------------------------------*/
12
13 #ifndef JUNCTION_CONCURRENTMAP_LINEAR_H
14 #define JUNCTION_CONCURRENTMAP_LINEAR_H
15
16 #include <junction/Core.h>
17 #include <junction/details/Linear.h>
18 #include <junction/QSBR.h>
19 #include <turf/Heap.h>
20 #include <turf/Trace.h>
21
22 namespace junction {
23
24 TURF_TRACE_DECLARE(ConcurrentMap_Linear, 18)
25
26 template <typename K, typename V, class KT = DefaultKeyTraits<K>, class VT = DefaultValueTraits<V>>
27 class ConcurrentMap_Linear {
28 public:
29     typedef K Key;
30     typedef V Value;
31     typedef KT KeyTraits;
32     typedef VT ValueTraits;
33     typedef typename turf::util::BestFit<Key>::Unsigned Hash;
34     typedef details::Linear<ConcurrentMap_Linear> Details;
35
36 private:
37     turf::Atomic<typename Details::Table*> m_root;
38
39 public:
40     ConcurrentMap_Linear(ureg capacity) {
41         ureg limitNumValues = capacity * 3 / 4;
42         m_root.storeNonatomic(Details::Table::create(capacity, limitNumValues));
43     }
44
45     ~ConcurrentMap_Linear() {
46         typename Details::Table* table = m_root.loadNonatomic();
47         table->destroy();
48     }
49
50     // publishTableMigration() is called by exactly one thread from Details::TableMigration::run()
51     // after all the threads participating in the migration have completed their work.
52     void publishTableMigration(typename Details::TableMigration* migration) {
53         // There are no racing calls to this function.
54         typename Details::Table* oldRoot = m_root.loadNonatomic();
55         m_root.store(migration->m_destination, turf::Release);
56         TURF_ASSERT(oldRoot == migration->m_source);
57         // Caller will GC the TableMigration and the source table.
58     }
59
60     // A Mutator represents a known cell in the hash table.
61     // It's meant for manipulations within a temporary function scope.
62     // Obviously you must not call QSBR::Update while holding a Mutator.
63     // Any operation that modifies the table (exchangeValue, eraseValue)
64     // may be forced to follow a redirected cell, which changes the Mutator itself.
65     // Note that even if the Mutator was constructed from an existing cell,
66     // exchangeValue() can still trigger a resize if the existing cell was previously marked deleted,
67     // or if another thread deletes the key between the two steps.
68     class Mutator {
69     private:
70         friend class ConcurrentMap_Linear;
71
72         ConcurrentMap_Linear& m_map;
73         typename Details::Table* m_table;
74         typename Details::Cell* m_cell;
75         Value m_value;
76
77         // Constructor: Find existing cell
78         Mutator(ConcurrentMap_Linear& map, Key key, bool) : m_map(map), m_value(Value(ValueTraits::NullValue)) {
79             TURF_TRACE(ConcurrentMap_Linear, 0, "[Mutator] find constructor called", uptr(m_table), uptr(key));
80             Hash hash = KeyTraits::hash(key);
81             for (;;) {
82                 m_table = m_map.m_root.load(turf::Consume);
83                 m_cell = Details::find(hash, m_table);
84                 if (!m_cell)
85                     return;
86                 m_value = m_cell->value.load(turf::Consume);
87                 if (m_value != Value(ValueTraits::Redirect))
88                     return;                        // Found an existing value
89                 // We've encountered a Redirect value. Help finish the migration.
90                 TURF_TRACE(ConcurrentMap_Linear, 1, "[Mutator] find was redirected", uptr(m_table), uptr(0));
91                 m_table->jobCoordinator.participate();
92                 // Try again using the latest root.
93             }
94         }
95
96         // Constructor: Insert cell
97         Mutator(ConcurrentMap_Linear& map, Key key) : m_map(map), m_table(map.m_root.load(turf::Consume)), m_value(Value(ValueTraits::NullValue)) {
98             TURF_TRACE(ConcurrentMap_Linear, 2, "[Mutator] insert constructor called", uptr(m_table), uptr(key));
99             Hash hash = KeyTraits::hash(key);
100             for (;;) {
101                 m_table = m_map.m_root.load(turf::Consume);
102                 switch (Details::insert(hash, m_table, m_cell)) {   // Modifies m_cell
103                     case Details::InsertResult_InsertedNew: {
104                         // We've inserted a new cell. Don't load m_cell->value.
105                         return;     
106                     }
107                     case Details::InsertResult_AlreadyFound: {
108                         // The hash was already found in the table.
109                         m_value = m_cell->value.load(turf::Consume);
110                         if (m_value == Value(ValueTraits::Redirect)) {
111                             // We've encountered a Redirect value.
112                             TURF_TRACE(ConcurrentMap_Linear, 3, "[Mutator] insert was redirected", uptr(m_table), uptr(m_value));
113                             break;   // Help finish the migration.
114                         }
115                         return;     // Found an existing value
116                     }
117                     case Details::InsertResult_Overflow: {
118                         Details::beginTableMigration(m_map, m_table);
119                         break;
120                     }
121                 }
122                 // A migration has been started (either by us, or another thread). Participate until it's complete.
123                 m_table->jobCoordinator.participate();
124                 // Try again using the latest root.
125             }
126         }
127
128     public:
129         Value getValue() const {
130             // Return previously loaded value. Don't load it again.
131             return Value(m_value);
132         }
133
134         Value exchangeValue(Value desired) {
135             TURF_ASSERT(desired != Value(ValueTraits::NullValue));
136             TURF_ASSERT(m_cell);    // Cell must have been found or inserted
137             TURF_TRACE(ConcurrentMap_Linear, 4, "[Mutator::exchangeValue] called", uptr(m_table), uptr(m_value));
138             for (;;) {
139                 Value oldValue = m_value;
140                 s32 prevRemainingValues = s32(-1);
141                 if (oldValue == Value(ValueTraits::NullValue)) {
142                     // It's a deleted or newly initialized cell.
143                     // Decrement remainingValues to ensure we have permission to (re)insert a value.
144                     prevRemainingValues = m_table->valuesRemaining.fetchSub(1, turf::Relaxed);
145                     if (prevRemainingValues <= 0) {
146                         TURF_TRACE(ConcurrentMap_Linear, 5, "[Mutator::exchangeValue] ran out of valuesRemaining", uptr(m_table), prevRemainingValues);
147                         // Can't (re)insert any more values.
148                         // There are two ways this can happen. One with a TableMigration already in progress, and one without:
149                         // 1. A TableMigration puts a cap on the number of values late-arriving threads are allowed to insert.
150                         // 2. Two threads race to insert the same key, and it's the last free cell in the table.
151                         // (Note: We could get tid of the valuesRemaining counter by handling the possibility of migration failure,
152                         // as LeapFrog and Grampa do...)
153                         m_table->valuesRemaining.fetchAdd(1, turf::Relaxed);    // Undo valuesRemaining decrement
154                         // Since we don't know whether there's already a TableMigration in progress, always attempt to start one here:
155                         Details::beginTableMigration(m_map, m_table);
156                         goto helpMigrate;
157                     }
158                 }
159                 if (m_cell->value.compareExchangeStrong(m_value, desired, turf::ConsumeRelease)) {
160                     // Exchange was successful. Return previous value.
161                     TURF_TRACE(ConcurrentMap_Linear, 6, "[Mutator::exchangeValue] exchanged Value", uptr(m_value), uptr(desired));
162                     Value result = m_value;
163                     m_value = desired;  // Leave the mutator in a valid state
164                     return result;
165                 }
166                 // The CAS failed and m_value has been updated with the latest value.
167                 if (m_value != Value(ValueTraits::Redirect)) {
168                     TURF_TRACE(ConcurrentMap_Linear, 7, "[Mutator::exchangeValue] detected race to write value", uptr(m_table), uptr(m_value));
169                     if (oldValue == Value(ValueTraits::NullValue) && m_value != Value(ValueTraits::NullValue)) {
170                         TURF_TRACE(ConcurrentMap_Linear, 8, "[Mutator::exchangeValue] racing write inserted new value", uptr(m_table), uptr(m_value));
171                         m_table->valuesRemaining.fetchAdd(1, turf::Relaxed);    // Undo valuesRemaining decrement
172                     }
173                     // There was a racing write (or erase) to this cell.
174                     // Pretend we exchanged with ourselves, and just let the racing write win.
175                     return desired;
176                 }
177                 // We've encountered a Redirect value. Help finish the migration.
178                 TURF_TRACE(ConcurrentMap_Linear, 9, "[Mutator::exchangeValue] was redirected", uptr(m_table), uptr(m_value));
179             helpMigrate:
180                 // Help migrate to new table.
181                 Hash hash = m_cell->hash.load(turf::Relaxed);
182                 for (;;) {
183                     // Help complete the migration.
184                     m_table->jobCoordinator.participate();
185                     // Try again in the new table.
186                     m_table = m_map.m_root.load(turf::Consume);
187                     m_value = Value(ValueTraits::NullValue);
188                     switch (Details::insert(hash, m_table, m_cell)) {   // Modifies m_cell
189                     case Details::InsertResult_AlreadyFound:
190                         m_value = m_cell->value.load(turf::Consume);
191                         if (m_value == Value(ValueTraits::Redirect)) {
192                             TURF_TRACE(ConcurrentMap_Linear, 10, "[Mutator::exchangeValue] was re-redirected", uptr(m_table), uptr(m_value));
193                             break;
194                         }
195                         goto breakOuter;
196                     case Details::InsertResult_InsertedNew:
197                         goto breakOuter;
198                     case Details::InsertResult_Overflow:
199                         TURF_TRACE(ConcurrentMap_Linear, 11, "[Mutator::exchangeValue] overflow after redirect", uptr(m_table), 0);
200                         Details::beginTableMigration(m_map, m_table);
201                         break;
202                     }
203                     // We were redirected... again
204                 }
205             breakOuter:
206                 ;
207                 // Try again in the new table.
208             }
209         }
210
211         void setValue(Value desired) {
212             exchangeValue(desired);
213         }
214
215         Value eraseValue() {
216             TURF_ASSERT(m_cell);    // Cell must have been found or inserted
217             TURF_TRACE(ConcurrentMap_Linear, 12, "[Mutator::eraseValue] called", uptr(m_table), m_cell - m_table->getCells());
218             for (;;) {
219                 if (m_value == Value(ValueTraits::NullValue))
220                     return Value(m_value);
221                 TURF_ASSERT(m_cell);    // m_value is non-NullValue, therefore cell must have been found or inserted.
222                 if (m_cell->value.compareExchangeStrong(m_value, Value(ValueTraits::NullValue), turf::Consume)) {
223                     // Exchange was successful and a non-NULL value was erased and returned by reference in m_value.
224                     TURF_ASSERT(m_value != ValueTraits::NullValue);   // Implied by the test at the start of the loop.
225                     m_table->valuesRemaining.fetchAdd(1, turf::Relaxed);
226                     Value result = m_value;
227                     m_value = Value(ValueTraits::NullValue);   // Leave the mutator in a valid state
228                     return result;
229                 }
230                 // The CAS failed and m_value has been updated with the latest value.
231                 TURF_TRACE(ConcurrentMap_Linear, 13, "[Mutator::eraseValue] detected race to write value", uptr(m_table), m_cell - m_table->getCells());
232                 if (m_value != Value(ValueTraits::Redirect)) {
233                     // There was a racing write (or erase) to this cell.
234                     // Pretend we erased nothing, and just let the racing write win.
235                     return Value(ValueTraits::NullValue);
236                 }
237                 // We've been redirected to a new table.
238                 TURF_TRACE(ConcurrentMap_Linear, 14, "[Mutator::eraseValue] was redirected", uptr(m_table), m_cell - m_table->getCells());
239                 Hash hash = m_cell->hash.load(turf::Relaxed);           // Re-fetch hash
240                 for (;;) {
241                     // Help complete the migration.
242                     m_table->jobCoordinator.participate();
243                     // Try again in the new table.
244                     m_table = m_map.m_root.load(turf::Consume);
245                     m_cell = Details::find(hash, m_table);
246                     if (!m_cell) {
247                         m_value = Value(ValueTraits::NullValue);
248                         return m_value;
249                     }
250                     m_value = m_cell->value.load(turf::Relaxed);
251                     if (m_value != Value(ValueTraits::Redirect))
252                         break;
253                     TURF_TRACE(ConcurrentMap_Linear, 15, "[Mutator::eraseValue] was re-redirected", uptr(m_table), m_cell - m_table->getCells());
254                 }
255             }
256         }
257     };
258
259     Mutator insert(Key key) {
260         return Mutator(*this, key);
261     }
262
263     Mutator find(Key key) {
264         return Mutator(*this, key, false);
265     }
266
267     // Lookup without creating a temporary Mutator.
268     Value get(Key key) {
269         Hash hash = KeyTraits::hash(key);
270         TURF_TRACE(ConcurrentMap_Linear, 16, "[get] called", uptr(this), uptr(hash));
271         for (;;) {
272             typename Details::Table* table = m_root.load(turf::Consume);
273             typename Details::Cell* cell = Details::find(hash, table);
274             if (!cell)
275                 return Value(ValueTraits::NullValue);
276             Value value = cell->value.load(turf::Consume);
277             if (value != Value(ValueTraits::Redirect))
278                 return value;                        // Found an existing value
279             // We've been redirected to a new table. Help with the migration.
280             TURF_TRACE(ConcurrentMap_Linear, 17, "[get] was redirected", uptr(table), uptr(cell));
281             table->jobCoordinator.participate();
282             // Try again in the new table.
283         }
284     }
285
286     Value insert(Key key, Value desired) {
287         Mutator iter(*this, key);
288         return iter.exchangeValue(desired);
289     }
290
291     Value exchange(Key key, Value desired) {
292         Mutator iter(*this, key);
293         return iter.exchangeValue(desired);
294     }
295
296     Value erase(Key key) {
297         Mutator iter(*this, key, false);
298         return iter.eraseValue();
299     }
300
301     // The easiest way to implement an Iterator is to prevent all Redirects.
302     // The currrent Iterator does that by forbidding concurrent inserts.
303     // To make it work with concurrent inserts, we'd need a way to block TableMigrations.
304     class Iterator {
305     private:
306         typename Details::Table* m_table;
307         ureg m_idx;
308         Key m_hash;
309         Value m_value;
310
311     public:
312         Iterator(ConcurrentMap_Linear& map) {
313             // Since we've forbidden concurrent inserts (for now), nonatomic would suffice here, but let's plan ahead:
314             m_table = map.m_root.load(turf::Consume);
315             m_idx = -1;
316             next();
317         }
318
319         void next() {
320             TURF_ASSERT(m_table);
321             TURF_ASSERT(isValid() || m_idx == -1);  // Either the Iterator is already valid, or we've just started iterating.
322             while (++m_idx <= m_table->sizeMask) {
323                 // Index still inside range of table.
324                 typename Details::Cell *cell = m_table->getCells() + m_idx;
325                 m_hash = cell->hash.load(turf::Relaxed);
326                 if (m_hash != KeyTraits::NullHash) {
327                     // Cell has been reserved.
328                     m_value = cell->value.load(turf::Relaxed);
329                     TURF_ASSERT(m_value != Value(ValueTraits::Redirect));
330                     if (m_value != Value(ValueTraits::NullValue))
331                         return;     // Yield this cell.
332                 }
333             }
334             // That's the end of the map.
335             m_hash = KeyTraits::NullHash;
336             m_value = ValueTraits::NullValue;
337         }
338
339         bool isValid() const {
340             return m_value != Value(ValueTraits::NullValue);
341         }
342
343         Key getKey() const {
344             TURF_ASSERT(isValid());
345             // Since we've forbidden concurrent inserts (for now), nonatomic would suffice here, but let's plan ahead:
346             return KeyTraits::dehash(m_hash);
347         }
348
349         Value getValue() const {
350             TURF_ASSERT(isValid());
351             return m_value;
352         }
353     };
354 };
355
356 } // namespace junction
357
358 #endif // JUNCTION_CONCURRENTMAP_LINEAR_H