1 /*
2  * Copyright (C) 2019 The Android Open Source Project
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 #ifndef SRC_PROFILING_MEMORY_SCOPED_SPINLOCK_H_
18 #define SRC_PROFILING_MEMORY_SCOPED_SPINLOCK_H_
19 
20 #include "perfetto/base/logging.h"
21 #include "perfetto/ext/base/utils.h"
22 
23 #include <atomic>
24 #include <new>
25 #include <utility>
26 
27 namespace perfetto {
28 namespace profiling {
29 
30 class ScopedSpinlock {
31  public:
32   enum class Mode {
33     // Try for a fixed number of attempts, then return an unlocked handle.
34     Try,
35     // Keep spinning until successful.
36     Blocking
37   };
38 
ScopedSpinlock(std::atomic<bool> * lock,Mode mode)39   ScopedSpinlock(std::atomic<bool>* lock, Mode mode) : lock_(lock) {
40     if (PERFETTO_LIKELY(!lock_->exchange(true, std::memory_order_acquire))) {
41       locked_ = true;
42       return;
43     }
44     LockSlow(mode);
45   }
46 
47   ScopedSpinlock(const ScopedSpinlock&) = delete;
48   ScopedSpinlock& operator=(const ScopedSpinlock&) = delete;
49 
ScopedSpinlock(ScopedSpinlock && other)50   ScopedSpinlock(ScopedSpinlock&& other) noexcept
51       : lock_(other.lock_), locked_(other.locked_) {
52     other.locked_ = false;
53   }
54 
55   ScopedSpinlock& operator=(ScopedSpinlock&& other) {
56     if (this != &other) {
57       this->~ScopedSpinlock();
58       new (this) ScopedSpinlock(std::move(other));
59     }
60     return *this;
61   }
62 
~ScopedSpinlock()63   ~ScopedSpinlock() { Unlock(); }
64 
Unlock()65   void Unlock() {
66     if (locked_) {
67       PERFETTO_DCHECK(lock_->load());
68       lock_->store(false, std::memory_order_release);
69     }
70     locked_ = false;
71   }
72 
locked()73   bool locked() const { return locked_; }
blocked_us()74   size_t blocked_us() const { return blocked_us_; }
75 
76  private:
77   void LockSlow(Mode mode);
78   std::atomic<bool>* lock_;
79   size_t blocked_us_ = 0;
80   bool locked_ = false;
81 };
82 
83 }  // namespace profiling
84 }  // namespace perfetto
85 
86 #endif  // SRC_PROFILING_MEMORY_SCOPED_SPINLOCK_H_
87