blob: 75a1b22f2f3d71de9a35405fcc5937bf4b16df6c [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 Hung10ac7112022-03-28 08:00:40 -070021#include <android-base/logging.h>
Andy Hunga2a1ac32022-03-18 16:12:11 -070022#include <audio_utils/clock.h>
Marco Nelissencf90b492019-09-26 11:20:54 -070023#include <mediautils/EventLog.h>
Andy Hung224f82f2022-03-22 00:00:49 -070024#include <mediautils/MethodStatistics.h>
Ytai Ben-Tsvi1ea62c92021-11-10 14:38:27 -080025#include <mediautils/TimeCheck.h>
26#include <utils/Log.h>
Eric Laurent42896a02019-09-27 15:40:33 -070027#include "debuggerd/handler.h"
Eric Laurent3528c932018-02-23 17:17:22 -080028
Andy Hung5c6d68a2022-03-09 21:54:59 -080029namespace android::mediautils {
Eric Laurent3528c932018-02-23 17:17:22 -080030
Andy Hunga2a1ac32022-03-18 16:12:11 -070031/**
32 * Returns the std::string "HH:MM:SS.MSc" from a system_clock time_point.
33 */
Ytai Ben-Tsvi34f26b12021-12-02 13:58:38 -080034std::string formatTime(std::chrono::system_clock::time_point t) {
Andy Hunga2a1ac32022-03-18 16:12:11 -070035 auto time_string = audio_utils_time_string_from_ns(
36 std::chrono::nanoseconds(t.time_since_epoch()).count());
37
38 // The time string is 19 characters (including null termination).
39 // Example: "03-27 16:47:06.187"
40 // MM DD HH MM SS MS
41 // We offset by 6 to get HH:MM:SS.MSc
42 //
43 return time_string.time + 6; // offset to remove month/day.
Ytai Ben-Tsvi34f26b12021-12-02 13:58:38 -080044}
45
Andy Hunga2a1ac32022-03-18 16:12:11 -070046/**
47 * Finds the end of the common time prefix.
48 *
49 * This is as an option to remove the common time prefix to avoid
50 * unnecessary duplicated strings.
51 *
52 * \param time1 a time string
53 * \param time2 a time string
54 * \return the position where the common time prefix ends. For abbreviated
55 * printing of time2, offset the character pointer by this position.
56 */
57static size_t commonTimePrefixPosition(std::string_view time1, std::string_view time2) {
58 const size_t endPos = std::min(time1.size(), time2.size());
59 size_t i;
60
61 // Find location of the first mismatch between strings
62 for (i = 0; ; ++i) {
63 if (i == endPos) {
64 return i; // strings match completely to the length of one of the strings.
65 }
66 if (time1[i] != time2[i]) {
67 break;
68 }
69 if (time1[i] == '\0') {
70 return i; // "printed" strings match completely. No need to check further.
71 }
72 }
73
74 // Go backwards until we find a delimeter or space.
75 for (; i > 0
76 && isdigit(time1[i]) // still a number
77 && time1[i - 1] != ' '
78 ; --i) {
79 }
80 return i;
81}
82
83/**
84 * Returns the unique suffix of time2 that isn't present in time1.
85 *
86 * If time2 is identical to time1, then an empty string_view is returned.
87 * This method is used to elide the common prefix when printing times.
88 */
89std::string_view timeSuffix(std::string_view time1, std::string_view time2) {
90 const size_t pos = commonTimePrefixPosition(time1, time2);
91 return time2.substr(pos);
92}
Ytai Ben-Tsvi34f26b12021-12-02 13:58:38 -080093
Eric Laurent42896a02019-09-27 15:40:33 -070094// Audio HAL server pids vector used to generate audio HAL processes tombstone
95// when audioserver watchdog triggers.
96// We use a lockless storage to avoid potential deadlocks in the context of watchdog
97// trigger.
98// Protection again simultaneous writes is not needed given one update takes place
99// during AudioFlinger construction and other comes necessarily later once the IAudioFlinger
100// interface is available.
101// The use of an atomic index just guaranties that current vector is fully initialized
102// when read.
103/* static */
104void TimeCheck::accessAudioHalPids(std::vector<pid_t>* pids, bool update) {
105 static constexpr int kNumAudioHalPidsVectors = 3;
106 static std::vector<pid_t> audioHalPids[kNumAudioHalPidsVectors];
Andy Hung5c6d68a2022-03-09 21:54:59 -0800107 static std::atomic<unsigned> curAudioHalPids = 0;
Eric Laurent42896a02019-09-27 15:40:33 -0700108
109 if (update) {
Eric Laurent1ad278b2021-03-05 18:09:01 +0100110 audioHalPids[(curAudioHalPids++ + 1) % kNumAudioHalPidsVectors] = *pids;
Eric Laurent42896a02019-09-27 15:40:33 -0700111 } else {
Eric Laurent1ad278b2021-03-05 18:09:01 +0100112 *pids = audioHalPids[curAudioHalPids % kNumAudioHalPidsVectors];
Eric Laurent42896a02019-09-27 15:40:33 -0700113 }
114}
115
116/* static */
117void TimeCheck::setAudioHalPids(const std::vector<pid_t>& pids) {
118 accessAudioHalPids(&(const_cast<std::vector<pid_t>&>(pids)), true);
119}
120
121/* static */
122std::vector<pid_t> TimeCheck::getAudioHalPids() {
123 std::vector<pid_t> pids;
124 accessAudioHalPids(&pids, false);
125 return pids;
126}
127
Eric Laurent3528c932018-02-23 17:17:22 -0800128/* static */
Andy Hung5c6d68a2022-03-09 21:54:59 -0800129TimerThread& TimeCheck::getTimeCheckThread() {
130 static TimerThread sTimeCheckThread{};
Eric Laurent3528c932018-02-23 17:17:22 -0800131 return sTimeCheckThread;
132}
133
Andy Hunga2a1ac32022-03-18 16:12:11 -0700134/* static */
135std::string TimeCheck::toString() {
136 // note pending and retired are individually locked for maximum concurrency,
137 // snapshot is not instantaneous at a single time.
138 return getTimeCheckThread().toString();
139}
140
Andy Hung5c6d68a2022-03-09 21:54:59 -0800141TimeCheck::TimeCheck(std::string tag, OnTimerFunc&& onTimer, uint32_t timeoutMs,
142 bool crashOnTimeout)
143 : mTimeCheckHandler(new TimeCheckHandler{
144 std::move(tag), std::move(onTimer), crashOnTimeout,
145 std::chrono::system_clock::now(), gettid()})
Andy Hunga2a1ac32022-03-18 16:12:11 -0700146 , mTimerHandle(timeoutMs == 0
147 ? getTimeCheckThread().trackTask(mTimeCheckHandler->tag)
148 : getTimeCheckThread().scheduleTask(
149 mTimeCheckHandler->tag,
150 // Pass in all the arguments by value to this task for safety.
151 // The thread could call the callback before the constructor is finished.
152 // The destructor is not blocked on callback.
153 [ timeCheckHandler = mTimeCheckHandler ] {
154 timeCheckHandler->onTimeout();
155 },
156 std::chrono::milliseconds(timeoutMs))) {}
Eric Laurent3528c932018-02-23 17:17:22 -0800157
158TimeCheck::~TimeCheck() {
Andy Hunga2a1ac32022-03-18 16:12:11 -0700159 if (mTimeCheckHandler) {
160 mTimeCheckHandler->onCancel(mTimerHandle);
161 }
Eric Laurent3528c932018-02-23 17:17:22 -0800162}
163
Andy Hung5c6d68a2022-03-09 21:54:59 -0800164void TimeCheck::TimeCheckHandler::onCancel(TimerThread::Handle timerHandle) const
165{
166 if (TimeCheck::getTimeCheckThread().cancelTask(timerHandle) && onTimer) {
167 const std::chrono::system_clock::time_point endTime = std::chrono::system_clock::now();
168 onTimer(false /* timeout */,
169 std::chrono::duration_cast<std::chrono::duration<float, std::milli>>(
170 endTime - startTime).count());
171 }
172}
173
174void TimeCheck::TimeCheckHandler::onTimeout() const
175{
176 const std::chrono::system_clock::time_point endTime = std::chrono::system_clock::now();
177 if (onTimer) {
178 onTimer(true /* timeout */,
179 std::chrono::duration_cast<std::chrono::duration<float, std::milli>>(
180 endTime - startTime).count());
181 }
182
183 if (!crashOnTimeout) return;
Ytai Ben-Tsvi34f26b12021-12-02 13:58:38 -0800184
Andy Hunga2a1ac32022-03-18 16:12:11 -0700185 // Generate the TimerThread summary string early before sending signals to the
186 // HAL processes which can affect thread behavior.
187 const std::string summary = getTimeCheckThread().toString(4 /* retiredCount */);
188
Ytai Ben-Tsvi1ea62c92021-11-10 14:38:27 -0800189 // Generate audio HAL processes tombstones and allow time to complete
190 // before forcing restart
Andy Hung5c6d68a2022-03-09 21:54:59 -0800191 std::vector<pid_t> pids = TimeCheck::getAudioHalPids();
Ytai Ben-Tsvi1ea62c92021-11-10 14:38:27 -0800192 if (pids.size() != 0) {
193 for (const auto& pid : pids) {
194 ALOGI("requesting tombstone for pid: %d", pid);
195 sigqueue(pid, DEBUGGER_SIGNAL, {.sival_int = 0});
Eric Laurent3528c932018-02-23 17:17:22 -0800196 }
Ytai Ben-Tsvi1ea62c92021-11-10 14:38:27 -0800197 sleep(1);
198 } else {
199 ALOGI("No HAL process pid available, skipping tombstones");
Eric Laurent39b09b52018-06-29 12:24:40 -0700200 }
Andy Hungf45f34c2022-03-25 13:09:03 -0700201
Andy Hung5c6d68a2022-03-09 21:54:59 -0800202 LOG_EVENT_STRING(LOGTAG_AUDIO_BINDER_TIMEOUT, tag.c_str());
Andy Hung10ac7112022-03-28 08:00:40 -0700203
204 // Create abort message string - caution: this can be very large.
205 const std::string abortMessage = std::string("TimeCheck timeout for ")
206 .append(tag)
207 .append(" scheduled ").append(formatTime(startTime))
208 .append(" on thread ").append(std::to_string(tid)).append("\n")
209 .append(summary);
210
211 // Note: LOG_ALWAYS_FATAL limits the size of the string - per log/log.h:
212 // Log message text may be truncated to less than an
213 // implementation-specific limit (1023 bytes).
214 //
215 // Here, we send the string through android-base/logging.h LOG()
216 // to avoid the size limitation. LOG(FATAL) does an abort whereas
217 // LOG(FATAL_WITHOUT_ABORT) does not abort.
218
219 LOG(FATAL) << abortMessage;
Eric Laurent3528c932018-02-23 17:17:22 -0800220}
221
Andy Hung224f82f2022-03-22 00:00:49 -0700222// Automatically create a TimeCheck class for a class and method.
223// This is used for Audio HIDL support.
224mediautils::TimeCheck makeTimeCheckStatsForClassMethod(
225 std::string_view className, std::string_view methodName) {
226 std::shared_ptr<MethodStatistics<std::string>> statistics =
227 mediautils::getStatisticsForClass(className);
228 if (!statistics) return {}; // empty TimeCheck.
229 return mediautils::TimeCheck(
230 std::string(className).append("::").append(methodName),
231 [ clazz = std::string(className), method = std::string(methodName),
232 stats = std::move(statistics) ]
233 (bool timeout, float elapsedMs) {
234 if (timeout) {
235 ; // ignored, there is no timeout value.
236 } else {
237 stats->event(method, elapsedMs);
238 }
239 }, 0 /* timeoutMs */);
240}
241
Andy Hung5c6d68a2022-03-09 21:54:59 -0800242} // namespace android::mediautils