Remove Stream
[folly.git] / folly / AtomicHashArray-inl.h
1 /*
2  * Copyright 2012 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #ifndef FOLLY_ATOMICHASHARRAY_H_
18 #error "This should only be included by AtomicHashArray.h"
19 #endif
20
21 #include "folly/Bits.h"
22 #include "folly/detail/AtomicHashUtils.h"
23
24 namespace folly {
25
26 // AtomicHashArray private constructor --
27 template <class KeyT, class ValueT, class HashFcn>
28 AtomicHashArray<KeyT, ValueT, HashFcn>::
29 AtomicHashArray(size_t capacity, KeyT emptyKey, KeyT lockedKey,
30                 KeyT erasedKey, double maxLoadFactor, size_t cacheSize)
31     : capacity_(capacity), maxEntries_(size_t(maxLoadFactor * capacity_ + 0.5)),
32       kEmptyKey_(emptyKey), kLockedKey_(lockedKey), kErasedKey_(erasedKey),
33       kAnchorMask_(nextPowTwo(capacity_) - 1), numEntries_(0, cacheSize),
34       numPendingEntries_(0, cacheSize), isFull_(0), numErases_(0) {
35 }
36
37 /*
38  * findInternal --
39  *
40  *   Sets ret.second to value found and ret.index to index
41  *   of key and returns true, or if key does not exist returns false and
42  *   ret.index is set to capacity_.
43  */
44 template <class KeyT, class ValueT, class HashFcn>
45 typename AtomicHashArray<KeyT, ValueT, HashFcn>::SimpleRetT
46 AtomicHashArray<KeyT, ValueT, HashFcn>::
47 findInternal(const KeyT key_in) {
48   DCHECK_NE(key_in, kEmptyKey_);
49   DCHECK_NE(key_in, kLockedKey_);
50   DCHECK_NE(key_in, kErasedKey_);
51   for (size_t idx = keyToAnchorIdx(key_in), numProbes = 0;
52        ;
53        idx = probeNext(idx, numProbes)) {
54     const KeyT key = acquireLoadKey(cells_[idx]);
55     if (LIKELY(key == key_in)) {
56       return SimpleRetT(idx, true);
57     }
58     if (UNLIKELY(key == kEmptyKey_)) {
59       // if we hit an empty element, this key does not exist
60       return SimpleRetT(capacity_, false);
61     }
62     ++numProbes;
63     if (UNLIKELY(numProbes >= capacity_)) {
64       // probed every cell...fail
65       return SimpleRetT(capacity_, false);
66     }
67   }
68 }
69
70 /*
71  * insertInternal --
72  *
73  *   Returns false on failure due to key collision or full.
74  *   Also sets ret.index to the index of the key.  If the map is full, sets
75  *   ret.index = capacity_.  Also sets ret.second to cell value, thus if insert
76  *   successful this will be what we just inserted, if there is a key collision
77  *   this will be the previously inserted value, and if the map is full it is
78  *   default.
79  */
80 template <class KeyT, class ValueT, class HashFcn>
81 template <class T>
82 typename AtomicHashArray<KeyT, ValueT, HashFcn>::SimpleRetT
83 AtomicHashArray<KeyT, ValueT, HashFcn>::
84 insertInternal(KeyT key_in, T&& value) {
85   const short NO_NEW_INSERTS = 1;
86   const short NO_PENDING_INSERTS = 2;
87   CHECK_NE(key_in, kEmptyKey_);
88   CHECK_NE(key_in, kLockedKey_);
89   CHECK_NE(key_in, kErasedKey_);
90
91   size_t idx = keyToAnchorIdx(key_in);
92   size_t numProbes = 0;
93   for (;;) {
94     DCHECK_LT(idx, capacity_);
95     value_type* cell = &cells_[idx];
96     if (relaxedLoadKey(*cell) == kEmptyKey_) {
97       // NOTE: isFull_ is set based on numEntries_.readFast(), so it's
98       // possible to insert more than maxEntries_ entries. However, it's not
99       // possible to insert past capacity_.
100       ++numPendingEntries_;
101       if (isFull_.load(std::memory_order_acquire)) {
102         --numPendingEntries_;
103
104         // Before deciding whether this insert succeeded, this thread needs to
105         // wait until no other thread can add a new entry.
106
107         // Correctness assumes isFull_ is true at this point. If
108         // another thread now does ++numPendingEntries_, we expect it
109         // to pass the isFull_.load() test above. (It shouldn't insert
110         // a new entry.)
111         FOLLY_SPIN_WAIT(
112           isFull_.load(std::memory_order_acquire) != NO_PENDING_INSERTS
113             && numPendingEntries_.readFull() != 0
114         );
115         isFull_.store(NO_PENDING_INSERTS, std::memory_order_release);
116
117         if (relaxedLoadKey(*cell) == kEmptyKey_) {
118           // Don't insert past max load factor
119           return SimpleRetT(capacity_, false);
120         }
121       } else {
122         // An unallocated cell. Try once to lock it. If we succeed, insert here.
123         // If we fail, fall through to comparison below; maybe the insert that
124         // just beat us was for this very key....
125         if (tryLockCell(cell)) {
126           // Write the value - done before unlocking
127           try {
128             DCHECK(relaxedLoadKey(*cell) == kLockedKey_);
129             /*
130              * This happens using the copy constructor because we won't have
131              * constructed a lhs to use an assignment operator on when
132              * values are being set.
133              */
134             new (&cell->second) ValueT(std::forward<T>(value));
135             unlockCell(cell, key_in); // Sets the new key
136           } catch (...) {
137             // Transition back to empty key---requires handling
138             // locked->empty below.
139             unlockCell(cell, kEmptyKey_);
140             --numPendingEntries_;
141             throw;
142           }
143           DCHECK(relaxedLoadKey(*cell) == key_in);
144           --numPendingEntries_;
145           ++numEntries_;  // This is a thread cached atomic increment :)
146           if (numEntries_.readFast() >= maxEntries_) {
147             isFull_.store(NO_NEW_INSERTS, std::memory_order_relaxed);
148           }
149           return SimpleRetT(idx, true);
150         }
151         --numPendingEntries_;
152       }
153     }
154     DCHECK(relaxedLoadKey(*cell) != kEmptyKey_);
155     if (kLockedKey_ == acquireLoadKey(*cell)) {
156       FOLLY_SPIN_WAIT(
157         kLockedKey_ == acquireLoadKey(*cell)
158       );
159     }
160
161     const KeyT thisKey = acquireLoadKey(*cell);
162     if (thisKey == key_in) {
163       // Found an existing entry for our key, but we don't overwrite the
164       // previous value.
165       return SimpleRetT(idx, false);
166     } else if (thisKey == kEmptyKey_ || thisKey == kLockedKey_) {
167       // We need to try again (i.e., don't increment numProbes or
168       // advance idx): this case can happen if the constructor for
169       // ValueT threw for this very cell (the rethrow block above).
170       continue;
171     }
172
173     ++numProbes;
174     if (UNLIKELY(numProbes >= capacity_)) {
175       // probed every cell...fail
176       return SimpleRetT(capacity_, false);
177     }
178
179     idx = probeNext(idx, numProbes);
180   }
181 }
182
183
184 /*
185  * erase --
186  *
187  *   This will attempt to erase the given key key_in if the key is found. It
188  *   returns 1 iff the key was located and marked as erased, and 0 otherwise.
189  *
190  *   Memory is not freed or reclaimed by erase, i.e. the cell containing the
191  *   erased key will never be reused. If there's an associated value, we won't
192  *   touch it either.
193  */
194 template <class KeyT, class ValueT, class HashFcn>
195 size_t AtomicHashArray<KeyT, ValueT, HashFcn>::
196 erase(KeyT key_in) {
197   CHECK_NE(key_in, kEmptyKey_);
198   CHECK_NE(key_in, kLockedKey_);
199   CHECK_NE(key_in, kErasedKey_);
200   for (size_t idx = keyToAnchorIdx(key_in), numProbes = 0;
201        ;
202        idx = probeNext(idx, numProbes)) {
203     DCHECK_LT(idx, capacity_);
204     value_type* cell = &cells_[idx];
205     KeyT currentKey = acquireLoadKey(*cell);
206     if (currentKey == kEmptyKey_ || currentKey == kLockedKey_) {
207       // If we hit an empty (or locked) element, this key does not exist. This
208       // is similar to how it's handled in find().
209       return 0;
210     }
211     if (key_in == currentKey) {
212       // Found an existing entry for our key, attempt to mark it erased.
213       // Some other thread may have erased our key, but this is ok.
214       KeyT expect = key_in;
215       if (cellKeyPtr(*cell)->compare_exchange_strong(expect, kErasedKey_)) {
216         numErases_.fetch_add(1, std::memory_order_relaxed);
217
218         // Even if there's a value in the cell, we won't delete (or even
219         // default construct) it because some other thread may be accessing it.
220         // Locking it meanwhile won't work either since another thread may be
221         // holding a pointer to it.
222
223         // We found the key and successfully erased it.
224         return 1;
225       }
226       // If another thread succeeds in erasing our key, we'll stop our search.
227       return 0;
228     }
229     ++numProbes;
230     if (UNLIKELY(numProbes >= capacity_)) {
231       // probed every cell...fail
232       return 0;
233     }
234   }
235 }
236
237 template <class KeyT, class ValueT, class HashFcn>
238 const typename AtomicHashArray<KeyT, ValueT, HashFcn>::Config
239 AtomicHashArray<KeyT, ValueT, HashFcn>::defaultConfig;
240
241 template <class KeyT, class ValueT, class HashFcn>
242 typename AtomicHashArray<KeyT, ValueT, HashFcn>::SmartPtr
243 AtomicHashArray<KeyT, ValueT, HashFcn>::
244 create(size_t maxSize, const Config& c) {
245   CHECK_LE(c.maxLoadFactor, 1.0);
246   CHECK_GT(c.maxLoadFactor, 0.0);
247   CHECK_NE(c.emptyKey, c.lockedKey);
248   size_t capacity = size_t(maxSize / c.maxLoadFactor);
249   size_t sz = sizeof(AtomicHashArray) + sizeof(value_type) * capacity;
250
251   std::unique_ptr<void, void(*)(void*)> mem(malloc(sz), free);
252   new(mem.get()) AtomicHashArray(capacity, c.emptyKey, c.lockedKey, c.erasedKey,
253                                  c.maxLoadFactor, c.entryCountThreadCacheSize);
254   SmartPtr map(static_cast<AtomicHashArray*>(mem.release()));
255
256   /*
257    * Mark all cells as empty.
258    *
259    * Note: we're bending the rules a little here accessing the key
260    * element in our cells even though the cell object has not been
261    * constructed, and casting them to atomic objects (see cellKeyPtr).
262    * (Also, in fact we never actually invoke the value_type
263    * constructor.)  This is in order to avoid needing to default
264    * construct a bunch of value_type when we first start up: if you
265    * have an expensive default constructor for the value type this can
266    * noticeably speed construction time for an AHA.
267    */
268   FOR_EACH_RANGE(i, 0, map->capacity_) {
269     cellKeyPtr(map->cells_[i])->store(map->kEmptyKey_,
270       std::memory_order_relaxed);
271   }
272   return map;
273 }
274
275 template <class KeyT, class ValueT, class HashFcn>
276 void AtomicHashArray<KeyT, ValueT, HashFcn>::
277 destroy(AtomicHashArray* p) {
278   assert(p);
279   FOR_EACH_RANGE(i, 0, p->capacity_) {
280     if (p->cells_[i].first != p->kEmptyKey_) {
281       p->cells_[i].~value_type();
282     }
283   }
284   p->~AtomicHashArray();
285   free(p);
286 }
287
288 // clear -- clears all keys and values in the map and resets all counters
289 template <class KeyT, class ValueT, class HashFcn>
290 void AtomicHashArray<KeyT, ValueT, HashFcn>::
291 clear() {
292   FOR_EACH_RANGE(i, 0, capacity_) {
293     if (cells_[i].first != kEmptyKey_) {
294       cells_[i].~value_type();
295       *const_cast<KeyT*>(&cells_[i].first) = kEmptyKey_;
296     }
297     CHECK(cells_[i].first == kEmptyKey_);
298   }
299   numEntries_.set(0);
300   numPendingEntries_.set(0);
301   isFull_.store(0, std::memory_order_relaxed);
302   numErases_.store(0, std::memory_order_relaxed);
303 }
304
305
306 // Iterator implementation
307
308 template <class KeyT, class ValueT, class HashFcn>
309 template <class ContT, class IterVal>
310 struct AtomicHashArray<KeyT, ValueT, HashFcn>::aha_iterator
311     : boost::iterator_facade<aha_iterator<ContT,IterVal>,
312                              IterVal,
313                              boost::forward_traversal_tag>
314 {
315   explicit aha_iterator() : aha_(0) {}
316
317   // Conversion ctor for interoperability between const_iterator and
318   // iterator.  The enable_if<> magic keeps us well-behaved for
319   // is_convertible<> (v. the iterator_facade documentation).
320   template<class OtherContT, class OtherVal>
321   aha_iterator(const aha_iterator<OtherContT,OtherVal>& o,
322                typename std::enable_if<
323                std::is_convertible<OtherVal*,IterVal*>::value >::type* = 0)
324       : aha_(o.aha_)
325       , offset_(o.offset_)
326   {}
327
328   explicit aha_iterator(ContT* array, size_t offset)
329       : aha_(array)
330       , offset_(offset)
331   {
332     advancePastEmpty();
333   }
334
335   // Returns unique index that can be used with findAt().
336   // WARNING: The following function will fail silently for hashtable
337   // with capacity > 2^32
338   uint32_t getIndex() const { return offset_; }
339
340  private:
341   friend class AtomicHashArray;
342   friend class boost::iterator_core_access;
343
344   void increment() {
345     ++offset_;
346     advancePastEmpty();
347   }
348
349   bool equal(const aha_iterator& o) const {
350     return aha_ == o.aha_ && offset_ == o.offset_;
351   }
352
353   IterVal& dereference() const {
354     return aha_->cells_[offset_];
355   }
356
357   void advancePastEmpty() {
358     while (offset_ < aha_->capacity_ && !isValid()) {
359       ++offset_;
360     }
361   }
362
363   bool isValid() const {
364     KeyT key = acquireLoadKey(aha_->cells_[offset_]);
365     return key != aha_->kEmptyKey_  &&
366       key != aha_->kLockedKey_ &&
367       key != aha_->kErasedKey_;
368   }
369
370  private:
371   ContT* aha_;
372   size_t offset_;
373 }; // aha_iterator
374
375 } // namespace folly
376
377 #undef FOLLY_SPIN_WAIT