blob: d0dc9e183149d71a38ca4d8bbd6de4aec2c3805c [file] [log] [blame]
Eric Laurent3528c932018-02-23 17:17:22 -08001/*
2 * Copyright (C) 2018 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
Eric Laurent42896a02019-09-27 15:40:33 -070017#define LOG_TAG "TimeCheck"
Eric Laurent3528c932018-02-23 17:17:22 -080018
Ytai Ben-Tsvi1ea62c92021-11-10 14:38:27 -080019#include <optional>
20
Andy Hunga2a1ac32022-03-18 16:12:11 -070021#include <audio_utils/clock.h>
Marco Nelissencf90b492019-09-26 11:20:54 -070022#include <mediautils/EventLog.h>
Andy Hung224f82f2022-03-22 00:00:49 -070023#include <mediautils/MethodStatistics.h>
Ytai Ben-Tsvi1ea62c92021-11-10 14:38:27 -080024#include <mediautils/TimeCheck.h>
25#include <utils/Log.h>
Eric Laurent42896a02019-09-27 15:40:33 -070026#include "debuggerd/handler.h"
Eric Laurent3528c932018-02-23 17:17:22 -080027
Andy Hung5c6d68a2022-03-09 21:54:59 -080028namespace android::mediautils {
Eric Laurent3528c932018-02-23 17:17:22 -080029
Andy Hunga2a1ac32022-03-18 16:12:11 -070030/**
31 * Returns the std::string "HH:MM:SS.MSc" from a system_clock time_point.
32 */
Ytai Ben-Tsvi34f26b12021-12-02 13:58:38 -080033std::string formatTime(std::chrono::system_clock::time_point t) {
Andy Hunga2a1ac32022-03-18 16:12:11 -070034 auto time_string = audio_utils_time_string_from_ns(
35 std::chrono::nanoseconds(t.time_since_epoch()).count());
36
37 // The time string is 19 characters (including null termination).
38 // Example: "03-27 16:47:06.187"
39 // MM DD HH MM SS MS
40 // We offset by 6 to get HH:MM:SS.MSc
41 //
42 return time_string.time + 6; // offset to remove month/day.
Ytai Ben-Tsvi34f26b12021-12-02 13:58:38 -080043}
44
Andy Hunga2a1ac32022-03-18 16:12:11 -070045/**
46 * Finds the end of the common time prefix.
47 *
48 * This is as an option to remove the common time prefix to avoid
49 * unnecessary duplicated strings.
50 *
51 * \param time1 a time string
52 * \param time2 a time string
53 * \return the position where the common time prefix ends. For abbreviated
54 * printing of time2, offset the character pointer by this position.
55 */
56static size_t commonTimePrefixPosition(std::string_view time1, std::string_view time2) {
57 const size_t endPos = std::min(time1.size(), time2.size());
58 size_t i;
59
60 // Find location of the first mismatch between strings
61 for (i = 0; ; ++i) {
62 if (i == endPos) {
63 return i; // strings match completely to the length of one of the strings.
64 }
65 if (time1[i] != time2[i]) {
66 break;
67 }
68 if (time1[i] == '\0') {
69 return i; // "printed" strings match completely. No need to check further.
70 }
71 }
72
73 // Go backwards until we find a delimeter or space.
74 for (; i > 0
75 && isdigit(time1[i]) // still a number
76 && time1[i - 1] != ' '
77 ; --i) {
78 }
79 return i;
80}
81
82/**
83 * Returns the unique suffix of time2 that isn't present in time1.
84 *
85 * If time2 is identical to time1, then an empty string_view is returned.
86 * This method is used to elide the common prefix when printing times.
87 */
88std::string_view timeSuffix(std::string_view time1, std::string_view time2) {
89 const size_t pos = commonTimePrefixPosition(time1, time2);
90 return time2.substr(pos);
91}
Ytai Ben-Tsvi34f26b12021-12-02 13:58:38 -080092
Eric Laurent42896a02019-09-27 15:40:33 -070093// Audio HAL server pids vector used to generate audio HAL processes tombstone
94// when audioserver watchdog triggers.
95// We use a lockless storage to avoid potential deadlocks in the context of watchdog
96// trigger.
97// Protection again simultaneous writes is not needed given one update takes place
98// during AudioFlinger construction and other comes necessarily later once the IAudioFlinger
99// interface is available.
100// The use of an atomic index just guaranties that current vector is fully initialized
101// when read.
102/* static */
103void TimeCheck::accessAudioHalPids(std::vector<pid_t>* pids, bool update) {
104 static constexpr int kNumAudioHalPidsVectors = 3;
105 static std::vector<pid_t> audioHalPids[kNumAudioHalPidsVectors];
Andy Hung5c6d68a2022-03-09 21:54:59 -0800106 static std::atomic<unsigned> curAudioHalPids = 0;
Eric Laurent42896a02019-09-27 15:40:33 -0700107
108 if (update) {
Eric Laurent1ad278b2021-03-05 18:09:01 +0100109 audioHalPids[(curAudioHalPids++ + 1) % kNumAudioHalPidsVectors] = *pids;
Eric Laurent42896a02019-09-27 15:40:33 -0700110 } else {
Eric Laurent1ad278b2021-03-05 18:09:01 +0100111 *pids = audioHalPids[curAudioHalPids % kNumAudioHalPidsVectors];
Eric Laurent42896a02019-09-27 15:40:33 -0700112 }
113}
114
115/* static */
116void TimeCheck::setAudioHalPids(const std::vector<pid_t>& pids) {
117 accessAudioHalPids(&(const_cast<std::vector<pid_t>&>(pids)), true);
118}
119
120/* static */
121std::vector<pid_t> TimeCheck::getAudioHalPids() {
122 std::vector<pid_t> pids;
123 accessAudioHalPids(&pids, false);
124 return pids;
125}
126
Eric Laurent3528c932018-02-23 17:17:22 -0800127/* static */
Andy Hung5c6d68a2022-03-09 21:54:59 -0800128TimerThread& TimeCheck::getTimeCheckThread() {
129 static TimerThread sTimeCheckThread{};
Eric Laurent3528c932018-02-23 17:17:22 -0800130 return sTimeCheckThread;
131}
132
Andy Hunga2a1ac32022-03-18 16:12:11 -0700133/* static */
134std::string TimeCheck::toString() {
135 // note pending and retired are individually locked for maximum concurrency,
136 // snapshot is not instantaneous at a single time.
137 return getTimeCheckThread().toString();
138}
139
Andy Hung5c6d68a2022-03-09 21:54:59 -0800140TimeCheck::TimeCheck(std::string tag, OnTimerFunc&& onTimer, uint32_t timeoutMs,
141 bool crashOnTimeout)
142 : mTimeCheckHandler(new TimeCheckHandler{
143 std::move(tag), std::move(onTimer), crashOnTimeout,
144 std::chrono::system_clock::now(), gettid()})
Andy Hunga2a1ac32022-03-18 16:12:11 -0700145 , mTimerHandle(timeoutMs == 0
146 ? getTimeCheckThread().trackTask(mTimeCheckHandler->tag)
147 : getTimeCheckThread().scheduleTask(
148 mTimeCheckHandler->tag,
149 // Pass in all the arguments by value to this task for safety.
150 // The thread could call the callback before the constructor is finished.
151 // The destructor is not blocked on callback.
152 [ timeCheckHandler = mTimeCheckHandler ] {
153 timeCheckHandler->onTimeout();
154 },
155 std::chrono::milliseconds(timeoutMs))) {}
Eric Laurent3528c932018-02-23 17:17:22 -0800156
157TimeCheck::~TimeCheck() {
Andy Hunga2a1ac32022-03-18 16:12:11 -0700158 if (mTimeCheckHandler) {
159 mTimeCheckHandler->onCancel(mTimerHandle);
160 }
Eric Laurent3528c932018-02-23 17:17:22 -0800161}
162
Andy Hung5c6d68a2022-03-09 21:54:59 -0800163void TimeCheck::TimeCheckHandler::onCancel(TimerThread::Handle timerHandle) const
164{
165 if (TimeCheck::getTimeCheckThread().cancelTask(timerHandle) && onTimer) {
166 const std::chrono::system_clock::time_point endTime = std::chrono::system_clock::now();
167 onTimer(false /* timeout */,
168 std::chrono::duration_cast<std::chrono::duration<float, std::milli>>(
169 endTime - startTime).count());
170 }
171}
172
173void TimeCheck::TimeCheckHandler::onTimeout() const
174{
175 const std::chrono::system_clock::time_point endTime = std::chrono::system_clock::now();
176 if (onTimer) {
177 onTimer(true /* timeout */,
178 std::chrono::duration_cast<std::chrono::duration<float, std::milli>>(
179 endTime - startTime).count());
180 }
181
182 if (!crashOnTimeout) return;
Ytai Ben-Tsvi34f26b12021-12-02 13:58:38 -0800183
Andy Hunga2a1ac32022-03-18 16:12:11 -0700184 // Generate the TimerThread summary string early before sending signals to the
185 // HAL processes which can affect thread behavior.
186 const std::string summary = getTimeCheckThread().toString(4 /* retiredCount */);
187
Ytai Ben-Tsvi1ea62c92021-11-10 14:38:27 -0800188 // Generate audio HAL processes tombstones and allow time to complete
189 // before forcing restart
Andy Hung5c6d68a2022-03-09 21:54:59 -0800190 std::vector<pid_t> pids = TimeCheck::getAudioHalPids();
Ytai Ben-Tsvi1ea62c92021-11-10 14:38:27 -0800191 if (pids.size() != 0) {
192 for (const auto& pid : pids) {
193 ALOGI("requesting tombstone for pid: %d", pid);
194 sigqueue(pid, DEBUGGER_SIGNAL, {.sival_int = 0});
Eric Laurent3528c932018-02-23 17:17:22 -0800195 }
Ytai Ben-Tsvi1ea62c92021-11-10 14:38:27 -0800196 sleep(1);
197 } else {
198 ALOGI("No HAL process pid available, skipping tombstones");
Eric Laurent39b09b52018-06-29 12:24:40 -0700199 }
Andy Hung5c6d68a2022-03-09 21:54:59 -0800200 LOG_EVENT_STRING(LOGTAG_AUDIO_BINDER_TIMEOUT, tag.c_str());
Andy Hunga2a1ac32022-03-18 16:12:11 -0700201 LOG_ALWAYS_FATAL("TimeCheck timeout for %s scheduled %s on thread %d\n%s",
202 tag.c_str(), formatTime(startTime).c_str(), tid, summary.c_str());
Eric Laurent3528c932018-02-23 17:17:22 -0800203}
204
Andy Hung224f82f2022-03-22 00:00:49 -0700205// Automatically create a TimeCheck class for a class and method.
206// This is used for Audio HIDL support.
207mediautils::TimeCheck makeTimeCheckStatsForClassMethod(
208 std::string_view className, std::string_view methodName) {
209 std::shared_ptr<MethodStatistics<std::string>> statistics =
210 mediautils::getStatisticsForClass(className);
211 if (!statistics) return {}; // empty TimeCheck.
212 return mediautils::TimeCheck(
213 std::string(className).append("::").append(methodName),
214 [ clazz = std::string(className), method = std::string(methodName),
215 stats = std::move(statistics) ]
216 (bool timeout, float elapsedMs) {
217 if (timeout) {
218 ; // ignored, there is no timeout value.
219 } else {
220 stats->event(method, elapsedMs);
221 }
222 }, 0 /* timeoutMs */);
223}
224
Andy Hung5c6d68a2022-03-09 21:54:59 -0800225} // namespace android::mediautils