blob: 6de6b13518aebc0534c3e4c1c62fcc207181f90d [file] [log] [blame]
Ytai Ben-Tsvi1ea62c92021-11-10 14:38:27 -08001/*
2 * Copyright (C) 2021 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#define LOG_TAG "TimerThread"
18
19#include <optional>
Andy Hunga2a1ac32022-03-18 16:12:11 -070020#include <sstream>
21#include <unistd.h>
22#include <vector>
Ytai Ben-Tsvi1ea62c92021-11-10 14:38:27 -080023
Andy Hungd4265822022-04-01 18:54:32 -070024#include <mediautils/MediaUtilsDelayed.h>
Ytai Ben-Tsvi1ea62c92021-11-10 14:38:27 -080025#include <mediautils/TimerThread.h>
26#include <utils/ThreadDefs.h>
27
Andy Hunga2a1ac32022-03-18 16:12:11 -070028namespace android::mediautils {
Ytai Ben-Tsvi1ea62c92021-11-10 14:38:27 -080029
Andy Hunga2a1ac32022-03-18 16:12:11 -070030extern std::string formatTime(std::chrono::system_clock::time_point t);
31extern std::string_view timeSuffix(std::string_view time1, std::string_view time2);
32
33TimerThread::Handle TimerThread::scheduleTask(
34 std::string tag, std::function<void()>&& func, std::chrono::milliseconds timeout) {
35 const auto now = std::chrono::system_clock::now();
36 std::shared_ptr<const Request> request{
37 new Request{ now, now + timeout, gettid(), std::move(tag) }};
38 return mMonitorThread.add(std::move(request), std::move(func), timeout);
Ytai Ben-Tsvi1ea62c92021-11-10 14:38:27 -080039}
40
Andy Hunga2a1ac32022-03-18 16:12:11 -070041TimerThread::Handle TimerThread::trackTask(std::string tag) {
42 const auto now = std::chrono::system_clock::now();
43 std::shared_ptr<const Request> request{
44 new Request{ now, now, gettid(), std::move(tag) }};
45 return mNoTimeoutMap.add(std::move(request));
46}
47
48bool TimerThread::cancelTask(Handle handle) {
49 std::shared_ptr<const Request> request = mNoTimeoutMap.isValidHandle(handle) ?
50 mNoTimeoutMap.remove(handle) : mMonitorThread.remove(handle);
51 if (!request) return false;
52 mRetiredQueue.add(std::move(request));
53 return true;
54}
55
56std::string TimerThread::toString(size_t retiredCount) const {
Andy Hungf45f34c2022-03-25 13:09:03 -070057 // Note: These request queues are snapshot very close together but
58 // not at "identical" times as we don't use a class-wide lock.
59
60 std::vector<std::shared_ptr<const Request>> timeoutRequests;
61 std::vector<std::shared_ptr<const Request>> retiredRequests;
62 mTimeoutQueue.copyRequests(timeoutRequests);
63 mRetiredQueue.copyRequests(retiredRequests, retiredCount);
64 std::vector<std::shared_ptr<const Request>> pendingRequests =
65 getPendingRequests();
66
67 struct Analysis analysis = analyzeTimeout(timeoutRequests, pendingRequests);
68 std::string analysisSummary;
69 if (!analysis.summary.empty()) {
70 analysisSummary = std::string("\nanalysis [ ").append(analysis.summary).append(" ]");
71 }
Andy Hung10ac7112022-03-28 08:00:40 -070072 std::string timeoutStack;
73 if (analysis.timeoutTid != -1) {
74 timeoutStack = std::string("\ntimeout(")
75 .append(std::to_string(analysis.timeoutTid)).append(") callstack [\n")
Andy Hungd4265822022-04-01 18:54:32 -070076 .append(getCallStackStringForTid(analysis.timeoutTid)).append("]");
Andy Hung10ac7112022-03-28 08:00:40 -070077 }
78 std::string blockedStack;
79 if (analysis.HALBlockedTid != -1) {
80 blockedStack = std::string("\nblocked(")
81 .append(std::to_string(analysis.HALBlockedTid)).append(") callstack [\n")
Andy Hungd4265822022-04-01 18:54:32 -070082 .append(getCallStackStringForTid(analysis.HALBlockedTid)).append("]");
Andy Hung10ac7112022-03-28 08:00:40 -070083 }
84
Andy Hunga2a1ac32022-03-18 16:12:11 -070085 return std::string("now ")
86 .append(formatTime(std::chrono::system_clock::now()))
Andy Hungf45f34c2022-03-25 13:09:03 -070087 .append(analysisSummary)
88 .append("\ntimeout [ ")
89 .append(requestsToString(timeoutRequests))
90 .append(" ]\npending [ ")
91 .append(requestsToString(pendingRequests))
Andy Hunga2a1ac32022-03-18 16:12:11 -070092 .append(" ]\nretired [ ")
Andy Hungf45f34c2022-03-25 13:09:03 -070093 .append(requestsToString(retiredRequests))
Andy Hung10ac7112022-03-28 08:00:40 -070094 .append(" ]")
95 .append(timeoutStack)
96 .append(blockedStack);
Andy Hunga2a1ac32022-03-18 16:12:11 -070097}
98
Andy Hungf45f34c2022-03-25 13:09:03 -070099// A HAL method is where the substring "Hidl" is in the class name.
100// The tag should look like: ... Hidl ... :: ...
101// When the audio HAL is updated to AIDL perhaps we will use instead
102// a global directory of HAL classes.
103//
104// See MethodStatistics.cpp:
105// mediautils::getStatisticsClassesForModule(METHOD_STATISTICS_MODULE_NAME_AUDIO_HIDL)
106//
107/* static */
108bool TimerThread::isRequestFromHal(const std::shared_ptr<const Request>& request) {
109 const size_t hidlPos = request->tag.find("Hidl");
110 if (hidlPos == std::string::npos) return false;
111 // should be a separator afterwards Hidl which indicates the string was in the class.
112 const size_t separatorPos = request->tag.find("::", hidlPos);
113 return separatorPos != std::string::npos;
114}
115
116/* static */
117struct TimerThread::Analysis TimerThread::analyzeTimeout(
118 const std::vector<std::shared_ptr<const Request>>& timeoutRequests,
119 const std::vector<std::shared_ptr<const Request>>& pendingRequests) {
120
121 if (timeoutRequests.empty() || pendingRequests.empty()) return {}; // nothing to say.
122
123 // for now look at last timeout (in our case, the only timeout)
124 const std::shared_ptr<const Request> timeout = timeoutRequests.back();
125
126 // pending Requests that are problematic.
127 std::vector<std::shared_ptr<const Request>> pendingExact;
128 std::vector<std::shared_ptr<const Request>> pendingPossible;
129
130 // We look at pending requests that were scheduled no later than kDuration
131 // after the timeout request. This prevents false matches with calls
132 // that naturally block for a short period of time
133 // such as HAL write() and read().
134 //
135 auto constexpr kDuration = std::chrono::milliseconds(1000);
136 for (const auto& pending : pendingRequests) {
137 // If the pending tid is the same as timeout tid, problem identified.
138 if (pending->tid == timeout->tid) {
139 pendingExact.emplace_back(pending);
140 continue;
141 }
142
143 // if the pending tid is scheduled within time limit
144 if (pending->scheduled - timeout->scheduled < kDuration) {
145 pendingPossible.emplace_back(pending);
146 }
147 }
148
149 struct Analysis analysis{};
150
151 analysis.timeoutTid = timeout->tid;
152 std::string& summary = analysis.summary;
153 if (!pendingExact.empty()) {
154 const auto& request = pendingExact.front();
155 const bool hal = isRequestFromHal(request);
156
157 if (hal) {
158 summary = std::string("Blocked directly due to HAL call: ")
159 .append(request->toString());
160 }
161 }
162 if (summary.empty() && !pendingPossible.empty()) {
163 for (const auto& request : pendingPossible) {
164 const bool hal = isRequestFromHal(request);
165 if (hal) {
166 // The first blocked call is the most likely one.
167 // Recent calls might be temporarily blocked
168 // calls such as write() or read() depending on kDuration.
169 summary = std::string("Blocked possibly due to HAL call: ")
170 .append(request->toString());
171 analysis.HALBlockedTid = request->tid;
172 }
173 }
174 }
175 return analysis;
176}
177
Andy Hunga2a1ac32022-03-18 16:12:11 -0700178std::vector<std::shared_ptr<const TimerThread::Request>> TimerThread::getPendingRequests() const {
179 constexpr size_t kEstimatedPendingRequests = 8; // approx 128 byte alloc.
180 std::vector<std::shared_ptr<const Request>> pendingRequests;
181 pendingRequests.reserve(kEstimatedPendingRequests); // preallocate vector out of lock.
182
183 // following are internally locked calls, which add to our local pendingRequests.
184 mMonitorThread.copyRequests(pendingRequests);
185 mNoTimeoutMap.copyRequests(pendingRequests);
186
187 // Sort in order of scheduled time.
188 std::sort(pendingRequests.begin(), pendingRequests.end(),
189 [](const std::shared_ptr<const Request>& r1,
190 const std::shared_ptr<const Request>& r2) {
191 return r1->scheduled < r2->scheduled;
192 });
193 return pendingRequests;
194}
195
196std::string TimerThread::pendingToString() const {
197 return requestsToString(getPendingRequests());
198}
199
200std::string TimerThread::retiredToString(size_t n) const {
201 std::vector<std::shared_ptr<const Request>> retiredRequests;
202 mRetiredQueue.copyRequests(retiredRequests, n);
203
204 // Dump to string
205 return requestsToString(retiredRequests);
206}
207
208std::string TimerThread::timeoutToString(size_t n) const {
209 std::vector<std::shared_ptr<const Request>> timeoutRequests;
210 mTimeoutQueue.copyRequests(timeoutRequests, n);
211
212 // Dump to string
213 return requestsToString(timeoutRequests);
214}
215
216std::string TimerThread::Request::toString() const {
217 const auto scheduledString = formatTime(scheduled);
218 const auto deadlineString = formatTime(deadline);
219 return std::string(tag)
220 .append(" scheduled ").append(scheduledString)
221 .append(" deadline ").append(timeSuffix(scheduledString, deadlineString))
222 .append(" tid ").append(std::to_string(tid));
223}
224
225void TimerThread::RequestQueue::add(std::shared_ptr<const Request> request) {
226 std::lock_guard lg(mRQMutex);
227 mRequestQueue.emplace_back(std::chrono::system_clock::now(), std::move(request));
228 if (mRequestQueue.size() > mRequestQueueMax) {
229 mRequestQueue.pop_front();
230 }
231}
232
233void TimerThread::RequestQueue::copyRequests(
234 std::vector<std::shared_ptr<const Request>>& requests, size_t n) const {
235 std::lock_guard lg(mRQMutex);
236 const size_t size = mRequestQueue.size();
237 size_t i = n >= size ? 0 : size - n;
238 for (; i < size; ++i) {
239 const auto &[time, request] = mRequestQueue[i];
240 requests.emplace_back(request);
241 }
242}
243
244bool TimerThread::NoTimeoutMap::isValidHandle(Handle handle) const {
245 return handle > getIndexedHandle(mNoTimeoutRequests);
246}
247
248TimerThread::Handle TimerThread::NoTimeoutMap::add(std::shared_ptr<const Request> request) {
249 std::lock_guard lg(mNTMutex);
250 // A unique handle is obtained by mNoTimeoutRequests.fetch_add(1),
251 // This need not be under a lock, but we do so anyhow.
252 const Handle handle = getIndexedHandle(mNoTimeoutRequests++);
253 mMap[handle] = request;
254 return handle;
255}
256
257std::shared_ptr<const TimerThread::Request> TimerThread::NoTimeoutMap::remove(Handle handle) {
258 std::lock_guard lg(mNTMutex);
259 auto it = mMap.find(handle);
260 if (it == mMap.end()) return {};
261 auto request = it->second;
262 mMap.erase(it);
263 return request;
264}
265
266void TimerThread::NoTimeoutMap::copyRequests(
267 std::vector<std::shared_ptr<const Request>>& requests) const {
268 std::lock_guard lg(mNTMutex);
269 for (const auto &[handle, request] : mMap) {
270 requests.emplace_back(request);
271 }
272}
273
274TimerThread::Handle TimerThread::MonitorThread::getUniqueHandle_l(
275 std::chrono::milliseconds timeout) {
276 // To avoid key collisions, advance by 1 tick until the key is unique.
277 auto deadline = std::chrono::steady_clock::now() + timeout;
278 for (; mMonitorRequests.find(deadline) != mMonitorRequests.end();
279 deadline += std::chrono::steady_clock::duration(1))
280 ;
281 return deadline;
282}
283
284TimerThread::MonitorThread::MonitorThread(RequestQueue& timeoutQueue)
285 : mTimeoutQueue(timeoutQueue)
286 , mThread([this] { threadFunc(); }) {
287 pthread_setname_np(mThread.native_handle(), "TimerThread");
288 pthread_setschedprio(mThread.native_handle(), PRIORITY_URGENT_AUDIO);
289}
290
291TimerThread::MonitorThread::~MonitorThread() {
Ytai Ben-Tsvi1ea62c92021-11-10 14:38:27 -0800292 {
293 std::lock_guard _l(mMutex);
294 mShouldExit = true;
295 mCond.notify_all();
296 }
297 mThread.join();
298}
299
Andy Hunga2a1ac32022-03-18 16:12:11 -0700300void TimerThread::MonitorThread::threadFunc() {
Ytai Ben-Tsvi1ea62c92021-11-10 14:38:27 -0800301 std::unique_lock _l(mMutex);
Ytai Ben-Tsvi1ea62c92021-11-10 14:38:27 -0800302 while (!mShouldExit) {
303 if (!mMonitorRequests.empty()) {
Andy Hunga2a1ac32022-03-18 16:12:11 -0700304 Handle nextDeadline = mMonitorRequests.begin()->first;
Ytai Ben-Tsvi1ea62c92021-11-10 14:38:27 -0800305 if (nextDeadline < std::chrono::steady_clock::now()) {
Andy Hunga2a1ac32022-03-18 16:12:11 -0700306 // Deadline has expired, handle the request.
307 {
308 auto node = mMonitorRequests.extract(mMonitorRequests.begin());
309 _l.unlock();
310 // We add Request to retired queue early so that it can be dumped out.
311 mTimeoutQueue.add(std::move(node.mapped().first));
312 node.mapped().second(); // Caution: we don't hold lock here - but do we care?
313 // this is the timeout case! We will crash soon,
314 // maybe before returning.
315 // anything left over is released here outside lock.
316 }
317 // reacquire the lock - if something was added, we loop immediately to check.
318 _l.lock();
319 continue;
Ytai Ben-Tsvi1ea62c92021-11-10 14:38:27 -0800320 }
321 mCond.wait_until(_l, nextDeadline);
322 } else {
323 mCond.wait(_l);
324 }
325 }
326}
327
Andy Hunga2a1ac32022-03-18 16:12:11 -0700328TimerThread::Handle TimerThread::MonitorThread::add(
329 std::shared_ptr<const Request> request, std::function<void()>&& func,
330 std::chrono::milliseconds timeout) {
331 std::lock_guard _l(mMutex);
332 const Handle handle = getUniqueHandle_l(timeout);
333 mMonitorRequests.emplace(handle, std::make_pair(std::move(request), std::move(func)));
334 mCond.notify_all();
335 return handle;
336}
337
338std::shared_ptr<const TimerThread::Request> TimerThread::MonitorThread::remove(Handle handle) {
339 std::unique_lock ul(mMutex);
340 const auto it = mMonitorRequests.find(handle);
341 if (it == mMonitorRequests.end()) {
342 return {};
343 }
344 std::shared_ptr<const TimerThread::Request> request = std::move(it->second.first);
345 std::function<void()> func = std::move(it->second.second);
346 mMonitorRequests.erase(it);
347 ul.unlock(); // manually release lock here so func is released outside of lock.
348 return request;
349}
350
351void TimerThread::MonitorThread::copyRequests(
352 std::vector<std::shared_ptr<const Request>>& requests) const {
353 std::lock_guard lg(mMutex);
354 for (const auto &[deadline, monitorpair] : mMonitorRequests) {
355 requests.emplace_back(monitorpair.first);
356 }
357}
358
359} // namespace android::mediautils