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