Add a default timeout parameter to HHWheelTimer.
[folly.git] / folly / 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 {
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   SharedMutexImpl(const SharedMutexImpl&) = delete;
243   SharedMutexImpl(SharedMutexImpl&&) = delete;
244   SharedMutexImpl& operator = (const SharedMutexImpl&) = delete;
245   SharedMutexImpl& operator = (SharedMutexImpl&&) = delete;
246
247   // It is an error to destroy an SharedMutex that still has
248   // any outstanding locks.  This is checked if NDEBUG isn't defined.
249   // SharedMutex's exclusive mode can be safely used to guard the lock's
250   // own destruction.  If, for example, you acquire the lock in exclusive
251   // mode and then observe that the object containing the lock is no longer
252   // needed, you can unlock() and then immediately destroy the lock.
253   // See https://sourceware.org/bugzilla/show_bug.cgi?id=13690 for a
254   // description about why this property needs to be explicitly mentioned.
255   ~SharedMutexImpl() {
256     auto state = state_.load(std::memory_order_relaxed);
257     if (UNLIKELY((state & kHasS) != 0)) {
258       cleanupTokenlessSharedDeferred(state);
259     }
260
261 #ifndef NDEBUG
262     // if a futexWait fails to go to sleep because the value has been
263     // changed, we don't necessarily clean up the wait bits, so it is
264     // possible they will be set here in a correct system
265     assert((state & ~(kWaitingAny | kMayDefer)) == 0);
266     if ((state & kMayDefer) != 0) {
267       for (uint32_t slot = 0; slot < kMaxDeferredReaders; ++slot) {
268         auto slotValue = deferredReader(slot)->load(std::memory_order_relaxed);
269         assert(!slotValueIsThis(slotValue));
270       }
271     }
272 #endif
273   }
274
275   void lock() {
276     WaitForever ctx;
277     (void)lockExclusiveImpl(kHasSolo, ctx);
278   }
279
280   bool try_lock() {
281     WaitNever ctx;
282     return lockExclusiveImpl(kHasSolo, ctx);
283   }
284
285   template <class Rep, class Period>
286   bool try_lock_for(const std::chrono::duration<Rep, Period>& duration) {
287     WaitForDuration<Rep, Period> ctx(duration);
288     return lockExclusiveImpl(kHasSolo, ctx);
289   }
290
291   template <class Clock, class Duration>
292   bool try_lock_until(
293       const std::chrono::time_point<Clock, Duration>& absDeadline) {
294     WaitUntilDeadline<Clock, Duration> ctx{absDeadline};
295     return lockExclusiveImpl(kHasSolo, ctx);
296   }
297
298   void unlock() {
299     // It is possible that we have a left-over kWaitingNotS if the last
300     // unlock_shared() that let our matching lock() complete finished
301     // releasing before lock()'s futexWait went to sleep.  Clean it up now
302     auto state = (state_ &= ~(kWaitingNotS | kPrevDefer | kHasE));
303     assert((state & ~kWaitingAny) == 0);
304     wakeRegisteredWaiters(state, kWaitingE | kWaitingU | kWaitingS);
305   }
306
307   // Managing the token yourself makes unlock_shared a bit faster
308
309   void lock_shared() {
310     WaitForever ctx;
311     (void)lockSharedImpl(nullptr, ctx);
312   }
313
314   void lock_shared(Token& token) {
315     WaitForever ctx;
316     (void)lockSharedImpl(&token, ctx);
317   }
318
319   bool try_lock_shared() {
320     WaitNever ctx;
321     return lockSharedImpl(nullptr, ctx);
322   }
323
324   bool try_lock_shared(Token& token) {
325     WaitNever ctx;
326     return lockSharedImpl(&token, ctx);
327   }
328
329   template <class Rep, class Period>
330   bool try_lock_shared_for(const std::chrono::duration<Rep, Period>& duration) {
331     WaitForDuration<Rep, Period> ctx(duration);
332     return lockSharedImpl(nullptr, ctx);
333   }
334
335   template <class Rep, class Period>
336   bool try_lock_shared_for(const std::chrono::duration<Rep, Period>& duration,
337                            Token& token) {
338     WaitForDuration<Rep, Period> ctx(duration);
339     return lockSharedImpl(&token, ctx);
340   }
341
342   template <class Clock, class Duration>
343   bool try_lock_shared_until(
344       const std::chrono::time_point<Clock, Duration>& absDeadline) {
345     WaitUntilDeadline<Clock, Duration> ctx{absDeadline};
346     return lockSharedImpl(nullptr, ctx);
347   }
348
349   template <class Clock, class Duration>
350   bool try_lock_shared_until(
351       const std::chrono::time_point<Clock, Duration>& absDeadline,
352       Token& token) {
353     WaitUntilDeadline<Clock, Duration> ctx{absDeadline};
354     return lockSharedImpl(&token, ctx);
355   }
356
357   void unlock_shared() {
358     auto state = state_.load(std::memory_order_acquire);
359
360     // kPrevDefer can only be set if HasE or BegunE is set
361     assert((state & (kPrevDefer | kHasE | kBegunE)) != kPrevDefer);
362
363     // lock() strips kMayDefer immediately, but then copies it to
364     // kPrevDefer so we can tell if the pre-lock() lock_shared() might
365     // have deferred
366     if ((state & (kMayDefer | kPrevDefer)) == 0 ||
367         !tryUnlockTokenlessSharedDeferred()) {
368       // Matching lock_shared() couldn't have deferred, or the deferred
369       // lock has already been inlined by applyDeferredReaders()
370       unlockSharedInline();
371     }
372   }
373
374   void unlock_shared(Token& token) {
375     assert(token.type_ == Token::Type::INLINE_SHARED ||
376            token.type_ == Token::Type::DEFERRED_SHARED);
377
378     if (token.type_ != Token::Type::DEFERRED_SHARED ||
379         !tryUnlockSharedDeferred(token.slot_)) {
380       unlockSharedInline();
381     }
382 #ifndef NDEBUG
383     token.type_ = Token::Type::INVALID;
384 #endif
385   }
386
387   void unlock_and_lock_shared() {
388     // We can't use state_ -=, because we need to clear 2 bits (1 of which
389     // has an uncertain initial state) and set 1 other.  We might as well
390     // clear the relevant wake bits at the same time.  Note that since S
391     // doesn't block the beginning of a transition to E (writer priority
392     // can cut off new S, reader priority grabs BegunE and blocks deferred
393     // S) we need to wake E as well.
394     auto state = state_.load(std::memory_order_acquire);
395     do {
396       assert((state & ~(kWaitingAny | kPrevDefer)) == kHasE);
397     } while (!state_.compare_exchange_strong(
398         state, (state & ~(kWaitingAny | kPrevDefer | kHasE)) + kIncrHasS));
399     if ((state & (kWaitingE | kWaitingU | kWaitingS)) != 0) {
400       futexWakeAll(kWaitingE | kWaitingU | kWaitingS);
401     }
402   }
403
404   void unlock_and_lock_shared(Token& token) {
405     unlock_and_lock_shared();
406     token.type_ = Token::Type::INLINE_SHARED;
407   }
408
409   void lock_upgrade() {
410     WaitForever ctx;
411     (void)lockUpgradeImpl(ctx);
412   }
413
414   bool try_lock_upgrade() {
415     WaitNever ctx;
416     return lockUpgradeImpl(ctx);
417   }
418
419   template <class Rep, class Period>
420   bool try_lock_upgrade_for(
421       const std::chrono::duration<Rep, Period>& duration) {
422     WaitForDuration<Rep, Period> ctx(duration);
423     return lockUpgradeImpl(ctx);
424   }
425
426   template <class Clock, class Duration>
427   bool try_lock_upgrade_until(
428       const std::chrono::time_point<Clock, Duration>& absDeadline) {
429     WaitUntilDeadline<Clock, Duration> ctx{absDeadline};
430     return lockUpgradeImpl(ctx);
431   }
432
433   void unlock_upgrade() {
434     auto state = (state_ -= kHasU);
435     assert((state & (kWaitingNotS | kHasSolo)) == 0);
436     wakeRegisteredWaiters(state, kWaitingE | kWaitingU);
437   }
438
439   void unlock_upgrade_and_lock() {
440     // no waiting necessary, so waitMask is empty
441     WaitForever ctx;
442     (void)lockExclusiveImpl(0, ctx);
443   }
444
445   void unlock_upgrade_and_lock_shared() {
446     auto state = (state_ -= kHasU - kIncrHasS);
447     assert((state & (kWaitingNotS | kHasSolo)) == 0);
448     wakeRegisteredWaiters(state, kWaitingE | kWaitingU);
449   }
450
451   void unlock_upgrade_and_lock_shared(Token& token) {
452     unlock_upgrade_and_lock_shared();
453     token.type_ = Token::Type::INLINE_SHARED;
454   }
455
456   void unlock_and_lock_upgrade() {
457     // We can't use state_ -=, because we need to clear 2 bits (1 of
458     // which has an uncertain initial state) and set 1 other.  We might
459     // as well clear the relevant wake bits at the same time.
460     auto state = state_.load(std::memory_order_acquire);
461     while (true) {
462       assert((state & ~(kWaitingAny | kPrevDefer)) == kHasE);
463       auto after =
464           (state & ~(kWaitingNotS | kWaitingS | kPrevDefer | kHasE)) + kHasU;
465       if (state_.compare_exchange_strong(state, after)) {
466         if ((state & kWaitingS) != 0) {
467           futexWakeAll(kWaitingS);
468         }
469         return;
470       }
471     }
472   }
473
474  private:
475   typedef typename folly::detail::Futex<Atom> Futex;
476
477   // Internally we use four kinds of wait contexts.  These are structs
478   // that provide a doWait method that returns true if a futex wake
479   // was issued that intersects with the waitMask, false if there was a
480   // timeout and no more waiting should be performed.  Spinning occurs
481   // before the wait context is invoked.
482
483   struct WaitForever {
484     bool canBlock() { return true; }
485     bool canTimeOut() { return false; }
486     bool shouldTimeOut() { return false; }
487
488     bool doWait(Futex& futex, uint32_t expected, uint32_t waitMask) {
489       futex.futexWait(expected, waitMask);
490       return true;
491     }
492   };
493
494   struct WaitNever {
495     bool canBlock() { return false; }
496     bool canTimeOut() { return true; }
497     bool shouldTimeOut() { return true; }
498
499     bool doWait(Futex& futex, uint32_t expected, uint32_t waitMask) {
500       return false;
501     }
502   };
503
504   template <class Rep, class Period>
505   struct WaitForDuration {
506     std::chrono::duration<Rep, Period> duration_;
507     bool deadlineComputed_;
508     std::chrono::steady_clock::time_point deadline_;
509
510     explicit WaitForDuration(const std::chrono::duration<Rep, Period>& duration)
511         : duration_(duration), deadlineComputed_(false) {}
512
513     std::chrono::steady_clock::time_point deadline() {
514       if (!deadlineComputed_) {
515         deadline_ = std::chrono::steady_clock::now() + duration_;
516         deadlineComputed_ = true;
517       }
518       return deadline_;
519     }
520
521     bool canBlock() { return duration_.count() > 0; }
522     bool canTimeOut() { return true; }
523
524     bool shouldTimeOut() {
525       return std::chrono::steady_clock::now() > deadline();
526     }
527
528     bool doWait(Futex& futex, uint32_t expected, uint32_t waitMask) {
529       auto result = futex.futexWaitUntil(expected, deadline(), waitMask);
530       return result != folly::detail::FutexResult::TIMEDOUT;
531     }
532   };
533
534   template <class Clock, class Duration>
535   struct WaitUntilDeadline {
536     std::chrono::time_point<Clock, Duration> absDeadline_;
537
538     bool canBlock() { return true; }
539     bool canTimeOut() { return true; }
540     bool shouldTimeOut() { return Clock::now() > absDeadline_; }
541
542     bool doWait(Futex& futex, uint32_t expected, uint32_t waitMask) {
543       auto result = futex.futexWaitUntil(expected, absDeadline_, waitMask);
544       return result != folly::detail::FutexResult::TIMEDOUT;
545     }
546   };
547
548   // 32 bits of state
549   Futex state_;
550
551   // S count needs to be on the end, because we explicitly allow it to
552   // underflow.  This can occur while we are in the middle of applying
553   // deferred locks (we remove them from deferredReaders[] before
554   // inlining them), or during token-less unlock_shared() if a racing
555   // lock_shared();unlock_shared() moves the deferredReaders slot while
556   // the first unlock_shared() is scanning.  The former case is cleaned
557   // up before we finish applying the locks.  The latter case can persist
558   // until destruction, when it is cleaned up.
559   static constexpr uint32_t kIncrHasS = 1 << 10;
560   static constexpr uint32_t kHasS = ~(kIncrHasS - 1);
561
562   // If false, then there are definitely no deferred read locks for this
563   // instance.  Cleared after initialization and when exclusively locked.
564   static constexpr uint32_t kMayDefer = 1 << 9;
565
566   // lock() cleared kMayDefer as soon as it starts draining readers (so
567   // that it doesn't have to do a second CAS once drain completes), but
568   // unlock_shared() still needs to know whether to scan deferredReaders[]
569   // or not.  We copy kMayDefer to kPrevDefer when setting kHasE or
570   // kBegunE, and clear it when clearing those bits.
571   static constexpr uint32_t kPrevDefer = 1 << 8;
572
573   // Exclusive-locked blocks all read locks and write locks.  This bit
574   // may be set before all readers have finished, but in that case the
575   // thread that sets it won't return to the caller until all read locks
576   // have been released.
577   static constexpr uint32_t kHasE = 1 << 7;
578
579   // Exclusive-draining means that lock() is waiting for existing readers
580   // to leave, but that new readers may still acquire shared access.
581   // This is only used in reader priority mode.  New readers during
582   // drain must be inline.  The difference between this and kHasU is that
583   // kBegunE prevents kMayDefer from being set.
584   static constexpr uint32_t kBegunE = 1 << 6;
585
586   // At most one thread may have either exclusive or upgrade lock
587   // ownership.  Unlike exclusive mode, ownership of the lock in upgrade
588   // mode doesn't preclude other threads holding the lock in shared mode.
589   // boost's concept for this doesn't explicitly say whether new shared
590   // locks can be acquired one lock_upgrade has succeeded, but doesn't
591   // list that as disallowed.  RWSpinLock disallows new read locks after
592   // lock_upgrade has been acquired, but the boost implementation doesn't.
593   // We choose the latter.
594   static constexpr uint32_t kHasU = 1 << 5;
595
596   // There are three states that we consider to be "solo", in that they
597   // cannot coexist with other solo states.  These are kHasE, kBegunE,
598   // and kHasU.  Note that S doesn't conflict with any of these, because
599   // setting the kHasE is only one of the two steps needed to actually
600   // acquire the lock in exclusive mode (the other is draining the existing
601   // S holders).
602   static constexpr uint32_t kHasSolo = kHasE | kBegunE | kHasU;
603
604   // Once a thread sets kHasE it needs to wait for the current readers
605   // to exit the lock.  We give this a separate wait identity from the
606   // waiting to set kHasE so that we can perform partial wakeups (wake
607   // one instead of wake all).
608   static constexpr uint32_t kWaitingNotS = 1 << 4;
609
610   // When waking writers we can either wake them all, in which case we
611   // can clear kWaitingE, or we can call futexWake(1).  futexWake tells
612   // us if anybody woke up, but even if we detect that nobody woke up we
613   // can't clear the bit after the fact without issuing another wakeup.
614   // To avoid thundering herds when there are lots of pending lock()
615   // without needing to call futexWake twice when there is only one
616   // waiter, kWaitingE actually encodes if we have observed multiple
617   // concurrent waiters.  Tricky: ABA issues on futexWait mean that when
618   // we see kWaitingESingle we can't assume that there is only one.
619   static constexpr uint32_t kWaitingESingle = 1 << 2;
620   static constexpr uint32_t kWaitingEMultiple = 1 << 3;
621   static constexpr uint32_t kWaitingE = kWaitingESingle | kWaitingEMultiple;
622
623   // kWaitingU is essentially a 1 bit saturating counter.  It always
624   // requires a wakeAll.
625   static constexpr uint32_t kWaitingU = 1 << 1;
626
627   // All blocked lock_shared() should be awoken, so it is correct (not
628   // suboptimal) to wakeAll if there are any shared readers.
629   static constexpr uint32_t kWaitingS = 1 << 0;
630
631   // kWaitingAny is a mask of all of the bits that record the state of
632   // threads, rather than the state of the lock.  It is convenient to be
633   // able to mask them off during asserts.
634   static constexpr uint32_t kWaitingAny =
635       kWaitingNotS | kWaitingE | kWaitingU | kWaitingS;
636
637   // The reader count at which a reader will attempt to use the lock
638   // in deferred mode.  If this value is 2, then the second concurrent
639   // reader will set kMayDefer and use deferredReaders[].  kMayDefer is
640   // cleared during exclusive access, so this threshold must be reached
641   // each time a lock is held in exclusive mode.
642   static constexpr uint32_t kNumSharedToStartDeferring = 2;
643
644   // The typical number of spins that a thread will wait for a state
645   // transition.  There is no bound on the number of threads that can wait
646   // for a writer, so we are pretty conservative here to limit the chance
647   // that we are starving the writer of CPU.  Each spin is 6 or 7 nanos,
648   // almost all of which is in the pause instruction.
649   static constexpr uint32_t kMaxSpinCount = !BlockImmediately ? 1000 : 2;
650
651   // The maximum number of soft yields before falling back to futex.
652   // If the preemption heuristic is activated we will fall back before
653   // this.  A soft yield takes ~900 nanos (two sched_yield plus a call
654   // to getrusage, with checks of the goal at each step).  Soft yields
655   // aren't compatible with deterministic execution under test (unlike
656   // futexWaitUntil, which has a capricious but deterministic back end).
657   static constexpr uint32_t kMaxSoftYieldCount = !BlockImmediately ? 1000 : 0;
658
659   // If AccessSpreader assigns indexes from 0..k*n-1 on a system where some
660   // level of the memory hierarchy is symmetrically divided into k pieces
661   // (NUMA nodes, last-level caches, L1 caches, ...), then slot indexes
662   // that are the same after integer division by k share that resource.
663   // Our strategy for deferred readers is to probe up to numSlots/4 slots,
664   // using the full granularity of AccessSpreader for the start slot
665   // and then search outward.  We can use AccessSpreader::current(n)
666   // without managing our own spreader if kMaxDeferredReaders <=
667   // AccessSpreader::kMaxCpus, which is currently 128.
668   //
669   // Our 2-socket E5-2660 machines have 8 L1 caches on each chip,
670   // with 64 byte cache lines.  That means we need 64*16 bytes of
671   // deferredReaders[] to give each L1 its own playground.  On x86_64
672   // each DeferredReaderSlot is 8 bytes, so we need kMaxDeferredReaders
673   // * kDeferredSeparationFactor >= 64 * 16 / 8 == 128.  If
674   // kDeferredSearchDistance * kDeferredSeparationFactor <=
675   // 64 / 8 then we will search only within a single cache line, which
676   // guarantees we won't have inter-L1 contention.  We give ourselves
677   // a factor of 2 on the core count, which should hold us for a couple
678   // processor generations.  deferredReaders[] is 2048 bytes currently.
679  public:
680   static constexpr uint32_t kMaxDeferredReaders = 64;
681   static constexpr uint32_t kDeferredSearchDistance = 2;
682   static constexpr uint32_t kDeferredSeparationFactor = 4;
683
684  private:
685
686   static_assert(!(kMaxDeferredReaders & (kMaxDeferredReaders - 1)),
687                 "kMaxDeferredReaders must be a power of 2");
688   static_assert(!(kDeferredSearchDistance & (kDeferredSearchDistance - 1)),
689                 "kDeferredSearchDistance must be a power of 2");
690
691   // The number of deferred locks that can be simultaneously acquired
692   // by a thread via the token-less methods without performing any heap
693   // allocations.  Each of these costs 3 pointers (24 bytes, probably)
694   // per thread.  There's not much point in making this larger than
695   // kDeferredSearchDistance.
696   static constexpr uint32_t kTokenStackTLSCapacity = 2;
697
698   // We need to make sure that if there is a lock_shared()
699   // and lock_shared(token) followed by unlock_shared() and
700   // unlock_shared(token), the token-less unlock doesn't null
701   // out deferredReaders[token.slot_].  If we allowed that, then
702   // unlock_shared(token) wouldn't be able to assume that its lock
703   // had been inlined by applyDeferredReaders when it finds that
704   // deferredReaders[token.slot_] no longer points to this.  We accomplish
705   // this by stealing bit 0 from the pointer to record that the slot's
706   // element has no token, hence our use of uintptr_t in deferredReaders[].
707   static constexpr uintptr_t kTokenless = 0x1;
708
709   // This is the starting location for Token-less unlock_shared().
710   static FOLLY_TLS uint32_t tls_lastTokenlessSlot;
711
712   // Only indexes divisible by kDeferredSeparationFactor are used.
713   // If any of those elements points to a SharedMutexImpl, then it
714   // should be considered that there is a shared lock on that instance.
715   // See kTokenless.
716  public:
717   typedef Atom<uintptr_t> DeferredReaderSlot;
718
719  private:
720   FOLLY_ALIGN_TO_AVOID_FALSE_SHARING static DeferredReaderSlot deferredReaders
721       [kMaxDeferredReaders *
722        kDeferredSeparationFactor];
723
724   // Performs an exclusive lock, waiting for state_ & waitMask to be
725   // zero first
726   template <class WaitContext>
727   bool lockExclusiveImpl(uint32_t preconditionGoalMask, WaitContext& ctx) {
728     uint32_t state = state_.load(std::memory_order_acquire);
729     if (LIKELY(
730             (state & (preconditionGoalMask | kMayDefer | kHasS)) == 0 &&
731             state_.compare_exchange_strong(state, (state | kHasE) & ~kHasU))) {
732       return true;
733     } else {
734       return lockExclusiveImpl(state, preconditionGoalMask, ctx);
735     }
736   }
737
738   template <class WaitContext>
739   bool lockExclusiveImpl(uint32_t& state,
740                          uint32_t preconditionGoalMask,
741                          WaitContext& ctx) {
742     while (true) {
743       if (UNLIKELY((state & preconditionGoalMask) != 0) &&
744           !waitForZeroBits(state, preconditionGoalMask, kWaitingE, ctx) &&
745           ctx.canTimeOut()) {
746         return false;
747       }
748
749       uint32_t after = (state & kMayDefer) == 0 ? 0 : kPrevDefer;
750       if (!ReaderPriority || (state & (kMayDefer | kHasS)) == 0) {
751         // Block readers immediately, either because we are in write
752         // priority mode or because we can acquire the lock in one
753         // step.  Note that if state has kHasU, then we are doing an
754         // unlock_upgrade_and_lock() and we should clear it (reader
755         // priority branch also does this).
756         after |= (state | kHasE) & ~(kHasU | kMayDefer);
757       } else {
758         after |= (state | kBegunE) & ~(kHasU | kMayDefer);
759       }
760       if (state_.compare_exchange_strong(state, after)) {
761         auto before = state;
762         state = after;
763
764         // If we set kHasE (writer priority) then no new readers can
765         // arrive.  If we set kBegunE then they can still enter, but
766         // they must be inline.  Either way we need to either spin on
767         // deferredReaders[] slots, or inline them so that we can wait on
768         // kHasS to zero itself.  deferredReaders[] is pointers, which on
769         // x86_64 are bigger than futex() can handle, so we inline the
770         // deferred locks instead of trying to futexWait on each slot.
771         // Readers are responsible for rechecking state_ after recording
772         // a deferred read to avoid atomicity problems between the state_
773         // CAS and applyDeferredReader's reads of deferredReaders[].
774         if (UNLIKELY((before & kMayDefer) != 0)) {
775           applyDeferredReaders(state, ctx);
776         }
777         while (true) {
778           assert((state & (kHasE | kBegunE)) != 0 && (state & kHasU) == 0);
779           if (UNLIKELY((state & kHasS) != 0) &&
780               !waitForZeroBits(state, kHasS, kWaitingNotS, ctx) &&
781               ctx.canTimeOut()) {
782             // Ugh.  We blocked new readers and other writers for a while,
783             // but were unable to complete.  Move on.  On the plus side
784             // we can clear kWaitingNotS because nobody else can piggyback
785             // on it.
786             state = (state_ &= ~(kPrevDefer | kHasE | kBegunE | kWaitingNotS));
787             wakeRegisteredWaiters(state, kWaitingE | kWaitingU | kWaitingS);
788             return false;
789           }
790
791           if (ReaderPriority && (state & kHasE) == 0) {
792             assert((state & kBegunE) != 0);
793             if (!state_.compare_exchange_strong(state,
794                                                 (state & ~kBegunE) | kHasE)) {
795               continue;
796             }
797           }
798
799           return true;
800         }
801       }
802     }
803   }
804
805   template <class WaitContext>
806   bool waitForZeroBits(uint32_t& state,
807                        uint32_t goal,
808                        uint32_t waitMask,
809                        WaitContext& ctx) {
810     uint32_t spinCount = 0;
811     while (true) {
812       state = state_.load(std::memory_order_acquire);
813       if ((state & goal) == 0) {
814         return true;
815       }
816       asm_volatile_pause();
817       ++spinCount;
818       if (UNLIKELY(spinCount >= kMaxSpinCount)) {
819         return ctx.canBlock() &&
820                yieldWaitForZeroBits(state, goal, waitMask, ctx);
821       }
822     }
823   }
824
825   template <class WaitContext>
826   bool yieldWaitForZeroBits(uint32_t& state,
827                             uint32_t goal,
828                             uint32_t waitMask,
829                             WaitContext& ctx) {
830 #ifdef RUSAGE_THREAD
831     struct rusage usage;
832     long before = -1;
833 #endif
834     for (uint32_t yieldCount = 0; yieldCount < kMaxSoftYieldCount;
835          ++yieldCount) {
836       for (int softState = 0; softState < 3; ++softState) {
837         if (softState < 2) {
838           std::this_thread::yield();
839         } else {
840 #ifdef RUSAGE_THREAD
841           getrusage(RUSAGE_THREAD, &usage);
842 #endif
843         }
844         if (((state = state_.load(std::memory_order_acquire)) & goal) == 0) {
845           return true;
846         }
847         if (ctx.shouldTimeOut()) {
848           return false;
849         }
850       }
851 #ifdef RUSAGE_THREAD
852       if (before >= 0 && usage.ru_nivcsw >= before + 2) {
853         // One involuntary csw might just be occasional background work,
854         // but if we get two in a row then we guess that there is someone
855         // else who can profitably use this CPU.  Fall back to futex
856         break;
857       }
858       before = usage.ru_nivcsw;
859 #endif
860     }
861     return futexWaitForZeroBits(state, goal, waitMask, ctx);
862   }
863
864   template <class WaitContext>
865   bool futexWaitForZeroBits(uint32_t& state,
866                             uint32_t goal,
867                             uint32_t waitMask,
868                             WaitContext& ctx) {
869     assert(waitMask == kWaitingNotS || waitMask == kWaitingE ||
870            waitMask == kWaitingU || waitMask == kWaitingS);
871
872     while (true) {
873       state = state_.load(std::memory_order_acquire);
874       if ((state & goal) == 0) {
875         return true;
876       }
877
878       auto after = state;
879       if (waitMask == kWaitingE) {
880         if ((state & kWaitingESingle) != 0) {
881           after |= kWaitingEMultiple;
882         } else {
883           after |= kWaitingESingle;
884         }
885       } else {
886         after |= waitMask;
887       }
888
889       // CAS is better than atomic |= here, because it lets us avoid
890       // setting the wait flag when the goal is concurrently achieved
891       if (after != state && !state_.compare_exchange_strong(state, after)) {
892         continue;
893       }
894
895       if (!ctx.doWait(state_, after, waitMask)) {
896         // timed out
897         return false;
898       }
899     }
900   }
901
902   // Wakes up waiters registered in state_ as appropriate, clearing the
903   // awaiting bits for anybody that was awoken.  Tries to perform direct
904   // single wakeup of an exclusive waiter if appropriate
905   void wakeRegisteredWaiters(uint32_t& state, uint32_t wakeMask) {
906     if (UNLIKELY((state & wakeMask) != 0)) {
907       wakeRegisteredWaitersImpl(state, wakeMask);
908     }
909   }
910
911   void wakeRegisteredWaitersImpl(uint32_t& state, uint32_t wakeMask) {
912     // If there are multiple lock() pending only one of them will actually
913     // get to wake up, so issuing futexWakeAll will make a thundering herd.
914     // There's nothing stopping us from issuing futexWake(1) instead,
915     // so long as the wait bits are still an accurate reflection of
916     // the waiters.  If we notice (via futexWake's return value) that
917     // nobody woke up then we can try again with the normal wake-all path.
918     // Note that we can't just clear the bits at that point; we need to
919     // clear the bits and then issue another wakeup.
920     //
921     // It is possible that we wake an E waiter but an outside S grabs the
922     // lock instead, at which point we should wake pending U and S waiters.
923     // Rather than tracking state to make the failing E regenerate the
924     // wakeup, we just disable the optimization in the case that there
925     // are waiting U or S that we are eligible to wake.
926     if ((wakeMask & kWaitingE) == kWaitingE &&
927         (state & wakeMask) == kWaitingE &&
928         state_.futexWake(1, kWaitingE) > 0) {
929       // somebody woke up, so leave state_ as is and clear it later
930       return;
931     }
932
933     if ((state & wakeMask) != 0) {
934       auto prev = state_.fetch_and(~wakeMask);
935       if ((prev & wakeMask) != 0) {
936         futexWakeAll(wakeMask);
937       }
938       state = prev & ~wakeMask;
939     }
940   }
941
942   void futexWakeAll(uint32_t wakeMask) {
943     state_.futexWake(std::numeric_limits<int>::max(), wakeMask);
944   }
945
946   DeferredReaderSlot* deferredReader(uint32_t slot) {
947     return &deferredReaders[slot * kDeferredSeparationFactor];
948   }
949
950   uintptr_t tokenfulSlotValue() { return reinterpret_cast<uintptr_t>(this); }
951
952   uintptr_t tokenlessSlotValue() { return tokenfulSlotValue() | kTokenless; }
953
954   bool slotValueIsThis(uintptr_t slotValue) {
955     return (slotValue & ~kTokenless) == tokenfulSlotValue();
956   }
957
958   // Clears any deferredReaders[] that point to this, adjusting the inline
959   // shared lock count to compensate.  Does some spinning and yielding
960   // to avoid the work.  Always finishes the application, even if ctx
961   // times out.
962   template <class WaitContext>
963   void applyDeferredReaders(uint32_t& state, WaitContext& ctx) {
964     uint32_t slot = 0;
965
966     uint32_t spinCount = 0;
967     while (true) {
968       while (!slotValueIsThis(
969                  deferredReader(slot)->load(std::memory_order_acquire))) {
970         if (++slot == kMaxDeferredReaders) {
971           return;
972         }
973       }
974       asm_pause();
975       if (UNLIKELY(++spinCount >= kMaxSpinCount)) {
976         applyDeferredReaders(state, ctx, slot);
977         return;
978       }
979     }
980   }
981
982   template <class WaitContext>
983   void applyDeferredReaders(uint32_t& state, WaitContext& ctx, uint32_t slot) {
984
985 #ifdef RUSAGE_THREAD
986     struct rusage usage;
987     long before = -1;
988 #endif
989     for (uint32_t yieldCount = 0; yieldCount < kMaxSoftYieldCount;
990          ++yieldCount) {
991       for (int softState = 0; softState < 3; ++softState) {
992         if (softState < 2) {
993           std::this_thread::yield();
994         } else {
995 #ifdef RUSAGE_THREAD
996           getrusage(RUSAGE_THREAD, &usage);
997 #endif
998         }
999         while (!slotValueIsThis(
1000                    deferredReader(slot)->load(std::memory_order_acquire))) {
1001           if (++slot == kMaxDeferredReaders) {
1002             return;
1003           }
1004         }
1005         if (ctx.shouldTimeOut()) {
1006           // finish applying immediately on timeout
1007           break;
1008         }
1009       }
1010 #ifdef RUSAGE_THREAD
1011       if (before >= 0 && usage.ru_nivcsw >= before + 2) {
1012         // heuristic says run queue is not empty
1013         break;
1014       }
1015       before = usage.ru_nivcsw;
1016 #endif
1017     }
1018
1019     uint32_t movedSlotCount = 0;
1020     for (; slot < kMaxDeferredReaders; ++slot) {
1021       auto slotPtr = deferredReader(slot);
1022       auto slotValue = slotPtr->load(std::memory_order_acquire);
1023       if (slotValueIsThis(slotValue) &&
1024           slotPtr->compare_exchange_strong(slotValue, 0)) {
1025         ++movedSlotCount;
1026       }
1027     }
1028
1029     if (movedSlotCount > 0) {
1030       state = (state_ += movedSlotCount * kIncrHasS);
1031     }
1032     assert((state & (kHasE | kBegunE)) != 0);
1033
1034     // if state + kIncrHasS overflows (off the end of state) then either
1035     // we have 2^(32-9) readers (almost certainly an application bug)
1036     // or we had an underflow (also a bug)
1037     assert(state < state + kIncrHasS);
1038   }
1039
1040   // It is straightfoward to make a token-less lock_shared() and
1041   // unlock_shared() either by making the token-less version always use
1042   // INLINE_SHARED mode or by removing the token version.  Supporting
1043   // deferred operation for both types is trickier than it appears, because
1044   // the purpose of the token it so that unlock_shared doesn't have to
1045   // look in other slots for its deferred lock.  Token-less unlock_shared
1046   // might place a deferred lock in one place and then release a different
1047   // slot that was originally used by the token-ful version.  If this was
1048   // important we could solve the problem by differentiating the deferred
1049   // locks so that cross-variety release wouldn't occur.  The best way
1050   // is probably to steal a bit from the pointer, making deferredLocks[]
1051   // an array of Atom<uintptr_t>.
1052
1053   template <class WaitContext>
1054   bool lockSharedImpl(Token* token, WaitContext& ctx) {
1055     uint32_t state = state_.load(std::memory_order_relaxed);
1056     if ((state & (kHasS | kMayDefer | kHasE)) == 0 &&
1057         state_.compare_exchange_strong(state, state + kIncrHasS)) {
1058       if (token != nullptr) {
1059         token->type_ = Token::Type::INLINE_SHARED;
1060       }
1061       return true;
1062     }
1063     return lockSharedImpl(state, token, ctx);
1064   }
1065
1066   template <class WaitContext>
1067   bool lockSharedImpl(uint32_t& state, Token* token, WaitContext& ctx) {
1068     while (true) {
1069       if (UNLIKELY((state & kHasE) != 0) &&
1070           !waitForZeroBits(state, kHasE, kWaitingS, ctx) && ctx.canTimeOut()) {
1071         return false;
1072       }
1073
1074       uint32_t slot;
1075       uintptr_t slotValue = 1; // any non-zero value will do
1076
1077       bool canAlreadyDefer = (state & kMayDefer) != 0;
1078       bool aboveDeferThreshold =
1079           (state & kHasS) >= (kNumSharedToStartDeferring - 1) * kIncrHasS;
1080       bool drainInProgress = ReaderPriority && (state & kBegunE) != 0;
1081       if (canAlreadyDefer || (aboveDeferThreshold && !drainInProgress)) {
1082         // starting point for our empty-slot search, can change after
1083         // calling waitForZeroBits
1084         uint32_t bestSlot =
1085             (uint32_t)folly::detail::AccessSpreader<Atom>::current(
1086                 kMaxDeferredReaders);
1087
1088         // deferred readers are already enabled, or it is time to
1089         // enable them if we can find a slot
1090         for (uint32_t i = 0; i < kDeferredSearchDistance; ++i) {
1091           slot = bestSlot ^ i;
1092           assert(slot < kMaxDeferredReaders);
1093           slotValue = deferredReader(slot)->load(std::memory_order_relaxed);
1094           if (slotValue == 0) {
1095             // found empty slot
1096             break;
1097           }
1098         }
1099       }
1100
1101       if (slotValue != 0) {
1102         // not yet deferred, or no empty slots
1103         if (state_.compare_exchange_strong(state, state + kIncrHasS)) {
1104           // successfully recorded the read lock inline
1105           if (token != nullptr) {
1106             token->type_ = Token::Type::INLINE_SHARED;
1107           }
1108           return true;
1109         }
1110         // state is updated, try again
1111         continue;
1112       }
1113
1114       // record that deferred readers might be in use if necessary
1115       if ((state & kMayDefer) == 0) {
1116         if (!state_.compare_exchange_strong(state, state | kMayDefer)) {
1117           // keep going if CAS failed because somebody else set the bit
1118           // for us
1119           if ((state & (kHasE | kMayDefer)) != kMayDefer) {
1120             continue;
1121           }
1122         }
1123         // state = state | kMayDefer;
1124       }
1125
1126       // try to use the slot
1127       bool gotSlot = deferredReader(slot)->compare_exchange_strong(
1128           slotValue,
1129           token == nullptr ? tokenlessSlotValue() : tokenfulSlotValue());
1130
1131       // If we got the slot, we need to verify that an exclusive lock
1132       // didn't happen since we last checked.  If we didn't get the slot we
1133       // need to recheck state_ anyway to make sure we don't waste too much
1134       // work.  It is also possible that since we checked state_ someone
1135       // has acquired and released the write lock, clearing kMayDefer.
1136       // Both cases are covered by looking for the readers-possible bit,
1137       // because it is off when the exclusive lock bit is set.
1138       state = state_.load(std::memory_order_acquire);
1139
1140       if (!gotSlot) {
1141         continue;
1142       }
1143
1144       if (token == nullptr) {
1145         tls_lastTokenlessSlot = slot;
1146       }
1147
1148       if ((state & kMayDefer) != 0) {
1149         assert((state & kHasE) == 0);
1150         // success
1151         if (token != nullptr) {
1152           token->type_ = Token::Type::DEFERRED_SHARED;
1153           token->slot_ = (uint16_t)slot;
1154         }
1155         return true;
1156       }
1157
1158       // release the slot before retrying
1159       if (token == nullptr) {
1160         // We can't rely on slot.  Token-less slot values can be freed by
1161         // any unlock_shared(), so we need to do the full deferredReader
1162         // search during unlock.  Unlike unlock_shared(), we can't trust
1163         // kPrevDefer here.  This deferred lock isn't visible to lock()
1164         // (that's the whole reason we're undoing it) so there might have
1165         // subsequently been an unlock() and lock() with no intervening
1166         // transition to deferred mode.
1167         if (!tryUnlockTokenlessSharedDeferred()) {
1168           unlockSharedInline();
1169         }
1170       } else {
1171         if (!tryUnlockSharedDeferred(slot)) {
1172           unlockSharedInline();
1173         }
1174       }
1175
1176       // We got here not because the lock was unavailable, but because
1177       // we lost a compare-and-swap.  Try-lock is typically allowed to
1178       // have spurious failures, but there is no lock efficiency gain
1179       // from exploiting that freedom here.
1180     }
1181   }
1182
1183   // Updates the state in/out argument as if the locks were made inline,
1184   // but does not update state_
1185   void cleanupTokenlessSharedDeferred(uint32_t& state) {
1186     for (uint32_t i = 0; i < kMaxDeferredReaders; ++i) {
1187       auto slotPtr = deferredReader(i);
1188       auto slotValue = slotPtr->load(std::memory_order_relaxed);
1189       if (slotValue == tokenlessSlotValue()) {
1190         slotPtr->store(0, std::memory_order_relaxed);
1191         state += kIncrHasS;
1192         if ((state & kHasS) == 0) {
1193           break;
1194         }
1195       }
1196     }
1197   }
1198
1199   bool tryUnlockTokenlessSharedDeferred() {
1200     auto bestSlot = tls_lastTokenlessSlot;
1201     for (uint32_t i = 0; i < kMaxDeferredReaders; ++i) {
1202       auto slotPtr = deferredReader(bestSlot ^ i);
1203       auto slotValue = slotPtr->load(std::memory_order_relaxed);
1204       if (slotValue == tokenlessSlotValue() &&
1205           slotPtr->compare_exchange_strong(slotValue, 0)) {
1206         tls_lastTokenlessSlot = bestSlot ^ i;
1207         return true;
1208       }
1209     }
1210     return false;
1211   }
1212
1213   bool tryUnlockSharedDeferred(uint32_t slot) {
1214     assert(slot < kMaxDeferredReaders);
1215     auto slotValue = tokenfulSlotValue();
1216     return deferredReader(slot)->compare_exchange_strong(slotValue, 0);
1217   }
1218
1219   uint32_t unlockSharedInline() {
1220     uint32_t state = (state_ -= kIncrHasS);
1221     assert((state & (kHasE | kBegunE | kMayDefer)) != 0 ||
1222            state < state + kIncrHasS);
1223     if ((state & kHasS) == 0) {
1224       // Only the second half of lock() can be blocked by a non-zero
1225       // reader count, so that's the only thing we need to wake
1226       wakeRegisteredWaiters(state, kWaitingNotS);
1227     }
1228     return state;
1229   }
1230
1231   template <class WaitContext>
1232   bool lockUpgradeImpl(WaitContext& ctx) {
1233     uint32_t state;
1234     do {
1235       if (!waitForZeroBits(state, kHasSolo, kWaitingU, ctx)) {
1236         return false;
1237       }
1238     } while (!state_.compare_exchange_strong(state, state | kHasU));
1239     return true;
1240   }
1241
1242  public:
1243   class ReadHolder {
1244    public:
1245     ReadHolder() : lock_(nullptr) {}
1246
1247     explicit ReadHolder(const SharedMutexImpl* lock) : ReadHolder(*lock) {}
1248
1249     explicit ReadHolder(const SharedMutexImpl& lock)
1250         : lock_(const_cast<SharedMutexImpl*>(&lock)) {
1251       lock_->lock_shared(token_);
1252     }
1253
1254     ReadHolder(ReadHolder&& rhs) noexcept : lock_(rhs.lock_),
1255                                             token_(rhs.token_) {
1256       rhs.lock_ = nullptr;
1257     }
1258
1259     // Downgrade from upgrade mode
1260     explicit ReadHolder(UpgradeHolder&& upgraded) : lock_(upgraded.lock_) {
1261       assert(upgraded.lock_ != nullptr);
1262       upgraded.lock_ = nullptr;
1263       lock_->unlock_upgrade_and_lock_shared(token_);
1264     }
1265
1266     // Downgrade from exclusive mode
1267     explicit ReadHolder(WriteHolder&& writer) : lock_(writer.lock_) {
1268       assert(writer.lock_ != nullptr);
1269       writer.lock_ = nullptr;
1270       lock_->unlock_and_lock_shared(token_);
1271     }
1272
1273     ReadHolder& operator=(ReadHolder&& rhs) noexcept {
1274       std::swap(lock_, rhs.lock_);
1275       std::swap(token_, rhs.token_);
1276       return *this;
1277     }
1278
1279     ReadHolder(const ReadHolder& rhs) = delete;
1280     ReadHolder& operator=(const ReadHolder& rhs) = delete;
1281
1282     ~ReadHolder() {
1283       if (lock_) {
1284         lock_->unlock_shared(token_);
1285       }
1286     }
1287
1288    private:
1289     friend class UpgradeHolder;
1290     friend class WriteHolder;
1291     SharedMutexImpl* lock_;
1292     SharedMutexToken token_;
1293   };
1294
1295   class UpgradeHolder {
1296    public:
1297     UpgradeHolder() : lock_(nullptr) {}
1298
1299     explicit UpgradeHolder(SharedMutexImpl* lock) : UpgradeHolder(*lock) {}
1300
1301     explicit UpgradeHolder(SharedMutexImpl& lock) : lock_(&lock) {
1302       lock_->lock_upgrade();
1303     }
1304
1305     // Downgrade from exclusive mode
1306     explicit UpgradeHolder(WriteHolder&& writer) : lock_(writer.lock_) {
1307       assert(writer.lock_ != nullptr);
1308       writer.lock_ = nullptr;
1309       lock_->unlock_and_lock_upgrade();
1310     }
1311
1312     UpgradeHolder(UpgradeHolder&& rhs) noexcept : lock_(rhs.lock_) {
1313       rhs.lock_ = nullptr;
1314     }
1315
1316     UpgradeHolder& operator=(UpgradeHolder&& rhs) noexcept {
1317       std::swap(lock_, rhs.lock_);
1318       return *this;
1319     }
1320
1321     UpgradeHolder(const UpgradeHolder& rhs) = delete;
1322     UpgradeHolder& operator=(const UpgradeHolder& rhs) = delete;
1323
1324     ~UpgradeHolder() {
1325       if (lock_) {
1326         lock_->unlock_upgrade();
1327       }
1328     }
1329
1330    private:
1331     friend class WriteHolder;
1332     friend class ReadHolder;
1333     SharedMutexImpl* lock_;
1334   };
1335
1336   class WriteHolder {
1337    public:
1338     WriteHolder() : lock_(nullptr) {}
1339
1340     explicit WriteHolder(SharedMutexImpl* lock) : WriteHolder(*lock) {}
1341
1342     explicit WriteHolder(SharedMutexImpl& lock) : lock_(&lock) {
1343       lock_->lock();
1344     }
1345
1346     // Promotion from upgrade mode
1347     explicit WriteHolder(UpgradeHolder&& upgrade) : lock_(upgrade.lock_) {
1348       assert(upgrade.lock_ != nullptr);
1349       upgrade.lock_ = nullptr;
1350       lock_->unlock_upgrade_and_lock();
1351     }
1352
1353     WriteHolder(WriteHolder&& rhs) noexcept : lock_(rhs.lock_) {
1354       rhs.lock_ = nullptr;
1355     }
1356
1357     WriteHolder& operator=(WriteHolder&& rhs) noexcept {
1358       std::swap(lock_, rhs.lock_);
1359       return *this;
1360     }
1361
1362     WriteHolder(const WriteHolder& rhs) = delete;
1363     WriteHolder& operator=(const WriteHolder& rhs) = delete;
1364
1365     ~WriteHolder() {
1366       if (lock_) {
1367         lock_->unlock();
1368       }
1369     }
1370
1371    private:
1372     friend class ReadHolder;
1373     friend class UpgradeHolder;
1374     SharedMutexImpl* lock_;
1375   };
1376
1377   // Adapters for Synchronized<>
1378   friend void acquireRead(SharedMutexImpl& lock) { lock.lock_shared(); }
1379   friend void acquireReadWrite(SharedMutexImpl& lock) { lock.lock(); }
1380   friend void releaseRead(SharedMutexImpl& lock) { lock.unlock_shared(); }
1381   friend void releaseReadWrite(SharedMutexImpl& lock) { lock.unlock(); }
1382 };
1383
1384 #define COMMON_CONCURRENCY_SHARED_MUTEX_DECLARE_STATIC_STORAGE(type) \
1385   template <>                                                        \
1386   type::DeferredReaderSlot                                           \
1387       type::deferredReaders[type::kMaxDeferredReaders *              \
1388                             type::kDeferredSeparationFactor] = {};   \
1389   template <>                                                        \
1390   FOLLY_TLS uint32_t type::tls_lastTokenlessSlot = 0;
1391
1392 typedef SharedMutexImpl<true> SharedMutexReadPriority;
1393 typedef SharedMutexImpl<false> SharedMutexWritePriority;
1394 typedef SharedMutexWritePriority SharedMutex;
1395
1396 } // namespace folly