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