diff --git a/BUILD.md b/BUILD.md index 548542e27b..ce82dd01c8 100644 --- a/BUILD.md +++ b/BUILD.md @@ -218,7 +218,7 @@ See https://developer.android.com/ndk/guides/cmake#command-line for CMake NDK do # Build release binary for arm64-v8a cmake -S . -B build \ -D CMAKE_TOOLCHAIN_FILE=$ANDROID_NDK_HOME/build/cmake/android.toolchain.cmake \ - -D ANDROID_PLATFORM=29 \ + -D ANDROID_PLATFORM=31 \ -D CMAKE_ANDROID_ARCH_ABI=arm64-v8a \ -D CMAKE_ANDROID_STL_TYPE=c++_static \ -D ANDROID_USE_LEGACY_TOOLCHAIN_FILE=NO \ diff --git a/CMakeLists.txt b/CMakeLists.txt index 3787aa7618..71ddce6361 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -138,6 +138,10 @@ if(ANDROID) add_subdirectory(agi_launch_producer) endif() +if(ANDROID OR BUILD_TESTS) + add_subdirectory(thermal_monitor) +endif() + if(BUILD_LAYERMGR) if(NOT Qt6_FOUND) message("WARNING: Vulkan Configurator will be excluded from the build because Qt6 was not found. Please add Qt6 into the PATH environment variable") diff --git a/scripts/android.py b/scripts/android.py index db9bd09d63..942403d2bd 100755 --- a/scripts/android.py +++ b/scripts/android.py @@ -116,7 +116,7 @@ def main(): cmake_cmd += f' -D BUILD_TESTS={build_tests}' cmake_cmd += f' -D CMAKE_ANDROID_STL_TYPE=c++_static' - cmake_cmd += ' -D ANDROID_PLATFORM=29' + cmake_cmd += ' -D ANDROID_PLATFORM=31' cmake_cmd += ' -D ANDROID_USE_LEGACY_TOOLCHAIN_FILE=NO' RunShellCmd(cmake_cmd) diff --git a/thermal_monitor/CMakeLists.txt b/thermal_monitor/CMakeLists.txt new file mode 100644 index 0000000000..298bf49ddc --- /dev/null +++ b/thermal_monitor/CMakeLists.txt @@ -0,0 +1,47 @@ +# Copyright (C) 2026 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# The sampling policy has no Android dependencies, so it is also built on the host for the unit tests. +add_library(thermal_collector STATIC thermal_collector.cpp thermal_collector.h) +target_include_directories(thermal_collector PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) +if(NOT ANDROID) + # Stands in for the NDK's so that the collector builds off-device. + target_include_directories(thermal_collector PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/host_stubs) +endif() + +if(WIN32 AND (QT_TARGET_TYPE STREQUAL STATIC_LIBRARY)) + set_property(TARGET thermal_collector PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") +endif() + +if(ANDROID) + # The Perfetto SDK that the layers use. Built as its own library so that the availability checks + # below only apply to main.cpp. + set(PERFETTO_SDK_DIR ${PROJECT_SOURCE_DIR}/layersvt/perfetto) + add_library(thermal_monitor_perfetto STATIC ${PERFETTO_SDK_DIR}/perfetto.cc) + target_include_directories(thermal_monitor_perfetto PUBLIC ${PROJECT_SOURCE_DIR}/layersvt) + target_compile_options(thermal_monitor_perfetto PRIVATE -Wno-deprecated-declarations) + target_link_libraries(thermal_monitor_perfetto PUBLIC log) + + add_executable(thermal_monitor main.cpp) + target_link_libraries(thermal_monitor PRIVATE thermal_collector thermal_monitor_perfetto android log) + # AThermal_getThermalHeadroomThresholds() is API 35, above ANDROID_PLATFORM, so it is weakly + # linked and guarded by __builtin_available. + target_compile_definitions(thermal_monitor PRIVATE __ANDROID_UNAVAILABLE_SYMBOLS_ARE_WEAK__) + target_compile_options(thermal_monitor PRIVATE -Werror=unguarded-availability) + install(TARGETS thermal_monitor DESTINATION ${CMAKE_INSTALL_BINDIR}) +endif() + +if(BUILD_TESTS AND NOT ANDROID) + add_subdirectory(test) +endif() diff --git a/thermal_monitor/host_stubs/android/thermal.h b/thermal_monitor/host_stubs/android/thermal.h new file mode 100644 index 0000000000..b34ba185ab --- /dev/null +++ b/thermal_monitor/host_stubs/android/thermal.h @@ -0,0 +1,32 @@ +/* Copyright (C) 2026 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Host-only stand-in for the NDK's , so that ThermalCollector, which only needs +// the AThermalStatus type, can be built and unit tested off-device. Only on the include path for +// non-Android builds; Android builds use the real NDK header. The values are part of the NDK ABI. + +#pragma once + +enum AThermalStatus { + ATHERMAL_STATUS_ERROR = -1, + ATHERMAL_STATUS_NONE = 0, + ATHERMAL_STATUS_LIGHT = 1, + ATHERMAL_STATUS_MODERATE = 2, + ATHERMAL_STATUS_SEVERE = 3, + ATHERMAL_STATUS_CRITICAL = 4, + ATHERMAL_STATUS_EMERGENCY = 5, + ATHERMAL_STATUS_SHUTDOWN = 6, +}; +typedef enum AThermalStatus AThermalStatus; diff --git a/thermal_monitor/main.cpp b/thermal_monitor/main.cpp new file mode 100644 index 0000000000..ad63f77942 --- /dev/null +++ b/thermal_monitor/main.cpp @@ -0,0 +1,225 @@ +/* Copyright (C) 2026 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "thermal_collector.h" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "perfetto/perfetto.h" + +PERFETTO_DEFINE_CATEGORIES( + perfetto::Category(apa::thermal::ThermalConstants::kTrackEventCategory).SetDescription("Framework thermal status and headroom")); + +PERFETTO_TRACK_EVENT_STATIC_STORAGE(); + +namespace apa::thermal { +namespace { + +constexpr const char* kLogTag = "ThermalMonitor"; + +// Queries the Android framework's thermal state via the NDK AThermal API in libandroid.so. +// The binary targets API 31 (see scripts/android.py), which covers everything except +// AThermal_getThermalHeadroomThresholds() (API 35). That symbol is weakly linked +// (__ANDROID_UNAVAILABLE_SYMBOLS_ARE_WEAK__) and guarded by __builtin_available. +class NdkThermalSource final : public ThermalSource { + public: + NdkThermalSource() : manager_(AThermal_acquireManager()) {} + + ~NdkThermalSource() override { + if (manager_ != nullptr) { + AThermal_releaseManager(manager_); + } + } + + NdkThermalSource(const NdkThermalSource&) = delete; + NdkThermalSource& operator=(const NdkThermalSource&) = delete; + + [[nodiscard]] bool IsValid() const { return manager_ != nullptr; } + + std::optional CurrentThermalStatus() override { + const AThermalStatus status = AThermal_getCurrentThermalStatus(manager_); + if (status < ATHERMAL_STATUS_NONE || status > ATHERMAL_STATUS_SHUTDOWN) { + return std::nullopt; + } + return status; + } + + std::optional ThermalHeadroom(int forecast_seconds) override { + const float headroom = AThermal_getThermalHeadroom(manager_, forecast_seconds); + if (std::isnan(headroom)) { + return std::nullopt; + } + return headroom; + } + + std::map ThermalHeadroomThresholds() override { + std::map result; + // AThermal_getThermalHeadroomThresholds() was added in Android 15 (API 35). Older versions + // cannot report thresholds, so they get an empty map. + if (__builtin_available(android 35, *)) { + const AThermalHeadroomThreshold* thresholds = nullptr; + size_t size = 0; + if (AThermal_getThermalHeadroomThresholds(manager_, &thresholds, &size) != 0 || thresholds == nullptr) { + return result; + } + for (size_t i = 0; i < size; ++i) { + const AThermalStatus status = thresholds[i].thermalStatus; + if (status >= ATHERMAL_STATUS_NONE && status <= ATHERMAL_STATUS_SHUTDOWN) { + result[status] = thresholds[i].headroom; + } + } + // The NDK allocates the array and documents that the client array-deletes it. + delete[] thresholds; + } + return result; + } + + private: + AThermalManager* manager_ = nullptr; +}; + +// Emits the headroom thresholds at the start of every tracing session that enables the category. +// The thresholds never change, so emitting them once per session is enough, and the monitor can be +// started before tracing is. +class ThresholdSessionObserver final : public perfetto::TrackEventSessionObserver { + public: + explicit ThresholdSessionObserver(const ThermalCollector& collector) : collector_(collector) { + perfetto::TrackEvent::AddSessionObserver(this); + } + + ~ThresholdSessionObserver() override { perfetto::TrackEvent::RemoveSessionObserver(this); } + + ThresholdSessionObserver(const ThresholdSessionObserver&) = delete; + ThresholdSessionObserver& operator=(const ThresholdSessionObserver&) = delete; + + void OnStart(const perfetto::DataSourceBase::StartArgs&) override { collector_.EmitThresholds(); } + + private: + const ThermalCollector& collector_; +}; + +void EmitCounter(const char* name, double value) { + // The names are ThermalConstants string literals, so they outlive the track. + TRACE_COUNTER(ThermalConstants::kTrackEventCategory, perfetto::CounterTrack(perfetto::StaticString{name}), value); +} + +volatile std::sig_atomic_t g_stop_requested = 0; + +void HandleStopSignal(int /*signum*/) { g_stop_requested = 1; } + +std::optional ParseInt(std::string_view str) { + int value = 0; + const char* begin = str.data(); + const char* end = begin + str.size(); + const auto [ptr, ec] = std::from_chars(begin, end, value); + if (ec != std::errc() || ptr != end) { + return std::nullopt; + } + return value; +} + +struct Options { + int poll_interval_ms = ThermalConstants::kDefaultPollIntervalMs; + int forecast_seconds = ThermalConstants::kDefaultForecastSeconds; +}; + +// Reads the value that follows argv[*i] into *out, logging an error and exiting when it is missing +// or malformed. +void ParseIntOption(int argc, char** argv, int* i, int* out) { + const char* flag = argv[*i]; + if (*i + 1 >= argc) { + __android_log_print(ANDROID_LOG_ERROR, kLogTag, "Missing value for %s", flag); + std::exit(1); + } + const char* value = argv[++*i]; + if (const std::optional parsed = ParseInt(value); parsed.has_value()) { + *out = *parsed; + return; + } + __android_log_print(ANDROID_LOG_ERROR, kLogTag, "Invalid value '%s' for %s", value, flag); + std::exit(1); +} + +Options ParseOptions(int argc, char** argv) { + Options options; + for (int i = 1; i < argc; ++i) { + if (std::strcmp(argv[i], "--poll-interval-ms") == 0) { + ParseIntOption(argc, argv, &i, &options.poll_interval_ms); + } else if (std::strcmp(argv[i], "--forecast-seconds") == 0) { + ParseIntOption(argc, argv, &i, &options.forecast_seconds); + } else { + __android_log_print(ANDROID_LOG_ERROR, kLogTag, "Unknown argument '%s'", argv[i]); + std::exit(1); + } + } + options.poll_interval_ms = std::max(options.poll_interval_ms, ThermalConstants::kMinPollIntervalMs); + options.forecast_seconds = std::clamp(options.forecast_seconds, 0, ThermalConstants::kMaxForecastSeconds); + return options; +} + +} // namespace +} // namespace apa::thermal + +int main(int argc, char** argv) { + using namespace apa::thermal; + + struct sigaction sa = {}; + sa.sa_handler = HandleStopSignal; + sigemptyset(&sa.sa_mask); + sigaction(SIGTERM, &sa, nullptr); + sigaction(SIGINT, &sa, nullptr); + + const Options options = ParseOptions(argc, argv); + + NdkThermalSource source; + if (!source.IsValid()) { + __android_log_print(ANDROID_LOG_WARN, kLogTag, "AThermalManager is unavailable on this device"); + return 0; + } + + perfetto::TracingInitArgs args; + args.backends = perfetto::kSystemBackend; + perfetto::Tracing::Initialize(args); + perfetto::TrackEvent::Register(); + + ThermalCollector collector(source, EmitCounter, options.forecast_seconds); + ThresholdSessionObserver observer(collector); + // OnStart() only reports sessions that start after the observer is added. + collector.EmitThresholds(); + + while (!g_stop_requested) { + collector.Sample(); + if (g_stop_requested) { + break; + } + poll(nullptr, 0, options.poll_interval_ms); + } + + // Commits the last samples to the tracing service before the process exits. + perfetto::TrackEvent::Flush(); + return 0; +} diff --git a/thermal_monitor/test/CMakeLists.txt b/thermal_monitor/test/CMakeLists.txt new file mode 100644 index 0000000000..6da0645ae1 --- /dev/null +++ b/thermal_monitor/test/CMakeLists.txt @@ -0,0 +1,22 @@ +# Copyright (C) 2026 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +add_executable(test_thermal_collector test_thermal_collector.cpp) +target_link_libraries(test_thermal_collector PRIVATE thermal_collector GTest::gtest GTest::gtest_main) +add_test(NAME test_thermal_collector COMMAND test_thermal_collector) +set_target_properties(test_thermal_collector PROPERTIES FOLDER "thermal_monitor/Test") + +if(WIN32 AND (QT_TARGET_TYPE STREQUAL STATIC_LIBRARY)) + set_property(TARGET test_thermal_collector PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") +endif() diff --git a/thermal_monitor/test/test_thermal_collector.cpp b/thermal_monitor/test/test_thermal_collector.cpp new file mode 100644 index 0000000000..905d6b43d6 --- /dev/null +++ b/thermal_monitor/test/test_thermal_collector.cpp @@ -0,0 +1,280 @@ +/* Copyright (C) 2026 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "thermal_collector.h" + +#include + +#include +#include +#include +#include +#include +#include + +namespace apa::thermal { +namespace { + +using CounterSample = std::pair; + +class FakeThermalSource final : public ThermalSource { + public: + FakeThermalSource(std::optional status, std::optional headroom, + std::optional forecast = std::nullopt, std::map thresholds = {}) + : status_(status), headroom_(headroom), forecast_(forecast), thresholds_(std::move(thresholds)) {} + + std::optional CurrentThermalStatus() override { return status_; } + + std::optional ThermalHeadroom(int forecast_seconds) override { + headroom_queries_.push_back(forecast_seconds); + return forecast_seconds == 0 ? headroom_ : forecast_; + } + + std::map ThermalHeadroomThresholds() override { + ++thresholds_read_count_; + return thresholds_; + } + + int ThresholdsReadCount() const { return thresholds_read_count_; } + + const std::vector& HeadroomQueries() const { return headroom_queries_; } + + private: + std::optional status_; + std::optional headroom_; + std::optional forecast_; + std::map thresholds_; + int thresholds_read_count_ = 0; + std::vector headroom_queries_; +}; + +// Tests for ThermalCollector's sampling policy, which is the part that has to cope with what real +// devices actually report. +class ThermalCollectorTest : public ::testing::Test { + protected: + std::vector emitted_; + ThermalCollector::Emitter emitter_ = [this](const char* name, double value) { emitted_.emplace_back(name, value); }; +}; + +TEST_F(ThermalCollectorTest, InterleavesCurrentAndForecastHeadroomOnAlternatingTicks) { + FakeThermalSource source(/*status=*/ATHERMAL_STATUS_MODERATE, /*headroom=*/0.93f, /*forecast=*/1.04f); + ThermalCollector collector(source, emitter_, /*forecast_seconds=*/10); + + collector.Sample(); + collector.Sample(); + collector.Sample(); + + EXPECT_EQ(source.HeadroomQueries(), (std::vector{0, 10, 0})); + const std::vector expected = { + {ThermalConstants::kStatusCounter, 2}, {ThermalConstants::kHeadroomCounter, 0.93f}, + {ThermalConstants::kStatusCounter, 2}, {ThermalConstants::kHeadroomForecastCounter, 1.04f}, + {ThermalConstants::kStatusCounter, 2}, {ThermalConstants::kHeadroomCounter, 0.93f}, + }; + EXPECT_EQ(emitted_, expected); +} + +TEST_F(ThermalCollectorTest, DisablesForecastWhenHorizonIsZero) { + FakeThermalSource source(/*status=*/ATHERMAL_STATUS_LIGHT, /*headroom=*/0.8f, /*forecast=*/0.9f); + ThermalCollector collector(source, emitter_, /*forecast_seconds=*/0); + + collector.Sample(); + collector.Sample(); + + EXPECT_EQ(source.HeadroomQueries(), (std::vector{0, 0})); + const std::vector expected = { + {ThermalConstants::kStatusCounter, 1}, + {ThermalConstants::kHeadroomCounter, 0.8f}, + {ThermalConstants::kStatusCounter, 1}, + {ThermalConstants::kHeadroomCounter, 0.8f}, + }; + EXPECT_EQ(emitted_, expected); +} + +TEST_F(ThermalCollectorTest, SkipsFailedForecastTickWithoutRetryingCurrentHeadroom) { + FakeThermalSource source(/*status=*/ATHERMAL_STATUS_LIGHT, /*headroom=*/0.8f, /*forecast=*/std::nullopt); + ThermalCollector collector(source, emitter_, /*forecast_seconds=*/10); + + collector.Sample(); + collector.Sample(); + + // Retrying the current headroom on the failed forecast tick would hit the ~1 Hz rate limit. + EXPECT_EQ(source.HeadroomQueries(), (std::vector{0, 10})); + const std::vector expected = { + {ThermalConstants::kStatusCounter, 1}, + {ThermalConstants::kHeadroomCounter, 0.8f}, + {ThermalConstants::kStatusCounter, 1}, + }; + EXPECT_EQ(emitted_, expected); +} + +TEST_F(ThermalCollectorTest, DropsForecastOnlyAfterRepeatedFailures) { + FakeThermalSource source(/*status=*/std::nullopt, /*headroom=*/0.8f, /*forecast=*/std::nullopt); + ThermalCollector collector(source, emitter_, /*forecast_seconds=*/10); + + for (int i = 0; i < 9; ++i) { + collector.Sample(); + } + + // Three failed forecast ticks (1, 3, 5) disable the forecast; after that every tick is current. + EXPECT_EQ(source.HeadroomQueries(), (std::vector{0, 10, 0, 10, 0, 10, 0, 0, 0})); +} + +TEST_F(ThermalCollectorTest, KeepsForecastAfterTransientFailures) { + // Each fake failure is followed by a success, so the failure count never reaches the limit. + class FlakyForecastSource final : public ThermalSource { + public: + std::optional CurrentThermalStatus() override { return std::nullopt; } + std::optional ThermalHeadroom(int forecast_seconds) override { + if (forecast_seconds == 0) { + return 0.8f; + } + return (forecast_calls_++ % 2) == 0 ? std::nullopt : std::optional(0.9f); + } + std::map ThermalHeadroomThresholds() override { return {}; } + + private: + int forecast_calls_ = 0; + } source; + ThermalCollector collector(source, emitter_, /*forecast_seconds=*/10); + + for (int i = 0; i < 12; ++i) { + collector.Sample(); + } + + const std::vector expected = { + {ThermalConstants::kHeadroomCounter, 0.8f}, {ThermalConstants::kHeadroomCounter, 0.8f}, + {ThermalConstants::kHeadroomForecastCounter, 0.9f}, {ThermalConstants::kHeadroomCounter, 0.8f}, + {ThermalConstants::kHeadroomCounter, 0.8f}, {ThermalConstants::kHeadroomForecastCounter, 0.9f}, + {ThermalConstants::kHeadroomCounter, 0.8f}, {ThermalConstants::kHeadroomCounter, 0.8f}, + {ThermalConstants::kHeadroomForecastCounter, 0.9f}, + }; + EXPECT_EQ(emitted_, expected); +} + +TEST_F(ThermalCollectorTest, EmitsHeadroomWithoutRounding) { + // The Galaxy S25 puts LIGHT at 0.867 and MODERATE at 0.933, so any rounding has to keep at + // least three decimal places. Perfetto counters are doubles, so there is none. + FakeThermalSource source(/*status=*/ATHERMAL_STATUS_NONE, /*headroom=*/0.8674f); + ThermalCollector(source, emitter_).Sample(); + + ASSERT_EQ(emitted_.size(), 2u); + EXPECT_EQ(emitted_[1], CounterSample(ThermalConstants::kHeadroomCounter, 0.8674f)); +} + +TEST_F(ThermalCollectorTest, OmitsHeadroomEntirelyOnDeviceThatDoesNotReportIt) { + FakeThermalSource source( + /*status=*/ATHERMAL_STATUS_LIGHT, + /*headroom=*/std::nullopt, + /*forecast=*/std::nullopt, + /*thresholds=*/{{ATHERMAL_STATUS_LIGHT, 0.7f}}); + ThermalCollector collector(source, emitter_); + + collector.Sample(); + + // A status track and no headroom track, rather than a headroom track full of a sentinel the + // host would have to strip. + const std::vector expected = { + {ThermalConstants::kStatusCounter, 1}, + }; + EXPECT_EQ(emitted_, expected); +} + +TEST_F(ThermalCollectorTest, IgnoresNonFiniteOrNegativeHeadroom) { + FakeThermalSource nan_source( + /*status=*/ATHERMAL_STATUS_LIGHT, + /*headroom=*/std::numeric_limits::quiet_NaN(), + /*forecast=*/std::nullopt, + /*thresholds=*/{{ATHERMAL_STATUS_LIGHT, 0.7f}}); + ThermalCollector(nan_source, emitter_).Sample(); + + FakeThermalSource negative_source( + /*status=*/ATHERMAL_STATUS_LIGHT, + /*headroom=*/-1.0f, + /*forecast=*/-1.0f, + /*thresholds=*/{{ATHERMAL_STATUS_LIGHT, 0.7f}}); + ThermalCollector negative_collector(negative_source, emitter_, /*forecast_seconds=*/10); + negative_collector.Sample(); + negative_collector.Sample(); + + // A rejected forecast tick emits no headroom rather than retrying the current headroom. + EXPECT_EQ(negative_source.HeadroomQueries(), (std::vector{0, 10})); + const std::vector expected = { + {ThermalConstants::kStatusCounter, 1}, + {ThermalConstants::kStatusCounter, 1}, + {ThermalConstants::kStatusCounter, 1}, + }; + EXPECT_EQ(emitted_, expected); +} + +TEST_F(ThermalCollectorTest, OmitsStatusOnDeviceThatDoesNotReportIt) { + FakeThermalSource source(/*status=*/std::nullopt, /*headroom=*/0.5f); + ThermalCollector collector(source, emitter_); + + collector.Sample(); + + const std::vector expected = { + {ThermalConstants::kHeadroomCounter, 0.5}, + }; + EXPECT_EQ(emitted_, expected); +} + +TEST_F(ThermalCollectorTest, SamplesDoNotIncludeThresholds) { + FakeThermalSource source( + /*status=*/ATHERMAL_STATUS_NONE, + /*headroom=*/0.8f, + /*forecast=*/std::nullopt, + /*thresholds=*/{{ATHERMAL_STATUS_LIGHT, 0.867f}}); + ThermalCollector collector(source, emitter_, /*forecast_seconds=*/0); + + collector.Sample(); + + const std::vector expected = { + {ThermalConstants::kStatusCounter, 0}, + {ThermalConstants::kHeadroomCounter, 0.8f}, + }; + EXPECT_EQ(emitted_, expected); +} + +TEST_F(ThermalCollectorTest, ReadsThresholdsOnceAndEmitsTheValidOnes) { + // The Galaxy S25 reports SEVERE as NaN even though LIGHT and MODERATE are populated. + FakeThermalSource source( + /*status=*/ATHERMAL_STATUS_NONE, + /*headroom=*/0.8f, + /*forecast=*/0.9f, + /*thresholds=*/ + { + {ATHERMAL_STATUS_NONE, 0.0f}, + {ATHERMAL_STATUS_LIGHT, 0.867f}, + {ATHERMAL_STATUS_MODERATE, 0.933f}, + {ATHERMAL_STATUS_SEVERE, std::numeric_limits::quiet_NaN()}, + }); + ThermalCollector collector(source, emitter_, /*forecast_seconds=*/10); + + // Once per tracing session. + collector.EmitThresholds(); + collector.EmitThresholds(); + + EXPECT_EQ(source.ThresholdsReadCount(), 1); + const std::vector expected = { + {"sherlock.thermal.headroom.threshold.light", 0.867f}, + {"sherlock.thermal.headroom.threshold.moderate", 0.933f}, + {"sherlock.thermal.headroom.threshold.light", 0.867f}, + {"sherlock.thermal.headroom.threshold.moderate", 0.933f}, + }; + EXPECT_EQ(emitted_, expected); +} + +} // namespace +} // namespace apa::thermal diff --git a/thermal_monitor/thermal_collector.cpp b/thermal_monitor/thermal_collector.cpp new file mode 100644 index 0000000000..4548319f00 --- /dev/null +++ b/thermal_monitor/thermal_collector.cpp @@ -0,0 +1,70 @@ +/* Copyright (C) 2026 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "thermal_collector.h" + +#include +#include + +namespace apa::thermal { + +ThermalCollector::ThermalCollector(ThermalSource& source, Emitter emitter, int forecast_seconds) + : source_(source), + emitter_(std::move(emitter)), + thresholds_(ReadThresholds(source)), + forecast_seconds_(forecast_seconds), + forecast_supported_(forecast_seconds > 0) {} + +void ThermalCollector::Sample() { + if (const std::optional status = source_.CurrentThermalStatus(); status.has_value()) { + emitter_(ThermalConstants::kStatusCounter, static_cast(*status)); + } + if (forecast_supported_ && (tick_++ % 2) == 1) { + if (EmitHeadroom(ThermalConstants::kHeadroomForecastCounter, source_.ThermalHeadroom(forecast_seconds_))) { + forecast_failures_ = 0; + } else if (++forecast_failures_ >= kMaxForecastFailures) { + forecast_supported_ = false; + } + return; + } + EmitHeadroom(ThermalConstants::kHeadroomCounter, source_.ThermalHeadroom(0)); +} + +void ThermalCollector::EmitThresholds() const { + for (const auto& [name, value] : thresholds_) { + EmitHeadroom(name, value); + } +} + +ThermalCollector::ThresholdList ThermalCollector::ReadThresholds(ThermalSource& source) { + ThresholdList thresholds; + for (const auto& [status, value] : source.ThermalHeadroomThresholds()) { + const char* name = ThermalConstants::ThresholdCounterName(status); + if (name != nullptr) { + thresholds.emplace_back(name, value); + } + } + return thresholds; +} + +bool ThermalCollector::EmitHeadroom(const char* counter, std::optional headroom) const { + if (!headroom.has_value() || !std::isfinite(*headroom) || *headroom < 0.0f) { + return false; + } + emitter_(counter, *headroom); + return true; +} + +} // namespace apa::thermal diff --git a/thermal_monitor/thermal_collector.h b/thermal_monitor/thermal_collector.h new file mode 100644 index 0000000000..d35a800bf6 --- /dev/null +++ b/thermal_monitor/thermal_collector.h @@ -0,0 +1,128 @@ +/* Copyright (C) 2026 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include + +#include +#include +#include +#include +#include + +namespace apa::thermal { + +// Must match the track event category and counter names that the Android Performance Analyzer trace +// viewer reads. +namespace ThermalConstants { +// Perfetto track event category that the counters are written to. +inline constexpr const char* kTrackEventCategory = "Thermals"; +inline constexpr int kDefaultPollIntervalMs = 1000; +// Polling faster than this would only collect NaNs from the ~1 Hz rate-limited headroom API. +inline constexpr int kMinPollIntervalMs = kDefaultPollIntervalMs; +inline constexpr int kDefaultForecastSeconds = 10; +inline constexpr int kMaxForecastSeconds = 60; +inline constexpr const char* kHeadroomCounter = "sherlock.thermal.headroom"; +inline constexpr const char* kHeadroomForecastCounter = "sherlock.thermal.headroom.forecast"; +inline constexpr const char* kStatusCounter = "sherlock.thermal.status"; + +// Counter names for the thermal statuses that can carry a headroom threshold. +inline constexpr const char* ThresholdCounterName(AThermalStatus status) { + switch (status) { + case ATHERMAL_STATUS_LIGHT: + return "sherlock.thermal.headroom.threshold.light"; + case ATHERMAL_STATUS_MODERATE: + return "sherlock.thermal.headroom.threshold.moderate"; + case ATHERMAL_STATUS_SEVERE: + return "sherlock.thermal.headroom.threshold.severe"; + case ATHERMAL_STATUS_CRITICAL: + return "sherlock.thermal.headroom.threshold.critical"; + case ATHERMAL_STATUS_EMERGENCY: + return "sherlock.thermal.headroom.threshold.emergency"; + case ATHERMAL_STATUS_SHUTDOWN: + return "sherlock.thermal.headroom.threshold.shutdown"; + default: + return nullptr; + } +} +} // namespace ThermalConstants + +// Reads framework thermal signals (AThermal / PowerManager). Abstracted so ThermalCollector can be +// unit tested without a device. +class ThermalSource { + public: + virtual ~ThermalSource() = default; + + // AThermal_getCurrentThermalStatus(), or nullopt if the device cannot report it. + virtual std::optional CurrentThermalStatus() = 0; + + // AThermal_getThermalHeadroom(forecast_seconds); 0 asks for the current headroom. The returned + // headroom is 0.0 with no thermal load and rises with it: 1.0 means the device is (or, for a + // forecast, will be) throttled at ATHERMAL_STATUS_SEVERE, and values above 1.0 mean it + // is throttled beyond that. Returns nullopt if the API returns NaN, e.g. when the device does + // not support headroom or the call was rate-limited. + virtual std::optional ThermalHeadroom(int forecast_seconds) = 0; + + // Headroom at which each thermal status starts, or empty if the device or OS version cannot + // report it. + virtual std::map ThermalHeadroomThresholds() = 0; +}; + +// Samples the framework's thermal state and emits it as trace counters. +// +// AThermal_getThermalHeadroom() is rate-limited to ~1 Hz across all forecast_seconds values, which +// is why ThermalConstants::kDefaultPollIntervalMs is one second and why, when forecast_seconds is +// positive, current and forecast headroom are sampled on alternating ticks rather than on the same +// tick. A forecast tick that fails emits no headroom at all rather than retrying the current +// headroom, which the rate limit would reject. +// +// The headroom thresholds are static for a device, so they are read once, at construction, and +// emitted separately by EmitThresholds() once per tracing session. +class ThermalCollector { + public: + using Emitter = std::function; + + ThermalCollector(ThermalSource& source, Emitter emitter, int forecast_seconds = ThermalConstants::kDefaultForecastSeconds); + + // Emits the current status and either the current or the forecast headroom. Call it once per + // poll interval. + void Sample(); + + // Emits the device's headroom thresholds. Only reads state that is fixed at construction, so it + // can be called from another thread than Sample(), as long as the emitter is thread-safe. + void EmitThresholds() const; + + private: + using ThresholdList = std::vector>; + + // AThermal_getThermalHeadroom() also returns NaN when it is called too often or the thermal + // service hiccups, so one failure does not prove that the device cannot forecast. + static constexpr int kMaxForecastFailures = 3; + + static ThresholdList ReadThresholds(ThermalSource& source); + + bool EmitHeadroom(const char* counter, std::optional headroom) const; + + ThermalSource& source_; + const Emitter emitter_; + const ThresholdList thresholds_; + int forecast_seconds_; + int tick_ = 0; + int forecast_failures_ = 0; + bool forecast_supported_; +}; + +} // namespace apa::thermal