Sort #include lines
[folly.git] / folly / ConcurrentSkipList-inl.h
1 /*
2  * Copyright 2017 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 // @author: Xin Liu <xliux@fb.com>
18
19 #pragma once
20
21 #include <algorithm>
22 #include <atomic>
23 #include <climits>
24 #include <cmath>
25 #include <memory>
26 #include <mutex>
27 #include <type_traits>
28 #include <vector>
29
30 #include <boost/noncopyable.hpp>
31 #include <boost/random.hpp>
32 #include <boost/type_traits.hpp>
33 #include <glog/logging.h>
34
35 #include <folly/Memory.h>
36 #include <folly/MicroSpinLock.h>
37 #include <folly/ThreadLocal.h>
38
39 namespace folly { namespace detail {
40
41 template<typename ValT, typename NodeT> class csl_iterator;
42
43 template<typename T>
44 class SkipListNode : private boost::noncopyable {
45   enum : uint16_t {
46     IS_HEAD_NODE = 1,
47     MARKED_FOR_REMOVAL = (1 << 1),
48     FULLY_LINKED = (1 << 2),
49   };
50
51  public:
52   typedef T value_type;
53
54   template<typename NodeAlloc, typename U,
55     typename=typename std::enable_if<std::is_convertible<U, T>::value>::type>
56   static SkipListNode* create(
57       NodeAlloc& alloc, int height, U&& data, bool isHead = false) {
58     DCHECK(height >= 1 && height < 64) << height;
59
60     size_t size = sizeof(SkipListNode) +
61       height * sizeof(std::atomic<SkipListNode*>);
62     auto* node = static_cast<SkipListNode*>(alloc.allocate(size));
63     // do placement new
64     new (node) SkipListNode(uint8_t(height), std::forward<U>(data), isHead);
65     return node;
66   }
67
68   template<typename NodeAlloc>
69   static void destroy(NodeAlloc& alloc, SkipListNode* node) {
70     node->~SkipListNode();
71     alloc.deallocate(node);
72   }
73
74   template<typename NodeAlloc>
75   struct DestroyIsNoOp : std::integral_constant<bool,
76     IsArenaAllocator<NodeAlloc>::value &&
77     boost::has_trivial_destructor<SkipListNode>::value> { };
78
79   // copy the head node to a new head node assuming lock acquired
80   SkipListNode* copyHead(SkipListNode* node) {
81     DCHECK(node != nullptr && height_ > node->height_);
82     setFlags(node->getFlags());
83     for (uint8_t i = 0; i < node->height_; ++i) {
84       setSkip(i, node->skip(i));
85     }
86     return this;
87   }
88
89   inline SkipListNode* skip(int layer) const {
90     DCHECK_LT(layer, height_);
91     return skip_[layer].load(std::memory_order_consume);
92   }
93
94   // next valid node as in the linked list
95   SkipListNode* next() {
96     SkipListNode* node;
97     for (node = skip(0);
98         (node != nullptr && node->markedForRemoval());
99         node = node->skip(0)) {}
100     return node;
101   }
102
103   void setSkip(uint8_t h, SkipListNode* next) {
104     DCHECK_LT(h, height_);
105     skip_[h].store(next, std::memory_order_release);
106   }
107
108   value_type& data() { return data_; }
109   const value_type& data() const { return data_; }
110   int maxLayer() const { return height_ - 1; }
111   int height() const { return height_; }
112
113   std::unique_lock<MicroSpinLock> acquireGuard() {
114     return std::unique_lock<MicroSpinLock>(spinLock_);
115   }
116
117   bool fullyLinked() const      { return getFlags() & FULLY_LINKED; }
118   bool markedForRemoval() const { return getFlags() & MARKED_FOR_REMOVAL; }
119   bool isHeadNode() const       { return getFlags() & IS_HEAD_NODE; }
120
121   void setIsHeadNode() {
122     setFlags(uint16_t(getFlags() | IS_HEAD_NODE));
123   }
124   void setFullyLinked() {
125     setFlags(uint16_t(getFlags() | FULLY_LINKED));
126   }
127   void setMarkedForRemoval() {
128     setFlags(uint16_t(getFlags() | MARKED_FOR_REMOVAL));
129   }
130
131  private:
132   // Note! this can only be called from create() as a placement new.
133   template<typename U>
134   SkipListNode(uint8_t height, U&& data, bool isHead) :
135       height_(height), data_(std::forward<U>(data)) {
136     spinLock_.init();
137     setFlags(0);
138     if (isHead) setIsHeadNode();
139     // need to explicitly init the dynamic atomic pointer array
140     for (uint8_t i = 0; i < height_; ++i) {
141       new (&skip_[i]) std::atomic<SkipListNode*>(nullptr);
142     }
143   }
144
145   ~SkipListNode() {
146     for (uint8_t i = 0; i < height_; ++i) {
147       skip_[i].~atomic();
148     }
149   }
150
151   uint16_t getFlags() const {
152     return flags_.load(std::memory_order_consume);
153   }
154   void setFlags(uint16_t flags) {
155     flags_.store(flags, std::memory_order_release);
156   }
157
158   // TODO(xliu): on x86_64, it's possible to squeeze these into
159   // skip_[0] to maybe save 8 bytes depending on the data alignments.
160   // NOTE: currently this is x86_64 only anyway, due to the
161   // MicroSpinLock.
162   std::atomic<uint16_t> flags_;
163   const uint8_t height_;
164   MicroSpinLock spinLock_;
165
166   value_type data_;
167
168   std::atomic<SkipListNode*> skip_[0];
169 };
170
171 class SkipListRandomHeight {
172   enum { kMaxHeight = 64 };
173  public:
174   // make it a singleton.
175   static SkipListRandomHeight *instance() {
176     static SkipListRandomHeight instance_;
177     return &instance_;
178   }
179
180   int getHeight(int maxHeight) const {
181     DCHECK_LE(maxHeight, kMaxHeight) << "max height too big!";
182     double p = randomProb();
183     for (int i = 0; i < maxHeight; ++i) {
184       if (p < lookupTable_[i]) {
185         return i + 1;
186       }
187     }
188     return maxHeight;
189   }
190
191   size_t getSizeLimit(int height) const {
192     DCHECK_LT(height, kMaxHeight);
193     return sizeLimitTable_[height];
194   }
195
196  private:
197   SkipListRandomHeight() { initLookupTable(); }
198
199   void initLookupTable() {
200     // set skip prob = 1/E
201     static const double kProbInv = exp(1);
202     static const double kProb = 1.0 / kProbInv;
203     static const size_t kMaxSizeLimit = std::numeric_limits<size_t>::max();
204
205     double sizeLimit = 1;
206     double p = lookupTable_[0] = (1 - kProb);
207     sizeLimitTable_[0] = 1;
208     for (int i = 1; i < kMaxHeight - 1; ++i) {
209       p *= kProb;
210       sizeLimit *= kProbInv;
211       lookupTable_[i] = lookupTable_[i - 1] + p;
212       sizeLimitTable_[i] = sizeLimit > kMaxSizeLimit ?
213         kMaxSizeLimit :
214         static_cast<size_t>(sizeLimit);
215     }
216     lookupTable_[kMaxHeight - 1] = 1;
217     sizeLimitTable_[kMaxHeight - 1] = kMaxSizeLimit;
218   }
219
220   static double randomProb() {
221     static ThreadLocal<boost::lagged_fibonacci2281> rng_;
222     return (*rng_)();
223   }
224
225   double lookupTable_[kMaxHeight];
226   size_t sizeLimitTable_[kMaxHeight];
227 };
228
229 template<typename NodeType, typename NodeAlloc, typename = void>
230 class NodeRecycler;
231
232 template<typename NodeType, typename NodeAlloc>
233 class NodeRecycler<NodeType, NodeAlloc, typename std::enable_if<
234   !NodeType::template DestroyIsNoOp<NodeAlloc>::value>::type> {
235  public:
236   explicit NodeRecycler(const NodeAlloc& alloc)
237     : refs_(0), dirty_(false), alloc_(alloc) { lock_.init(); }
238
239   explicit NodeRecycler() : refs_(0), dirty_(false) { lock_.init(); }
240
241   ~NodeRecycler() {
242     CHECK_EQ(refs(), 0);
243     if (nodes_) {
244       for (auto& node : *nodes_) {
245         NodeType::destroy(alloc_, node);
246       }
247     }
248   }
249
250   void add(NodeType* node) {
251     std::lock_guard<MicroSpinLock> g(lock_);
252     if (nodes_.get() == nullptr) {
253       nodes_.reset(new std::vector<NodeType*>(1, node));
254     } else {
255       nodes_->push_back(node);
256     }
257     DCHECK_GT(refs(), 0);
258     dirty_.store(true, std::memory_order_relaxed);
259   }
260
261   int addRef() {
262     return refs_.fetch_add(1, std::memory_order_relaxed);
263   }
264
265   int releaseRef() {
266     // We don't expect to clean the recycler immediately everytime it is OK
267     // to do so. Here, it is possible that multiple accessors all release at
268     // the same time but nobody would clean the recycler here. If this
269     // happens, the recycler will usually still get cleaned when
270     // such a race doesn't happen. The worst case is the recycler will
271     // eventually get deleted along with the skiplist.
272     if (LIKELY(!dirty_.load(std::memory_order_relaxed) || refs() > 1)) {
273       return refs_.fetch_add(-1, std::memory_order_relaxed);
274     }
275
276     std::unique_ptr<std::vector<NodeType*>> newNodes;
277     {
278       std::lock_guard<MicroSpinLock> g(lock_);
279       if (nodes_.get() == nullptr || refs() > 1) {
280         return refs_.fetch_add(-1, std::memory_order_relaxed);
281       }
282       // once refs_ reaches 1 and there is no other accessor, it is safe to
283       // remove all the current nodes in the recycler, as we already acquired
284       // the lock here so no more new nodes can be added, even though new
285       // accessors may be added after that.
286       newNodes.swap(nodes_);
287       dirty_.store(false, std::memory_order_relaxed);
288     }
289
290     // TODO(xliu) should we spawn a thread to do this when there are large
291     // number of nodes in the recycler?
292     for (auto& node : *newNodes) {
293       NodeType::destroy(alloc_, node);
294     }
295
296     // decrease the ref count at the very end, to minimize the
297     // chance of other threads acquiring lock_ to clear the deleted
298     // nodes again.
299     return refs_.fetch_add(-1, std::memory_order_relaxed);
300   }
301
302   NodeAlloc& alloc() { return alloc_; }
303
304  private:
305   int refs() const {
306     return refs_.load(std::memory_order_relaxed);
307   }
308
309   std::unique_ptr<std::vector<NodeType*>> nodes_;
310   std::atomic<int32_t> refs_; // current number of visitors to the list
311   std::atomic<bool> dirty_; // whether *nodes_ is non-empty
312   MicroSpinLock lock_; // protects access to *nodes_
313   NodeAlloc alloc_;
314 };
315
316 // In case of arena allocator, no recycling is necessary, and it's possible
317 // to save on ConcurrentSkipList size.
318 template<typename NodeType, typename NodeAlloc>
319 class NodeRecycler<NodeType, NodeAlloc, typename std::enable_if<
320   NodeType::template DestroyIsNoOp<NodeAlloc>::value>::type> {
321  public:
322   explicit NodeRecycler(const NodeAlloc& alloc) : alloc_(alloc) { }
323
324   void addRef() { }
325   void releaseRef() { }
326
327   void add(NodeType* /* node */) {}
328
329   NodeAlloc& alloc() { return alloc_; }
330
331  private:
332   NodeAlloc alloc_;
333 };
334
335 }}  // namespaces