| 1 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ |
| 2 |
/* vim: set ts=8 sts=2 et sw=2 tw=80: */ |
| 3 |
/* This Source Code Form is subject to the terms of the Mozilla Public |
| 4 |
* License, v. 2.0. If a copy of the MPL was not distributed with this |
| 5 |
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 6 |
|
| 7 |
// The Gecko Profiler is an always-on profiler that takes fast and low overhead |
| 8 |
// samples of the program execution using only userspace functionality for |
| 9 |
// portability. The goal of this module is to provide performance data in a |
| 10 |
// generic cross-platform way without requiring custom tools or kernel support. |
| 11 |
// |
| 12 |
// Samples are collected to form a timeline with optional timeline event |
| 13 |
// (markers) used for filtering. The samples include both native stacks and |
| 14 |
// platform-independent "label stack" frames. |
| 15 |
|
| 16 |
#ifndef BaseProfilerState_h |
| 17 |
#define BaseProfilerState_h |
| 18 |
|
| 19 |
// This header contains most functions that give information about the Base |
| 20 |
// Profiler: Whether it is active or not, paused, the selected features, and |
| 21 |
// some generic process and thread information. |
| 22 |
// It is safe to include unconditionally, but uses of structs and functions must |
| 23 |
// be guarded by `#ifdef MOZ_GECKO_PROFILER`. |
| 24 |
|
| 25 |
#include "mozilla/BaseProfilerUtils.h" |
| 26 |
|
| 27 |
#ifndef MOZ_GECKO_PROFILER |
| 28 |
|
| 29 |
# define AUTO_PROFILER_STATS(name) |
| 30 |
|
| 31 |
namespace mozilla::baseprofiler { |
| 32 |
|
| 33 |
[[nodiscard]] inline bool profiler_is_active() { return false; } |
| 34 |
[[nodiscard]] inline bool profiler_is_active_and_unpaused() { return false; } |
| 35 |
|
| 36 |
} // namespace mozilla::baseprofiler |
| 37 |
|
| 38 |
#else // !MOZ_GECKO_PROFILER |
| 39 |
|
| 40 |
# include "mozilla/Atomics.h" |
| 41 |
# include "mozilla/Maybe.h" |
| 42 |
|
| 43 |
# include <stdint.h> |
| 44 |
# include <string> |
| 45 |
|
| 46 |
// Uncomment the following line to display profiler runtime statistics at |
| 47 |
// shutdown. |
| 48 |
// # define PROFILER_RUNTIME_STATS |
| 49 |
|
| 50 |
# ifdef PROFILER_RUNTIME_STATS |
| 51 |
# include "mozilla/TimeStamp.h" |
| 52 |
# endif |
| 53 |
|
| 54 |
namespace mozilla::baseprofiler { |
| 55 |
|
| 56 |
# ifdef PROFILER_RUNTIME_STATS |
| 57 |
// This class gathers durations and displays some basic stats when destroyed. |
| 58 |
// It is intended to be used as a static variable (see `AUTO_PROFILER_STATS` |
| 59 |
// below), to display stats at the end of the program. |
| 60 |
class StaticBaseProfilerStats { |
| 61 |
public: |
| 62 |
explicit StaticBaseProfilerStats(const char* aName) : mName(aName) {} |
| 63 |
|
| 64 |
~StaticBaseProfilerStats() { |
| 65 |
// Using unsigned long long for computations and printfs. |
| 66 |
using ULL = unsigned long long; |
| 67 |
ULL n = static_cast<ULL>(mNumberDurations); |
| 68 |
if (n != 0) { |
| 69 |
ULL sumNs = static_cast<ULL>(mSumDurationsNs); |
| 70 |
printf( |
| 71 |
"[%d] Profiler stats `%s`: %llu ns / %llu = %llu ns, max %llu ns\n", |
| 72 |
int(profiler_current_process_id().ToNumber()), mName, sumNs, n, |
| 73 |
sumNs / n, static_cast<ULL>(mLongestDurationNs)); |
| 74 |
} else { |
| 75 |
printf("[%d] Profiler stats `%s`: (nothing)\n", |
| 76 |
int(profiler_current_process_id().ToNumber()), mName); |
| 77 |
} |
| 78 |
} |
| 79 |
|
| 80 |
void AddDurationFrom(TimeStamp aStart) { |
| 81 |
DurationNs duration = static_cast<DurationNs>( |
| 82 |
(TimeStamp::Now() - aStart).ToMicroseconds() * 1000 + 0.5); |
| 83 |
mSumDurationsNs += duration; |
| 84 |
++mNumberDurations; |
| 85 |
// Update mLongestDurationNs if this one is longer. |
| 86 |
for (;;) { |
| 87 |
DurationNs longest = mLongestDurationNs; |
| 88 |
if (MOZ_LIKELY(longest >= duration)) { |
| 89 |
// This duration is not the longest, nothing to do. |
| 90 |
break; |
| 91 |
} |
| 92 |
if (MOZ_LIKELY(mLongestDurationNs.compareExchange(longest, duration))) { |
| 93 |
// Successfully updated `mLongestDurationNs` with the new value. |
| 94 |
break; |
| 95 |
} |
| 96 |
// Otherwise someone else just updated `mLongestDurationNs`, we need to |
| 97 |
// try again by looping. |
| 98 |
} |
| 99 |
} |
| 100 |
|
| 101 |
private: |
| 102 |
using DurationNs = uint64_t; |
| 103 |
using Count = uint32_t; |
| 104 |
|
| 105 |
Atomic<DurationNs> mSumDurationsNs{0}; |
| 106 |
Atomic<DurationNs> mLongestDurationNs{0}; |
| 107 |
Atomic<Count> mNumberDurations{0}; |
| 108 |
const char* mName; |
| 109 |
}; |
| 110 |
|
| 111 |
// RAII object that measure its scoped lifetime duration and reports it to a |
| 112 |
// `StaticBaseProfilerStats`. |
| 113 |
class MOZ_RAII AutoProfilerStats { |
| 114 |
public: |
| 115 |
explicit AutoProfilerStats(StaticBaseProfilerStats& aStats) |
| 116 |
: mStats(aStats), mStart(TimeStamp::Now()) {} |
| 117 |
|
| 118 |
~AutoProfilerStats() { mStats.AddDurationFrom(mStart); } |
| 119 |
|
| 120 |
private: |
| 121 |
StaticBaseProfilerStats& mStats; |
| 122 |
TimeStamp mStart; |
| 123 |
}; |
| 124 |
|
| 125 |
// Macro that should be used to collect basic statistics from measurements of |
| 126 |
// block durations, from where this macro is, until the end of its enclosing |
| 127 |
// scope. The name is used in the static variable name and when displaying stats |
| 128 |
// at the end of the program; Another location could use the same name but their |
| 129 |
// stats will not be combined, so use different name if these locations should |
| 130 |
// be distinguished. |
| 131 |
# define AUTO_PROFILER_STATS(name) \ |
| 132 |
static ::mozilla::baseprofiler::StaticBaseProfilerStats sStat##name( \ |
| 133 |
#name); \ |
| 134 |
::mozilla::baseprofiler::AutoProfilerStats autoStat##name(sStat##name); |
| 135 |
|
| 136 |
# else // PROFILER_RUNTIME_STATS |
| 137 |
|
| 138 |
# define AUTO_PROFILER_STATS(name) |
| 139 |
|
| 140 |
# endif // PROFILER_RUNTIME_STATS else |
| 141 |
|
| 142 |
//--------------------------------------------------------------------------- |
| 143 |
// Profiler features |
| 144 |
//--------------------------------------------------------------------------- |
| 145 |
|
| 146 |
# if defined(__APPLE__) && defined(__aarch64__) |
| 147 |
# define POWER_HELP "Sample per process power use" |
| 148 |
# elif defined(__APPLE__) && defined(__x86_64__) |
| 149 |
# define POWER_HELP \ |
| 150 |
"Record the power used by the entire system with each sample." |
| 151 |
# elif defined(__linux__) && defined(__x86_64__) |
| 152 |
# define POWER_HELP \ |
| 153 |
"Record the power used by the entire system with each sample. " \ |
| 154 |
"Only available with Intel CPUs and requires setting " \ |
| 155 |
"the sysctl kernel.perf_event_paranoid to 0." |
| 156 |
# elif defined(_MSC_VER) |
| 157 |
# define POWER_HELP \ |
| 158 |
"Record the value of every energy meter available on the system with " \ |
| 159 |
"each sample. Only available on Windows 11 with Intel CPUs." |
| 160 |
# else |
| 161 |
# define POWER_HELP "Not supported on this platform." |
| 162 |
# endif |
| 163 |
|
| 164 |
// Higher-order macro containing all the feature info in one place. Define |
| 165 |
// |MACRO| appropriately to extract the relevant parts. Note that the number |
| 166 |
// values are used internally only and so can be changed without consequence. |
| 167 |
// Any changes to this list should also be applied to the feature list in |
| 168 |
// toolkit/components/extensions/schemas/geckoProfiler.json. |
| 169 |
// *** Synchronize with lists in ProfilerState.h and geckoProfiler.json *** |
| 170 |
# define BASE_PROFILER_FOR_EACH_FEATURE(MACRO) \ |
| 171 |
MACRO(0, "java", Java, "Profile Java code, Android only") \ |
| 172 |
\ |
| 173 |
MACRO(1, "js", JS, \ |
| 174 |
"Get the JS engine to expose the JS stack to the profiler") \ |
| 175 |
\ |
| 176 |
MACRO(2, "mainthreadio", MainThreadIO, "Add main thread file I/O") \ |
| 177 |
\ |
| 178 |
MACRO(3, "fileio", FileIO, \ |
| 179 |
"Add file I/O from all profiled threads, implies mainthreadio") \ |
| 180 |
\ |
| 181 |
MACRO(4, "fileioall", FileIOAll, \ |
| 182 |
"Add file I/O from all threads, implies fileio") \ |
| 183 |
\ |
| 184 |
MACRO(5, "nomarkerstacks", NoMarkerStacks, \ |
| 185 |
"Markers do not capture stacks, to reduce overhead") \ |
| 186 |
\ |
| 187 |
MACRO(6, "screenshots", Screenshots, \ |
| 188 |
"Take a snapshot of the window on every composition") \ |
| 189 |
\ |
| 190 |
MACRO(7, "seqstyle", SequentialStyle, \ |
| 191 |
"Disable parallel traversal in styling") \ |
| 192 |
\ |
| 193 |
MACRO(8, "stackwalk", StackWalk, \ |
| 194 |
"Walk the C++ stack, not available on all platforms") \ |
| 195 |
\ |
| 196 |
MACRO(9, "jsallocations", JSAllocations, \ |
| 197 |
"Have the JavaScript engine track allocations") \ |
| 198 |
\ |
| 199 |
MACRO(10, "nostacksampling", NoStackSampling, \ |
| 200 |
"Disable all stack sampling: Cancels \"js\", \"stackwalk\" and " \ |
| 201 |
"labels") \ |
| 202 |
\ |
| 203 |
MACRO(11, "nativeallocations", NativeAllocations, \ |
| 204 |
"Collect the stacks from a smaller subset of all native " \ |
| 205 |
"allocations, biasing towards collecting larger allocations") \ |
| 206 |
\ |
| 207 |
MACRO(12, "ipcmessages", IPCMessages, \ |
| 208 |
"Have the IPC layer track cross-process messages") \ |
| 209 |
\ |
| 210 |
MACRO(13, "audiocallbacktracing", AudioCallbackTracing, \ |
| 211 |
"Audio callback tracing") \ |
| 212 |
\ |
| 213 |
MACRO(14, "cpu", CPUUtilization, "CPU utilization") \ |
| 214 |
\ |
| 215 |
MACRO(15, "notimerresolutionchange", NoTimerResolutionChange, \ |
| 216 |
"Do not adjust the timer resolution for fast sampling, so that " \ |
| 217 |
"other Firefox timers do not get affected") \ |
| 218 |
\ |
| 219 |
MACRO(16, "cpuallthreads", CPUAllThreads, \ |
| 220 |
"Sample the CPU utilization of all registered threads") \ |
| 221 |
\ |
| 222 |
MACRO(17, "samplingallthreads", SamplingAllThreads, \ |
| 223 |
"Sample the stacks of all registered threads") \ |
| 224 |
\ |
| 225 |
MACRO(18, "markersallthreads", MarkersAllThreads, \ |
| 226 |
"Record markers from all registered threads") \ |
| 227 |
\ |
| 228 |
MACRO(19, "unregisteredthreads", UnregisteredThreads, \ |
| 229 |
"Discover and profile unregistered threads -- beware: expensive!") \ |
| 230 |
\ |
| 231 |
MACRO(20, "processcpu", ProcessCPU, \ |
| 232 |
"Sample the CPU utilization of each process") \ |
| 233 |
\ |
| 234 |
MACRO(21, "power", Power, POWER_HELP) \ |
| 235 |
\ |
| 236 |
MACRO(22, "cpufreq", CPUFrequency, \ |
| 237 |
"Record the clock frequency of " \ |
| 238 |
"every CPU core for every profiler sample.") \ |
| 239 |
\ |
| 240 |
MACRO(23, "bandwidth", Bandwidth, \ |
| 241 |
"Record the network bandwidth used for every profiler sample.") \ |
| 242 |
\ |
| 243 |
MACRO(24, "memory", Memory, \ |
| 244 |
"Track the memory allocations and deallocations per process over " \ |
| 245 |
"time.") \ |
| 246 |
\ |
| 247 |
MACRO(25, "tracing", Tracing, \ |
| 248 |
"Instead of sampling periodically, captures information about " \ |
| 249 |
"every function executed for the duration (JS only)") \ |
| 250 |
\ |
| 251 |
MACRO(26, "sandbox", Sandbox, \ |
| 252 |
"Report sandbox syscalls and logs in the " \ |
| 253 |
"profiler.") \ |
| 254 |
\ |
| 255 |
MACRO(27, "flows", Flows, \ |
| 256 |
"Include all flow-related markers. These markers show the program" \ |
| 257 |
"better but can cause more overhead in some places than normal.") |
| 258 |
|
| 259 |
// *** Synchronize with lists in ProfilerState.h and geckoProfiler.json *** |
| 260 |
|
| 261 |
struct ProfilerFeature { |
| 262 |
# define DECLARE(n_, str_, Name_, desc_) \ |
| 263 |
static constexpr uint32_t Name_ = (1u << n_); \ |
| 264 |
[[nodiscard]] static constexpr bool Has##Name_(uint32_t aFeatures) { \ |
| 265 |
return aFeatures & Name_; \ |
| 266 |
} \ |
| 267 |
static constexpr void Set##Name_(uint32_t& aFeatures) { \ |
| 268 |
aFeatures |= Name_; \ |
| 269 |
} \ |
| 270 |
static constexpr void Clear##Name_(uint32_t& aFeatures) { \ |
| 271 |
aFeatures &= ~Name_; \ |
| 272 |
} |
| 273 |
|
| 274 |
// Define a bitfield constant, a getter, and two setters for each feature. |
| 275 |
BASE_PROFILER_FOR_EACH_FEATURE(DECLARE) |
| 276 |
|
| 277 |
# undef DECLARE |
| 278 |
}; |
| 279 |
|
| 280 |
namespace detail { |
| 281 |
|
| 282 |
// RacyFeatures is only defined in this header file so that its methods can |
| 283 |
// be inlined into profiler_is_active(). Please do not use anything from the |
| 284 |
// detail namespace outside the profiler. |
| 285 |
|
| 286 |
// Within the profiler's code, the preferred way to check profiler activeness |
| 287 |
// and features is via ActivePS(). However, that requires locking gPSMutex. |
| 288 |
// There are some hot operations where absolute precision isn't required, so we |
| 289 |
// duplicate the activeness/feature state in a lock-free manner in this class. |
| 290 |
class RacyFeatures { |
| 291 |
public: |
| 292 |
MFBT_API static void SetActive(uint32_t aFeatures); |
| 293 |
|
| 294 |
MFBT_API static void SetInactive(); |
| 295 |
|
| 296 |
MFBT_API static void SetPaused(); |
| 297 |
|
| 298 |
MFBT_API static void SetUnpaused(); |
| 299 |
|
| 300 |
MFBT_API static void SetSamplingPaused(); |
| 301 |
|
| 302 |
MFBT_API static void SetSamplingUnpaused(); |
| 303 |
|
| 304 |
[[nodiscard]] MFBT_API static mozilla::Maybe<uint32_t> FeaturesIfActive() { |
| 305 |
if (uint32_t af = sActiveAndFeatures; af & Active) { |
| 306 |
// Active, remove the Active&Paused bits to get all features. |
| 307 |
return Some(af & ~(Active | Paused | SamplingPaused)); |
| 308 |
} |
| 309 |
return Nothing(); |
| 310 |
} |
| 311 |
|
| 312 |
[[nodiscard]] MFBT_API static bool IsActive(); |
| 313 |
|
| 314 |
[[nodiscard]] MFBT_API static bool IsActiveWithFeature(uint32_t aFeature); |
| 315 |
|
| 316 |
[[nodiscard]] MFBT_API static bool IsActiveWithoutFeature(uint32_t aFeature); |
| 317 |
|
| 318 |
// True if profiler is active, and not fully paused. |
| 319 |
// Note that periodic sampling *could* be paused! |
| 320 |
[[nodiscard]] MFBT_API static bool IsActiveAndUnpaused(); |
| 321 |
|
| 322 |
// True if profiler is active, and sampling is not paused (though generic |
| 323 |
// `SetPaused()` or specific `SetSamplingPaused()`). |
| 324 |
[[nodiscard]] MFBT_API static bool IsActiveAndSamplingUnpaused(); |
| 325 |
|
| 326 |
private: |
| 327 |
static constexpr uint32_t Active = 1u << 31; |
| 328 |
static constexpr uint32_t Paused = 1u << 30; |
| 329 |
static constexpr uint32_t SamplingPaused = 1u << 29; |
| 330 |
|
| 331 |
// Ensure Active/Paused don't overlap with any of the feature bits. |
| 332 |
# define NO_OVERLAP(n_, str_, Name_, desc_) \ |
| 333 |
static_assert(ProfilerFeature::Name_ != SamplingPaused, \ |
| 334 |
"bad feature value"); |
| 335 |
|
| 336 |
BASE_PROFILER_FOR_EACH_FEATURE(NO_OVERLAP); |
| 337 |
|
| 338 |
# undef NO_OVERLAP |
| 339 |
|
| 340 |
// We combine the active bit with the feature bits so they can be read or |
| 341 |
// written in a single atomic operation. |
| 342 |
// TODO: Could this be MFBT_DATA for better inlining optimization? |
| 343 |
MFBT_DATA static Atomic<uint32_t, MemoryOrdering::Relaxed> sActiveAndFeatures; |
| 344 |
}; |
| 345 |
|
| 346 |
MFBT_API bool IsThreadBeingProfiled(); |
| 347 |
|
| 348 |
} // namespace detail |
| 349 |
|
| 350 |
//--------------------------------------------------------------------------- |
| 351 |
// Get information from the profiler |
| 352 |
//--------------------------------------------------------------------------- |
| 353 |
|
| 354 |
// Is the profiler active? Note: the return value of this function can become |
| 355 |
// immediately out-of-date. E.g. the profile might be active but then |
| 356 |
// profiler_stop() is called immediately afterward. One common and reasonable |
| 357 |
// pattern of usage is the following: |
| 358 |
// |
| 359 |
// if (profiler_is_active()) { |
| 360 |
// ExpensiveData expensiveData = CreateExpensiveData(); |
| 361 |
// PROFILER_OPERATION(expensiveData); |
| 362 |
// } |
| 363 |
// |
| 364 |
// where PROFILER_OPERATION is a no-op if the profiler is inactive. In this |
| 365 |
// case the profiler_is_active() check is just an optimization -- it prevents |
| 366 |
// us calling CreateExpensiveData() unnecessarily in most cases, but the |
| 367 |
// expensive data will end up being created but not used if another thread |
| 368 |
// stops the profiler between the CreateExpensiveData() and PROFILER_OPERATION |
| 369 |
// calls. |
| 370 |
[[nodiscard]] inline bool profiler_is_active() { |
| 371 |
return baseprofiler::detail::RacyFeatures::IsActive(); |
| 372 |
} |
| 373 |
|
| 374 |
// Same as profiler_is_active(), but also checks if the profiler is not paused. |
| 375 |
[[nodiscard]] inline bool profiler_is_active_and_unpaused() { |
| 376 |
return baseprofiler::detail::RacyFeatures::IsActiveAndUnpaused(); |
| 377 |
} |
| 378 |
|
| 379 |
// Is the profiler active and unpaused, and is the current thread being |
| 380 |
// profiled? (Same caveats and recommented usage as profiler_is_active().) |
| 381 |
[[nodiscard]] inline bool profiler_thread_is_being_profiled() { |
| 382 |
return baseprofiler::detail::RacyFeatures::IsActiveAndUnpaused() && |
| 383 |
baseprofiler::detail::IsThreadBeingProfiled(); |
| 384 |
} |
| 385 |
|
| 386 |
// Is the profiler active and paused? Returns false if the profiler is inactive. |
| 387 |
[[nodiscard]] MFBT_API bool profiler_is_paused(); |
| 388 |
|
| 389 |
// Is the profiler active and sampling is paused? Returns false if the profiler |
| 390 |
// is inactive. |
| 391 |
[[nodiscard]] MFBT_API bool profiler_is_sampling_paused(); |
| 392 |
|
| 393 |
// Is the current thread sleeping? |
| 394 |
[[nodiscard]] MFBT_API bool profiler_thread_is_sleeping(); |
| 395 |
|
| 396 |
// Get all the features supported by the profiler that are accepted by |
| 397 |
// profiler_start(). The result is the same whether the profiler is active or |
| 398 |
// not. |
| 399 |
[[nodiscard]] MFBT_API uint32_t profiler_get_available_features(); |
| 400 |
|
| 401 |
// Returns the full feature set if the profiler is active. |
| 402 |
// Note: the return value can become immediately out-of-date, much like the |
| 403 |
// return value of profiler_is_active(). |
| 404 |
[[nodiscard]] inline mozilla::Maybe<uint32_t> profiler_features_if_active() { |
| 405 |
return baseprofiler::detail::RacyFeatures::FeaturesIfActive(); |
| 406 |
} |
| 407 |
|
| 408 |
// Check if a profiler feature (specified via the ProfilerFeature type) is |
| 409 |
// active. Returns false if the profiler is inactive. Note: the return value |
| 410 |
// can become immediately out-of-date, much like the return value of |
| 411 |
// profiler_is_active(). |
| 412 |
[[nodiscard]] MFBT_API bool profiler_feature_active(uint32_t aFeature); |
| 413 |
|
| 414 |
// Check if the profiler is active without a feature (specified via the |
| 415 |
// ProfilerFeature type). Note: the return value can become immediately |
| 416 |
// out-of-date, much like the return value of profiler_is_active(). |
| 417 |
[[nodiscard]] MFBT_API bool profiler_active_without_feature(uint32_t aFeature); |
| 418 |
|
| 419 |
// Returns true if any of the profiler mutexes are currently locked *on the |
| 420 |
// current thread*. This may be used by re-entrant code that may call profiler |
| 421 |
// functions while the same of a different profiler mutex is locked, which could |
| 422 |
// deadlock. |
| 423 |
[[nodiscard]] bool profiler_is_locked_on_current_thread(); |
| 424 |
|
| 425 |
} // namespace mozilla::baseprofiler |
| 426 |
|
| 427 |
#endif // !MOZ_GECKO_PROFILER |
| 428 |
|
| 429 |
#endif // BaseProfilerState_h |