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 #pragma once
18 
19 #include <map>
20 #include <unordered_map>
21 
22 #include "AdpfTypes.h"
23 #include "ChannelGroup.h"
24 #include "SessionChannel.h"
25 
26 namespace aidl::google::hardware::power::impl::pixel {
27 
28 template <class ChannelGroupT = ChannelGroup<>>
29 class ChannelManager : public Immobile {
30   public:
31     ~ChannelManager() = default;
32     bool closeChannel(int32_t tgid, int32_t uid);
33     bool getChannelConfig(int32_t tgid, int32_t uid, ChannelConfig *config);
34     int getGroupCount();
35     int getChannelCount();
36     // The instance of this class is actually owned by the PowerSessionManager singleton
37     // This is mostly to reduce the number of singletons and make it simpler to mock
38     static ChannelManager *getInstance();
39 
40     union ChannelMapKey {
41         struct {
42             int32_t tgid;
43             int32_t uid;
44         };
45         int64_t key;
int64_t()46         operator int64_t() { return key; }
47     };
48 
49     union ChannelMapValue {
50         struct {
51             int32_t groupId;
52             int32_t offset;
53         };
54         int64_t value;
int64_t()55         operator int64_t() { return value; }
56     };
57 
58   private:
59     std::mutex mChannelManagerMutex;
60 
61     std::map<int32_t, ChannelGroupT> mChannelGroups GUARDED_BY(mChannelManagerMutex);
62     std::shared_ptr<SessionChannel> getOrCreateChannel(int32_t tgid, int32_t uid)
63             REQUIRES(mChannelManagerMutex);
64 
65     // Used to look up where channels actually are in this data structure, and guarantee uniqueness
66     std::unordered_map<int64_t, int64_t> mChannelMap GUARDED_BY(mChannelManagerMutex);
67 };
68 
69 }  // namespace aidl::google::hardware::power::impl::pixel
70