Eliminate redundant load in insert constructors
[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, 17)
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 = Details::InitialSize) : m_root(Details::Table::create(capacity)) {
41     }
42
43     ~ConcurrentMap_Linear() {
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_Linear;
69
70         ConcurrentMap_Linear& 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_Linear& map, Key key, bool) : m_map(map), m_value(Value(ValueTraits::NullValue)) {
77             TURF_TRACE(ConcurrentMap_Linear, 0, "[Mutator] find constructor called", uptr(0), 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_Linear, 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_Linear& map, Key key) : m_map(map), m_value(Value(ValueTraits::NullValue)) {
96             TURF_TRACE(ConcurrentMap_Linear, 2, "[Mutator] insert constructor called", uptr(0), uptr(key));
97             Hash hash = KeyTraits::hash(key);
98             bool mustDouble = false;
99             for (;;) {
100                 m_table = m_map.m_root.load(turf::Consume);
101                 switch (Details::insert(hash, m_table, m_cell)) { // Modifies m_cell
102                 case Details::InsertResult_InsertedNew: {
103                     // We've inserted a new cell. Don't load m_cell->value.
104                     return;
105                 }
106                 case Details::InsertResult_AlreadyFound: {
107                     // The hash was already found in the table.
108                     m_value = m_cell->value.load(turf::Consume);
109                     if (m_value == Value(ValueTraits::Redirect)) {
110                         // We've encountered a Redirect value.
111                         TURF_TRACE(ConcurrentMap_Linear, 3, "[Mutator] insert was redirected", uptr(m_table), uptr(m_value));
112                         break; // Help finish the migration.
113                     }
114                     return; // Found an existing value
115                 }
116                 case Details::InsertResult_Overflow: {
117                     Details::beginTableMigration(m_map, m_table, mustDouble);
118                     break;
119                 }
120                 }
121                 // A migration has been started (either by us, or another thread). Participate until it's complete.
122                 m_table->jobCoordinator.participate();
123                 // If we still overflow after this, avoid an infinite loop by forcing the next table to double.
124                 mustDouble = true;
125                 // Try again using the latest root.
126             }
127         }
128
129     public:
130         Value getValue() const {
131             // Return previously loaded value. Don't load it again.
132             return Value(m_value);
133         }
134
135         Value exchangeValue(Value desired) {
136             TURF_ASSERT(desired != Value(ValueTraits::NullValue));
137             TURF_ASSERT(desired != Value(ValueTraits::Redirect));
138             TURF_ASSERT(m_cell); // Cell must have been found or inserted
139             TURF_TRACE(ConcurrentMap_Linear, 4, "[Mutator::exchangeValue] called", uptr(m_table), uptr(m_value));
140             bool mustDouble = false;
141             for (;;) {
142                 Value oldValue = m_value;
143                 if (m_cell->value.compareExchangeStrong(m_value, desired, turf::ConsumeRelease)) {
144                     // Exchange was successful. Return previous value.
145                     TURF_TRACE(ConcurrentMap_Linear, 5, "[Mutator::exchangeValue] exchanged Value", uptr(m_value), uptr(desired));
146                     Value result = m_value;
147                     m_value = desired; // Leave the mutator in a valid state
148                     return result;
149                 }
150                 // The CAS failed and m_value has been updated with the latest value.
151                 if (m_value != Value(ValueTraits::Redirect)) {
152                     TURF_TRACE(ConcurrentMap_Linear, 6, "[Mutator::exchangeValue] detected race to write value", uptr(m_table),
153                                uptr(m_value));
154                     if (oldValue == Value(ValueTraits::NullValue) && m_value != Value(ValueTraits::NullValue)) {
155                         TURF_TRACE(ConcurrentMap_Linear, 7, "[Mutator::exchangeValue] racing write inserted new value",
156                                    uptr(m_table), uptr(m_value));
157                     }
158                     // There was a racing write (or erase) to this cell.
159                     // Pretend we exchanged with ourselves, and just let the racing write win.
160                     return desired;
161                 }
162                 // We've encountered a Redirect value. Help finish the migration.
163                 TURF_TRACE(ConcurrentMap_Linear, 8, "[Mutator::exchangeValue] was redirected", uptr(m_table), uptr(m_value));
164                 Hash hash = m_cell->hash.load(turf::Relaxed);
165                 for (;;) {
166                     // Help complete the migration.
167                     m_table->jobCoordinator.participate();
168                     // Try again in the new table.
169                     m_table = m_map.m_root.load(turf::Consume);
170                     m_value = Value(ValueTraits::NullValue);
171                     switch (Details::insert(hash, m_table, m_cell)) { // 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_Linear, 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_Linear, 10, "[Mutator::exchangeValue] overflow after redirect", uptr(m_table), 0);
184                         Details::beginTableMigration(m_map, m_table, mustDouble);
185                         break;
186                     }
187                     // If we still overflow after this, avoid an infinite loop by forcing the next table to double.
188                     mustDouble = true;
189                     // We were redirected... again
190                 }
191             breakOuter:;
192                 // Try again in the new table.
193             }
194         }
195
196         void setValue(Value desired) {
197             exchangeValue(desired);
198         }
199
200         Value eraseValue() {
201             TURF_ASSERT(m_cell); // Cell must have been found or inserted
202             TURF_TRACE(ConcurrentMap_Linear, 11, "[Mutator::eraseValue] called", uptr(m_table), m_cell - m_table->getCells());
203             for (;;) {
204                 if (m_value == Value(ValueTraits::NullValue))
205                     return Value(m_value);
206                 TURF_ASSERT(m_cell); // m_value is non-NullValue, therefore cell must have been found or inserted.
207                 if (m_cell->value.compareExchangeStrong(m_value, Value(ValueTraits::NullValue), turf::Consume)) {
208                     // Exchange was successful and a non-NULL value was erased and returned by reference in m_value.
209                     TURF_ASSERT(m_value != ValueTraits::NullValue); // Implied by the test at the start of the loop.
210                     Value result = m_value;
211                     m_value = Value(ValueTraits::NullValue); // Leave the mutator in a valid state
212                     return result;
213                 }
214                 // The CAS failed and m_value has been updated with the latest value.
215                 TURF_TRACE(ConcurrentMap_Linear, 12, "[Mutator::eraseValue] detected race to write value", uptr(m_table),
216                            m_cell - m_table->getCells());
217                 if (m_value != Value(ValueTraits::Redirect)) {
218                     // There was a racing write (or erase) to this cell.
219                     // Pretend we erased nothing, and just let the racing write win.
220                     return Value(ValueTraits::NullValue);
221                 }
222                 // We've been redirected to a new table.
223                 TURF_TRACE(ConcurrentMap_Linear, 13, "[Mutator::eraseValue] was redirected", uptr(m_table),
224                            m_cell - m_table->getCells());
225                 Hash hash = m_cell->hash.load(turf::Relaxed); // Re-fetch hash
226                 for (;;) {
227                     // Help complete the migration.
228                     m_table->jobCoordinator.participate();
229                     // Try again in the new table.
230                     m_table = m_map.m_root.load(turf::Consume);
231                     m_cell = Details::find(hash, m_table);
232                     if (!m_cell) {
233                         m_value = Value(ValueTraits::NullValue);
234                         return m_value;
235                     }
236                     m_value = m_cell->value.load(turf::Relaxed);
237                     if (m_value != Value(ValueTraits::Redirect))
238                         break;
239                     TURF_TRACE(ConcurrentMap_Linear, 14, "[Mutator::eraseValue] was re-redirected", uptr(m_table),
240                                m_cell - m_table->getCells());
241                 }
242             }
243         }
244     };
245
246     Mutator insert(Key key) {
247         return Mutator(*this, key);
248     }
249
250     Mutator find(Key key) {
251         return Mutator(*this, key, false);
252     }
253
254     // Lookup without creating a temporary Mutator.
255     Value get(Key key) {
256         Hash hash = KeyTraits::hash(key);
257         TURF_TRACE(ConcurrentMap_Linear, 15, "[get] called", uptr(this), uptr(hash));
258         for (;;) {
259             typename Details::Table* table = m_root.load(turf::Consume);
260             typename Details::Cell* cell = Details::find(hash, table);
261             if (!cell)
262                 return Value(ValueTraits::NullValue);
263             Value value = cell->value.load(turf::Consume);
264             if (value != Value(ValueTraits::Redirect))
265                 return value; // Found an existing value
266             // We've been redirected to a new table. Help with the migration.
267             TURF_TRACE(ConcurrentMap_Linear, 16, "[get] was redirected", uptr(table), uptr(cell));
268             table->jobCoordinator.participate();
269             // Try again in the new table.
270         }
271     }
272
273     Value insert(Key key, Value desired) {
274         Mutator iter(*this, key);
275         return iter.exchangeValue(desired);
276     }
277
278     Value exchange(Key key, Value desired) {
279         Mutator iter(*this, key);
280         return iter.exchangeValue(desired);
281     }
282
283     Value erase(Key key) {
284         Mutator iter(*this, key, false);
285         return iter.eraseValue();
286     }
287
288     // The easiest way to implement an Iterator is to prevent all Redirects.
289     // The currrent Iterator does that by forbidding concurrent inserts.
290     // To make it work with concurrent inserts, we'd need a way to block TableMigrations.
291     class Iterator {
292     private:
293         typename Details::Table* m_table;
294         ureg m_idx;
295         Key m_hash;
296         Value m_value;
297
298     public:
299         Iterator(ConcurrentMap_Linear& map) {
300             // Since we've forbidden concurrent inserts (for now), nonatomic would suffice here, but let's plan ahead:
301             m_table = map.m_root.load(turf::Consume);
302             m_idx = -1;
303             next();
304         }
305
306         void next() {
307             TURF_ASSERT(m_table);
308             TURF_ASSERT(isValid() || m_idx == -1); // Either the Iterator is already valid, or we've just started iterating.
309             while (++m_idx <= m_table->sizeMask) {
310                 // Index still inside range of table.
311                 typename Details::Cell* cell = m_table->getCells() + m_idx;
312                 m_hash = cell->hash.load(turf::Relaxed);
313                 if (m_hash != KeyTraits::NullHash) {
314                     // Cell has been reserved.
315                     m_value = cell->value.load(turf::Relaxed);
316                     TURF_ASSERT(m_value != Value(ValueTraits::Redirect));
317                     if (m_value != Value(ValueTraits::NullValue))
318                         return; // Yield this cell.
319                 }
320             }
321             // That's the end of the map.
322             m_hash = KeyTraits::NullHash;
323             m_value = Value(ValueTraits::NullValue);
324         }
325
326         bool isValid() const {
327             return m_value != Value(ValueTraits::NullValue);
328         }
329
330         Key getKey() const {
331             TURF_ASSERT(isValid());
332             // Since we've forbidden concurrent inserts (for now), nonatomic would suffice here, but let's plan ahead:
333             return KeyTraits::dehash(m_hash);
334         }
335
336         Value getValue() const {
337             TURF_ASSERT(isValid());
338             return m_value;
339         }
340     };
341 };
342
343 } // namespace junction
344
345 #endif // JUNCTION_CONCURRENTMAP_LINEAR_H