1 /*
2 * Copyright 2022 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 #include <compositionengine/impl/HwcAsyncWorker.h>
18 #include <processgroup/sched_policy.h>
19 #include <pthread.h>
20 #include <sched.h>
21 #include <sys/prctl.h>
22 #include <sys/resource.h>
23 #include <system/thread_defs.h>
24
25 #include <android-base/thread_annotations.h>
26 #include <cutils/sched_policy.h>
27 #include <ftl/fake_guard.h>
28
29 namespace android::compositionengine::impl {
30
HwcAsyncWorker()31 HwcAsyncWorker::HwcAsyncWorker() {
32 mThread = std::thread(&HwcAsyncWorker::run, this);
33 pthread_setname_np(mThread.native_handle(), "HwcAsyncWorker");
34 }
35
~HwcAsyncWorker()36 HwcAsyncWorker::~HwcAsyncWorker() {
37 {
38 std::scoped_lock lock(mMutex);
39 mDone = true;
40 mCv.notify_all();
41 }
42 if (mThread.joinable()) {
43 mThread.join();
44 }
45 }
send(std::function<bool ()> task)46 std::future<bool> HwcAsyncWorker::send(std::function<bool()> task) {
47 std::unique_lock<std::mutex> lock(mMutex);
48 android::base::ScopedLockAssertion assumeLock(mMutex);
49 mTask = std::packaged_task<bool()>([task = std::move(task)]() { return task(); });
50 mTaskRequested = true;
51 mCv.notify_one();
52 return mTask.get_future();
53 }
54
run()55 void HwcAsyncWorker::run() {
56 set_sched_policy(0, SP_FOREGROUND);
57 struct sched_param param = {0};
58 param.sched_priority = 2;
59 sched_setscheduler(gettid(), SCHED_FIFO, ¶m);
60
61 std::unique_lock<std::mutex> lock(mMutex);
62 android::base::ScopedLockAssertion assumeLock(mMutex);
63 while (!mDone) {
64 mCv.wait(lock, [this]() FTL_FAKE_GUARD(mMutex) { return mTaskRequested || mDone; });
65 if (mTaskRequested && mTask.valid()) {
66 mTask();
67 mTaskRequested = false;
68 }
69 }
70 }
71
72 } // namespace android::compositionengine::impl
73