1 /*
2  * Copyright (c) Facebook, Inc. and its affiliates.
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 #include <folly/MicroLock.h>
18 
19 #include <thread>
20 
21 #include <folly/portability/Asm.h>
22 
23 namespace folly {
24 
lockSlowPath(uint32_t oldWord,detail::Futex<> * wordPtr,unsigned baseShift,unsigned maxSpins,unsigned maxYields)25 uint8_t MicroLockCore::lockSlowPath(
26     uint32_t oldWord,
27     detail::Futex<>* wordPtr,
28     unsigned baseShift,
29     unsigned maxSpins,
30     unsigned maxYields) noexcept {
31   uint32_t newWord;
32   unsigned spins = 0;
33   uint32_t heldBit = 1 << baseShift;
34   uint32_t waitBit = heldBit << 1;
35   uint32_t needWaitBit = 0;
36 
37 retry:
38   if ((oldWord & heldBit) != 0) {
39     ++spins;
40     if (spins > maxSpins + maxYields) {
41       // Somebody appears to have the lock.  Block waiting for the
42       // holder to unlock the lock.  We set heldbit(slot) so that the
43       // lock holder knows to FUTEX_WAKE us.
44       newWord = oldWord | waitBit;
45       if (newWord != oldWord) {
46         if (!wordPtr->compare_exchange_weak(
47                 oldWord,
48                 newWord,
49                 std::memory_order_relaxed,
50                 std::memory_order_relaxed)) {
51           goto retry;
52         }
53       }
54       detail::futexWait(wordPtr, newWord, heldBit);
55       needWaitBit = waitBit;
56     } else if (spins > maxSpins) {
57       // sched_yield(), but more portable
58       std::this_thread::yield();
59     } else {
60       folly::asm_volatile_pause();
61     }
62     oldWord = wordPtr->load(std::memory_order_relaxed);
63     goto retry;
64   }
65 
66   newWord = oldWord | heldBit | needWaitBit;
67   if (!wordPtr->compare_exchange_weak(
68           oldWord,
69           newWord,
70           std::memory_order_acquire,
71           std::memory_order_relaxed)) {
72     goto retry;
73   }
74   return decodeDataFromWord(newWord, baseShift);
75 }
76 } // namespace folly
77