apply clang-tidy modernize-use-override
[folly.git] / folly / PicoSpinLock.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 /*
18  * N.B. You most likely do _not_ want to use PicoSpinLock or any other
19  * kind of spinlock.  Consider MicroLock instead.
20  *
21  * In short, spinlocks in preemptive multi-tasking operating systems
22  * have serious problems and fast mutexes like std::mutex are almost
23  * certainly the better choice, because letting the OS scheduler put a
24  * thread to sleep is better for system responsiveness and throughput
25  * than wasting a timeslice repeatedly querying a lock held by a
26  * thread that's blocked, and you can't prevent userspace
27  * programs blocking.
28  *
29  * Spinlocks in an operating system kernel make much more sense than
30  * they do in userspace.
31  */
32
33 #pragma once
34 #define FOLLY_PICO_SPIN_LOCK_H_
35
36 /*
37  * @author Keith Adams <kma@fb.com>
38  * @author Jordan DeLong <delong.j@fb.com>
39  */
40
41 #include <array>
42 #include <atomic>
43 #include <cinttypes>
44 #include <cstdlib>
45 #include <folly/Portability.h>
46 #include <mutex>
47 #include <type_traits>
48
49 #include <folly/detail/Sleeper.h>
50 #include <glog/logging.h>
51
52 #if !FOLLY_X64 && !FOLLY_A64 && !FOLLY_PPC64
53 # error "PicoSpinLock.h is currently x64, aarch64 and ppc64 only."
54 #endif
55
56 namespace folly {
57
58 /*
59  * Spin lock on a single bit in an integral type.  You can use this
60  * with 16, 32, or 64-bit integral types.
61  *
62  * This is useful if you want a small lock and already have an int
63  * with a bit in it that you aren't using.  But note that it can't be
64  * as small as MicroSpinLock (1 byte), if you don't already have a
65  * convenient int with an unused bit lying around to put it on.
66  *
67  * To construct these, either use init() or zero initialize.  We don't
68  * have a real constructor because we want this to be a POD type so we
69  * can put it into packed structs.
70  */
71 template<class IntType, int Bit = sizeof(IntType) * 8 - 1>
72 struct PicoSpinLock {
73   // Internally we deal with the unsigned version of the type.
74   typedef typename std::make_unsigned<IntType>::type UIntType;
75
76   static_assert(std::is_integral<IntType>::value,
77                 "PicoSpinLock needs an integral type");
78   static_assert(sizeof(IntType) == 2 || sizeof(IntType) == 4 ||
79                   sizeof(IntType) == 8,
80                 "PicoSpinLock can't work on integers smaller than 2 bytes");
81
82  public:
83   static const UIntType kLockBitMask_ = UIntType(1) << Bit;
84   mutable UIntType lock_;
85
86   /*
87    * You must call this function before using this class, if you
88    * default constructed it.  If you zero-initialized it you can
89    * assume the PicoSpinLock is in a valid unlocked state with
90    * getData() == 0.
91    *
92    * (This doesn't use a constructor because we want to be a POD.)
93    */
94   void init(IntType initialValue = 0) {
95     CHECK(!(initialValue & kLockBitMask_));
96     reinterpret_cast<std::atomic<UIntType>*>(&lock_)->store(
97         UIntType(initialValue), std::memory_order_release);
98   }
99
100   /*
101    * Returns the value of the integer we using for our lock, except
102    * with the bit we are using as a lock cleared, regardless of
103    * whether the lock is held.
104    *
105    * It is 'safe' to call this without holding the lock.  (As in: you
106    * get the same guarantees for simultaneous accesses to an integer
107    * as you normally get.)
108    */
109   IntType getData() const {
110     auto res = reinterpret_cast<std::atomic<UIntType>*>(&lock_)->load(
111                    std::memory_order_relaxed) &
112         ~kLockBitMask_;
113     return res;
114   }
115
116   /*
117    * Set the value of the other bits in our integer.
118    *
119    * Don't use this when you aren't holding the lock, unless it can be
120    * guaranteed that no other threads may be trying to use this.
121    */
122   void setData(IntType w) {
123     CHECK(!(w & kLockBitMask_));
124     auto l = reinterpret_cast<std::atomic<UIntType>*>(&lock_);
125     l->store(
126         (l->load(std::memory_order_relaxed) & kLockBitMask_) | w,
127         std::memory_order_relaxed);
128   }
129
130   /*
131    * Try to get the lock without blocking: returns whether or not we
132    * got it.
133    */
134   bool try_lock() const {
135     bool ret = false;
136
137 #if defined(FOLLY_SANITIZE_THREAD)
138     // TODO: Might be able to fully move to std::atomic when gcc emits lock btr:
139     // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=49244
140     ret =
141         !(reinterpret_cast<std::atomic<UIntType>*>(&lock_)->fetch_or(
142               kLockBitMask_, std::memory_order_acquire) &
143           kLockBitMask_);
144 #elif _MSC_VER
145     switch (sizeof(IntType)) {
146       case 2:
147         // There is no _interlockedbittestandset16 for some reason :(
148         ret = _InterlockedOr16(
149             (volatile short*)&lock_, (short)kLockBitMask_) & kLockBitMask_;
150         break;
151       case 4:
152         ret = _interlockedbittestandset((volatile long*)&lock_, Bit);
153         break;
154       case 8:
155         ret = _interlockedbittestandset64((volatile long long*)&lock_, Bit);
156         break;
157     }
158 #elif FOLLY_X64
159 #define FB_DOBTS(size)                                  \
160   asm volatile("lock; bts" #size " %1, (%2); setnc %0"  \
161                : "=r" (ret)                             \
162                : "i" (Bit),                             \
163                  "r" (&lock_)                           \
164                : "memory", "flags")
165
166     switch (sizeof(IntType)) {
167     case 2: FB_DOBTS(w); break;
168     case 4: FB_DOBTS(l); break;
169     case 8: FB_DOBTS(q); break;
170     }
171
172 #undef FB_DOBTS
173 #elif FOLLY_A64
174     ret =
175         !(__atomic_fetch_or(&lock_, kLockBitMask_, __ATOMIC_SEQ_CST) &
176           kLockBitMask_);
177 #elif FOLLY_PPC64
178 #define FB_DOBTS(size)                                 \
179     asm volatile("\teieio\n"                           \
180                  "\tl" #size "arx 14,0,%[lockPtr]\n"   \
181                  "\tli 15,1\n"                         \
182                  "\tsldi 15,15,%[bit]\n"               \
183                  "\tand. 16,15,14\n"                   \
184                  "\tbne 0f\n"                          \
185                  "\tor 14,14,15\n"                     \
186                  "\tst" #size "cx. 14,0,%[lockPtr]\n"  \
187                  "\tbne 0f\n"                          \
188                  "\tori %[output],%[output],1\n"       \
189                  "\tisync\n"                           \
190                  "0:\n"                                \
191                  : [output] "+r" (ret)                 \
192                  : [lockPtr] "r"(&lock_),              \
193                    [bit] "i" (Bit)                     \
194                  : "cr0", "memory", "r14", "r15", "r16")
195
196     switch (sizeof(IntType)) {
197     case 2: FB_DOBTS(h); break;
198     case 4: FB_DOBTS(w); break;
199     case 8: FB_DOBTS(d); break;
200     }
201
202 #undef FB_DOBTS
203 #else
204 #error "x86 aarch64 ppc64 only"
205 #endif
206
207     return ret;
208   }
209
210   /*
211    * Block until we can acquire the lock.  Uses Sleeper to wait.
212    */
213   void lock() const {
214     detail::Sleeper sleeper;
215     while (!try_lock()) {
216       sleeper.wait();
217     }
218   }
219
220   /*
221    * Release the lock, without changing the value of the rest of the
222    * integer.
223    */
224   void unlock() const {
225 #ifdef _MSC_VER
226     switch (sizeof(IntType)) {
227       case 2:
228         // There is no _interlockedbittestandreset16 for some reason :(
229         _InterlockedAnd16((volatile short*)&lock_, (short)~kLockBitMask_);
230         break;
231       case 4:
232         _interlockedbittestandreset((volatile long*)&lock_, Bit);
233         break;
234       case 8:
235         _interlockedbittestandreset64((volatile long long*)&lock_, Bit);
236         break;
237     }
238 #elif FOLLY_X64
239 #define FB_DOBTR(size)                          \
240   asm volatile("lock; btr" #size " %0, (%1)"    \
241                :                                \
242                : "i" (Bit),                     \
243                  "r" (&lock_)                   \
244                : "memory", "flags")
245
246
247     // Reads and writes can not be reordered wrt locked instructions,
248     // so we don't need a memory fence here.
249     switch (sizeof(IntType)) {
250     case 2: FB_DOBTR(w); break;
251     case 4: FB_DOBTR(l); break;
252     case 8: FB_DOBTR(q); break;
253     }
254
255 #undef FB_DOBTR
256 #elif FOLLY_A64
257     __atomic_fetch_and(&lock_, ~kLockBitMask_, __ATOMIC_SEQ_CST);
258 #elif FOLLY_PPC64
259 #define FB_DOBTR(size)                                 \
260     asm volatile("\teieio\n"                           \
261                  "0:  l" #size "arx 14,0,%[lockPtr]\n" \
262                  "\tli 15,1\n"                         \
263                  "\tsldi 15,15,%[bit]\n"               \
264                  "\txor 14,14,15\n"                    \
265                  "\tst" #size "cx. 14,0,%[lockPtr]\n"  \
266                  "\tbne 0b\n"                          \
267                  "\tisync\n"                           \
268                  :                                     \
269                  : [lockPtr] "r"(&lock_),              \
270                    [bit] "i" (Bit)                     \
271                  : "cr0", "memory", "r14", "r15")
272
273     switch (sizeof(IntType)) {
274     case 2: FB_DOBTR(h); break;
275     case 4: FB_DOBTR(w); break;
276     case 8: FB_DOBTR(d); break;
277     }
278
279 #undef FB_DOBTR
280 #else
281 # error "x64 aarch64 ppc64 only"
282 #endif
283   }
284 };
285
286 }