f6b1e6c0c24fd5f7d5d6a53542f10f899c2d9411
[junction.git] / junction / ConcurrentMap_LeapFrog.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_LEAPFROG_H
14 #define JUNCTION_CONCURRENTMAP_LEAPFROG_H
15
16 #include <junction/Core.h>
17 #include <junction/details/LeapFrog.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_LeapFrog, 17)
25
26 template <typename K, typename V, class KT = DefaultKeyTraits<K>, class VT = DefaultValueTraits<V> >
27 class ConcurrentMap_LeapFrog {
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::LeapFrog<ConcurrentMap_LeapFrog> Details;
35
36 private:
37     turf::Atomic<typename Details::Table*> m_root;
38
39 public:
40     ConcurrentMap_LeapFrog(ureg capacity = Details::InitialSize) : m_root(Details::Table::create(capacity)) {
41     }
42
43     ~ConcurrentMap_LeapFrog() {
44         typename Details::Table* table = m_root.loadNonatomic();
45         table->destroy();
46     }
47
48     // publishTableMigration() is called by exactly one thread from Details::TableMigration::run()
49     // after all the threads participating in the migration have completed their work.
50     void publishTableMigration(typename Details::TableMigration* migration) {
51         // There are no racing calls to this function.
52         typename Details::Table* oldRoot = m_root.loadNonatomic();
53         m_root.store(migration->m_destination, turf::Release);
54         TURF_ASSERT(oldRoot == migration->getSources()[0].table);
55         // Caller will GC the TableMigration and the source table.
56     }
57
58     // A Mutator represents a known cell in the hash table.
59     // It's meant for manipulations within a temporary function scope.
60     // Obviously you must not call QSBR::Update while holding a Mutator.
61     // Any operation that modifies the table (exchangeValue, eraseValue)
62     // may be forced to follow a redirected cell, which changes the Mutator itself.
63     // Note that even if the Mutator was constructed from an existing cell,
64     // exchangeValue() can still trigger a resize if the existing cell was previously marked deleted,
65     // or if another thread deletes the key between the two steps.
66     class Mutator {
67     private:
68         friend class ConcurrentMap_LeapFrog;
69
70         ConcurrentMap_LeapFrog& m_map;
71         typename Details::Table* m_table;
72         typename Details::Cell* m_cell;
73         Value m_value;
74
75         // Constructor: Find existing cell
76         Mutator(ConcurrentMap_LeapFrog& map, Key key, bool) : m_map(map), m_value(Value(ValueTraits::NullValue)) {
77             TURF_TRACE(ConcurrentMap_LeapFrog, 0, "[Mutator] find constructor called", uptr(m_table), uptr(key));
78             Hash hash = KeyTraits::hash(key);
79             for (;;) {
80                 m_table = m_map.m_root.load(turf::Consume);
81                 m_cell = Details::find(hash, m_table);
82                 if (!m_cell)
83                     return;
84                 m_value = m_cell->value.load(turf::Consume);
85                 if (m_value != Value(ValueTraits::Redirect))
86                     return; // Found an existing value
87                 // We've encountered a Redirect value. Help finish the migration.
88                 TURF_TRACE(ConcurrentMap_LeapFrog, 1, "[Mutator] find was redirected", uptr(m_table), 0);
89                 m_table->jobCoordinator.participate();
90                 // Try again using the latest root.
91             }
92         }
93
94         // Constructor: Insert cell
95         Mutator(ConcurrentMap_LeapFrog& map, Key key)
96             : m_map(map), m_table(map.m_root.load(turf::Consume)), m_value(Value(ValueTraits::NullValue)) {
97             TURF_TRACE(ConcurrentMap_LeapFrog, 2, "[Mutator] insert constructor called", uptr(m_table), uptr(key));
98             Hash hash = KeyTraits::hash(key);
99             for (;;) {
100                 m_table = m_map.m_root.load(turf::Consume);
101                 ureg overflowIdx;
102                 switch (Details::insert(hash, m_table, m_cell, overflowIdx)) { // 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_LeapFrog, 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, overflowIdx);
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(desired != Value(ValueTraits::Redirect));
137             TURF_ASSERT(m_cell); // Cell must have been found or inserted
138             TURF_TRACE(ConcurrentMap_LeapFrog, 4, "[Mutator::exchangeValue] called", uptr(m_table), uptr(m_value));
139             for (;;) {
140                 Value oldValue = m_value;
141                 if (m_cell->value.compareExchangeStrong(m_value, desired, turf::ConsumeRelease)) {
142                     // Exchange was successful. Return previous value.
143                     TURF_TRACE(ConcurrentMap_LeapFrog, 5, "[Mutator::exchangeValue] exchanged Value", uptr(m_value),
144                                uptr(desired));
145                     Value result = m_value;
146                     m_value = desired; // Leave the mutator in a valid state
147                     return result;
148                 }
149                 // The CAS failed and m_value has been updated with the latest value.
150                 if (m_value != Value(ValueTraits::Redirect)) {
151                     TURF_TRACE(ConcurrentMap_LeapFrog, 6, "[Mutator::exchangeValue] detected race to write value", uptr(m_table),
152                                uptr(m_value));
153                     if (oldValue == Value(ValueTraits::NullValue) && m_value != Value(ValueTraits::NullValue)) {
154                         TURF_TRACE(ConcurrentMap_LeapFrog, 7, "[Mutator::exchangeValue] racing write inserted new value",
155                                    uptr(m_table), uptr(m_value));
156                     }
157                     // There was a racing write (or erase) to this cell.
158                     // Pretend we exchanged with ourselves, and just let the racing write win.
159                     return desired;
160                 }
161                 // We've encountered a Redirect value. Help finish the migration.
162                 TURF_TRACE(ConcurrentMap_LeapFrog, 8, "[Mutator::exchangeValue] was redirected", uptr(m_table), uptr(m_value));
163                 Hash hash = m_cell->hash.load(turf::Relaxed);
164                 for (;;) {
165                     // Help complete the migration.
166                     m_table->jobCoordinator.participate();
167                     // Try again in the new table.
168                     m_table = m_map.m_root.load(turf::Consume);
169                     m_value = Value(ValueTraits::NullValue);
170                     ureg overflowIdx;
171                     switch (Details::insert(hash, m_table, m_cell, overflowIdx)) { // Modifies m_cell
172                     case Details::InsertResult_AlreadyFound:
173                         m_value = m_cell->value.load(turf::Consume);
174                         if (m_value == Value(ValueTraits::Redirect)) {
175                             TURF_TRACE(ConcurrentMap_LeapFrog, 9, "[Mutator::exchangeValue] was re-redirected", uptr(m_table),
176                                        uptr(m_value));
177                             break;
178                         }
179                         goto breakOuter;
180                     case Details::InsertResult_InsertedNew:
181                         goto breakOuter;
182                     case Details::InsertResult_Overflow:
183                         TURF_TRACE(ConcurrentMap_LeapFrog, 10, "[Mutator::exchangeValue] overflow after redirect", uptr(m_table),
184                                    overflowIdx);
185                         Details::beginTableMigration(m_map, m_table, overflowIdx);
186                         break;
187                     }
188                     // We were redirected... again
189                 }
190             breakOuter:;
191                 // Try again in the new table.
192             }
193         }
194
195         void setValue(Value desired) {
196             exchangeValue(desired);
197         }
198
199         Value eraseValue() {
200             TURF_ASSERT(m_cell); // Cell must have been found or inserted
201             TURF_TRACE(ConcurrentMap_LeapFrog, 11, "[Mutator::eraseValue] called", uptr(m_table), uptr(m_cell));
202             for (;;) {
203                 if (m_value == Value(ValueTraits::NullValue))
204                     return Value(m_value);
205                 TURF_ASSERT(m_cell); // m_value is non-NullValue, therefore cell must have been found or inserted.
206                 if (m_cell->value.compareExchangeStrong(m_value, Value(ValueTraits::NullValue), turf::Consume)) {
207                     // Exchange was successful and a non-NULL value was erased and returned by reference in m_value.
208                     TURF_ASSERT(m_value != ValueTraits::NullValue); // Implied by the test at the start of the loop.
209                     Value result = m_value;
210                     m_value = Value(ValueTraits::NullValue); // Leave the mutator in a valid state
211                     return result;
212                 }
213                 // The CAS failed and m_value has been updated with the latest value.
214                 TURF_TRACE(ConcurrentMap_LeapFrog, 12, "[Mutator::eraseValue] detected race to write value", uptr(m_table),
215                            uptr(m_cell));
216                 if (m_value != Value(ValueTraits::Redirect)) {
217                     // There was a racing write (or erase) to this cell.
218                     // Pretend we erased nothing, and just let the racing write win.
219                     return Value(ValueTraits::NullValue);
220                 }
221                 // We've been redirected to a new table.
222                 TURF_TRACE(ConcurrentMap_LeapFrog, 13, "[Mutator::eraseValue] was redirected", uptr(m_table), uptr(m_cell));
223                 Hash hash = m_cell->hash.load(turf::Relaxed); // Re-fetch hash
224                 for (;;) {
225                     // Help complete the migration.
226                     m_table->jobCoordinator.participate();
227                     // Try again in the new table.
228                     m_table = m_map.m_root.load(turf::Consume);
229                     m_cell = Details::find(hash, m_table);
230                     if (!m_cell) {
231                         m_value = Value(ValueTraits::NullValue);
232                         return m_value;
233                     }
234                     m_value = m_cell->value.load(turf::Relaxed);
235                     if (m_value != Value(ValueTraits::Redirect))
236                         break;
237                     TURF_TRACE(ConcurrentMap_LeapFrog, 14, "[Mutator::eraseValue] was re-redirected", uptr(m_table),
238                                uptr(m_cell));
239                 }
240             }
241         }
242     };
243
244     Mutator insert(Key key) {
245         return Mutator(*this, key);
246     }
247
248     Mutator find(Key key) {
249         return Mutator(*this, key, false);
250     }
251
252     // Lookup without creating a temporary Mutator.
253     Value get(Key key) {
254         Hash hash = KeyTraits::hash(key);
255         TURF_TRACE(ConcurrentMap_LeapFrog, 15, "[get] called", uptr(this), uptr(hash));
256         for (;;) {
257             typename Details::Table* table = m_root.load(turf::Consume);
258             typename Details::Cell* cell = Details::find(hash, table);
259             if (!cell)
260                 return Value(ValueTraits::NullValue);
261             Value value = cell->value.load(turf::Consume);
262             if (value != Value(ValueTraits::Redirect))
263                 return value; // Found an existing value
264             // We've been redirected to a new table. Help with the migration.
265             TURF_TRACE(ConcurrentMap_LeapFrog, 16, "[get] was redirected", uptr(table), uptr(hash));
266             table->jobCoordinator.participate();
267             // Try again in the new table.
268         }
269     }
270
271     Value insert(Key key, Value desired) {
272         Mutator iter(*this, key);
273         return iter.exchangeValue(desired);
274     }
275
276     Value exchange(Key key, Value desired) {
277         Mutator iter(*this, key);
278         return iter.exchangeValue(desired);
279     }
280
281     Value erase(Key key) {
282         Mutator iter(*this, key, false);
283         return iter.eraseValue();
284     }
285
286     // The easiest way to implement an Iterator is to prevent all Redirects.
287     // The currrent Iterator does that by forbidding concurrent inserts.
288     // To make it work with concurrent inserts, we'd need a way to block TableMigrations.
289     class Iterator {
290     private:
291         typename Details::Table* m_table;
292         ureg m_idx;
293         Key m_hash;
294         Value m_value;
295
296     public:
297         Iterator(ConcurrentMap_LeapFrog& map) {
298             // Since we've forbidden concurrent inserts (for now), nonatomic would suffice here, but let's plan ahead:
299             m_table = map.m_root.load(turf::Consume);
300             m_idx = -1;
301             next();
302         }
303
304         void next() {
305             TURF_ASSERT(m_table);
306             TURF_ASSERT(isValid() || m_idx == -1); // Either the Iterator is already valid, or we've just started iterating.
307             while (++m_idx <= m_table->sizeMask) {
308                 // Index still inside range of table.
309                 typename Details::CellGroup* group = m_table->getCellGroups() + (m_idx >> 2);
310                 typename Details::Cell* cell = group->cells + (m_idx & 3);
311                 m_hash = cell->hash.load(turf::Relaxed);
312                 if (m_hash != KeyTraits::NullHash) {
313                     // Cell has been reserved.
314                     m_value = cell->value.load(turf::Relaxed);
315                     TURF_ASSERT(m_value != Value(ValueTraits::Redirect));
316                     if (m_value != Value(ValueTraits::NullValue))
317                         return; // Yield this cell.
318                 }
319             }
320             // That's the end of the map.
321             m_hash = KeyTraits::NullHash;
322             m_value = ValueTraits::NullValue;
323         }
324
325         bool isValid() const {
326             return m_value != Value(ValueTraits::NullValue);
327         }
328
329         Key getKey() const {
330             TURF_ASSERT(isValid());
331             // Since we've forbidden concurrent inserts (for now), nonatomic would suffice here, but let's plan ahead:
332             return KeyTraits::dehash(m_hash);
333         }
334
335         Value getValue() const {
336             TURF_ASSERT(isValid());
337             return m_value;
338         }
339     };
340 };
341
342 } // namespace junction
343
344 #endif // JUNCTION_CONCURRENTMAP_LEAPFROG_H