Fix FBString under MSVC
[folly.git] / folly / MicroLock.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 #pragma once
18
19 #include <assert.h>
20 #include <climits>
21 #include <stdint.h>
22 #include <folly/detail/Futex.h>
23 #include <folly/Portability.h>
24
25 #if defined(__clang__)
26 #define NO_SANITIZE_ADDRESS __attribute__((no_sanitize_address))
27 #else
28 #define NO_SANITIZE_ADDRESS
29 #endif
30
31 namespace folly {
32
33 /**
34  * Tiny exclusive lock that packs four lock slots into a single
35  * byte. Each slot is an independent real, sleeping lock.  The default
36  * lock and unlock functions operate on slot zero, which modifies only
37  * the low two bits of the host byte.
38  *
39  * You should zero-initialize the bits of a MicroLock that you intend
40  * to use.
41  *
42  * If you're not space-constrained, prefer std::mutex, which will
43  * likely be faster, since it has more than two bits of information to
44  * work with.
45  *
46  * You are free to put a MicroLock in a union with some other object.
47  * If, for example, you want to use the bottom two bits of a pointer
48  * as a lock, you can put a MicroLock in a union with the pointer and
49  * limit yourself to MicroLock slot zero, which will use the two
50  * least-significant bits in the bottom byte.
51  *
52  * (Note that such a union is safe only because MicroLock is based on
53  * a character type, and even under a strict interpretation of C++'s
54  * aliasing rules, character types may alias anything.)
55  *
56  * MicroLock uses a dirty trick: it actually operates on the full
57  * 32-bit, four-byte-aligned bit of memory into which it is embedded.
58  * It never modifies bits outside the ones it's defined to modify, but
59  * it _accesses_ all the bits in the 32-bit memory location for
60  * purposes of futex management.
61  *
62  * The MaxSpins template parameter controls the number of times we
63  * spin trying to acquire the lock.  MaxYields controls the number of
64  * times we call sched_yield; once we've tried to acquire the lock
65  * MaxSpins + MaxYields times, we sleep on the lock futex.
66  * By adjusting these parameters, you can make MicroLock behave as
67  * much or as little like a conventional spinlock as you'd like.
68  *
69  * Performance
70  * -----------
71  *
72  * With the default template options, the timings for uncontended
73  * acquire-then-release come out as follows on Intel(R) Xeon(R) CPU
74  * E5-2660 0 @ 2.20GHz, in @mode/opt, as of the master tree at Tue, 01
75  * Mar 2016 19:48:15.
76  *
77  * ========================================================================
78  * folly/test/SmallLocksBenchmark.cpp          relative  time/iter  iters/s
79  * ========================================================================
80  * MicroSpinLockUncontendedBenchmark                       13.46ns   74.28M
81  * PicoSpinLockUncontendedBenchmark                        14.99ns   66.71M
82  * MicroLockUncontendedBenchmark                           27.06ns   36.96M
83  * StdMutexUncontendedBenchmark                            25.18ns   39.72M
84  * VirtualFunctionCall                                      1.72ns  579.78M
85  * ========================================================================
86  *
87  * (The virtual dispatch benchmark is provided for scale.)
88  *
89  * While the uncontended case for MicroLock is competitive with the
90  * glibc 2.2.0 implementation of std::mutex, std::mutex is likely to be
91  * faster in the contended case, because we need to wake up all waiters
92  * when we release.
93  *
94  * Make sure to benchmark your particular workload.
95  *
96  */
97
98 class MicroLockCore {
99  protected:
100 #if defined(__SANITIZE_ADDRESS__) && !defined(__clang__) && \
101     (defined(__GNUC__) || defined(__GNUG__))
102   uint32_t lock_;
103 #else
104   uint8_t lock_;
105 #endif
106   inline detail::Futex<>* word() const; // Well, halfword on 64-bit systems
107   inline uint32_t baseShift(unsigned slot) const;
108   inline uint32_t heldBit(unsigned slot) const;
109   inline uint32_t waitBit(unsigned slot) const;
110   static void lockSlowPath(uint32_t oldWord,
111                            detail::Futex<>* wordPtr,
112                            uint32_t slotHeldBit,
113                            unsigned maxSpins,
114                            unsigned maxYields);
115
116  public:
117   inline void unlock(unsigned slot) NO_SANITIZE_ADDRESS;
118   inline void unlock() { unlock(0); }
119   // Initializes all the slots.
120   inline void init() { lock_ = 0; }
121 };
122
123 inline detail::Futex<>* MicroLockCore::word() const {
124   uintptr_t lockptr = (uintptr_t)&lock_;
125   lockptr &= ~(sizeof(uint32_t) - 1);
126   return (detail::Futex<>*)lockptr;
127 }
128
129 inline unsigned MicroLockCore::baseShift(unsigned slot) const {
130   assert(slot < CHAR_BIT / 2);
131
132   unsigned offset_bytes = (unsigned)((uintptr_t)&lock_ - (uintptr_t)word());
133
134   return (
135       unsigned)(kIsLittleEndian ? offset_bytes * CHAR_BIT + slot * 2 : CHAR_BIT * (sizeof(uint32_t) - offset_bytes - 1) + slot * 2);
136 }
137
138 inline uint32_t MicroLockCore::heldBit(unsigned slot) const {
139   return 1U << (baseShift(slot) + 0);
140 }
141
142 inline uint32_t MicroLockCore::waitBit(unsigned slot) const {
143   return 1U << (baseShift(slot) + 1);
144 }
145
146 void MicroLockCore::unlock(unsigned slot) {
147   detail::Futex<>* wordPtr = word();
148   uint32_t oldWord;
149   uint32_t newWord;
150
151   oldWord = wordPtr->load(std::memory_order_relaxed);
152   do {
153     assert(oldWord & heldBit(slot));
154     newWord = oldWord & ~(heldBit(slot) | waitBit(slot));
155   } while (!wordPtr->compare_exchange_weak(
156       oldWord, newWord, std::memory_order_release, std::memory_order_relaxed));
157
158   if (oldWord & waitBit(slot)) {
159     // We don't track the number of waiters, so wake everyone
160     (void)wordPtr->futexWake(std::numeric_limits<int>::max(), heldBit(slot));
161   }
162 }
163
164 template <unsigned MaxSpins = 1000, unsigned MaxYields = 0>
165 class MicroLockBase : public MicroLockCore {
166  public:
167   inline void lock(unsigned slot) NO_SANITIZE_ADDRESS;
168   inline void lock() { lock(0); }
169   inline bool try_lock(unsigned slot) NO_SANITIZE_ADDRESS;
170   inline bool try_lock() { return try_lock(0); }
171 };
172
173 template <unsigned MaxSpins, unsigned MaxYields>
174 bool MicroLockBase<MaxSpins, MaxYields>::try_lock(unsigned slot) {
175
176   // N.B. You might think that try_lock is just the fast path of lock,
177   // but you'd be wrong.  Keep in mind that other parts of our host
178   // word might be changing while we take the lock!  We're not allowed
179   // to fail spuriously if the lock is in fact not held, even if other
180   // people are concurrently modifying other parts of the word.
181   //
182   // We need to loop until we either see firm evidence that somebody
183   // else has the lock (by looking at heldBit) or see our CAS succeed.
184   // A failed CAS by itself does not indicate lock-acquire failure.
185
186   detail::Futex<>* wordPtr = word();
187   uint32_t oldWord = wordPtr->load(std::memory_order_relaxed);
188   do {
189     if (oldWord & heldBit(slot)) {
190       return false;
191     }
192   } while (!wordPtr->compare_exchange_weak(oldWord,
193                                            oldWord | heldBit(slot),
194                                            std::memory_order_acquire,
195                                            std::memory_order_relaxed));
196
197   return true;
198 }
199
200 template <unsigned MaxSpins, unsigned MaxYields>
201 void MicroLockBase<MaxSpins, MaxYields>::lock(unsigned slot) {
202
203   static_assert(MaxSpins + MaxYields < (unsigned)-1, "overflow");
204
205   detail::Futex<>* wordPtr = word();
206   uint32_t oldWord;
207   oldWord = wordPtr->load(std::memory_order_relaxed);
208   if ((oldWord & heldBit(slot)) == 0 &&
209       wordPtr->compare_exchange_weak(oldWord,
210                                      oldWord | heldBit(slot),
211                                      std::memory_order_acquire,
212                                      std::memory_order_relaxed)) {
213     // Fast uncontended case: memory_order_acquire above is our barrier
214   } else {
215     // lockSlowPath doesn't have any slot-dependent computation; it
216     // just shifts the input bit.  Make sure its shifting produces the
217     // same result a call to waitBit for our slot would.
218     assert(heldBit(slot) << 1 == waitBit(slot));
219     // lockSlowPath emits its own memory barrier
220     lockSlowPath(oldWord, wordPtr, heldBit(slot), MaxSpins, MaxYields);
221   }
222 }
223
224 typedef MicroLockBase<> MicroLock;
225 }