1 // Copyright (C) 2014 The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #pragma once
16 
17 #include "aemu/base/Compiler.h"
18 
19 #include "aemu/base/ThreadAnnotations.h"
20 
21 #include <atomic>
22 
23 #ifdef _WIN32
24 #define WIN32_LEAN_AND_MEAN 1
25 #include <windows.h>
26 #else
27 #include <pthread.h>
28 #endif
29 
30 #include <assert.h>
31 
32 namespace android {
33 namespace base {
34 
35 class AutoLock;
36 class AutoWriteLock;
37 class AutoReadLock;
38 
39 // A wrapper class for mutexes only suitable for using in static context,
40 // where it's OK to leak the underlying system object. Use Lock for scoped or
41 // member locks.
42 class CAPABILITY("mutex") StaticLock {
43 public:
44     using AutoLock = android::base::AutoLock;
45 
46     constexpr StaticLock() = default;
47 
48     // Acquire the lock.
lock()49     void lock() ACQUIRE() {
50 #ifdef _WIN32
51         ::AcquireSRWLockExclusive(&mLock);
52 #else
53         ::pthread_mutex_lock(&mLock);
54 #endif
55     }
56 
tryLock()57     bool tryLock() TRY_ACQUIRE(true) {
58         bool ret = false;
59 #ifdef _WIN32
60         ret = ::TryAcquireSRWLockExclusive(&mLock);
61 #else
62         ret = ::pthread_mutex_trylock(&mLock) == 0;
63 #endif
64         return ret;
65     }
66 
67     // Release the lock.
unlock()68     void unlock() RELEASE() {
69 #ifdef _WIN32
70         ::ReleaseSRWLockExclusive(&mLock);
71 #else
72         ::pthread_mutex_unlock(&mLock);
73 #endif
74     }
75 
76 protected:
77     friend class ConditionVariable;
78 
79 #ifdef _WIN32
80     // Benchmarks show that on Windows SRWLOCK performs a little bit better than
81     // CRITICAL_SECTION for uncontended mode and much better in case of
82     // contention.
83     SRWLOCK mLock = SRWLOCK_INIT;
84 #else
85     pthread_mutex_t mLock = PTHREAD_MUTEX_INITIALIZER;
86 #endif
87     // Both POSIX threads and WinAPI don't allow move (undefined behavior).
88     DISALLOW_COPY_ASSIGN_AND_MOVE(StaticLock);
89 };
90 
91 // Simple wrapper class for mutexes used in non-static context.
92 class Lock : public StaticLock {
93 public:
94     using StaticLock::AutoLock;
95 
96     constexpr Lock() = default;
97 #ifndef _WIN32
98     // The only difference is that POSIX requires a deallocation function call
99     // for its mutexes.
~Lock()100     ~Lock() { ::pthread_mutex_destroy(&mLock); }
101 #endif
102 };
103 
104 class ReadWriteLock {
105 public:
106     using AutoWriteLock = android::base::AutoWriteLock;
107     using AutoReadLock = android::base::AutoReadLock;
108 
109 #ifdef _WIN32
110     constexpr ReadWriteLock() = default;
111     ~ReadWriteLock() = default;
lockRead()112     void lockRead() { ::AcquireSRWLockShared(&mLock); }
unlockRead()113     void unlockRead() { ::ReleaseSRWLockShared(&mLock); }
lockWrite()114     void lockWrite() { ::AcquireSRWLockExclusive(&mLock); }
unlockWrite()115     void unlockWrite() { ::ReleaseSRWLockExclusive(&mLock); }
116 
117 private:
118     SRWLOCK mLock = SRWLOCK_INIT;
119 #else   // !_WIN32
ReadWriteLock()120     ReadWriteLock() { ::pthread_rwlock_init(&mLock, NULL); }
~ReadWriteLock()121     ~ReadWriteLock() { ::pthread_rwlock_destroy(&mLock); }
lockRead()122     void lockRead() { ::pthread_rwlock_rdlock(&mLock); }
unlockRead()123     void unlockRead() { ::pthread_rwlock_unlock(&mLock); }
lockWrite()124     void lockWrite() { ::pthread_rwlock_wrlock(&mLock); }
unlockWrite()125     void unlockWrite() { ::pthread_rwlock_unlock(&mLock); }
126 
127 private:
128     pthread_rwlock_t mLock;
129 #endif  // !_WIN32
130 
131     friend class ConditionVariable;
132     DISALLOW_COPY_ASSIGN_AND_MOVE(ReadWriteLock);
133 };
134 
135 // Helper class to lock / unlock a mutex automatically on scope
136 // entry and exit.
137 // NB: not thread-safe (as opposed to the Lock class)
138 class SCOPED_CAPABILITY AutoLock {
139 public:
AutoLock(StaticLock & lock)140     AutoLock(StaticLock& lock) ACQUIRE(mLock) : mLock(lock) { mLock.lock(); }
141 
AutoLock(AutoLock && other)142     AutoLock(AutoLock&& other) : mLock(other.mLock), mLocked(other.mLocked) {
143         other.mLocked = false;
144     }
145 
lock()146     void lock() ACQUIRE(mLock) {
147         assert(!mLocked);
148         mLock.lock();
149         mLocked = true;
150     }
151 
unlock()152     void unlock() RELEASE(mLock) {
153         assert(mLocked);
154         mLock.unlock();
155         mLocked = false;
156     }
157 
RELEASE()158     ~AutoLock() RELEASE() {
159         if (mLocked) {
160             mLock.unlock();
161         }
162     }
163 
164 private:
165     StaticLock& mLock;
166     bool mLocked = true;
167 
168     friend class ConditionVariable;
169     // Don't allow move because this class has a non-movable object.
170     DISALLOW_COPY_AND_ASSIGN(AutoLock);
171 };
172 
173 class AutoWriteLock {
174 public:
AutoWriteLock(ReadWriteLock & lock)175     AutoWriteLock(ReadWriteLock& lock) : mLock(lock) { mLock.lockWrite(); }
176 
lockWrite()177     void lockWrite() {
178         assert(!mWriteLocked);
179         mLock.lockWrite();
180         mWriteLocked = true;
181     }
182 
unlockWrite()183     void unlockWrite() {
184         assert(mWriteLocked);
185         mLock.unlockWrite();
186         mWriteLocked = false;
187     }
188 
~AutoWriteLock()189     ~AutoWriteLock() {
190         if (mWriteLocked) {
191             mLock.unlockWrite();
192         }
193     }
194 
195 private:
196     ReadWriteLock& mLock;
197     bool mWriteLocked = true;
198     // This class has a non-movable object.
199     DISALLOW_COPY_ASSIGN_AND_MOVE(AutoWriteLock);
200 };
201 
202 class AutoReadLock {
203 public:
AutoReadLock(ReadWriteLock & lock)204     AutoReadLock(ReadWriteLock& lock) : mLock(lock) { mLock.lockRead(); }
205 
lockRead()206     void lockRead() {
207         assert(!mReadLocked);
208         mLock.lockRead();
209         mReadLocked = true;
210     }
211 
unlockRead()212     void unlockRead() {
213         assert(mReadLocked);
214         mLock.unlockRead();
215         mReadLocked = false;
216     }
217 
~AutoReadLock()218     ~AutoReadLock() {
219         if (mReadLocked) {
220             mLock.unlockRead();
221         }
222     }
223 
224 private:
225     ReadWriteLock& mLock;
226     bool mReadLocked = true;
227     // This class has a non-movable object.
228     DISALLOW_COPY_ASSIGN_AND_MOVE(AutoReadLock);
229 };
230 
231 // Sequence lock implementation
232 // See https://en.wikipedia.org/wiki/Seqlock for more info
SmpWmb()233 static inline __attribute__((always_inline)) void SmpWmb() {
234 #if defined(__aarch64__)
235         asm volatile("dmb ishst" ::: "memory");
236 #elif defined(__x86_64__)
237         std::atomic_thread_fence(std::memory_order_release);
238 #elif defined(__riscv) && (__riscv_xlen == 64)
239         std::atomic_thread_fence(std::memory_order_release);
240 #endif
241 }
242 
SmpRmb()243 static inline __attribute__((always_inline)) void SmpRmb() {
244 #if defined(__aarch64__)
245         asm volatile("dmb ishld" ::: "memory");
246 #elif defined(__x86_64__)
247         std::atomic_thread_fence(std::memory_order_acquire);
248 #elif defined(__riscv) && (__riscv_xlen == 64)
249         std::atomic_thread_fence(std::memory_order_acquire);
250 #endif
251 }
252 
253 class SeqLock {
254 public:
beginWrite()255     void beginWrite() ACQUIRE(mWriteLock) {
256         mWriteLock.lock();
257         mSeq.fetch_add(1, std::memory_order_release);
258         SmpWmb();
259     }
260 
endWrite()261     void endWrite() RELEASE(mWriteLock) {
262         SmpWmb();
263         mSeq.fetch_add(1, std::memory_order_release);
264         mWriteLock.unlock();
265     }
266 
267 #ifdef __cplusplus
268 #   define SEQLOCK_LIKELY( exp )    (__builtin_expect( !!(exp), true ))
269 #   define SEQLOCK_UNLIKELY( exp )  (__builtin_expect( !!(exp), false ))
270 #else
271 #   define SEQLOCK_LIKELY( exp )    (__builtin_expect( !!(exp), 1 ))
272 #   define SEQLOCK_UNLIKELY( exp )  (__builtin_expect( !!(exp), 0 ))
273 #endif
274 
beginRead()275     uint32_t beginRead() {
276         uint32_t res;
277 
278 repeat:
279         res = mSeq.load(std::memory_order_acquire);
280         if (SEQLOCK_UNLIKELY(res & 1)) {
281             goto repeat;
282         }
283 
284         SmpRmb();
285         return res;
286     }
287 
shouldRetryRead(uint32_t prevSeq)288     bool shouldRetryRead(uint32_t prevSeq) {
289         SmpRmb();
290         uint32_t res = mSeq.load(std::memory_order_acquire);
291         return (res != prevSeq);
292     }
293 
294     // Convenience class for write
295     class ScopedWrite {
296     public:
ScopedWrite(SeqLock * lock)297         ScopedWrite(SeqLock* lock) : mLock(lock) {
298             mLock->beginWrite();
299         }
~ScopedWrite()300         ~ScopedWrite() {
301             mLock->endWrite();
302         }
303     private:
304         SeqLock* mLock;
305     };
306 
307     // Convenience macro for read (no std::function due to its considerable overhead)
308 #define AEMU_SEQLOCK_READ_WITH_RETRY(lock, readStuff) { uint32_t aemu_seqlock_curr_seq; do { \
309     aemu_seqlock_curr_seq = (lock)->beginRead(); \
310     readStuff; \
311     } while ((lock)->shouldRetryRead(aemu_seqlock_curr_seq)); }
312 
313 private:
314     std::atomic<uint32_t> mSeq { 0 }; // The sequence number
315     Lock mWriteLock; // Just use a normal mutex to protect writes
316 };
317 
318 }  // namespace base
319 }  // namespace android
320