1 /*
2  * Copyright 2023 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 <chrono>
20 #include <condition_variable>
21 #include <functional>
22 #include <mutex>
23 #include <queue>
24 #include <shared_mutex>
25 #include <string>
26 #include <thread>
27 #include <unordered_map>
28 
29 #include "AdpfTypes.h"
30 
31 namespace aidl {
32 namespace google {
33 namespace hardware {
34 namespace power {
35 namespace impl {
36 namespace pixel {
37 
38 // Background thread processing from priority queue based on time deadline
39 // This class isn't meant to be used directly, use TemplatePriorityQueueWorker below
40 class PriorityQueueWorkerPool {
41   public:
42     // CTOR
43     // thread count is number of threads to create in thread pool
44     // thread name prefix is use for naming threads to help with debugging
45     PriorityQueueWorkerPool(size_t threadCount, const std::string &threadNamePrefix);
46     // DTOR
47     ~PriorityQueueWorkerPool();
48     // Map callback id to callback function
49     void addCallback(int64_t templateQueueWorkerId, std::function<void(int64_t)> callback);
50     // Unmap callback id with callback function
51     void removeCallback(int64_t templateQueueWorkerId);
52     // Schedule work for specific worker id with package id to be run at time deadline
53     void schedule(int64_t templateQueueWorkerId, int64_t packageId,
54                   std::chrono::steady_clock::time_point deadline);
55 
56   private:
57     // Thread coordination
58     std::mutex mMutex;
59     bool mRunning;
60     std::condition_variable mCv;
61     std::vector<std::thread> mThreadPool;
62     void loop();
63 
64     // Work package with worker id to find correct callback in
65     struct Package {
PackagePackage66         Package() {}
PackagePackage67         Package(std::chrono::steady_clock::time_point pDeadline, int64_t pTemplateQueueWorkerId,
68                 int64_t pPackageId)
69             : deadline(pDeadline),
70               templateQueueWorkerId(pTemplateQueueWorkerId),
71               packageId(pPackageId) {}
72         std::chrono::steady_clock::time_point deadline;
73         int64_t templateQueueWorkerId{0};
74         int64_t packageId{0};
75         // Sort time earliest first
76         bool operator<(const Package &p) const { return deadline > p.deadline; }
77     };
78     std::priority_queue<Package> mPackageQueue;
79 
80     // Callback management
81     std::shared_mutex mSharedMutex;
82     std::unordered_map<int64_t, std::function<void(int64_t)>> mCallbackMap;
83 };
84 
85 // Generic templated worker for registering a single std::function callback one time
86 // and reusing it to reduce memory allocations. Many TemplatePriorityQueueWorkers
87 // can make use of the same PriorityQueue worker which enables sharing a thread pool
88 // across callbacks of different types. This class is a template to allow for different
89 // types of work packages while not requiring virtual calls.
90 template <typename PACKAGE>
91 class TemplatePriorityQueueWorker {
92   public:
93     // CTOR, callback to run when added work is run, worker to use for adding work to
TemplatePriorityQueueWorker(std::function<void (const PACKAGE &)> cb,std::shared_ptr<PriorityQueueWorkerPool> worker)94     TemplatePriorityQueueWorker(std::function<void(const PACKAGE &)> cb,
95                                 std::shared_ptr<PriorityQueueWorkerPool> worker)
96         : mCallbackId(reinterpret_cast<std::intptr_t>(this)), mCallback(cb), mWorker(worker) {
97         if (!mCallback) {
98             mCallback = [](const auto &) {};
99         }
100         mWorker->addCallback(mCallbackId, [&](int64_t packageId) { process(packageId); });
101     }
102 
103     // DTOR
~TemplatePriorityQueueWorker()104     ~TemplatePriorityQueueWorker() { mWorker->removeCallback(mCallbackId); }
105 
106     void schedule(const PACKAGE &package,
107                   std::chrono::steady_clock::time_point t = std::chrono::steady_clock::now()) {
108         {
109             std::lock_guard<std::mutex> lock(mMutex);
110             ++mPackageIdCounter;
111             mPackages.emplace(mPackageIdCounter, package);
112         }
113         mWorker->schedule(mCallbackId, mPackageIdCounter, t);
114     }
115 
116   private:
117     int64_t mCallbackId{0};
118     std::function<void(const PACKAGE &)> mCallback;
119     // Must ensure PriorityQueueWorker does not go out of scope before this class does
120     std::shared_ptr<PriorityQueueWorkerPool> mWorker;
121     mutable std::mutex mMutex;
122     // Counter is used as a unique identifier for work packages
123     int64_t mPackageIdCounter{0};
124     // Want a container that is:
125     // fast to add, fast random find find, fast random removal,
126     // and with reasonable space efficiency
127     std::unordered_map<int64_t, PACKAGE> mPackages;
128 
process(int64_t packageId)129     void process(int64_t packageId) {
130         PACKAGE package;
131         {
132             std::lock_guard<std::mutex> lock(mMutex);
133             auto itr = mPackages.find(packageId);
134             if (itr == mPackages.end()) {
135                 // Work id does not have matching entry, drop it
136                 return;
137             }
138 
139             package = itr->second;
140             mPackages.erase(itr);
141         }
142         mCallback(package);
143     }
144 };
145 
146 }  // namespace pixel
147 }  // namespace impl
148 }  // namespace power
149 }  // namespace hardware
150 }  // namespace google
151 }  // namespace aidl
152