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