7b1e39574ca8d3a73a1ef032e6d8e7a42177d7e8
[junction.git] / junction / details / 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_DETAILS_LEAPFROG_H
14 #define JUNCTION_DETAILS_LEAPFROG_H
15
16 #include <junction/Core.h>
17 #include <turf/Atomic.h>
18 #include <turf/Mutex.h>
19 #include <turf/ManualResetEvent.h>
20 #include <turf/Util.h>
21 #include <junction/MapTraits.h>
22 #include <turf/Trace.h>
23 #include <turf/Heap.h>
24 #include <junction/SimpleJobCoordinator.h>
25 #include <junction/QSBR.h>
26
27 namespace junction {
28 namespace details {
29
30 TURF_TRACE_DECLARE(LeapFrog, 33)
31
32 template<class Map>
33 struct LeapFrog {
34     typedef typename Map::Hash Hash;
35     typedef typename Map::Value Value;
36     typedef typename Map::KeyTraits KeyTraits;
37     typedef typename Map::ValueTraits ValueTraits;
38
39     static const ureg InitialSize = 8;
40     static const ureg TableMigrationUnitSize = 32;
41     static const ureg LinearSearchLimit = 128;
42     static const ureg CellsInUseSample = LinearSearchLimit;
43     TURF_STATIC_ASSERT(LinearSearchLimit > 0 && LinearSearchLimit < 256); // Must fit in CellGroup::links
44     TURF_STATIC_ASSERT(CellsInUseSample > 0 && CellsInUseSample <= LinearSearchLimit); // Limit sample to failed search chain
45
46     struct Cell {
47         turf::Atomic<Hash> hash;
48         turf::Atomic<Value> value;
49     };
50
51     struct CellGroup {
52         // Every cell in the table actually represents a bucket of cells, all linked together in a probe chain.
53         // Each cell in the probe chain is located within the table itself.
54         // "deltas" determines the index of the next cell in the probe chain.
55         // The first cell in the chain is the one that was hashed. It may or may not actually belong in the bucket.
56         // The "second" cell in the chain is given by deltas 0 - 3. It's guaranteed to belong in the bucket.
57         // All subsequent cells in the chain is given by deltas 4 - 7. Also guaranteed to belong in the bucket.
58         turf::Atomic<u8> deltas[8];
59         Cell cells[4];
60     };
61
62     struct Table {
63         const ureg sizeMask;                    // a power of two minus one
64         turf::Mutex mutex;                      // to DCLI the TableMigration (stored in the jobCoordinator)
65         SimpleJobCoordinator jobCoordinator;    // makes all blocked threads participate in the migration
66
67         Table(ureg sizeMask) : sizeMask(sizeMask) {
68         }
69
70         static Table* create(ureg tableSize) {
71             TURF_ASSERT(turf::util::isPowerOf2(tableSize));
72             TURF_ASSERT(tableSize >= 4);
73             ureg numGroups = tableSize >> 2;
74             Table* table = (Table*) TURF_HEAP.alloc(sizeof(Table) + sizeof(CellGroup) * numGroups);
75             new(table) Table(tableSize - 1);
76             for (ureg i = 0; i < numGroups; i++) {
77                 CellGroup* group = table->getCellGroups() + i;
78                 for (ureg j = 0; j < 4; j++) {
79                     group->deltas[j].storeNonatomic(0);
80                     group->deltas[j + 4].storeNonatomic(0);
81                     group->cells[j].hash.storeNonatomic(KeyTraits::NullHash);
82                     group->cells[j].value.storeNonatomic(Value(ValueTraits::NullValue));
83                 }
84             }
85             return table;
86         }
87
88         void destroy() {
89             this->Table::~Table();
90             TURF_HEAP.free(this);
91         }
92
93         CellGroup* getCellGroups() const {
94             return (CellGroup*) (this + 1);
95         }
96
97         ureg getNumMigrationUnits() const {
98             return sizeMask / TableMigrationUnitSize + 1;
99         }
100     };
101
102     class TableMigration : public SimpleJobCoordinator::Job {
103     public:
104         struct Source {
105             Table* table;
106             turf::Atomic<ureg> sourceIndex;
107         };
108
109         Map& m_map;
110         Table* m_destination;
111         turf::Atomic<ureg> m_workerStatus;          // number of workers + end flag
112         turf::Atomic<bool> m_overflowed;
113         turf::Atomic<sreg> m_unitsRemaining;
114         ureg m_numSources;
115
116         TableMigration(Map& map) : m_map(map) {
117         }
118
119         static TableMigration* create(Map& map, ureg numSources) {
120             TableMigration* migration = (TableMigration*) TURF_HEAP.alloc(sizeof(TableMigration) + sizeof(TableMigration::Source) * numSources);
121             new(migration) TableMigration(map);
122             migration->m_workerStatus.storeNonatomic(0);
123             migration->m_overflowed.storeNonatomic(false);
124             migration->m_unitsRemaining.storeNonatomic(0);
125             migration->m_numSources = numSources;
126             // Caller is responsible for filling in sources & destination
127             return migration;
128         }
129
130         virtual ~TableMigration() TURF_OVERRIDE {
131         }
132
133         void destroy() {
134             // Destroy all source tables.
135             for (ureg i = 0; i < m_numSources; i++)
136                 if (getSources()[i].table)
137                     getSources()[i].table->destroy();
138             // Delete the migration object itself.
139             this->TableMigration::~TableMigration();
140             TURF_HEAP.free(this);
141         }
142
143         Source* getSources() const {
144             return (Source*) (this + 1);
145         }
146
147         bool migrateRange(Table* srcTable, ureg startIdx);
148         virtual void run() TURF_OVERRIDE;
149     };
150
151     static Cell* find(Hash hash, Table* table) {
152         TURF_TRACE(LeapFrog, 0, "[find] called", uptr(table), hash);
153         TURF_ASSERT(table);
154         TURF_ASSERT(hash != KeyTraits::NullHash);
155         ureg sizeMask = table->sizeMask;
156         // Optimistically check hashed cell even though it might belong to another bucket
157         ureg idx = hash & sizeMask;
158         CellGroup* group = table->getCellGroups() + (idx >> 2);
159         Cell* cell = group->cells + (idx & 3);
160         Hash probeHash = cell->hash.load(turf::Relaxed);
161         if (probeHash == hash) {
162             TURF_TRACE(LeapFrog, 1, "[find] found existing cell optimistically", uptr(table), idx);
163             return cell;
164         } else if (probeHash == KeyTraits::NullHash) {
165             return cell = NULL;
166         }
167         // Follow probe chain for our bucket
168         u8 delta = group->deltas[idx & 3].load(turf::Relaxed);
169         while (delta) {
170             idx = (idx + delta) & sizeMask;
171             group = table->getCellGroups() + (idx >> 2);
172             cell = group->cells + (idx & 3);
173             Hash probeHash = cell->hash.load(turf::Relaxed);
174             // Note: probeHash might actually be NULL due to memory reordering of a concurrent insert,
175             // but we don't check for it. We just follow the probe chain.
176             if (probeHash == hash) {
177                 TURF_TRACE(LeapFrog, 2, "[find] found existing cell", uptr(table), idx);
178                 return cell;
179             }
180             delta = group->deltas[(idx & 3) + 4].load(turf::Relaxed);
181         }
182         // End of probe chain, not found
183         return NULL;
184     }
185
186     // FIXME: Possible optimization: Dedicated insert for migration? It wouldn't check for InsertResult_AlreadyFound.
187     enum InsertResult {
188         InsertResult_AlreadyFound,
189         InsertResult_InsertedNew,
190         InsertResult_Overflow
191     };
192     static InsertResult insert(Hash hash, Table* table, Cell*& cell, ureg& overflowIdx) {
193         TURF_TRACE(LeapFrog, 3, "[insert] called", uptr(table), hash);
194         TURF_ASSERT(table);
195         TURF_ASSERT(hash != KeyTraits::NullHash);
196         ureg sizeMask = table->sizeMask;
197         ureg idx = hash;
198
199         // Check hashed cell first, though it may not even belong to the bucket.
200         CellGroup* group = table->getCellGroups() + ((idx & sizeMask) >> 2);
201         cell = group->cells + (idx & 3);
202         Hash probeHash = cell->hash.load(turf::Relaxed);
203         if (probeHash == KeyTraits::NullHash) {
204             if (cell->hash.compareExchangeStrong(probeHash, hash, turf::Relaxed)) {
205                 TURF_TRACE(LeapFrog, 4, "[insert] reserved first cell", uptr(table), idx);
206                 // There are no links to set. We're done.
207                 return InsertResult_InsertedNew;
208             } else {
209                 TURF_TRACE(LeapFrog, 5, "[insert] race to reserve first cell", uptr(table), idx);
210                 // Fall through to check if it was the same hash...
211             }
212         }
213         if (probeHash == hash) {
214             TURF_TRACE(LeapFrog, 6, "[insert] found in first cell", uptr(table), idx);
215             return InsertResult_AlreadyFound;
216         }
217
218         // Follow the link chain for this bucket.
219         ureg maxIdx = idx + sizeMask;
220         ureg linkLevel = 0;
221         turf::Atomic<u8>* prevLink;
222         for (;;) {
223         followLink:
224             prevLink = group->deltas + ((idx & 3) + linkLevel);
225             linkLevel = 4;
226             u8 probeDelta = prevLink->load(turf::Relaxed);
227             if (probeDelta) {
228                 idx += probeDelta;
229                 // Check the hash for this cell.
230                 group = table->getCellGroups() + ((idx & sizeMask) >> 2);
231                 cell = group->cells + (idx & 3);
232                 probeHash = cell->hash.load(turf::Relaxed);
233                 if (probeHash == KeyTraits::NullHash) {
234                     // Cell was linked, but hash is not visible yet.
235                     // We could avoid this case (and guarantee it's visible) using acquire & release, but instead,
236                     // just poll until it becomes visible.
237                     TURF_TRACE(LeapFrog, 7, "[insert] race to read hash", uptr(table), idx);
238                     do {
239                         probeHash = cell->hash.load(turf::Acquire);
240                     } while (probeHash == KeyTraits::NullHash);
241                 }
242                 TURF_ASSERT(((probeHash ^ hash) & sizeMask) == 0);   // Only hashes in same bucket can be linked
243                 if (probeHash == hash) {
244                     TURF_TRACE(LeapFrog, 8, "[insert] found in probe chain", uptr(table), idx);
245                     return InsertResult_AlreadyFound;
246                 }
247             } else {
248                 // Reached the end of the link chain for this bucket.
249                 // Switch to linear probing until we reserve a new cell or find a late-arriving cell in the same bucket.
250                 ureg prevLinkIdx = idx;
251                 TURF_ASSERT(sreg(maxIdx - idx) >= 0);    // Nobody would have linked an idx that's out of range.
252                 ureg linearProbesRemaining = turf::util::min(maxIdx - idx, LinearSearchLimit);
253                 while (linearProbesRemaining-- > 0) {
254                     idx++;
255                     group = table->getCellGroups() + ((idx & sizeMask) >> 2);
256                     cell = group->cells + (idx & 3);
257                     probeHash = cell->hash.load(turf::Relaxed);
258                     if (probeHash == KeyTraits::NullHash) {
259                         // It's an empty cell. Try to reserve it.
260                         if (cell->hash.compareExchangeStrong(probeHash, hash, turf::Relaxed)) {
261                             // Success. We've reserved the cell. Link it to previous cell in same bucket.
262                             TURF_TRACE(LeapFrog, 9, "[insert] reserved cell", uptr(table), idx);
263                             TURF_ASSERT(probeDelta == 0);
264                             u8 desiredDelta = idx - prevLinkIdx;
265 #if TURF_WITH_ASSERTS                            
266                             probeDelta = prevLink->exchange(desiredDelta, turf::Relaxed);
267                             TURF_ASSERT(probeDelta == 0 || probeDelta == desiredDelta);
268 #else
269                             prevLink->store(desiredDelta, turf::Relaxed);
270 #endif
271                             return InsertResult_InsertedNew;
272                         } else {
273                             TURF_TRACE(LeapFrog, 10, "[insert] race to reserve cell", uptr(table), idx);
274                             // Fall through to check if it's the same hash...
275                         }
276                     }
277                     Hash x = (probeHash ^ hash);
278                     // Check for same hash.
279                     if (!x) {
280                         TURF_TRACE(LeapFrog, 11, "[insert] found outside probe chain", uptr(table), idx);
281                         return InsertResult_AlreadyFound;
282                     }
283                     // Check for same bucket.
284                     if ((x & sizeMask) == 0) {
285                         TURF_TRACE(LeapFrog, 12, "[insert] found late-arriving cell in same bucket", uptr(table), idx);
286                         // Attempt to set the link on behalf of the late-arriving cell.
287                         // This is usually redundant, but if we don't attempt to set the late-arriving cell's link here,
288                         // there's no guarantee that our own link chain will be well-formed by the time this function returns.
289                         // (Indeed, subsequent lookups sometimes failed during testing, for this exact reason.)
290                         u8 desiredDelta = idx - prevLinkIdx;
291 #if TURF_WITH_ASSERTS                            
292                         probeDelta = prevLink->exchange(desiredDelta, turf::Relaxed);
293                         TURF_ASSERT(probeDelta == 0 || probeDelta == desiredDelta);
294                         if (probeDelta == 0)
295                             TURF_TRACE(LeapFrog, 13, "[insert] set link on behalf of late-arriving cell", uptr(table), idx);
296 #else
297                         prevLink->store(desiredDelta, turf::Relaxed);
298 #endif                    
299                         goto followLink;  // Try to follow link chain for the bucket again.
300                     }
301                     // Continue linear search...
302                 }
303                 // Table is too full to insert.
304                 overflowIdx = idx + 1;
305                 TURF_TRACE(LeapFrog, 14, "[insert] overflow", uptr(table), overflowIdx);
306                 return InsertResult_Overflow;
307             }
308         }
309     }
310
311     static void beginTableMigrationToSize(Map& map, Table* table, ureg nextTableSize) {
312         // Create new migration by DCLI.
313         TURF_TRACE(LeapFrog, 15, "[beginTableMigrationToSize] called", 0, 0);
314         SimpleJobCoordinator::Job* job = table->jobCoordinator.loadConsume();
315         if (job) {
316             TURF_TRACE(LeapFrog, 16, "[beginTableMigrationToSize] new migration already exists", 0, 0);
317         } else {
318             turf::LockGuard<turf::Mutex> guard(table->mutex);
319             job = table->jobCoordinator.loadConsume();  // Non-atomic would be sufficient, but that's OK.
320             if (job) {
321                 TURF_TRACE(LeapFrog, 17, "[beginTableMigrationToSize] new migration already exists (double-checked)", 0, 0);
322             } else {
323                 // Create new migration.
324                 TableMigration* migration = TableMigration::create(map, 1);
325                 migration->m_unitsRemaining.storeNonatomic(table->getNumMigrationUnits());
326                 migration->getSources()[0].table = table;
327                 migration->getSources()[0].sourceIndex.storeNonatomic(0);
328                 migration->m_destination = Table::create(nextTableSize);
329                 // Publish the new migration.
330                 table->jobCoordinator.storeRelease(migration);
331             }
332         }
333     }
334
335     static void beginTableMigration(Map& map, Table* table, ureg overflowIdx) {
336         // Estimate number of cells in use based on a small sample.
337         ureg sizeMask = table->sizeMask;
338         ureg idx = overflowIdx - CellsInUseSample;
339         ureg inUseCells = 0;
340         for (ureg linearProbesRemaining = CellsInUseSample; linearProbesRemaining > 0; linearProbesRemaining--) {
341             CellGroup* group = table->getCellGroups() + ((idx & sizeMask) >> 2);
342             Cell* cell = group->cells + (idx & 3);
343             Value value = cell->value.load(turf::Relaxed);
344             if (value == Value(ValueTraits::Redirect)) {
345                 // Another thread kicked off the jobCoordinator. The caller will participate upon return.
346                 TURF_TRACE(LeapFrog, 18, "[beginTableMigration] redirected while determining table size", 0, 0);
347                 return;
348             }
349             if (value != Value(ValueTraits::NullValue))
350                 inUseCells++;
351             idx++;
352         }
353         float inUseRatio = float(inUseCells) / CellsInUseSample;
354         float estimatedInUse = (sizeMask + 1) * inUseRatio;
355         ureg nextTableSize = turf::util::roundUpPowerOf2(ureg(estimatedInUse * 2));
356         beginTableMigrationToSize(map, table, nextTableSize);
357     }
358 }; // LeapFrog
359
360 template<class Map>
361 bool LeapFrog<Map>::TableMigration::migrateRange(Table* srcTable, ureg startIdx) {
362     ureg srcSizeMask = srcTable->sizeMask;
363     ureg endIdx = turf::util::min(startIdx + TableMigrationUnitSize, srcSizeMask + 1);
364     // Iterate over source range.
365     for (ureg srcIdx = startIdx; srcIdx < endIdx; srcIdx++) {
366         CellGroup* srcGroup = srcTable->getCellGroups() + ((srcIdx & srcSizeMask) >> 2);
367         Cell* srcCell = srcGroup->cells + (srcIdx & 3);
368         Hash srcHash;
369         Value srcValue;
370         // Fetch the srcHash and srcValue.
371         for (;;) {
372             srcHash = srcCell->hash.load(turf::Relaxed);
373             if (srcHash == KeyTraits::NullHash) {
374                 // An unused cell. Try to put a Redirect marker in its value.
375                 srcValue = srcCell->value.compareExchange(Value(ValueTraits::NullValue), Value(ValueTraits::Redirect), turf::Relaxed);
376                 if (srcValue == Value(ValueTraits::Redirect)) {
377                     // srcValue is already marked Redirect due to previous incomplete migration.
378                     TURF_TRACE(LeapFrog, 19, "[migrateRange] empty cell already redirected", uptr(srcTable), srcIdx);
379                     break;
380                 }
381                 if (srcValue == Value(ValueTraits::NullValue))
382                     break;  // Redirect has been placed. Break inner loop, continue outer loop.
383                 TURF_TRACE(LeapFrog, 20, "[migrateRange] race to insert key", uptr(srcTable), srcIdx);
384                 // Otherwise, somebody just claimed the cell. Read srcHash again...
385             } else {
386                 // Check for deleted/uninitialized value.
387                 srcValue = srcCell->value.load(turf::Relaxed);
388                 if (srcValue == Value(ValueTraits::NullValue)) {
389                     // Try to put a Redirect marker.
390                     if (srcCell->value.compareExchangeStrong(srcValue, Value(ValueTraits::Redirect), turf::Relaxed))
391                         break;  // Redirect has been placed. Break inner loop, continue outer loop.
392                     TURF_TRACE(LeapFrog, 21, "[migrateRange] race to insert value", uptr(srcTable), srcIdx);
393                     if (srcValue == Value(ValueTraits::Redirect)) {
394                         // FIXME: I don't think this will happen. Investigate & change to assert
395                         TURF_TRACE(LeapFrog, 22, "[migrateRange] race inserted Redirect", uptr(srcTable), srcIdx);
396                         break;
397                     }
398                 } else if (srcValue == Value(ValueTraits::Redirect)) {
399                     // srcValue is already marked Redirect due to previous incomplete migration.
400                     TURF_TRACE(LeapFrog, 23, "[migrateRange] in-use cell already redirected", uptr(srcTable), srcIdx);
401                     break;
402                 }
403                 
404                 // We've got a key/value pair to migrate.
405                 // Reserve a destination cell in the destination.
406                 TURF_ASSERT(srcHash != KeyTraits::NullHash);
407                 TURF_ASSERT(srcValue != Value(ValueTraits::NullValue));
408                 TURF_ASSERT(srcValue != Value(ValueTraits::Redirect));
409                 Cell* dstCell;
410                 ureg overflowIdx;
411                 InsertResult result = insert(srcHash, m_destination, dstCell, overflowIdx);
412                 // During migration, a hash can only exist in one place among all the source tables,
413                 // and it is only migrated by one thread. Therefore, the hash will never already exist
414                 // in the destination table:
415                 TURF_ASSERT(result != InsertResult_AlreadyFound);
416                 if (result == InsertResult_Overflow) {
417                     // Destination overflow.
418                     // This can happen for several reasons. For example, the source table could have
419                     // existed of all deleted cells when it overflowed, resulting in a small destination
420                     // table size, but then another thread could re-insert all the same hashes
421                     // before the migration completed.
422                     // Caller will cancel the current migration and begin a new one.
423                     return false;
424                 }
425                 // Migrate the old value to the new cell.
426                 for (;;) {
427                     // Copy srcValue to the destination.
428                     dstCell->value.store(srcValue, turf::Relaxed);
429                     // Try to place a Redirect marker in srcValue.
430                     Value doubleCheckedSrcValue = srcCell->value.compareExchange(srcValue, Value(ValueTraits::Redirect), turf::Relaxed);
431                     TURF_ASSERT(doubleCheckedSrcValue != Value(ValueTraits::Redirect)); // Only one thread can redirect a cell at a time.
432                     if (doubleCheckedSrcValue == srcValue) {
433                         // No racing writes to the src. We've successfully placed the Redirect marker.
434                         // srcValue was non-NULL when we decided to migrate it, but it may have changed to NULL
435                         // by a late-arriving erase.
436                         if (srcValue == Value(ValueTraits::NullValue))
437                             TURF_TRACE(LeapFrog, 24, "[migrateRange] racing update was erase", uptr(srcTable), srcIdx);
438                         break;
439                     }
440                     // There was a late-arriving write (or erase) to the src. Migrate the new value and try again.
441                     TURF_TRACE(LeapFrog, 25, "[migrateRange] race to update migrated value", uptr(srcTable), srcIdx);
442                     srcValue = doubleCheckedSrcValue;
443                 }
444                 // Cell successfully migrated. Proceed to next source cell.
445                 break;
446             }
447         }
448     }
449     // Range has been migrated successfully.
450     return true;
451 }
452
453 template <class Map>
454 void LeapFrog<Map>::TableMigration::run() {
455     // Conditionally increment the shared # of workers.
456     ureg probeStatus = m_workerStatus.load(turf::Relaxed);
457     do {
458         if (probeStatus & 1) {
459             // End flag is already set, so do nothing.
460             TURF_TRACE(LeapFrog, 26, "[TableMigration::run] already ended", uptr(this), 0);
461             return;
462         }
463     } while (!m_workerStatus.compareExchangeWeak(probeStatus, probeStatus + 2, turf::Relaxed, turf::Relaxed));
464     // # of workers has been incremented, and the end flag is clear.
465     TURF_ASSERT((probeStatus & 1) == 0);
466
467     // Iterate over all source tables.
468     for (ureg s = 0; s < m_numSources; s++) {
469         Source& source = getSources()[s];
470         // Loop over all migration units in this source table.
471         for (;;) {
472             if (m_workerStatus.load(turf::Relaxed) & 1) {
473                 TURF_TRACE(LeapFrog, 27, "[TableMigration::run] detected end flag set", uptr(this), 0);
474                 goto endMigration;
475             }
476             ureg startIdx = source.sourceIndex.fetchAdd(TableMigrationUnitSize, turf::Relaxed);
477             if (startIdx >= source.table->sizeMask + 1)
478                 break;   // No more migration units in this table. Try next source table.
479             bool overflowed = !migrateRange(source.table, startIdx);
480             if (overflowed) {
481                 // *** FAILED MIGRATION ***
482                 // TableMigration failed due to destination table overflow.
483                 // No other thread can declare the migration successful at this point, because *this* unit will never complete, hence m_unitsRemaining won't reach zero.
484                 // However, multiple threads can independently detect a failed migration at the same time.
485                 TURF_TRACE(LeapFrog, 28, "[TableMigration::run] destination overflow", uptr(source.table), uptr(startIdx));
486                 // The reason we store overflowed in a shared variable is because we can must flush all the worker threads before
487                 // we can safely deal with the overflow. Therefore, the thread that detects the failure is often different from the thread
488                 // that deals with it.
489                 bool oldOverflowed = m_overflowed.exchange(overflowed, turf::Relaxed);
490                 if (oldOverflowed)
491                     TURF_TRACE(LeapFrog, 29, "[TableMigration::run] race to set m_overflowed", uptr(overflowed), uptr(oldOverflowed));
492                 m_workerStatus.fetchOr(1, turf::Relaxed);
493                 goto endMigration;
494             }
495             sreg prevRemaining = m_unitsRemaining.fetchSub(1, turf::Relaxed);
496             TURF_ASSERT(prevRemaining > 0);
497             if (prevRemaining == 1) {
498                 // *** SUCCESSFUL MIGRATION ***
499                 // That was the last chunk to migrate.
500                 m_workerStatus.fetchOr(1, turf::Relaxed);
501                 goto endMigration;
502             }
503         }
504     }
505     TURF_TRACE(LeapFrog, 30, "[TableMigration::run] out of migration units", uptr(this), 0);
506
507 endMigration:
508     // Decrement the shared # of workers.
509     probeStatus = m_workerStatus.fetchSub(2, turf::AcquireRelease);    // AcquireRelease makes all previous writes visible to the last worker thread.
510     if (probeStatus >= 4) {
511         // There are other workers remaining. Return here so that only the very last worker will proceed.
512         TURF_TRACE(LeapFrog, 31, "[TableMigration::run] not the last worker", uptr(this), uptr(probeStatus));
513         return;
514     }
515
516     // We're the very last worker thread.
517     // Perform the appropriate post-migration step depending on whether the migration succeeded or failed.
518     TURF_ASSERT(probeStatus == 3);
519     bool overflowed = m_overflowed.loadNonatomic();  // No racing writes at this point
520     if (!overflowed) {
521         // The migration succeeded. This is the most likely outcome. Publish the new subtree.
522         m_map.publishTableMigration(this);
523         // End the jobCoodinator.
524         getSources()[0].table->jobCoordinator.end();
525     } else {
526         // The migration failed due to the overflow of the destination table.
527         Table* origTable = getSources()[0].table;
528         turf::LockGuard<turf::Mutex> guard(origTable->mutex);
529         SimpleJobCoordinator::Job* checkedJob = origTable->jobCoordinator.loadConsume();
530         if (checkedJob != this) {
531             TURF_TRACE(LeapFrog, 32, "[TableMigration::run] a new TableMigration was already started", uptr(origTable), uptr(checkedJob));
532         } else {
533             TableMigration* migration = TableMigration::create(m_map, m_numSources + 1);
534             // Double the destination table size.
535             migration->m_destination = Table::create((m_destination->sizeMask + 1) * 2);
536             // Transfer source tables to the new migration.
537             for (ureg i = 0; i < m_numSources; i++) {
538                 migration->getSources()[i].table = getSources()[i].table;
539                 getSources()[i].table = NULL;
540                 migration->getSources()[i].sourceIndex.storeNonatomic(0);
541             }
542             migration->getSources()[m_numSources].table = m_destination;
543             migration->getSources()[m_numSources].sourceIndex.storeNonatomic(0);
544             // Calculate total number of migration units to move.
545             ureg unitsRemaining = 0;
546             for (ureg s = 0; s < migration->m_numSources; s++)
547                 unitsRemaining += migration->getSources()[s].table->getNumMigrationUnits();
548             migration->m_unitsRemaining.storeNonatomic(unitsRemaining);
549             // Publish the new migration.
550             origTable->jobCoordinator.storeRelease(migration);
551         }
552     }
553
554     // We're done with this TableMigration. Queue it for GC.
555     DefaultQSBR.enqueue(&TableMigration::destroy, this);
556 }
557
558 } // namespace details
559 } // namespace junction
560
561 #endif // JUNCTION_DETAILS_LEAPFROG_H