2 * Copyright 2015 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #ifndef FOLLY_SMALLLOCKS_H_
18 #define FOLLY_SMALLLOCKS_H_
21 * This header defines a few very small mutex types. These are useful
22 * in highly memory-constrained environments where contention is
25 * Note: these locks are for use when you aren't likely to contend on
26 * the critical section, or when the critical section is incredibly
27 * small. Given that, both of the locks defined in this header are
28 * inherently unfair: that is, the longer a thread is waiting, the
29 * longer it waits between attempts to acquire, so newer waiters are
30 * more likely to get the mutex. For the intended use-case this is
33 * @author Keith Adams <kma@fb.com>
34 * @author Jordan DeLong <delong.j@fb.com>
39 #include <type_traits>
41 #include <boost/noncopyable.hpp>
47 #include <glog/logging.h>
48 #include <folly/Portability.h>
51 # error "SmallLocks.h is currently x64-only."
56 //////////////////////////////////////////////////////////////////////
61 * A helper object for the contended case. Starts off with eager
62 * spinning, and falls back to sleeping for small quantums.
65 static const uint32_t kMaxActiveSpin = 4000;
70 Sleeper() : spinCount(0) {}
73 if (spinCount < kMaxActiveSpin) {
75 asm volatile("pause");
78 * Always sleep 0.5ms, assuming this will make the kernel put
79 * us down for whatever its minimum timer resolution is (in
80 * linux this varies by kernel version from 1ms to 10ms).
82 struct timespec ts = { 0, 500000 };
83 nanosleep(&ts, nullptr);
90 //////////////////////////////////////////////////////////////////////
93 * A really, *really* small spinlock for fine-grained locking of lots
96 * Zero initializing these is guaranteed to be as good as calling
97 * init(), since the free state is guaranteed to be all-bits zero.
99 * This class should be kept a POD, so we can used it in other packed
100 * structs (gcc does not allow __attribute__((__packed__)) on structs that
101 * contain non-POD data). This means avoid adding a constructor, or
102 * making some members private, etc.
104 struct MicroSpinLock {
105 enum { FREE = 0, LOCKED = 1 };
106 // lock_ can't be std::atomic<> to preserve POD-ness.
109 // Initialize this MSL. It is unnecessary to call this if you
110 // zero-initialize the MicroSpinLock.
112 payload()->store(FREE);
116 return cas(FREE, LOCKED);
120 detail::Sleeper sleeper;
122 while (payload()->load() != FREE) {
125 } while (!try_lock());
126 DCHECK(payload()->load() == LOCKED);
130 CHECK(payload()->load() == LOCKED);
131 payload()->store(FREE, std::memory_order_release);
135 std::atomic<uint8_t>* payload() {
136 return reinterpret_cast<std::atomic<uint8_t>*>(&this->lock_);
139 bool cas(uint8_t compare, uint8_t newVal) {
140 return std::atomic_compare_exchange_strong_explicit(payload(), &compare, newVal,
141 std::memory_order_acquire,
142 std::memory_order_relaxed);
146 //////////////////////////////////////////////////////////////////////
149 * Spin lock on a single bit in an integral type. You can use this
150 * with 16, 32, or 64-bit integral types.
152 * This is useful if you want a small lock and already have an int
153 * with a bit in it that you aren't using. But note that it can't be
154 * as small as MicroSpinLock (1 byte), if you don't already have a
155 * convenient int with an unused bit lying around to put it on.
157 * To construct these, either use init() or zero initialize. We don't
158 * have a real constructor because we want this to be a POD type so we
159 * can put it into packed structs.
161 template<class IntType, int Bit = sizeof(IntType) * 8 - 1>
162 struct PicoSpinLock {
163 // Internally we deal with the unsigned version of the type.
164 typedef typename std::make_unsigned<IntType>::type UIntType;
166 static_assert(std::is_integral<IntType>::value,
167 "PicoSpinLock needs an integral type");
168 static_assert(sizeof(IntType) == 2 || sizeof(IntType) == 4 ||
169 sizeof(IntType) == 8,
170 "PicoSpinLock can't work on integers smaller than 2 bytes");
173 static const UIntType kLockBitMask_ = UIntType(1) << Bit;
177 * You must call this function before using this class, if you
178 * default constructed it. If you zero-initialized it you can
179 * assume the PicoSpinLock is in a valid unlocked state with
182 * (This doesn't use a constructor because we want to be a POD.)
184 void init(IntType initialValue = 0) {
185 CHECK(!(initialValue & kLockBitMask_));
186 lock_ = initialValue;
190 * Returns the value of the integer we using for our lock, except
191 * with the bit we are using as a lock cleared, regardless of
192 * whether the lock is held.
194 * It is 'safe' to call this without holding the lock. (As in: you
195 * get the same guarantees for simultaneous accesses to an integer
196 * as you normally get.)
198 IntType getData() const {
199 return static_cast<IntType>(lock_ & ~kLockBitMask_);
203 * Set the value of the other bits in our integer.
205 * Don't use this when you aren't holding the lock, unless it can be
206 * guaranteed that no other threads may be trying to use this.
208 void setData(IntType w) {
209 CHECK(!(w & kLockBitMask_));
210 lock_ = (lock_ & kLockBitMask_) | w;
214 * Try to get the lock without blocking: returns whether or not we
217 bool try_lock() const {
220 #define FB_DOBTS(size) \
221 asm volatile("lock; bts" #size " %1, (%2); setnc %0" \
227 switch (sizeof(IntType)) {
228 case 2: FB_DOBTS(w); break;
229 case 4: FB_DOBTS(l); break;
230 case 8: FB_DOBTS(q); break;
239 * Block until we can acquire the lock. Uses Sleeper to wait.
242 detail::Sleeper sleeper;
243 while (!try_lock()) {
249 * Release the lock, without changing the value of the rest of the
252 void unlock() const {
253 #define FB_DOBTR(size) \
254 asm volatile("lock; btr" #size " %0, (%1)" \
261 // Reads and writes can not be reordered wrt locked instructions,
262 // so we don't need a memory fence here.
263 switch (sizeof(IntType)) {
264 case 2: FB_DOBTR(w); break;
265 case 4: FB_DOBTR(l); break;
266 case 8: FB_DOBTR(q); break;
273 //////////////////////////////////////////////////////////////////////
276 * Array of spinlocks where each one is padded to prevent false sharing.
277 * Useful for shard-based locking implementations in environments where
278 * contention is unlikely.
281 // TODO: generate it from configure (`getconf LEVEL1_DCACHE_LINESIZE`)
282 #define FOLLY_CACHE_LINE_SIZE 64
284 template <class T, size_t N>
285 struct SpinLockArray {
286 T& operator[](size_t i) {
287 return data_[i].lock;
290 const T& operator[](size_t i) const {
291 return data_[i].lock;
294 constexpr size_t size() const { return N; }
297 struct PaddedSpinLock {
298 PaddedSpinLock() : lock() { }
300 char padding[FOLLY_CACHE_LINE_SIZE - sizeof(T)];
302 static_assert(sizeof(PaddedSpinLock) == FOLLY_CACHE_LINE_SIZE,
303 "Invalid size of PaddedSpinLock");
305 // Check if T can theoretically cross a cache line.
306 // NOTE: It should be alignof(std::max_align_t), but max_align_t
307 // isn't supported by gcc 4.6.2.
308 static_assert(alignof(MaxAlign) > 0 &&
309 FOLLY_CACHE_LINE_SIZE % alignof(MaxAlign) == 0 &&
310 sizeof(T) <= alignof(MaxAlign),
311 "T can cross cache line boundaries");
313 char padding_[FOLLY_CACHE_LINE_SIZE];
314 std::array<PaddedSpinLock, N> data_;
315 } __attribute__((__aligned__));
317 //////////////////////////////////////////////////////////////////////
319 typedef std::lock_guard<MicroSpinLock> MSLGuard;
321 //////////////////////////////////////////////////////////////////////