blob: ad27af391c37a8450c986f5b064e666c856107f3 [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 Hung4c544c32023-11-03 15:56:24 -070024#include <audio_utils/mutex.h>
Andy Hungd4265822022-04-01 18:54:32 -070025#include <mediautils/MediaUtilsDelayed.h>
Atneya Nairf5b68512022-05-23 20:02:49 -040026#include <mediautils/TidWrapper.h>
Ytai Ben-Tsvi1ea62c92021-11-10 14:38:27 -080027#include <mediautils/TimerThread.h>
Andy Hungf8ab0932022-06-13 19:49:43 -070028#include <utils/Log.h>
Ytai Ben-Tsvi1ea62c92021-11-10 14:38:27 -080029#include <utils/ThreadDefs.h>
30
Andy Hung2aa15102022-06-13 19:49:43 -070031using namespace std::chrono_literals;
32
Andy Hunga2a1ac32022-03-18 16:12:11 -070033namespace android::mediautils {
Ytai Ben-Tsvi1ea62c92021-11-10 14:38:27 -080034
Andy Hunga2a1ac32022-03-18 16:12:11 -070035extern std::string formatTime(std::chrono::system_clock::time_point t);
36extern std::string_view timeSuffix(std::string_view time1, std::string_view time2);
37
38TimerThread::Handle TimerThread::scheduleTask(
Andy Hungf8ab0932022-06-13 19:49:43 -070039 std::string_view tag, TimerCallback&& func,
40 Duration timeoutDuration, Duration secondChanceDuration) {
Andy Hunga2a1ac32022-03-18 16:12:11 -070041 const auto now = std::chrono::system_clock::now();
Andy Hung2aa15102022-06-13 19:49:43 -070042 auto request = std::make_shared<const Request>(now, now +
43 std::chrono::duration_cast<std::chrono::system_clock::duration>(timeoutDuration),
Atneya Nairf5b68512022-05-23 20:02:49 -040044 secondChanceDuration, getThreadIdWrapper(), tag);
Andy Hung2aa15102022-06-13 19:49:43 -070045 return mMonitorThread.add(std::move(request), std::move(func), timeoutDuration);
Ytai Ben-Tsvi1ea62c92021-11-10 14:38:27 -080046}
47
Andy Hung35f96152022-07-15 15:18:59 -070048TimerThread::Handle TimerThread::trackTask(std::string_view tag) {
Andy Hunga2a1ac32022-03-18 16:12:11 -070049 const auto now = std::chrono::system_clock::now();
Andy Hungf8ab0932022-06-13 19:49:43 -070050 auto request = std::make_shared<const Request>(now, now,
Atneya Nairf5b68512022-05-23 20:02:49 -040051 Duration{} /* secondChanceDuration */, getThreadIdWrapper(), tag);
Andy Hunga2a1ac32022-03-18 16:12:11 -070052 return mNoTimeoutMap.add(std::move(request));
53}
54
55bool TimerThread::cancelTask(Handle handle) {
Andy Hung2aa15102022-06-13 19:49:43 -070056 std::shared_ptr<const Request> request = isNoTimeoutHandle(handle) ?
Andy Hunga2a1ac32022-03-18 16:12:11 -070057 mNoTimeoutMap.remove(handle) : mMonitorThread.remove(handle);
58 if (!request) return false;
59 mRetiredQueue.add(std::move(request));
60 return true;
61}
62
Andy Hung4c544c32023-11-03 15:56:24 -070063std::string TimerThread::SnapshotAnalysis::toString(bool showTimeoutStack) const {
Andy Hungf45f34c2022-03-25 13:09:03 -070064 // Note: These request queues are snapshot very close together but
65 // not at "identical" times as we don't use a class-wide lock.
Atneya Naircce14202022-09-05 20:17:50 -070066 std::string analysisSummary = std::string("\nanalysis [ ").append(description).append(" ]");
Andy Hung10ac7112022-03-28 08:00:40 -070067 std::string timeoutStack;
Andy Hung10ac7112022-03-28 08:00:40 -070068 std::string blockedStack;
Andy Hung4c544c32023-11-03 15:56:24 -070069 std::string mutexWaitChainStack;
70 if (showTimeoutStack && timeoutTid != -1) {
Atneya Naircce14202022-09-05 20:17:50 -070071 timeoutStack = std::string(suspectTid == timeoutTid ? "\ntimeout/blocked(" : "\ntimeout(")
72 .append(std::to_string(timeoutTid)).append(") callstack [\n")
73 .append(getCallStackStringForTid(timeoutTid)).append("]");
74 }
75
76 if (suspectTid != -1 && suspectTid != timeoutTid) {
Andy Hung10ac7112022-03-28 08:00:40 -070077 blockedStack = std::string("\nblocked(")
Atneya Naircce14202022-09-05 20:17:50 -070078 .append(std::to_string(suspectTid)).append(") callstack [\n")
79 .append(getCallStackStringForTid(suspectTid)).append("]");
Andy Hung10ac7112022-03-28 08:00:40 -070080 }
81
Andy Hung4c544c32023-11-03 15:56:24 -070082 if (!mutexWaitChain.empty()) {
83 mutexWaitChainStack.append("\nmutex wait chain [\n");
84 // the wait chain omits the initial timeout tid (which is good as we don't
85 // need to suppress it).
86 for (size_t i = 0; i < mutexWaitChain.size(); ++i) {
87 const auto& [tid, name] = mutexWaitChain[i];
88 mutexWaitChainStack.append("{ tid: ").append(std::to_string(tid))
89 .append(" (holding ").append(name).append(")");
90 if (tid == timeoutTid) {
91 mutexWaitChainStack.append(" TIMEOUT_STACK }\n");
92 } else if (tid == suspectTid) {
93 mutexWaitChainStack.append(" BLOCKED_STACK }\n");
94 } else if (hasMutexCycle && i == mutexWaitChain.size() - 1) {
95 // for a cycle, the last pid in the chain is repeated.
96 mutexWaitChainStack.append(" CYCLE_STACK }\n");
97 } else {
98 mutexWaitChainStack.append(" callstack [\n")
99 .append(getCallStackStringForTid(tid)).append("] }\n");
100 }
101 }
102 mutexWaitChainStack.append("]");
103 }
104
Andy Hunga2a1ac32022-03-18 16:12:11 -0700105 return std::string("now ")
106 .append(formatTime(std::chrono::system_clock::now()))
Andy Hungf8ab0932022-06-13 19:49:43 -0700107 .append("\nsecondChanceCount ")
Atneya Naircce14202022-09-05 20:17:50 -0700108 .append(std::to_string(secondChanceCount))
Andy Hungf45f34c2022-03-25 13:09:03 -0700109 .append(analysisSummary)
110 .append("\ntimeout [ ")
111 .append(requestsToString(timeoutRequests))
112 .append(" ]\npending [ ")
113 .append(requestsToString(pendingRequests))
Andy Hunga2a1ac32022-03-18 16:12:11 -0700114 .append(" ]\nretired [ ")
Andy Hungf45f34c2022-03-25 13:09:03 -0700115 .append(requestsToString(retiredRequests))
Andy Hung10ac7112022-03-28 08:00:40 -0700116 .append(" ]")
117 .append(timeoutStack)
Andy Hung4c544c32023-11-03 15:56:24 -0700118 .append(blockedStack)
119 .append(mutexWaitChainStack);
Andy Hunga2a1ac32022-03-18 16:12:11 -0700120}
121
Andy Hungf45f34c2022-03-25 13:09:03 -0700122// A HAL method is where the substring "Hidl" is in the class name.
123// The tag should look like: ... Hidl ... :: ...
124// When the audio HAL is updated to AIDL perhaps we will use instead
125// a global directory of HAL classes.
126//
127// See MethodStatistics.cpp:
128// mediautils::getStatisticsClassesForModule(METHOD_STATISTICS_MODULE_NAME_AUDIO_HIDL)
129//
130/* static */
131bool TimerThread::isRequestFromHal(const std::shared_ptr<const Request>& request) {
Andy Hung35f96152022-07-15 15:18:59 -0700132 const size_t hidlPos = request->tag.asStringView().find("Hidl");
Andy Hungf45f34c2022-03-25 13:09:03 -0700133 if (hidlPos == std::string::npos) return false;
134 // should be a separator afterwards Hidl which indicates the string was in the class.
Andy Hung35f96152022-07-15 15:18:59 -0700135 const size_t separatorPos = request->tag.asStringView().find("::", hidlPos);
Andy Hungf45f34c2022-03-25 13:09:03 -0700136 return separatorPos != std::string::npos;
137}
138
Atneya Naircce14202022-09-05 20:17:50 -0700139struct TimerThread::SnapshotAnalysis TimerThread::getSnapshotAnalysis(size_t retiredCount) const {
140 struct SnapshotAnalysis analysis{};
141 // The following snapshot of the TimerThread state will be utilized for
142 // analysis. Note, there is no lock around these calls, so there could be
143 // a state update between them.
144 mTimeoutQueue.copyRequests(analysis.timeoutRequests);
145 mRetiredQueue.copyRequests(analysis.retiredRequests, retiredCount);
146 analysis.pendingRequests = getPendingRequests();
147 analysis.secondChanceCount = mMonitorThread.getSecondChanceCount();
148 // No call has timed out, so there is no analysis to be done.
Andy Hung4c544c32023-11-03 15:56:24 -0700149 if (analysis.timeoutRequests.empty()) {
Atneya Naircce14202022-09-05 20:17:50 -0700150 return analysis;
Andy Hung4c544c32023-11-03 15:56:24 -0700151 }
152
Andy Hungf45f34c2022-03-25 13:09:03 -0700153 // for now look at last timeout (in our case, the only timeout)
Atneya Naircce14202022-09-05 20:17:50 -0700154 const std::shared_ptr<const Request> timeout = analysis.timeoutRequests.back();
155 analysis.timeoutTid = timeout->tid;
Andy Hung4c544c32023-11-03 15:56:24 -0700156
157 std::string& description = analysis.description;
158
159 // audio mutex specific wait chain analysis
160 auto deadlockInfo = audio_utils::mutex::deadlock_detection(analysis.timeoutTid);
161 ALOGD("%s: deadlockInfo: %s", __func__, deadlockInfo.to_string().c_str());
162
163 if (!deadlockInfo.empty()) {
164 if (!description.empty()) description.append("\n");
165 description.append(deadlockInfo.to_string());
166 }
167
168 analysis.hasMutexCycle = deadlockInfo.has_cycle;
169 analysis.mutexWaitChain = std::move(deadlockInfo.chain);
170
171 // no pending requests, we don't attempt to use temporal correlation between a recent call.
172 if (analysis.pendingRequests.empty()) {
173 return analysis;
174 }
175
Andy Hungf45f34c2022-03-25 13:09:03 -0700176 // pending Requests that are problematic.
177 std::vector<std::shared_ptr<const Request>> pendingExact;
178 std::vector<std::shared_ptr<const Request>> pendingPossible;
179
Andy Hung2aa15102022-06-13 19:49:43 -0700180 // We look at pending requests that were scheduled no later than kPendingDuration
Andy Hungf45f34c2022-03-25 13:09:03 -0700181 // after the timeout request. This prevents false matches with calls
182 // that naturally block for a short period of time
183 // such as HAL write() and read().
184 //
Andy Hung2aa15102022-06-13 19:49:43 -0700185 constexpr Duration kPendingDuration = 1000ms;
Atneya Naircce14202022-09-05 20:17:50 -0700186 for (const auto& pending : analysis.pendingRequests) {
Andy Hungf45f34c2022-03-25 13:09:03 -0700187 // If the pending tid is the same as timeout tid, problem identified.
188 if (pending->tid == timeout->tid) {
189 pendingExact.emplace_back(pending);
190 continue;
191 }
192
193 // if the pending tid is scheduled within time limit
Andy Hung2aa15102022-06-13 19:49:43 -0700194 if (pending->scheduled - timeout->scheduled < kPendingDuration) {
Andy Hungf45f34c2022-03-25 13:09:03 -0700195 pendingPossible.emplace_back(pending);
196 }
197 }
198
Andy Hungf45f34c2022-03-25 13:09:03 -0700199 if (!pendingExact.empty()) {
200 const auto& request = pendingExact.front();
201 const bool hal = isRequestFromHal(request);
202
203 if (hal) {
Andy Hung4c544c32023-11-03 15:56:24 -0700204 if (!description.empty()) description.append("\n");
205 description.append("Blocked directly due to HAL call: ")
Andy Hungf45f34c2022-03-25 13:09:03 -0700206 .append(request->toString());
Andy Hung4c544c32023-11-03 15:56:24 -0700207 analysis.suspectTid = request->tid;
Andy Hungf45f34c2022-03-25 13:09:03 -0700208 }
209 }
Atneya Naircce14202022-09-05 20:17:50 -0700210 if (description.empty() && !pendingPossible.empty()) {
Andy Hungf45f34c2022-03-25 13:09:03 -0700211 for (const auto& request : pendingPossible) {
212 const bool hal = isRequestFromHal(request);
213 if (hal) {
214 // The first blocked call is the most likely one.
215 // Recent calls might be temporarily blocked
216 // calls such as write() or read() depending on kDuration.
Atneya Naircce14202022-09-05 20:17:50 -0700217 description = std::string("Blocked possibly due to HAL call: ")
Andy Hungf45f34c2022-03-25 13:09:03 -0700218 .append(request->toString());
Atneya Naircce14202022-09-05 20:17:50 -0700219 analysis.suspectTid= request->tid;
Andy Hungf45f34c2022-03-25 13:09:03 -0700220 }
221 }
222 }
223 return analysis;
224}
225
Andy Hunga2a1ac32022-03-18 16:12:11 -0700226std::vector<std::shared_ptr<const TimerThread::Request>> TimerThread::getPendingRequests() const {
227 constexpr size_t kEstimatedPendingRequests = 8; // approx 128 byte alloc.
228 std::vector<std::shared_ptr<const Request>> pendingRequests;
229 pendingRequests.reserve(kEstimatedPendingRequests); // preallocate vector out of lock.
230
231 // following are internally locked calls, which add to our local pendingRequests.
232 mMonitorThread.copyRequests(pendingRequests);
233 mNoTimeoutMap.copyRequests(pendingRequests);
234
235 // Sort in order of scheduled time.
236 std::sort(pendingRequests.begin(), pendingRequests.end(),
237 [](const std::shared_ptr<const Request>& r1,
238 const std::shared_ptr<const Request>& r2) {
239 return r1->scheduled < r2->scheduled;
240 });
241 return pendingRequests;
242}
243
244std::string TimerThread::pendingToString() const {
245 return requestsToString(getPendingRequests());
246}
247
248std::string TimerThread::retiredToString(size_t n) const {
249 std::vector<std::shared_ptr<const Request>> retiredRequests;
250 mRetiredQueue.copyRequests(retiredRequests, n);
251
252 // Dump to string
253 return requestsToString(retiredRequests);
254}
255
256std::string TimerThread::timeoutToString(size_t n) const {
257 std::vector<std::shared_ptr<const Request>> timeoutRequests;
258 mTimeoutQueue.copyRequests(timeoutRequests, n);
259
260 // Dump to string
261 return requestsToString(timeoutRequests);
262}
263
264std::string TimerThread::Request::toString() const {
265 const auto scheduledString = formatTime(scheduled);
266 const auto deadlineString = formatTime(deadline);
267 return std::string(tag)
268 .append(" scheduled ").append(scheduledString)
269 .append(" deadline ").append(timeSuffix(scheduledString, deadlineString))
270 .append(" tid ").append(std::to_string(tid));
271}
272
273void TimerThread::RequestQueue::add(std::shared_ptr<const Request> request) {
274 std::lock_guard lg(mRQMutex);
275 mRequestQueue.emplace_back(std::chrono::system_clock::now(), std::move(request));
276 if (mRequestQueue.size() > mRequestQueueMax) {
277 mRequestQueue.pop_front();
278 }
279}
280
281void TimerThread::RequestQueue::copyRequests(
282 std::vector<std::shared_ptr<const Request>>& requests, size_t n) const {
283 std::lock_guard lg(mRQMutex);
284 const size_t size = mRequestQueue.size();
285 size_t i = n >= size ? 0 : size - n;
286 for (; i < size; ++i) {
287 const auto &[time, request] = mRequestQueue[i];
288 requests.emplace_back(request);
289 }
290}
291
Andy Hunga2a1ac32022-03-18 16:12:11 -0700292TimerThread::Handle TimerThread::NoTimeoutMap::add(std::shared_ptr<const Request> request) {
293 std::lock_guard lg(mNTMutex);
294 // A unique handle is obtained by mNoTimeoutRequests.fetch_add(1),
295 // This need not be under a lock, but we do so anyhow.
Andy Hung2aa15102022-06-13 19:49:43 -0700296 const Handle handle = getUniqueHandle_l();
Andy Hunga2a1ac32022-03-18 16:12:11 -0700297 mMap[handle] = request;
298 return handle;
299}
300
301std::shared_ptr<const TimerThread::Request> TimerThread::NoTimeoutMap::remove(Handle handle) {
302 std::lock_guard lg(mNTMutex);
303 auto it = mMap.find(handle);
304 if (it == mMap.end()) return {};
305 auto request = it->second;
306 mMap.erase(it);
307 return request;
308}
309
310void TimerThread::NoTimeoutMap::copyRequests(
311 std::vector<std::shared_ptr<const Request>>& requests) const {
312 std::lock_guard lg(mNTMutex);
313 for (const auto &[handle, request] : mMap) {
314 requests.emplace_back(request);
315 }
316}
317
Andy Hunga2a1ac32022-03-18 16:12:11 -0700318TimerThread::MonitorThread::MonitorThread(RequestQueue& timeoutQueue)
319 : mTimeoutQueue(timeoutQueue)
320 , mThread([this] { threadFunc(); }) {
321 pthread_setname_np(mThread.native_handle(), "TimerThread");
322 pthread_setschedprio(mThread.native_handle(), PRIORITY_URGENT_AUDIO);
323}
324
325TimerThread::MonitorThread::~MonitorThread() {
Ytai Ben-Tsvi1ea62c92021-11-10 14:38:27 -0800326 {
327 std::lock_guard _l(mMutex);
328 mShouldExit = true;
329 mCond.notify_all();
330 }
331 mThread.join();
332}
333
Andy Hunga2a1ac32022-03-18 16:12:11 -0700334void TimerThread::MonitorThread::threadFunc() {
Ytai Ben-Tsvi1ea62c92021-11-10 14:38:27 -0800335 std::unique_lock _l(mMutex);
Shunkai Yao7bf9e7c2023-02-08 18:55:17 +0000336 ::android::base::ScopedLockAssertion lock_assertion(mMutex);
Ytai Ben-Tsvi1ea62c92021-11-10 14:38:27 -0800337 while (!mShouldExit) {
Andy Hungf8ab0932022-06-13 19:49:43 -0700338 Handle nextDeadline = INVALID_HANDLE;
339 Handle now = INVALID_HANDLE;
Ytai Ben-Tsvi1ea62c92021-11-10 14:38:27 -0800340 if (!mMonitorRequests.empty()) {
Andy Hungf8ab0932022-06-13 19:49:43 -0700341 nextDeadline = mMonitorRequests.begin()->first;
342 now = std::chrono::steady_clock::now();
343 if (nextDeadline < now) {
344 auto node = mMonitorRequests.extract(mMonitorRequests.begin());
Andy Hunga2a1ac32022-03-18 16:12:11 -0700345 // Deadline has expired, handle the request.
Andy Hungf8ab0932022-06-13 19:49:43 -0700346 auto secondChanceDuration = node.mapped().first->secondChanceDuration;
347 if (secondChanceDuration.count() != 0) {
348 // We now apply the second chance duration to find the clock
349 // monotonic second deadline. The unique key is then the
350 // pair<second_deadline, first_deadline>.
351 //
352 // The second chance prevents a false timeout should there be
353 // any clock monotonic advancement during suspend.
354 auto newHandle = now + secondChanceDuration;
355 ALOGD("%s: TimeCheck second chance applied for %s",
356 __func__, node.mapped().first->tag.c_str()); // should be rare event.
357 mSecondChanceRequests.emplace_hint(mSecondChanceRequests.end(),
358 std::make_pair(newHandle, nextDeadline),
359 std::move(node.mapped()));
360 // increment second chance counter.
361 mSecondChanceCount.fetch_add(1 /* arg */, std::memory_order_relaxed);
362 } else {
363 {
364 _l.unlock();
365 // We add Request to retired queue early so that it can be dumped out.
366 mTimeoutQueue.add(std::move(node.mapped().first));
367 node.mapped().second(nextDeadline);
368 // Caution: we don't hold lock when we call TimerCallback,
369 // but this is the timeout case! We will crash soon,
370 // maybe before returning.
371 // anything left over is released here outside lock.
372 }
373 // reacquire the lock - if something was added, we loop immediately to check.
374 _l.lock();
375 }
376 // always process expiring monitor requests first.
377 continue;
378 }
379 }
380 // now process any second chance requests.
381 if (!mSecondChanceRequests.empty()) {
382 Handle secondDeadline = mSecondChanceRequests.begin()->first.first;
383 if (now == INVALID_HANDLE) now = std::chrono::steady_clock::now();
384 if (secondDeadline < now) {
385 auto node = mSecondChanceRequests.extract(mSecondChanceRequests.begin());
Andy Hunga2a1ac32022-03-18 16:12:11 -0700386 {
Andy Hunga2a1ac32022-03-18 16:12:11 -0700387 _l.unlock();
388 // We add Request to retired queue early so that it can be dumped out.
389 mTimeoutQueue.add(std::move(node.mapped().first));
Andy Hungf8ab0932022-06-13 19:49:43 -0700390 const Handle originalHandle = node.key().second;
391 node.mapped().second(originalHandle);
Andy Hung2aa15102022-06-13 19:49:43 -0700392 // Caution: we don't hold lock when we call TimerCallback.
393 // This is benign issue - we permit concurrent operations
394 // while in the callback to the MonitorQueue.
395 //
396 // Anything left over is released here outside lock.
Andy Hunga2a1ac32022-03-18 16:12:11 -0700397 }
398 // reacquire the lock - if something was added, we loop immediately to check.
399 _l.lock();
400 continue;
Ytai Ben-Tsvi1ea62c92021-11-10 14:38:27 -0800401 }
Andy Hungf8ab0932022-06-13 19:49:43 -0700402 // update the deadline.
403 if (nextDeadline == INVALID_HANDLE) {
404 nextDeadline = secondDeadline;
405 } else {
406 nextDeadline = std::min(nextDeadline, secondDeadline);
407 }
408 }
409 if (nextDeadline != INVALID_HANDLE) {
Ytai Ben-Tsvi1ea62c92021-11-10 14:38:27 -0800410 mCond.wait_until(_l, nextDeadline);
411 } else {
412 mCond.wait(_l);
413 }
414 }
415}
416
Andy Hunga2a1ac32022-03-18 16:12:11 -0700417TimerThread::Handle TimerThread::MonitorThread::add(
Andy Hung2aa15102022-06-13 19:49:43 -0700418 std::shared_ptr<const Request> request, TimerCallback&& func, Duration timeout) {
Andy Hunga2a1ac32022-03-18 16:12:11 -0700419 std::lock_guard _l(mMutex);
420 const Handle handle = getUniqueHandle_l(timeout);
Andy Hungf8ab0932022-06-13 19:49:43 -0700421 mMonitorRequests.emplace_hint(mMonitorRequests.end(),
422 handle, std::make_pair(std::move(request), std::move(func)));
Andy Hunga2a1ac32022-03-18 16:12:11 -0700423 mCond.notify_all();
424 return handle;
425}
426
427std::shared_ptr<const TimerThread::Request> TimerThread::MonitorThread::remove(Handle handle) {
Andy Hungf8ab0932022-06-13 19:49:43 -0700428 std::pair<std::shared_ptr<const Request>, TimerCallback> data;
Andy Hunga2a1ac32022-03-18 16:12:11 -0700429 std::unique_lock ul(mMutex);
Shunkai Yao7bf9e7c2023-02-08 18:55:17 +0000430 ::android::base::ScopedLockAssertion lock_assertion(mMutex);
Andy Hungf8ab0932022-06-13 19:49:43 -0700431 if (const auto it = mMonitorRequests.find(handle);
432 it != mMonitorRequests.end()) {
433 data = std::move(it->second);
434 mMonitorRequests.erase(it);
435 ul.unlock(); // manually release lock here so func (data.second)
436 // is released outside of lock.
437 return data.first; // request
Andy Hunga2a1ac32022-03-18 16:12:11 -0700438 }
Andy Hungf8ab0932022-06-13 19:49:43 -0700439
440 // this check is O(N), but since the second chance requests are ordered
441 // in terms of earliest expiration time, we would expect better than average results.
442 for (auto it = mSecondChanceRequests.begin(); it != mSecondChanceRequests.end(); ++it) {
443 if (it->first.second == handle) {
444 data = std::move(it->second);
445 mSecondChanceRequests.erase(it);
446 ul.unlock(); // manually release lock here so func (data.second)
447 // is released outside of lock.
448 return data.first; // request
449 }
450 }
451 return {};
Andy Hunga2a1ac32022-03-18 16:12:11 -0700452}
453
454void TimerThread::MonitorThread::copyRequests(
455 std::vector<std::shared_ptr<const Request>>& requests) const {
456 std::lock_guard lg(mMutex);
457 for (const auto &[deadline, monitorpair] : mMonitorRequests) {
458 requests.emplace_back(monitorpair.first);
459 }
Andy Hungf8ab0932022-06-13 19:49:43 -0700460 // we combine the second map with the first map - this is
461 // everything that is pending on the monitor thread.
462 // The second map will be older than the first map so this
463 // is in order.
464 for (const auto &[deadline, monitorpair] : mSecondChanceRequests) {
465 requests.emplace_back(monitorpair.first);
466 }
Andy Hunga2a1ac32022-03-18 16:12:11 -0700467}
468
469} // namespace android::mediautils