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 #include "src/profiling/memory/scoped_spinlock.h" 18 19 #include <unistd.h> 20 21 #include <atomic> 22 23 #include "perfetto/ext/base/utils.h" 24 25 namespace { IsPowerOfTwo(size_t v)26constexpr bool IsPowerOfTwo(size_t v) { 27 return (v != 0 && ((v & (v - 1)) == 0)); 28 } 29 // Wait for ~1s before timing out (+- spurious wakeups from the sleeps). 30 constexpr unsigned kSleepAttempts = 1000; 31 constexpr unsigned kLockAttemptsPerSleep = 1024; 32 constexpr unsigned kSleepDurationUs = 1000; 33 34 static_assert(IsPowerOfTwo(kLockAttemptsPerSleep), 35 "lock attempts of power of 2 produce faster code."); 36 } // namespace 37 38 namespace perfetto { 39 namespace profiling { 40 PoisonSpinlock(Spinlock * lock)41void PoisonSpinlock(Spinlock* lock) { 42 lock->poisoned.store(true, std::memory_order_relaxed); 43 } 44 LockSlow(Mode mode)45void ScopedSpinlock::LockSlow(Mode mode) { 46 size_t sleeps = 0; 47 // We need to start with attempt = 1, otherwise 48 // attempt % kLockAttemptsPerSleep is zero for the first iteration. 49 for (size_t attempt = 1; mode == Mode::Blocking || 50 attempt < kLockAttemptsPerSleep * kSleepAttempts; 51 attempt++) { 52 if (!lock_->locked.load(std::memory_order_relaxed) && 53 PERFETTO_LIKELY( 54 !lock_->locked.exchange(true, std::memory_order_acquire))) { 55 locked_ = true; 56 break; 57 } 58 if (attempt % kLockAttemptsPerSleep == 0) { 59 usleep(kSleepDurationUs); 60 sleeps++; 61 } 62 } 63 blocked_us_ = kSleepDurationUs * sleeps; 64 } 65 66 } // namespace profiling 67 } // namespace perfetto 68