1 /*
2  * Copyright 2024 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 "powerhal-libperfmgr"
18 #define ATRACE_TAG (ATRACE_TAG_POWER | ATRACE_TAG_HAL)
19 
20 #include "ChannelGroup.h"
21 
22 #include <gmock/gmock.h>
23 #include <processgroup/processgroup.h>
24 #include <sys/resource.h>
25 #include <utils/SystemClock.h>
26 #include <utils/Trace.h>
27 
28 #include <algorithm>
29 #include <mutex>
30 
31 #include "AdpfTypes.h"
32 #include "ChannelManager.h"
33 #include "log/log_main.h"
34 #include "tests/mocks/MockPowerHintSession.h"
35 #include "tests/mocks/MockPowerSessionManager.h"
36 
37 namespace aidl::google::hardware::power::impl::pixel {
38 using Tag = ChannelMessage::ChannelMessageContents::Tag;
39 
40 template <class PowerSessionManagerT, class PowerHintSessionT>
ChannelGroup(int32_t id)41 ChannelGroup<PowerSessionManagerT, PowerHintSessionT>::ChannelGroup(int32_t id)
42     : mGroupId(id),
43       mFlagQueue(std::make_shared<FlagQueue>(1, true)),
44       mGroupThread(std::thread(&ChannelGroup::runChannelGroup, this)) {}
45 
46 template <class PowerSessionManagerT, class PowerHintSessionT>
~ChannelGroup()47 ChannelGroup<PowerSessionManagerT, PowerHintSessionT>::~ChannelGroup() {
48     mDestructing = true;
49 
50     EventFlag *flag;
51     EventFlag::createEventFlag(mFlagQueue->getEventFlagWord(), &flag);
52     // Wake up the handler. 0xffffffff wakes on every bit in the flag,
53     // to ensure the wake-up will be handled regardless of other configuration settings,
54     // and even if some of these bits are already set.
55     flag->wake(0xffffffff);
56 
57     mGroupThread.join();
58 }
59 
60 template <class PowerSessionManagerT, class PowerHintSessionT>
getChannelCount() const61 int32_t ChannelGroup<PowerSessionManagerT, PowerHintSessionT>::getChannelCount() const {
62     return mLiveChannels;
63 }
64 
65 template <class PowerSessionManagerT, class PowerHintSessionT>
removeChannel(int32_t slot)66 bool ChannelGroup<PowerSessionManagerT, PowerHintSessionT>::removeChannel(int32_t slot) {
67     std::scoped_lock lock(mGroupMutex);
68     if (!mChannels[slot]) {
69         return false;
70     }
71     mChannels[slot] = nullptr;
72     --mLiveChannels;
73     return true;
74 }
75 
76 template <class PowerSessionManagerT, class PowerHintSessionT>
77 std::shared_ptr<SessionChannel>
createChannel(int32_t tgid,int32_t uid)78 ChannelGroup<PowerSessionManagerT, PowerHintSessionT>::createChannel(int32_t tgid, int32_t uid) {
79     std::scoped_lock lock(mGroupMutex);
80     ALOGV("Creating channel for tgid: %" PRId32 " uid: %" PRId32, tgid, uid);
81     int slot = 0;
82     for (slot = 0; slot < kMaxChannels; ++slot) {
83         if (!mChannels[slot]) {
84             break;
85         }
86     }
87     LOG_ALWAYS_FATAL_IF(slot == kMaxChannels, "Failed to create channel!");
88     ++mLiveChannels;
89     ChannelManager<SessionChannel>::ChannelMapValue channelId{
90             {.groupId = static_cast<int32_t>(mGroupId), .offset = slot}};
91     mChannels[slot] = std::make_shared<SessionChannel>(tgid, uid, channelId, slot);
92     ALOGV("Channel created on group: %" PRId32 " slot: %" PRId32, mGroupId, slot);
93     return mChannels[slot];
94 }
95 
96 template <class PowerSessionManagerT, class PowerHintSessionT>
getChannel(int32_t slot)97 std::shared_ptr<SessionChannel> ChannelGroup<PowerSessionManagerT, PowerHintSessionT>::getChannel(
98         int32_t slot) {
99     std::scoped_lock lock(mGroupMutex);
100     LOG_ALWAYS_FATAL_IF(!mChannels[slot], "Requesting a dead channel!");
101     return mChannels[slot];
102 }
103 
104 template <class PowerSessionManagerT, class PowerHintSessionT>
getFlagDesc(std::optional<FlagQueueDesc> * _return_desc) const105 void ChannelGroup<PowerSessionManagerT, PowerHintSessionT>::getFlagDesc(
106         std::optional<FlagQueueDesc> *_return_desc) const {
107     *_return_desc = std::make_optional(mFlagQueue->dupeDesc());
108 }
109 
110 template <class PowerSessionManagerT, class PowerHintSessionT>
runChannelGroup()111 void ChannelGroup<PowerSessionManagerT, PowerHintSessionT>::runChannelGroup() {
112     EventFlag *flag;
113     {
114         std::scoped_lock lock(mGroupMutex);
115         EventFlag::createEventFlag(mFlagQueue->getEventFlagWord(), &flag);
116     }
117 
118     setpriority(PRIO_PROCESS, getpid(), -20);
119 
120     uint32_t flagState = 0;
121     static std::set<uid_t> blocklist = {};
122     std::vector<ChannelMessage> messages;
123     std::vector<android::hardware::power::WorkDuration> durations;
124     durations.reserve(kFMQQueueSize);
125     messages.reserve(kFMQQueueSize);
126 
127     while (!mDestructing) {
128         messages.clear();
129         flag->wait(kWriteBits, &flagState, 0, true);
130         int64_t now = ::android::uptimeNanos();
131         if (mDestructing) {
132             return;
133         }
134         {
135             std::scoped_lock lock(mGroupMutex);
136             // Get the rightmost nonzero bit, corresponding to the next active channel
137             for (int channelNum = std::countr_zero(flagState);
138                  channelNum < kMaxChannels && !mDestructing;
139                  channelNum = std::countr_zero(flagState)) {
140                 // Drop the lowest set write bit
141                 flagState &= (flagState - 1);
142                 auto &channel = mChannels[channelNum];
143                 if (!channel || !channel->isValid()) {
144                     continue;
145                 }
146                 if (blocklist.contains(channel->getUid())) {
147                     continue;
148                 }
149                 int toRead = channel->getQueue()->availableToRead();
150                 if (toRead <= 0) {
151                     continue;
152                 }
153                 messages.resize(toRead);
154                 if (!channel->getQueue()->read(messages.data(), toRead)) {
155                     // stop messing with your buffer >:(
156                     blocklist.insert(channel->getUid());
157                     continue;
158                 }
159                 flag->wake(mChannels[channelNum]->getReadBitmask());
160                 for (int messageIndex = 0; messageIndex < messages.size() && !mDestructing;
161                      ++messageIndex) {
162                     ChannelMessage &message = messages[messageIndex];
163                     auto sessionPtr = std::static_pointer_cast<PowerHintSessionT>(
164                             PowerSessionManagerT::getInstance()->getSession(message.sessionID));
165                     if (!sessionPtr) {
166                         continue;
167                     }
168                     switch (message.data.getTag()) {
169                         case Tag::hint: {
170                             sessionPtr->sendHint(message.data.get<Tag::hint>());
171                             break;
172                         }
173                         case Tag::targetDuration: {
174                             sessionPtr->updateTargetWorkDuration(
175                                     message.data.get<Tag::targetDuration>());
176                             break;
177                         }
178                         case Tag::workDuration: {
179                             durations.clear();
180                             for (; !mDestructing && messageIndex < messages.size() &&
181                                    messages[messageIndex].data.getTag() == Tag::workDuration &&
182                                    messages[messageIndex].sessionID == message.sessionID;
183                                  ++messageIndex) {
184                                 ChannelMessage &currentMessage = messages[messageIndex];
185                                 auto &durationData = currentMessage.data.get<Tag::workDuration>();
186                                 durations.emplace_back(WorkDuration{
187                                         .timeStampNanos = currentMessage.timeStampNanos,
188                                         .durationNanos = durationData.durationNanos,
189                                         .cpuDurationNanos = durationData.cpuDurationNanos,
190                                         .gpuDurationNanos = durationData.gpuDurationNanos,
191                                         .workPeriodStartTimestampNanos =
192                                                 durationData.workPeriodStartTimestampNanos});
193                             }
194                             sessionPtr->reportActualWorkDuration(durations);
195                             break;
196                         }
197                         case Tag::mode: {
198                             auto mode = message.data.get<Tag::mode>();
199                             sessionPtr->setMode(mode.modeInt, mode.enabled);
200                             break;
201                         }
202                         default: {
203                             ALOGE("Invalid data tag sent: %s",
204                                   std::to_string(static_cast<int>(message.data.getTag())).c_str());
205                             break;
206                         }
207                     }
208                 }
209             }
210         }
211     }
212 }
213 
214 template class ChannelGroup<>;
215 template class ChannelGroup<testing::NiceMock<mock::pixel::MockPowerSessionManager>,
216                             testing::NiceMock<mock::pixel::MockPowerHintSession>>;
217 
218 }  // namespace aidl::google::hardware::power::impl::pixel
219