SharedMutex - a small fast scalable reader-writer lock
[folly.git] / folly / experimental / SharedMutex.h
1 /*
2  * Copyright 2015 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 Nathan Bronson (ngbronson@fb.com)
18
19 #pragma once
20
21 #include <stdint.h>
22 #include <atomic>
23 #include <thread>
24 #include <type_traits>
25 #include <folly/Likely.h>
26 #include <folly/detail/CacheLocality.h>
27 #include <folly/detail/Futex.h>
28 #include <sys/resource.h>
29
30 // SharedMutex is a reader-writer lock.  It is small, very fast, scalable
31 // on multi-core, and suitable for use when readers or writers may block.
32 // Unlike most other reader-writer locks, its throughput with concurrent
33 // readers scales linearly; it is able to acquire and release the lock
34 // in shared mode without cache line ping-ponging.  It is suitable for
35 // a wide range of lock hold times because it starts with spinning,
36 // proceeds to using sched_yield with a preemption heuristic, and then
37 // waits using futex and precise wakeups.
38 //
39 // SharedMutex provides all of the methods of folly::RWSpinLock,
40 // boost::shared_mutex, boost::upgrade_mutex, and C++14's
41 // std::shared_timed_mutex.  All operations that can block are available
42 // in try, try-for, and try-until (system_clock or steady_clock) versions.
43 //
44 // SharedMutexReadPriority gives priority to readers,
45 // SharedMutexWritePriority gives priority to writers.  SharedMutex is an
46 // alias for SharedMutexWritePriority, because writer starvation is more
47 // likely than reader starvation for the read-heavy workloads targetted
48 // by SharedMutex.
49 //
50 // In my tests SharedMutex is as good or better than the other
51 // reader-writer locks in use at Facebook for almost all use cases,
52 // sometimes by a wide margin.  (If it is rare that there are actually
53 // concurrent readers then RWSpinLock can be a few nanoseconds faster.)
54 // I compared it to folly::RWSpinLock, folly::RWTicketSpinLock64,
55 // boost::shared_mutex, pthread_rwlock_t, and a RWLock that internally uses
56 // spinlocks to guard state and pthread_mutex_t+pthread_cond_t to block.
57 // (Thrift's ReadWriteMutex is based underneath on pthread_rwlock_t.)
58 // It is generally as good or better than the rest when evaluating size,
59 // speed, scalability, or latency outliers.  In the corner cases where
60 // it is not the fastest (such as single-threaded use or heavy write
61 // contention) it is never very much worse than the best.  See the bottom
62 // of folly/test/SharedMutexTest.cpp for lots of microbenchmark results.
63 //
64 // Comparison to folly::RWSpinLock:
65 //
66 //  * SharedMutex is faster than RWSpinLock when there are actually
67 //    concurrent read accesses (sometimes much faster), and ~5 nanoseconds
68 //    slower when there is not actually any contention.  SharedMutex is
69 //    faster in every (benchmarked) scenario where the shared mode of
70 //    the lock is actually useful.
71 //
72 //  * Concurrent shared access to SharedMutex scales linearly, while total
73 //    RWSpinLock throughput drops as more threads try to access the lock
74 //    in shared mode.  Under very heavy read contention SharedMutex can
75 //    be two orders of magnitude faster than RWSpinLock (or any reader
76 //    writer lock that doesn't use striping or deferral).
77 //
78 //  * SharedMutex can safely protect blocking calls, because after an
79 //    initial period of spinning it waits using futex().
80 //
81 //  * RWSpinLock prioritizes readers, SharedMutex has both reader- and
82 //    writer-priority variants, but defaults to write priority.
83 //
84 //  * RWSpinLock's upgradeable mode blocks new readers, while SharedMutex's
85 //    doesn't.  Both semantics are reasonable.  The boost documentation
86 //    doesn't explicitly talk about this behavior (except by omitting
87 //    any statement that those lock modes conflict), but the boost
88 //    implementations do allow new readers while the upgradeable mode
89 //    is held.  See https://github.com/boostorg/thread/blob/master/
90 //      include/boost/thread/pthread/shared_mutex.hpp
91 //
92 //  * RWSpinLock::UpgradedHolder maps to SharedMutex::UpgradeHolder
93 //    (UpgradeableHolder would be even more pedantically correct).
94 //    SharedMutex's holders have fewer methods (no reset) and are less
95 //    tolerant (promotion and downgrade crash if the donor doesn't own
96 //    the lock, and you must use the default constructor rather than
97 //    passing a nullptr to the pointer constructor).
98 //
99 // Both SharedMutex and RWSpinLock provide "exclusive", "upgrade",
100 // and "shared" modes.  At all times num_threads_holding_exclusive +
101 // num_threads_holding_upgrade <= 1, and num_threads_holding_exclusive ==
102 // 0 || num_threads_holding_shared == 0.  RWSpinLock has the additional
103 // constraint that num_threads_holding_shared cannot increase while
104 // num_threads_holding_upgrade is non-zero.
105 //
106 // Comparison to the internal RWLock:
107 //
108 //  * SharedMutex doesn't allow a maximum reader count to be configured,
109 //    so it can't be used as a semaphore in the same way as RWLock.
110 //
111 //  * SharedMutex is 4 bytes, RWLock is 256.
112 //
113 //  * SharedMutex is as fast or faster than RWLock in all of my
114 //    microbenchmarks, and has positive rather than negative scalability.
115 //
116 //  * RWLock and SharedMutex are both writer priority locks.
117 //
118 //  * SharedMutex avoids latency outliers as well as RWLock.
119 //
120 //  * SharedMutex uses different names (t != 0 below):
121 //
122 //    RWLock::lock(0)    => SharedMutex::lock()
123 //
124 //    RWLock::lock(t)    => SharedMutex::try_lock_for(milliseconds(t))
125 //
126 //    RWLock::tryLock()  => SharedMutex::try_lock()
127 //
128 //    RWLock::unlock()   => SharedMutex::unlock()
129 //
130 //    RWLock::enter(0)   => SharedMutex::lock_shared()
131 //
132 //    RWLock::enter(t)   =>
133 //        SharedMutex::try_lock_shared_for(milliseconds(t))
134 //
135 //    RWLock::tryEnter() => SharedMutex::try_lock_shared()
136 //
137 //    RWLock::leave()    => SharedMutex::unlock_shared()
138 //
139 //  * RWLock allows the reader count to be adjusted by a value other
140 //    than 1 during enter() or leave(). SharedMutex doesn't currently
141 //    implement this feature.
142 //
143 //  * RWLock's methods are marked const, SharedMutex's aren't.
144 //
145 // Reader-writer locks have the potential to allow concurrent access
146 // to shared read-mostly data, but in practice they often provide no
147 // improvement over a mutex.  The problem is the cache coherence protocol
148 // of modern CPUs.  Coherence is provided by making sure that when a cache
149 // line is written it is present in only one core's cache.  Since a memory
150 // write is required to acquire a reader-writer lock in shared mode, the
151 // cache line holding the lock is invalidated in all of the other caches.
152 // This leads to cache misses when another thread wants to acquire or
153 // release the lock concurrently.  When the RWLock is colocated with the
154 // data it protects (common), cache misses can also continue occur when
155 // a thread that already holds the lock tries to read the protected data.
156 //
157 // Ideally, a reader-writer lock would allow multiple cores to acquire
158 // and release the lock in shared mode without incurring any cache misses.
159 // This requires that each core records its shared access in a cache line
160 // that isn't read or written by other read-locking cores.  (Writers will
161 // have to check all of the cache lines.)  Typical server hardware when
162 // this comment was written has 16 L1 caches and cache lines of 64 bytes,
163 // so a lock striped over all L1 caches would occupy a prohibitive 1024
164 // bytes.  Nothing says that we need a separate set of per-core memory
165 // locations for each lock, however.  Each SharedMutex instance is only
166 // 4 bytes, but all locks together share a 2K area in which they make a
167 // core-local record of lock acquisitions.
168 //
169 // SharedMutex's strategy of using a shared set of core-local stripes has
170 // a potential downside, because it means that acquisition of any lock in
171 // write mode can conflict with acquisition of any lock in shared mode.
172 // If a lock instance doesn't actually experience concurrency then this
173 // downside will outweight the upside of improved scalability for readers.
174 // To avoid this problem we dynamically detect concurrent accesses to
175 // SharedMutex, and don't start using the deferred mode unless we actually
176 // observe concurrency.  See kNumSharedToStartDeferring.
177 //
178 // It is explicitly allowed to call lock_unshared() from a different
179 // thread than lock_shared(), so long as they are properly paired.
180 // lock_unshared() needs to find the location at which lock_shared()
181 // recorded the lock, which might be in the lock itself or in any of
182 // the shared slots.  If you can conveniently pass state from lock
183 // acquisition to release then the fastest mechanism is to std::move
184 // the SharedMutex::ReadHolder instance or an SharedMutex::Token (using
185 // lock_shared(Token&) and unlock_sahred(Token&)).  The guard or token
186 // will tell unlock_shared where in deferredReaders[] to look for the
187 // deferred lock.  The Token-less version of unlock_shared() works in all
188 // cases, but is optimized for the common (no inter-thread handoff) case.
189 //
190 // In both read- and write-priority mode, a waiting lock() (exclusive mode)
191 // only blocks readers after it has waited for an active upgrade lock to be
192 // released; until the upgrade lock is released (or upgraded or downgraded)
193 // readers will still be able to enter.  Preferences about lock acquisition
194 // are not guaranteed to be enforced perfectly (even if they were, there
195 // is theoretically the chance that a thread could be arbitrarily suspended
196 // between calling lock() and SharedMutex code actually getting executed).
197 //
198 // try_*_for methods always try at least once, even if the duration
199 // is zero or negative.  The duration type must be compatible with
200 // std::chrono::steady_clock.  try_*_until methods also always try at
201 // least once.  std::chrono::system_clock and std::chrono::steady_clock
202 // are supported.
203 //
204 // If you have observed by profiling that your SharedMutex-s are getting
205 // cache misses on deferredReaders[] due to another SharedMutex user, then
206 // you can use the tag type plus the RWDEFERREDLOCK_DECLARE_STATIC_STORAGE
207 // macro to create your own instantiation of the type.  The contention
208 // threshold (see kNumSharedToStartDeferring) should make this unnecessary
209 // in all but the most extreme cases.  Make sure to check that the
210 // increased icache and dcache footprint of the tagged result is worth it.
211
212 namespace folly {
213
214 struct SharedMutexToken {
215   enum class Type : uint16_t {
216     INVALID = 0,
217     INLINE_SHARED,
218     DEFERRED_SHARED,
219   };
220
221   Type type_;
222   uint16_t slot_;
223 };
224
225 template <bool ReaderPriority,
226           typename Tag_ = void,
227           template <typename> class Atom = std::atomic,
228           bool BlockImmediately = false>
229 class SharedMutexImpl : boost::noncopyable {
230  public:
231   static constexpr bool kReaderPriority = ReaderPriority;
232   typedef Tag_ Tag;
233
234   typedef SharedMutexToken Token;
235
236   class ReadHolder;
237   class UpgradeHolder;
238   class WriteHolder;
239
240   SharedMutexImpl() : state_(0) {}
241
242   // It is an error to destroy an SharedMutex that still has
243   // any outstanding locks.  This is checked if NDEBUG isn't defined.
244   // SharedMutex's exclusive mode can be safely used to guard the lock's
245   // own destruction.  If, for example, you acquire the lock in exclusive
246   // mode and then observe that the object containing the lock is no longer
247   // needed, you can unlock() and then immediately destroy the lock.
248   // See https://sourceware.org/bugzilla/show_bug.cgi?id=13690 for a
249   // description about why this property needs to be explicitly mentioned.
250   ~SharedMutexImpl() {
251 #ifndef NDEBUG
252     auto state = state_.load(std::memory_order_acquire);
253
254     // if a futexWait fails to go to sleep because the value has been
255     // changed, we don't necessarily clean up the wait bits, so it is
256     // possible they will be set here in a correct system
257     assert((state & ~(kWaitingAny | kMayDefer)) == 0);
258     if ((state & kMayDefer) != 0) {
259       for (uint32_t slot = 0; slot < kMaxDeferredReaders; ++slot) {
260         auto slotValue = deferredReader(slot)->load(std::memory_order_acquire);
261         assert(!slotValueIsThis(slotValue));
262       }
263     }
264 #endif
265   }
266
267   void lock() {
268     WaitForever ctx;
269     (void)lockExclusiveImpl(kHasSolo, ctx);
270   }
271
272   bool try_lock() {
273     WaitNever ctx;
274     return lockExclusiveImpl(kHasSolo, ctx);
275   }
276
277   template <class Rep, class Period>
278   bool try_lock_for(const std::chrono::duration<Rep, Period>& duration) {
279     WaitForDuration<Rep, Period> ctx(duration);
280     return lockExclusiveImpl(kHasSolo, ctx);
281   }
282
283   template <class Clock, class Duration>
284   bool try_lock_until(
285       const std::chrono::time_point<Clock, Duration>& absDeadline) {
286     WaitUntilDeadline<Clock, Duration> ctx{absDeadline};
287     return lockExclusiveImpl(kHasSolo, ctx);
288   }
289
290   void unlock() {
291     // It is possible that we have a left-over kWaitingNotS if the last
292     // unlock_shared() that let our matching lock() complete finished
293     // releasing before lock()'s futexWait went to sleep.  Clean it up now
294     auto state = (state_ &= ~(kWaitingNotS | kPrevDefer | kHasE));
295     assert((state & ~kWaitingAny) == 0);
296     wakeRegisteredWaiters(state, kWaitingE | kWaitingU | kWaitingS);
297   }
298
299   // Managing the token yourself makes unlock_shared a bit faster
300
301   void lock_shared() {
302     WaitForever ctx;
303     (void)lockSharedImpl(nullptr, ctx);
304   }
305
306   void lock_shared(Token& token) {
307     WaitForever ctx;
308     (void)lockSharedImpl(&token, ctx);
309   }
310
311   bool try_lock_shared() {
312     WaitNever ctx;
313     return lockSharedImpl(nullptr, ctx);
314   }
315
316   bool try_lock_shared(Token& token) {
317     WaitNever ctx;
318     return lockSharedImpl(&token, ctx);
319   }
320
321   template <class Rep, class Period>
322   bool try_lock_shared_for(const std::chrono::duration<Rep, Period>& duration) {
323     WaitForDuration<Rep, Period> ctx(duration);
324     return lockSharedImpl(nullptr, ctx);
325   }
326
327   template <class Rep, class Period>
328   bool try_lock_shared_for(const std::chrono::duration<Rep, Period>& duration,
329                            Token& token) {
330     WaitForDuration<Rep, Period> ctx(duration);
331     return lockSharedImpl(&token, ctx);
332   }
333
334   template <class Clock, class Duration>
335   bool try_lock_shared_until(
336       const std::chrono::time_point<Clock, Duration>& absDeadline) {
337     WaitUntilDeadline<Clock, Duration> ctx{absDeadline};
338     return lockSharedImpl(nullptr, ctx);
339   }
340
341   template <class Clock, class Duration>
342   bool try_lock_shared_until(
343       const std::chrono::time_point<Clock, Duration>& absDeadline,
344       Token& token) {
345     WaitUntilDeadline<Clock, Duration> ctx{absDeadline};
346     return lockSharedImpl(&token, ctx);
347   }
348
349   void unlock_shared() {
350     auto state = state_.load(std::memory_order_acquire);
351
352     // kPrevDefer can only be set if HasE or BegunE is set
353     assert((state & (kPrevDefer | kHasE | kBegunE)) != kPrevDefer);
354
355     // lock() strips kMayDefer immediately, but then copies it to
356     // kPrevDefer so we can tell if the pre-lock() lock_shared() might
357     // have deferred
358     if ((state & (kMayDefer | kPrevDefer)) == 0 ||
359         !tryUnlockAnySharedDeferred()) {
360       // Matching lock_shared() couldn't have deferred, or the deferred
361       // lock has already been inlined by applyDeferredReaders()
362       unlockSharedInline();
363     }
364   }
365
366   void unlock_shared(Token& token) {
367     assert(token.type_ == Token::Type::INLINE_SHARED ||
368            token.type_ == Token::Type::DEFERRED_SHARED);
369
370     if (token.type_ != Token::Type::DEFERRED_SHARED ||
371         !tryUnlockSharedDeferred(token.slot_)) {
372       unlockSharedInline();
373     }
374 #ifndef NDEBUG
375     token.type_ = Token::Type::INVALID;
376 #endif
377   }
378
379   void unlock_and_lock_shared() {
380     // We can't use state_ -=, because we need to clear 2 bits (1 of which
381     // has an uncertain initial state) and set 1 other.  We might as well
382     // clear the relevant wake bits at the same time.  Note that since S
383     // doesn't block the beginning of a transition to E (writer priority
384     // can cut off new S, reader priority grabs BegunE and blocks deferred
385     // S) we need to wake E as well.
386     auto state = state_.load(std::memory_order_acquire);
387     do {
388       assert((state & ~(kWaitingAny | kPrevDefer)) == kHasE);
389     } while (!state_.compare_exchange_strong(
390         state, (state & ~(kWaitingAny | kPrevDefer | kHasE)) + kIncrHasS));
391     if ((state & (kWaitingE | kWaitingU | kWaitingS)) != 0) {
392       futexWakeAll(kWaitingE | kWaitingU | kWaitingS);
393     }
394   }
395
396   void unlock_and_lock_shared(Token& token) {
397     unlock_and_lock_shared();
398     token.type_ = Token::Type::INLINE_SHARED;
399   }
400
401   void lock_upgrade() {
402     WaitForever ctx;
403     (void)lockUpgradeImpl(ctx);
404   }
405
406   bool try_lock_upgrade() {
407     WaitNever ctx;
408     return lockUpgradeImpl(ctx);
409   }
410
411   template <class Rep, class Period>
412   bool try_lock_upgrade_for(
413       const std::chrono::duration<Rep, Period>& duration) {
414     WaitForDuration<Rep, Period> ctx(duration);
415     return lockUpgradeImpl(ctx);
416   }
417
418   template <class Clock, class Duration>
419   bool try_lock_upgrade_until(
420       const std::chrono::time_point<Clock, Duration>& absDeadline) {
421     WaitUntilDeadline<Clock, Duration> ctx{absDeadline};
422     return lockUpgradeImpl(ctx);
423   }
424
425   void unlock_upgrade() {
426     auto state = (state_ -= kHasU);
427     assert((state & (kWaitingNotS | kHasSolo)) == 0);
428     wakeRegisteredWaiters(state, kWaitingE | kWaitingU);
429   }
430
431   void unlock_upgrade_and_lock() {
432     // no waiting necessary, so waitMask is empty
433     WaitForever ctx;
434     (void)lockExclusiveImpl(0, ctx);
435   }
436
437   void unlock_upgrade_and_lock_shared() {
438     auto state = (state_ -= kHasU - kIncrHasS);
439     assert((state & (kWaitingNotS | kHasSolo)) == 0 && (state & kHasS) != 0);
440     wakeRegisteredWaiters(state, kWaitingE | kWaitingU);
441   }
442
443   void unlock_upgrade_and_lock_shared(Token& token) {
444     unlock_upgrade_and_lock_shared();
445     token.type_ = Token::Type::INLINE_SHARED;
446   }
447
448   void unlock_and_lock_upgrade() {
449     // We can't use state_ -=, because we need to clear 2 bits (1 of
450     // which has an uncertain initial state) and set 1 other.  We might
451     // as well clear the relevant wake bits at the same time.
452     auto state = state_.load(std::memory_order_acquire);
453     while (true) {
454       assert((state & ~(kWaitingAny | kPrevDefer)) == kHasE);
455       auto after =
456           (state & ~(kWaitingNotS | kWaitingS | kPrevDefer | kHasE)) + kHasU;
457       if (state_.compare_exchange_strong(state, after)) {
458         if ((state & kWaitingS) != 0) {
459           futexWakeAll(kWaitingS);
460         }
461         return;
462       }
463     }
464   }
465
466  private:
467   typedef typename folly::detail::Futex<Atom> Futex;
468
469   // Internally we use four kinds of wait contexts.  These are structs
470   // that provide a doWait method that returns true if a futex wake
471   // was issued that intersects with the waitMask, false if there was a
472   // timeout and no more waiting should be performed.  Spinning occurs
473   // before the wait context is invoked.
474
475   struct WaitForever {
476     bool canBlock() { return true; }
477     bool canTimeOut() { return false; }
478     bool shouldTimeOut() { return false; }
479
480     bool doWait(Futex& futex, uint32_t expected, uint32_t waitMask) {
481       futex.futexWait(expected, waitMask);
482       return true;
483     }
484   };
485
486   struct WaitNever {
487     bool canBlock() { return false; }
488     bool canTimeOut() { return true; }
489     bool shouldTimeOut() { return true; }
490
491     bool doWait(Futex& futex, uint32_t expected, uint32_t waitMask) {
492       return false;
493     }
494   };
495
496   template <class Rep, class Period>
497   struct WaitForDuration {
498     std::chrono::duration<Rep, Period> duration_;
499     bool deadlineComputed_;
500     std::chrono::steady_clock::time_point deadline_;
501
502     explicit WaitForDuration(const std::chrono::duration<Rep, Period>& duration)
503         : duration_(duration), deadlineComputed_(false) {}
504
505     std::chrono::steady_clock::time_point deadline() {
506       if (!deadlineComputed_) {
507         deadline_ = std::chrono::steady_clock::now() + duration_;
508         deadlineComputed_ = true;
509       }
510       return deadline_;
511     }
512
513     bool canBlock() { return duration_.count() > 0; }
514     bool canTimeOut() { return true; }
515
516     bool shouldTimeOut() {
517       return std::chrono::steady_clock::now() > deadline();
518     }
519
520     bool doWait(Futex& futex, uint32_t expected, uint32_t waitMask) {
521       auto result = futex.futexWaitUntil(expected, deadline(), waitMask);
522       return result != folly::detail::FutexResult::TIMEDOUT;
523     }
524   };
525
526   template <class Clock, class Duration>
527   struct WaitUntilDeadline {
528     std::chrono::time_point<Clock, Duration> absDeadline_;
529
530     bool canBlock() { return true; }
531     bool canTimeOut() { return true; }
532     bool shouldTimeOut() { return Clock::now() > absDeadline_; }
533
534     bool doWait(Futex& futex, uint32_t expected, uint32_t waitMask) {
535       auto result = futex.futexWaitUntil(expected, absDeadline_, waitMask);
536       return result != folly::detail::FutexResult::TIMEDOUT;
537     }
538   };
539
540   // 32 bits of state
541   Futex state_;
542
543   static constexpr uint32_t kIncrHasS = 1 << 10;
544   static constexpr uint32_t kHasS = ~(kIncrHasS - 1);
545
546   // If false, then there are definitely no deferred read locks for this
547   // instance.  Cleared after initialization and when exclusively locked.
548   static constexpr uint32_t kMayDefer = 1 << 9;
549
550   // lock() cleared kMayDefer as soon as it starts draining readers (so
551   // that it doesn't have to do a second CAS once drain completes), but
552   // unlock_shared() still needs to know whether to scan deferredReaders[]
553   // or not.  We copy kMayDefer to kPrevDefer when setting kHasE or
554   // kBegunE, and clear it when clearing those bits.
555   static constexpr uint32_t kPrevDefer = 1 << 8;
556
557   // Exclusive-locked blocks all read locks and write locks.  This bit
558   // may be set before all readers have finished, but in that case the
559   // thread that sets it won't return to the caller until all read locks
560   // have been released.
561   static constexpr uint32_t kHasE = 1 << 7;
562
563   // Exclusive-draining means that lock() is waiting for existing readers
564   // to leave, but that new readers may still acquire shared access.
565   // This is only used in reader priority mode.  New readers during
566   // drain must be inline.  The difference between this and kHasU is that
567   // kBegunE prevents kMayDefer from being set.
568   static constexpr uint32_t kBegunE = 1 << 6;
569
570   // At most one thread may have either exclusive or upgrade lock
571   // ownership.  Unlike exclusive mode, ownership of the lock in upgrade
572   // mode doesn't preclude other threads holding the lock in shared mode.
573   // boost's concept for this doesn't explicitly say whether new shared
574   // locks can be acquired one lock_upgrade has succeeded, but doesn't
575   // list that as disallowed.  RWSpinLock disallows new read locks after
576   // lock_upgrade has been acquired, but the boost implementation doesn't.
577   // We choose the latter.
578   static constexpr uint32_t kHasU = 1 << 5;
579
580   // There are three states that we consider to be "solo", in that they
581   // cannot coexist with other solo states.  These are kHasE, kBegunE,
582   // and kHasU.  Note that S doesn't conflict with any of these, because
583   // setting the kHasE is only one of the two steps needed to actually
584   // acquire the lock in exclusive mode (the other is draining the existing
585   // S holders).
586   static constexpr uint32_t kHasSolo = kHasE | kBegunE | kHasU;
587
588   // Once a thread sets kHasE it needs to wait for the current readers
589   // to exit the lock.  We give this a separate wait identity from the
590   // waiting to set kHasE so that we can perform partial wakeups (wake
591   // one instead of wake all).
592   static constexpr uint32_t kWaitingNotS = 1 << 4;
593
594   // If there are multiple pending waiters, then waking them all can
595   // lead to a thundering herd on the lock.  To avoid this, we keep
596   // a 2 bit saturating counter of the number of exclusive waiters
597   // (0, 1, 2, 3+), and if the value is >= 2 we perform futexWake(1)
598   // instead of futexWakeAll.  See wakeRegisteredWaiters for more.
599   // It isn't actually useful to make the counter bigger, because
600   // whenever a futexWait fails with EAGAIN the counter becomes higher
601   // than the actual number of waiters, and hence effectively saturated.
602   // Bigger counters just lead to more changes in state_, which increase
603   // contention and failed futexWait-s.
604   static constexpr uint32_t kIncrWaitingE = 1 << 2;
605   static constexpr uint32_t kWaitingE = 0x3 * kIncrWaitingE;
606
607   // kWaitingU is essentially a 1 bit saturating counter.  It always
608   // requires a wakeAll.
609   static constexpr uint32_t kWaitingU = 1 << 1;
610
611   // All blocked lock_shared() should be awoken, so it is correct (not
612   // suboptimal) to wakeAll if there are any shared readers.
613   static constexpr uint32_t kWaitingS = 1 << 0;
614
615   // kWaitingAny is a mask of all of the bits that record the state of
616   // threads, rather than the state of the lock.  It is convenient to be
617   // able to mask them off during asserts.
618   static constexpr uint32_t kWaitingAny =
619       kWaitingNotS | kWaitingE | kWaitingU | kWaitingS;
620
621   // The reader count at which a reader will attempt to use the lock
622   // in deferred mode.  If this value is 2, then the second concurrent
623   // reader will set kMayDefer and use deferredReaders[].  kMayDefer is
624   // cleared during exclusive access, so this threshold must be reached
625   // each time a lock is held in exclusive mode.
626   static constexpr uint32_t kNumSharedToStartDeferring = 2;
627
628   // The typical number of spins that a thread will wait for a state
629   // transition.  There is no bound on the number of threads that can wait
630   // for a writer, so we are pretty conservative here to limit the chance
631   // that we are starving the writer of CPU.  Each spin is 6 or 7 nanos,
632   // almost all of which is in the pause instruction.
633   static constexpr uint32_t kMaxSpinCount = !BlockImmediately ? 1000 : 2;
634
635   // The maximum number of soft yields before falling back to futex.
636   // If the preemption heuristic is activated we will fall back before
637   // this.  A soft yield takes ~900 nanos (two sched_yield plus a call
638   // to getrusage, with checks of the goal at each step).  Soft yields
639   // aren't compatible with deterministic execution under test (unlike
640   // futexWaitUntil, which has a capricious but deterministic back end).
641   static constexpr uint32_t kMaxSoftYieldCount = !BlockImmediately ? 1000 : 0;
642
643   // If AccessSpreader assigns indexes from 0..k*n-1 on a system where some
644   // level of the memory hierarchy is symmetrically divided into k pieces
645   // (NUMA nodes, last-level caches, L1 caches, ...), then slot indexes
646   // that are the same after integer division by k share that resource.
647   // Our strategy for deferred readers is to probe up to numSlots/4 slots,
648   // using the full granularity of AccessSpreader for the start slot
649   // and then search outward.  We can use AccessSpreader::current(n)
650   // without managing our own spreader if kMaxDeferredReaders <=
651   // AccessSpreader::kMaxCpus, which is currently 128.
652   //
653   // Our 2-socket E5-2660 machines have 8 L1 caches on each chip,
654   // with 64 byte cache lines.  That means we need 64*16 bytes of
655   // deferredReaders[] to give each L1 its own playground.  On x86_64
656   // each DeferredReaderSlot is 8 bytes, so we need kMaxDeferredReaders
657   // * kDeferredSeparationFactor >= 64 * 16 / 8 == 128.  If
658   // kDeferredSearchDistance * kDeferredSeparationFactor <=
659   // 64 / 8 then we will search only within a single cache line, which
660   // guarantees we won't have inter-L1 contention.  We give ourselves
661   // a factor of 2 on the core count, which should hold us for a couple
662   // processor generations.  deferredReaders[] is 2048 bytes currently.
663   static constexpr uint32_t kMaxDeferredReaders = 64;
664   static constexpr uint32_t kDeferredSearchDistance = 2;
665   static constexpr uint32_t kDeferredSeparationFactor = 4;
666
667   static_assert(!(kMaxDeferredReaders & (kMaxDeferredReaders - 1)),
668                 "kMaxDeferredReaders must be a power of 2");
669   static_assert(!(kDeferredSearchDistance & (kDeferredSearchDistance - 1)),
670                 "kDeferredSearchDistance must be a power of 2");
671
672   // The number of deferred locks that can be simultaneously acquired
673   // by a thread via the token-less methods without performing any heap
674   // allocations.  Each of these costs 3 pointers (24 bytes, probably)
675   // per thread.  There's not much point in making this larger than
676   // kDeferredSearchDistance.
677   static constexpr uint32_t kTokenStackTLSCapacity = 2;
678
679   // We need to make sure that if there is a lock_shared()
680   // and lock_shared(token) followed by unlock_shared() and
681   // unlock_shared(token), the token-less unlock doesn't null
682   // out deferredReaders[token.slot_].  If we allowed that, then
683   // unlock_shared(token) wouldn't be able to assume that its lock
684   // had been inlined by applyDeferredReaders when it finds that
685   // deferredReaders[token.slot_] no longer points to this.  We accomplish
686   // this by stealing bit 0 from the pointer to record that the slot's
687   // element has no token, hence our use of uintptr_t in deferredReaders[].
688   static constexpr uintptr_t kTokenless = 0x1;
689
690   // This is the starting location for Token-less unlock_shared().
691   static FOLLY_TLS uint32_t tls_lastTokenlessSlot;
692
693   // Only indexes divisible by kDeferredSeparationFactor are used.
694   // If any of those elements points to a SharedMutexImpl, then it
695   // should be considered that there is a shared lock on that instance.
696   // See kTokenless.
697   typedef Atom<uintptr_t> DeferredReaderSlot;
698   static DeferredReaderSlot deferredReaders
699       [kMaxDeferredReaders *
700        kDeferredSeparationFactor] FOLLY_ALIGN_TO_AVOID_FALSE_SHARING;
701
702   // Performs an exclusive lock, waiting for state_ & waitMask to be
703   // zero first
704   template <class WaitContext>
705   bool lockExclusiveImpl(uint32_t preconditionGoalMask, WaitContext& ctx) {
706     uint32_t state = state_.load(std::memory_order_acquire);
707     if (LIKELY(
708             (state & (preconditionGoalMask | kMayDefer | kHasS)) == 0 &&
709             state_.compare_exchange_strong(state, (state | kHasE) & ~kHasU))) {
710       return true;
711     } else {
712       return lockExclusiveImpl(state, preconditionGoalMask, ctx);
713     }
714   }
715
716   template <class WaitContext>
717   bool lockExclusiveImpl(uint32_t& state,
718                          uint32_t preconditionGoalMask,
719                          WaitContext& ctx) {
720     while (true) {
721       if (UNLIKELY((state & preconditionGoalMask) != 0) &&
722           !waitForZeroBits(state, preconditionGoalMask, kWaitingE, ctx) &&
723           ctx.canTimeOut()) {
724         return false;
725       }
726
727       uint32_t after = (state & kMayDefer) == 0 ? 0 : kPrevDefer;
728       if (!ReaderPriority || (state & (kMayDefer | kHasS)) == 0) {
729         // Block readers immediately, either because we are in write
730         // priority mode or because we can acquire the lock in one
731         // step.  Note that if state has kHasU, then we are doing an
732         // unlock_upgrade_and_lock() and we should clear it (reader
733         // priority branch also does this).
734         after |= (state | kHasE) & ~(kHasU | kMayDefer);
735       } else {
736         after |= (state | kBegunE) & ~(kHasU | kMayDefer);
737       }
738       if (state_.compare_exchange_strong(state, after)) {
739         auto before = state;
740         state = after;
741
742         // If we set kHasE (writer priority) then no new readers can
743         // arrive.  If we set kBegunE then they can still enter, but
744         // they must be inline.  Either way we need to either spin on
745         // deferredReaders[] slots, or inline them so that we can wait on
746         // kHasS to zero itself.  deferredReaders[] is pointers, which on
747         // x86_64 are bigger than futex() can handle, so we inline the
748         // deferred locks instead of trying to futexWait on each slot.
749         // Readers are responsible for rechecking state_ after recording
750         // a deferred read to avoid atomicity problems between the state_
751         // CAS and applyDeferredReader's reads of deferredReaders[].
752         if (UNLIKELY((before & kMayDefer) != 0)) {
753           applyDeferredReaders(state, ctx);
754         }
755         while (true) {
756           assert((state & (kHasE | kBegunE)) != 0 && (state & kHasU) == 0);
757           if (UNLIKELY((state & kHasS) != 0) &&
758               !waitForZeroBits(state, kHasS, kWaitingNotS, ctx) &&
759               ctx.canTimeOut()) {
760             // Ugh.  We blocked new readers and other writers for a while,
761             // but were unable to complete.  Move on.  On the plus side
762             // we can clear kWaitingNotS because nobody else can piggyback
763             // on it.
764             state = (state_ &= ~(kPrevDefer | kHasE | kBegunE | kWaitingNotS));
765             wakeRegisteredWaiters(state, kWaitingE | kWaitingU | kWaitingS);
766             return false;
767           }
768
769           if (ReaderPriority && (state & kHasE) == 0) {
770             assert((state & kBegunE) != 0);
771             if (!state_.compare_exchange_strong(state,
772                                                 (state & ~kBegunE) | kHasE)) {
773               continue;
774             }
775           }
776
777           return true;
778         }
779       }
780     }
781   }
782
783   template <class WaitContext>
784   bool waitForZeroBits(uint32_t& state,
785                        uint32_t goal,
786                        uint32_t waitMask,
787                        WaitContext& ctx) {
788     uint32_t spinCount = 0;
789     while (true) {
790       state = state_.load(std::memory_order_acquire);
791       if ((state & goal) == 0) {
792         return true;
793       }
794 #if FOLLY_X64
795       asm volatile("pause");
796 #endif
797       ++spinCount;
798       if (UNLIKELY(spinCount >= kMaxSpinCount)) {
799         return ctx.canBlock() &&
800                yieldWaitForZeroBits(state, goal, waitMask, ctx);
801       }
802     }
803   }
804
805   template <class WaitContext>
806   bool yieldWaitForZeroBits(uint32_t& state,
807                             uint32_t goal,
808                             uint32_t waitMask,
809                             WaitContext& ctx) {
810 #ifdef RUSAGE_THREAD
811     struct rusage usage;
812     long before = -1;
813 #endif
814     for (uint32_t yieldCount = 0; yieldCount < kMaxSoftYieldCount;
815          ++yieldCount) {
816       for (int softState = 0; softState < 3; ++softState) {
817         if (softState < 2) {
818           std::this_thread::yield();
819         } else {
820 #ifdef RUSAGE_THREAD
821           getrusage(RUSAGE_THREAD, &usage);
822 #endif
823         }
824         if (((state = state_.load(std::memory_order_acquire)) & goal) == 0) {
825           return true;
826         }
827         if (ctx.shouldTimeOut()) {
828           return false;
829         }
830       }
831 #ifdef RUSAGE_THREAD
832       if (before >= 0 && usage.ru_nivcsw >= before + 2) {
833         // One involuntary csw might just be occasional background work,
834         // but if we get two in a row then we guess that there is someone
835         // else who can profitably use this CPU.  Fall back to futex
836         break;
837       }
838       before = usage.ru_nivcsw;
839 #endif
840     }
841     return futexWaitForZeroBits(state, goal, waitMask, ctx);
842   }
843
844   template <class WaitContext>
845   bool futexWaitForZeroBits(uint32_t& state,
846                             uint32_t goal,
847                             uint32_t waitMask,
848                             WaitContext& ctx) {
849     assert(waitMask == kWaitingNotS || waitMask == kWaitingE ||
850            waitMask == kWaitingU || waitMask == kWaitingS);
851
852     while (true) {
853       state = state_.load(std::memory_order_acquire);
854       if ((state & goal) == 0) {
855         return true;
856       }
857
858       auto after = state;
859       if (waitMask == kWaitingE) {
860         if ((state & kWaitingE) != kWaitingE) {
861           after += kIncrWaitingE;
862         } // else counter is saturated
863       } else {
864         after |= waitMask;
865       }
866
867       // CAS is better than atomic |= here, because it lets us avoid
868       // setting the wait flag when the goal is concurrently achieved
869       if (after != state && !state_.compare_exchange_strong(state, after)) {
870         continue;
871       }
872
873       if (!ctx.doWait(state_, after, waitMask)) {
874         // timed out
875         return false;
876       }
877     }
878   }
879
880   // Wakes up waiters registered in state_ as appropriate, clearing the
881   // awaiting bits for anybody that was awoken.  Tries to perform direct
882   // single wakeup of an exclusive waiter if appropriate
883   void wakeRegisteredWaiters(uint32_t& state, uint32_t wakeMask) {
884     if (UNLIKELY((state & wakeMask) != 0)) {
885       wakeRegisteredWaitersImpl(state, wakeMask);
886     }
887   }
888
889   void wakeRegisteredWaitersImpl(uint32_t& state, uint32_t wakeMask) {
890     if ((wakeMask & kWaitingE) != 0) {
891       // If there are multiple lock() pending only one of them will
892       // actually get to wake up, so issuing futexWakeAll will make
893       // a thundering herd.  There's nothing stopping us from issuing
894       // futexWake(1) instead, so long as the wait bits are still an
895       // accurate reflection of the waiters.  If our pending lock() counter
896       // hasn't saturated we can decrement it.  If it has saturated,
897       // then we can clear it by noticing that futexWake(1) returns 0
898       // (indicating no actual waiters) and then retrying via the normal
899       // clear+futexWakeAll path.
900       //
901       // It is possible that we wake an E waiter but an outside S grabs
902       // the lock instead, at which point we should wake pending U and
903       // S waiters.  Rather than tracking state to make the failing E
904       // regenerate the wakeup, we just disable the optimization in the
905       // case that there are waiting U or S that we are eligible to wake.
906       //
907       // Note that in the contended scenario it is quite likely that the
908       // waiter's futexWait call will fail with EAGAIN (expected value
909       // mismatch), at which point the awaiting-exclusive count will be
910       // larger than the actual number of waiters.  At this point the
911       // counter is effectively saturated.  Since this is likely, it is
912       // actually less efficient to have a larger counter.  2 bits seems
913       // to be the best.
914       while ((state & kWaitingE) != 0 &&
915              (state & wakeMask & (kWaitingU | kWaitingS)) == 0) {
916         if ((state & kWaitingE) != kWaitingE) {
917           // not saturated
918           if (!state_.compare_exchange_strong(state, state - kIncrWaitingE)) {
919             continue;
920           }
921           state -= kIncrWaitingE;
922         }
923
924         if (state_.futexWake(1, kWaitingE) > 0) {
925           return;
926         }
927
928         // Despite the non-zero awaiting-exclusive count, there aren't
929         // actually any pending writers.  Fall through to the logic below
930         // to wake up other classes of locks and to clear the saturated
931         // counter (if necessary).
932         break;
933       }
934     }
935
936     if ((state & wakeMask) != 0) {
937       auto prev = state_.fetch_and(~wakeMask);
938       if ((prev & wakeMask) != 0) {
939         futexWakeAll(wakeMask);
940       }
941       state = prev & ~wakeMask;
942     }
943   }
944
945   void futexWakeAll(uint32_t wakeMask) {
946     state_.futexWake(std::numeric_limits<int>::max(), wakeMask);
947   }
948
949   DeferredReaderSlot* deferredReader(uint32_t slot) {
950     return &deferredReaders[slot * kDeferredSeparationFactor];
951   }
952
953   uintptr_t tokenfulSlotValue() { return reinterpret_cast<uintptr_t>(this); }
954
955   uintptr_t tokenlessSlotValue() { return tokenfulSlotValue() | kTokenless; }
956
957   bool slotValueIsThis(uintptr_t slotValue) {
958     return (slotValue & ~kTokenless) == tokenfulSlotValue();
959   }
960
961   // Clears any deferredReaders[] that point to this, adjusting the inline
962   // shared lock count to compensate.  Does some spinning and yielding
963   // to avoid the work.  Always finishes the application, even if ctx
964   // times out.
965   template <class WaitContext>
966   void applyDeferredReaders(uint32_t& state, WaitContext& ctx) {
967     uint32_t slot = 0;
968
969     uint32_t spinCount = 0;
970     while (true) {
971       while (!slotValueIsThis(
972                  deferredReader(slot)->load(std::memory_order_acquire))) {
973         if (++slot == kMaxDeferredReaders) {
974           return;
975         }
976       }
977 #if FOLLY_X64
978       asm("pause");
979 #endif
980       if (UNLIKELY(++spinCount >= kMaxSpinCount)) {
981         applyDeferredReaders(state, ctx, slot);
982         return;
983       }
984     }
985   }
986
987   template <class WaitContext>
988   void applyDeferredReaders(uint32_t& state, WaitContext& ctx, uint32_t slot) {
989
990 #ifdef RUSAGE_THREAD
991     struct rusage usage;
992     long before = -1;
993 #endif
994     for (uint32_t yieldCount = 0; yieldCount < kMaxSoftYieldCount;
995          ++yieldCount) {
996       for (int softState = 0; softState < 3; ++softState) {
997         if (softState < 2) {
998           std::this_thread::yield();
999         } else {
1000 #ifdef RUSAGE_THREAD
1001           getrusage(RUSAGE_THREAD, &usage);
1002 #endif
1003         }
1004         while (!slotValueIsThis(
1005                    deferredReader(slot)->load(std::memory_order_acquire))) {
1006           if (++slot == kMaxDeferredReaders) {
1007             return;
1008           }
1009         }
1010         if (ctx.shouldTimeOut()) {
1011           // finish applying immediately on timeout
1012           break;
1013         }
1014       }
1015 #ifdef RUSAGE_THREAD
1016       if (before >= 0 && usage.ru_nivcsw >= before + 2) {
1017         // heuristic says run queue is not empty
1018         break;
1019       }
1020       before = usage.ru_nivcsw;
1021 #endif
1022     }
1023
1024     uint32_t movedSlotCount = 0;
1025     for (; slot < kMaxDeferredReaders; ++slot) {
1026       auto slotPtr = deferredReader(slot);
1027       auto slotValue = slotPtr->load(std::memory_order_acquire);
1028       if (slotValueIsThis(slotValue) &&
1029           slotPtr->compare_exchange_strong(slotValue, 0)) {
1030         ++movedSlotCount;
1031       }
1032     }
1033
1034     if (movedSlotCount > 0) {
1035       state = (state_ += movedSlotCount * kIncrHasS);
1036     }
1037     assert((state & (kHasE | kBegunE)) != 0);
1038
1039     // if state + kIncrHasS overflows (off the end of state) then either
1040     // we have 2^(32-9) readers (almost certainly an application bug)
1041     // or we had an underflow (also a bug)
1042     assert(state < state + kIncrHasS);
1043   }
1044
1045   // It is straightfoward to make a token-less lock_shared() and
1046   // unlock_shared() either by making the token-less version always use
1047   // INLINE_SHARED mode or by removing the token version.  Supporting
1048   // deferred operation for both types is trickier than it appears, because
1049   // the purpose of the token it so that unlock_shared doesn't have to
1050   // look in other slots for its deferred lock.  Token-less unlock_shared
1051   // might place a deferred lock in one place and then release a different
1052   // slot that was originally used by the token-ful version.  If this was
1053   // important we could solve the problem by differentiating the deferred
1054   // locks so that cross-variety release wouldn't occur.  The best way
1055   // is probably to steal a bit from the pointer, making deferredLocks[]
1056   // an array of Atom<uintptr_t>.
1057
1058   template <class WaitContext>
1059   bool lockSharedImpl(Token* token, WaitContext& ctx) {
1060     uint32_t state = state_.load(std::memory_order_relaxed);
1061     if ((state & (kHasS | kMayDefer | kHasE)) == 0 &&
1062         state_.compare_exchange_strong(state, state + kIncrHasS)) {
1063       if (token != nullptr) {
1064         token->type_ = Token::Type::INLINE_SHARED;
1065       }
1066       return true;
1067     }
1068     return lockSharedImpl(state, token, ctx);
1069   }
1070
1071   template <class WaitContext>
1072   bool lockSharedImpl(uint32_t& state, Token* token, WaitContext& ctx) {
1073     while (true) {
1074       if (UNLIKELY((state & kHasE) != 0) &&
1075           !waitForZeroBits(state, kHasE, kWaitingS, ctx) && ctx.canTimeOut()) {
1076         return false;
1077       }
1078
1079       uint32_t slot;
1080       uintptr_t slotValue = 1; // any non-zero value will do
1081
1082       bool canAlreadyDefer = (state & kMayDefer) != 0;
1083       bool aboveDeferThreshold =
1084           (state & kHasS) >= (kNumSharedToStartDeferring - 1) * kIncrHasS;
1085       bool drainInProgress = ReaderPriority && (state & kBegunE) != 0;
1086       if (canAlreadyDefer || (aboveDeferThreshold && !drainInProgress)) {
1087         // starting point for our empty-slot search, can change after
1088         // calling waitForZeroBits
1089         uint32_t bestSlot =
1090             (uint32_t)folly::detail::AccessSpreader<Atom>::current(
1091                 kMaxDeferredReaders);
1092
1093         // deferred readers are already enabled, or it is time to
1094         // enable them if we can find a slot
1095         for (uint32_t i = 0; i < kDeferredSearchDistance; ++i) {
1096           slot = bestSlot ^ i;
1097           assert(slot < kMaxDeferredReaders);
1098           slotValue = deferredReader(slot)->load(std::memory_order_relaxed);
1099           if (slotValue == 0) {
1100             // found empty slot
1101             break;
1102           }
1103         }
1104       }
1105
1106       if (slotValue != 0) {
1107         // not yet deferred, or no empty slots
1108         if (state_.compare_exchange_strong(state, state + kIncrHasS)) {
1109           // successfully recorded the read lock inline
1110           if (token != nullptr) {
1111             token->type_ = Token::Type::INLINE_SHARED;
1112           }
1113           return true;
1114         }
1115         // state is updated, try again
1116         continue;
1117       }
1118
1119       // record that deferred readers might be in use if necessary
1120       if ((state & kMayDefer) == 0) {
1121         if (!state_.compare_exchange_strong(state, state | kMayDefer)) {
1122           // keep going if CAS failed because somebody else set the bit
1123           // for us
1124           if ((state & (kHasE | kMayDefer)) != kMayDefer) {
1125             continue;
1126           }
1127         }
1128         // state = state | kMayDefer;
1129       }
1130
1131       // try to use the slot
1132       bool gotSlot = deferredReader(slot)->compare_exchange_strong(
1133           slotValue,
1134           token == nullptr ? tokenlessSlotValue() : tokenfulSlotValue());
1135
1136       // If we got the slot, we need to verify that an exclusive lock
1137       // didn't happen since we last checked.  If we didn't get the slot we
1138       // need to recheck state_ anyway to make sure we don't waste too much
1139       // work.  It is also possible that since we checked state_ someone
1140       // has acquired and released the write lock, clearing kMayDefer.
1141       // Both cases are covered by looking for the readers-possible bit,
1142       // because it is off when the exclusive lock bit is set.
1143       state = state_.load(std::memory_order_acquire);
1144
1145       if (!gotSlot) {
1146         continue;
1147       }
1148
1149       if (token == nullptr) {
1150         tls_lastTokenlessSlot = slot;
1151       }
1152
1153       if ((state & kMayDefer) != 0) {
1154         assert((state & kHasE) == 0);
1155         // success
1156         if (token != nullptr) {
1157           token->type_ = Token::Type::DEFERRED_SHARED;
1158           token->slot_ = (uint16_t)slot;
1159         }
1160         return true;
1161       }
1162
1163       // release the slot before retrying
1164       if (token == nullptr) {
1165         // We can't rely on slot.  Token-less slot values can be freed by
1166         // any unlock_shared(), so we need to do the full deferredReader
1167         // search during unlock.  Unlike unlock_shared(), we can't trust
1168         // kPrevDefer here.  This deferred lock isn't visible to lock()
1169         // (that's the whole reason we're undoing it) so there might have
1170         // subsequently been an unlock() and lock() with no intervening
1171         // transition to deferred mode.
1172         if (!tryUnlockAnySharedDeferred()) {
1173           unlockSharedInline();
1174         }
1175       } else {
1176         if (!tryUnlockSharedDeferred(slot)) {
1177           unlockSharedInline();
1178         }
1179       }
1180
1181       // We got here not because the lock was unavailable, but because
1182       // we lost a compare-and-swap.  Try-lock is typically allowed to
1183       // have spurious failures, but there is no lock efficiency gain
1184       // from exploiting that freedom here.
1185     }
1186   }
1187
1188   bool tryUnlockAnySharedDeferred() {
1189     auto bestSlot = tls_lastTokenlessSlot;
1190     for (uint32_t i = 0; i < kMaxDeferredReaders; ++i) {
1191       auto slotPtr = deferredReader(bestSlot ^ i);
1192       auto slotValue = slotPtr->load(std::memory_order_relaxed);
1193       if (slotValue == tokenlessSlotValue() &&
1194           slotPtr->compare_exchange_strong(slotValue, 0)) {
1195         tls_lastTokenlessSlot = bestSlot ^ i;
1196         return true;
1197       }
1198     }
1199     return false;
1200   }
1201
1202   bool tryUnlockSharedDeferred(uint32_t slot) {
1203     assert(slot < kMaxDeferredReaders);
1204     auto slotValue = tokenfulSlotValue();
1205     return deferredReader(slot)->compare_exchange_strong(slotValue, 0);
1206   }
1207
1208   uint32_t unlockSharedInline() {
1209     uint32_t state = (state_ -= kIncrHasS);
1210     assert((state & (kHasE | kBegunE)) != 0 || state < state + kIncrHasS);
1211     if ((state & kHasS) == 0) {
1212       // Only the second half of lock() can be blocked by a non-zero
1213       // reader count, so that's the only thing we need to wake
1214       wakeRegisteredWaiters(state, kWaitingNotS);
1215     }
1216     return state;
1217   }
1218
1219   template <class WaitContext>
1220   bool lockUpgradeImpl(WaitContext& ctx) {
1221     uint32_t state;
1222     do {
1223       if (!waitForZeroBits(state, kHasSolo, kWaitingU, ctx)) {
1224         return false;
1225       }
1226     } while (!state_.compare_exchange_strong(state, state | kHasU));
1227     return true;
1228   }
1229
1230  public:
1231   class ReadHolder {
1232    public:
1233     ReadHolder() : lock_(nullptr) {}
1234
1235     explicit ReadHolder(const SharedMutexImpl* lock) : ReadHolder(*lock) {}
1236
1237     explicit ReadHolder(const SharedMutexImpl& lock)
1238         : lock_(const_cast<SharedMutexImpl*>(&lock)) {
1239       lock_->lock_shared(token_);
1240     }
1241
1242     ReadHolder(ReadHolder&& rhs) noexcept : lock_(rhs.lock_),
1243                                             token_(rhs.token_) {
1244       rhs.lock_ = nullptr;
1245     }
1246
1247     // Downgrade from upgrade mode
1248     explicit ReadHolder(UpgradeHolder&& upgraded) : lock_(upgraded.lock_) {
1249       assert(upgraded.lock_ != nullptr);
1250       upgraded.lock_ = nullptr;
1251       lock_->unlock_upgrade_and_lock_shared(token_);
1252     }
1253
1254     // Downgrade from exclusive mode
1255     explicit ReadHolder(WriteHolder&& writer) : lock_(writer.lock_) {
1256       assert(writer.lock_ != nullptr);
1257       writer.lock_ = nullptr;
1258       lock_->unlock_and_lock_shared(token_);
1259     }
1260
1261     ReadHolder& operator=(ReadHolder&& rhs) noexcept {
1262       std::swap(lock_, rhs.lock_);
1263       std::swap(token_, rhs.token_);
1264       return *this;
1265     }
1266
1267     ReadHolder(const ReadHolder& rhs) = delete;
1268     ReadHolder& operator=(const ReadHolder& rhs) = delete;
1269
1270     ~ReadHolder() {
1271       if (lock_) {
1272         lock_->unlock_shared(token_);
1273       }
1274     }
1275
1276    private:
1277     friend class UpgradeHolder;
1278     friend class WriteHolder;
1279     SharedMutexImpl* lock_;
1280     SharedMutexToken token_;
1281   };
1282
1283   class UpgradeHolder {
1284    public:
1285     UpgradeHolder() : lock_(nullptr) {}
1286
1287     explicit UpgradeHolder(SharedMutexImpl* lock) : UpgradeHolder(*lock) {}
1288
1289     explicit UpgradeHolder(SharedMutexImpl& lock) : lock_(&lock) {
1290       lock_->lock_upgrade();
1291     }
1292
1293     // Downgrade from exclusive mode
1294     explicit UpgradeHolder(WriteHolder&& writer) : lock_(writer.lock_) {
1295       assert(writer.lock_ != nullptr);
1296       writer.lock_ = nullptr;
1297       lock_->unlock_and_lock_upgrade();
1298     }
1299
1300     UpgradeHolder(UpgradeHolder&& rhs) noexcept : lock_(rhs.lock_) {
1301       rhs.lock_ = nullptr;
1302     }
1303
1304     UpgradeHolder& operator=(UpgradeHolder&& rhs) noexcept {
1305       std::swap(lock_, rhs.lock_);
1306       return *this;
1307     }
1308
1309     UpgradeHolder(const UpgradeHolder& rhs) = delete;
1310     UpgradeHolder& operator=(const UpgradeHolder& rhs) = delete;
1311
1312     ~UpgradeHolder() {
1313       if (lock_) {
1314         lock_->unlock_upgrade();
1315       }
1316     }
1317
1318    private:
1319     friend class WriteHolder;
1320     friend class ReadHolder;
1321     SharedMutexImpl* lock_;
1322   };
1323
1324   class WriteHolder {
1325    public:
1326     WriteHolder() : lock_(nullptr) {}
1327
1328     explicit WriteHolder(SharedMutexImpl* lock) : WriteHolder(*lock) {}
1329
1330     explicit WriteHolder(SharedMutexImpl& lock) : lock_(&lock) {
1331       lock_->lock();
1332     }
1333
1334     // Promotion from upgrade mode
1335     explicit WriteHolder(UpgradeHolder&& upgrade) : lock_(upgrade.lock_) {
1336       assert(upgrade.lock_ != nullptr);
1337       upgrade.lock_ = nullptr;
1338       lock_->unlock_upgrade_and_lock();
1339     }
1340
1341     WriteHolder(WriteHolder&& rhs) noexcept : lock_(rhs.lock_) {
1342       rhs.lock_ = nullptr;
1343     }
1344
1345     WriteHolder& operator=(WriteHolder&& rhs) noexcept {
1346       std::swap(lock_, rhs.lock_);
1347       return *this;
1348     }
1349
1350     WriteHolder(const WriteHolder& rhs) = delete;
1351     WriteHolder& operator=(const WriteHolder& rhs) = delete;
1352
1353     ~WriteHolder() {
1354       if (lock_) {
1355         lock_->unlock();
1356       }
1357     }
1358
1359    private:
1360     friend class ReadHolder;
1361     friend class UpgradeHolder;
1362     SharedMutexImpl* lock_;
1363   };
1364
1365   // Adapters for Synchronized<>
1366   friend void acquireRead(SharedMutexImpl& lock) { lock.lock_shared(); }
1367   friend void acquireReadWrite(SharedMutexImpl& lock) { lock.lock(); }
1368   friend void releaseRead(SharedMutexImpl& lock) { lock.unlock_shared(); }
1369   friend void releaseReadWrite(SharedMutexImpl& lock) { lock.unlock(); }
1370 };
1371
1372 #define COMMON_CONCURRENCY_SHARED_MUTEX_DECLARE_STATIC_STORAGE(type) \
1373   template <>                                                        \
1374   type::DeferredReaderSlot                                           \
1375       type::deferredReaders[type::kMaxDeferredReaders *              \
1376                             type::kDeferredSeparationFactor] = {};   \
1377   template <>                                                        \
1378   FOLLY_TLS uint32_t type::tls_lastTokenlessSlot = 0;
1379
1380 typedef SharedMutexImpl<true> SharedMutexReadPriority;
1381 typedef SharedMutexImpl<false> SharedMutexWritePriority;
1382 typedef SharedMutexWritePriority SharedMutex;
1383
1384 } // namespace folly