02d7bc924183f8f5d59facaff3062731ba821504
[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 <pthread.h>
48 #include <type_traits>
49
50 #include <glog/logging.h>
51 #include <folly/detail/Sleeper.h>
52
53 #if !FOLLY_X64 && !FOLLY_A64 && !FOLLY_PPC64
54 # error "PicoSpinLock.h is currently x64, aarch64 and ppc64 only."
55 #endif
56
57 namespace folly {
58
59 /*
60  * Spin lock on a single bit in an integral type.  You can use this
61  * with 16, 32, or 64-bit integral types.
62  *
63  * This is useful if you want a small lock and already have an int
64  * with a bit in it that you aren't using.  But note that it can't be
65  * as small as MicroSpinLock (1 byte), if you don't already have a
66  * convenient int with an unused bit lying around to put it on.
67  *
68  * To construct these, either use init() or zero initialize.  We don't
69  * have a real constructor because we want this to be a POD type so we
70  * can put it into packed structs.
71  */
72 template<class IntType, int Bit = sizeof(IntType) * 8 - 1>
73 struct PicoSpinLock {
74   // Internally we deal with the unsigned version of the type.
75   typedef typename std::make_unsigned<IntType>::type UIntType;
76
77   static_assert(std::is_integral<IntType>::value,
78                 "PicoSpinLock needs an integral type");
79   static_assert(sizeof(IntType) == 2 || sizeof(IntType) == 4 ||
80                   sizeof(IntType) == 8,
81                 "PicoSpinLock can't work on integers smaller than 2 bytes");
82
83  public:
84   static const UIntType kLockBitMask_ = UIntType(1) << Bit;
85   UIntType lock_;
86
87   /*
88    * You must call this function before using this class, if you
89    * default constructed it.  If you zero-initialized it you can
90    * assume the PicoSpinLock is in a valid unlocked state with
91    * getData() == 0.
92    *
93    * (This doesn't use a constructor because we want to be a POD.)
94    */
95   void init(IntType initialValue = 0) {
96     CHECK(!(initialValue & kLockBitMask_));
97     lock_ = UIntType(initialValue);
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     return static_cast<IntType>(lock_ & ~kLockBitMask_);
111   }
112
113   /*
114    * Set the value of the other bits in our integer.
115    *
116    * Don't use this when you aren't holding the lock, unless it can be
117    * guaranteed that no other threads may be trying to use this.
118    */
119   void setData(IntType w) {
120     CHECK(!(w & kLockBitMask_));
121     lock_ = UIntType((lock_ & kLockBitMask_) | w);
122   }
123
124   /*
125    * Try to get the lock without blocking: returns whether or not we
126    * got it.
127    */
128   bool try_lock() const {
129     bool ret = false;
130
131 #ifdef _MSC_VER
132     switch (sizeof(IntType)) {
133       case 2:
134         // There is no _interlockedbittestandset16 for some reason :(
135         ret = _InterlockedOr16(
136             (volatile short*)&lock_, (short)kLockBitMask_) & kLockBitMask_;
137         break;
138       case 4:
139         ret = _interlockedbittestandset((volatile long*)&lock_, Bit);
140         break;
141       case 8:
142         ret = _interlockedbittestandset64((volatile long long*)&lock_, Bit);
143         break;
144     }
145 #elif FOLLY_X64
146 #define FB_DOBTS(size)                                  \
147   asm volatile("lock; bts" #size " %1, (%2); setnc %0"  \
148                : "=r" (ret)                             \
149                : "i" (Bit),                             \
150                  "r" (&lock_)                           \
151                : "memory", "flags")
152
153     switch (sizeof(IntType)) {
154     case 2: FB_DOBTS(w); break;
155     case 4: FB_DOBTS(l); break;
156     case 8: FB_DOBTS(q); break;
157     }
158
159 #undef FB_DOBTS
160 #elif FOLLY_A64
161     ret = __atomic_fetch_or(&lock_, 1 << Bit, __ATOMIC_SEQ_CST);
162 #elif FOLLY_PPC64
163 #define FB_DOBTS(size)                                 \
164     asm volatile("\teieio\n"                           \
165                  "\tl" #size "arx 14,0,%[lockPtr]\n"   \
166                  "\tli 15,1\n"                         \
167                  "\tsldi 15,15,%[bit]\n"               \
168                  "\tand. 16,15,14\n"                   \
169                  "\tbne 0f\n"                          \
170                  "\tor 14,14,15\n"                     \
171                  "\tst" #size "cx. 14,0,%[lockPtr]\n"  \
172                  "\tbne 0f\n"                          \
173                  "\tori %[output],%[output],1\n"       \
174                  "\tisync\n"                           \
175                  "0:\n"                                \
176                  : [output] "+r" (ret)                 \
177                  : [lockPtr] "r"(&lock_),              \
178                    [bit] "i" (Bit)                     \
179                  : "cr0", "memory", "r14", "r15", "r16")
180
181     switch (sizeof(IntType)) {
182     case 2: FB_DOBTS(h); break;
183     case 4: FB_DOBTS(w); break;
184     case 8: FB_DOBTS(d); break;
185     }
186
187 #undef FB_DOBTS
188 #else
189 #error "x86 aarch64 ppc64 only"
190 #endif
191
192     return ret;
193   }
194
195   /*
196    * Block until we can acquire the lock.  Uses Sleeper to wait.
197    */
198   void lock() const {
199     detail::Sleeper sleeper;
200     while (!try_lock()) {
201       sleeper.wait();
202     }
203   }
204
205   /*
206    * Release the lock, without changing the value of the rest of the
207    * integer.
208    */
209   void unlock() const {
210 #ifdef _MSC_VER
211     switch (sizeof(IntType)) {
212       case 2:
213         // There is no _interlockedbittestandreset16 for some reason :(
214         _InterlockedAnd16((volatile short*)&lock_, (short)~kLockBitMask_);
215         break;
216       case 4:
217         _interlockedbittestandreset((volatile long*)&lock_, Bit);
218         break;
219       case 8:
220         _interlockedbittestandreset64((volatile long long*)&lock_, Bit);
221         break;
222     }
223 #elif FOLLY_X64
224 #define FB_DOBTR(size)                          \
225   asm volatile("lock; btr" #size " %0, (%1)"    \
226                :                                \
227                : "i" (Bit),                     \
228                  "r" (&lock_)                   \
229                : "memory", "flags")
230
231
232     // Reads and writes can not be reordered wrt locked instructions,
233     // so we don't need a memory fence here.
234     switch (sizeof(IntType)) {
235     case 2: FB_DOBTR(w); break;
236     case 4: FB_DOBTR(l); break;
237     case 8: FB_DOBTR(q); break;
238     }
239
240 #undef FB_DOBTR
241 #elif FOLLY_A64
242     __atomic_fetch_and(&lock_, ~(1 << Bit), __ATOMIC_SEQ_CST);
243 #elif FOLLY_PPC64
244 #define FB_DOBTR(size)                                 \
245     asm volatile("\teieio\n"                           \
246                  "0:  l" #size "arx 14,0,%[lockPtr]\n" \
247                  "\tli 15,1\n"                         \
248                  "\tsldi 15,15,%[bit]\n"               \
249                  "\txor 14,14,15\n"                    \
250                  "\tst" #size "cx. 14,0,%[lockPtr]\n"  \
251                  "\tbne 0b\n"                          \
252                  "\tisync\n"                           \
253                  :                                     \
254                  : [lockPtr] "r"(&lock_),              \
255                    [bit] "i" (Bit)                     \
256                  : "cr0", "memory", "r14", "r15")
257
258     switch (sizeof(IntType)) {
259     case 2: FB_DOBTR(h); break;
260     case 4: FB_DOBTR(w); break;
261     case 8: FB_DOBTR(d); break;
262     }
263
264 #undef FB_DOBTR
265 #else
266 # error "x64 aarch64 ppc64 only"
267 #endif
268   }
269 };
270
271 }