• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2 **
3 ** Copyright 2015, The Android Open Source Project
4 **
5 ** Licensed under the Apache License, Version 2.0 (the "License");
6 ** you may not use this file except in compliance with the License.
7 ** You may obtain a copy of the License at
8 **
9 **     http://www.apache.org/licenses/LICENSE-2.0
10 **
11 ** Unless required by applicable law or agreed to in writing, software
12 ** distributed under the License is distributed on an "AS IS" BASIS,
13 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 ** See the License for the specific language governing permissions and
15 ** limitations under the License.
16 */
17 
18 #ifndef ANDROID_MEDIA_RESOURCEMANAGERSERVICE_H
19 #define ANDROID_MEDIA_RESOURCEMANAGERSERVICE_H
20 
21 #include <map>
22 #include <set>
23 #include <mutex>
24 #include <string>
25 #include <vector>
26 
27 #include <aidl/android/media/BnResourceManagerService.h>
28 #include <media/MediaResource.h>
29 #include <utils/Errors.h>
30 #include <utils/String8.h>
31 #include <utils/threads.h>
32 
33 #include "ResourceManagerServiceUtils.h"
34 
35 namespace android {
36 
37 class ResourceObserverService;
38 class ServiceLog;
39 struct ProcessInfoInterface;
40 class ResourceManagerMetrics;
41 
42 using Status = ::ndk::ScopedAStatus;
43 using ::aidl::android::media::IResourceManagerClient;
44 using ::aidl::android::media::BnResourceManagerService;
45 using ::aidl::android::media::MediaResourceParcel;
46 using ::aidl::android::media::MediaResourcePolicyParcel;
47 using ::aidl::android::media::ClientInfoParcel;
48 using ::aidl::android::media::ClientConfigParcel;
49 
50 class ResourceManagerService : public BnResourceManagerService {
51 public:
52     struct SystemCallbackInterface : public RefBase {
53         virtual void noteStartVideo(int uid) = 0;
54         virtual void noteStopVideo(int uid) = 0;
55         virtual void noteResetVideo() = 0;
56         virtual bool requestCpusetBoost(bool enable) = 0;
57     };
58 
getServiceName()59     static char const *getServiceName() { return "media.resource_manager"; }
60     static void instantiate();
61 
62         // Static creation methods.
63     static std::shared_ptr<ResourceManagerService> Create();
64     static std::shared_ptr<ResourceManagerService> Create(
65         const sp<ProcessInfoInterface>& processInfo,
66         const sp<SystemCallbackInterface>& systemResource);
67 
68     virtual binder_status_t dump(
69             int /*fd*/, const char** /*args*/, uint32_t /*numArgs*/);
70 
71     ResourceManagerService();
72     explicit ResourceManagerService(const sp<ProcessInfoInterface> &processInfo,
73             const sp<SystemCallbackInterface> &systemResource);
74     virtual ~ResourceManagerService();
75 
76     virtual void setObserverService(
77             const std::shared_ptr<ResourceObserverService>& observerService);
78 
79     // IResourceManagerService interface
80     Status config(const std::vector<MediaResourcePolicyParcel>& policies) override;
81 
82     Status addResource(const ClientInfoParcel& clientInfo,
83                        const std::shared_ptr<IResourceManagerClient>& client,
84                        const std::vector<MediaResourceParcel>& resources) override;
85 
86     Status updateResource(const ClientInfoParcel& clientInfo,
87                           const std::vector<MediaResourceParcel>& resources) override;
88 
89     Status removeResource(const ClientInfoParcel& clientInfo,
90                           const std::vector<MediaResourceParcel>& resources) override;
91 
92     Status removeClient(const ClientInfoParcel& clientInfo) override;
93 
94     // Tries to reclaim resource from processes with lower priority than the calling process
95     // according to the requested resources.
96     // Returns true if any resource has been reclaimed, otherwise returns false.
97     Status reclaimResource(const ClientInfoParcel& clientInfo,
98                            const std::vector<MediaResourceParcel>& resources,
99                            bool* _aidl_return) override;
100 
101     Status overridePid(int32_t originalPid, int32_t newPid) override;
102 
103     Status overrideProcessInfo(const std::shared_ptr<IResourceManagerClient>& client,
104                                int32_t pid, int32_t procState, int32_t oomScore) override;
105 
106     Status markClientForPendingRemoval(const ClientInfoParcel& clientInfo) override;
107 
108     Status reclaimResourcesFromClientsPendingRemoval(int32_t pid) override;
109 
110     Status notifyClientCreated(const ClientInfoParcel& clientInfo) override;
111 
112     Status notifyClientStarted(const ClientConfigParcel& clientConfig) override;
113 
114     Status notifyClientStopped(const ClientConfigParcel& clientConfig) override;
115 
116     Status notifyClientConfigChanged(const ClientConfigParcel& clientConfig) override;
117 
118     Status getMediaResourceUsageReport(std::vector<MediaResourceParcel>* resources) override;
119 
120 protected:
121     // To get notifications when a resource is added for the first time.
122     void onFirstAdded(const MediaResourceParcel& res, uid_t uid);
123     // To get notifications when a resource has been removed at last.
124     void onLastRemoved(const MediaResourceParcel& res, uid_t uid);
125 
126     // Reclaims resources from |clients|. Returns true if reclaim succeeded
127     // for all clients.
128     bool reclaimUnconditionallyFrom(const std::vector<ClientInfo>& targetClients);
129 
130     // A helper function that returns true if the callingPid has higher priority than pid.
131     // Returns false otherwise.
132     bool isCallingPriorityHigher_l(int callingPid, int pid);
133 
134     // To notify the metrics about client being released.
135     void notifyClientReleased(const ClientInfoParcel& clientInfo);
136 
137     virtual Status removeResource(const ClientInfoParcel& clientInfo, bool checkValid);
138 
139 private:
140     friend class ResourceManagerServiceTest;
141     friend class ResourceManagerServiceTestBase;
142     friend class DeathNotifier;
143     friend class OverrideProcessInfoDeathNotifier;
144 
145     // Gets the client who owns biggest piece of specified resource type from pid.
146     // Returns false with no change to client if there are no clients holding resources of this
147     // type.
148     bool getBiggestClient_l(int pid, MediaResource::Type type,
149                             MediaResource::SubType subType,
150                             ClientInfo& clientsInfo,
151                             bool pendingRemovalOnly = false);
152 
153     // A helper function that gets the biggest clients of the process pid that
154     // is marked to be (pending) removed and has the needed resources.
155     bool getBiggestClientPendingRemoval_l(int pid, MediaResource::Type type,
156                                           MediaResource::SubType subType,
157                                           ClientInfo& clientsInfo);
158 
159     // From the list of clients, pick/select client(s) based on the reclaim policy.
160     void getClientForResource_l(const ResourceRequestInfo& resourceRequestInfo,
161                                 std::vector<ClientInfo>& clientsInfo);
162     // A helper function that pushes Reclaim Atom (for metric collection).
163     void pushReclaimAtom(const ClientInfoParcel& clientInfo,
164                          const std::vector<ClientInfo>& targetClients,
165                          bool reclaimed);
166 
167     // Remove the override info for the given process
168     void removeProcessInfoOverride_l(int pid);
169 
170     // Eventually we want to phase out this implementation of IResourceManagerService
171     // (ResourceManagerService) and replace that with the newer implementation
172     // (ResourceManagerServiceNew).
173     // So, marking the following methods as private virtual and for the newer implementation
174     // to override is the easiest way to maintain both implementation.
175 
176     // Initializes the internal state of the ResourceManagerService
177     virtual void init();
178 
179     // Gets the list of all the clients who own the list of specified resource type
180     // and satisfy the resource model and the reclaim policy.
181     virtual bool getTargetClients(
182         const ClientInfoParcel& clientInfo,
183         const std::vector<MediaResourceParcel>& resources,
184         std::vector<ClientInfo>& targetClients);
185 
186     // Gets the list of all the clients who own the specified resource type.
187     // Returns false if any client belongs to a process with higher priority than the
188     // calling process. The clients will remain unchanged if returns false.
189     virtual bool getAllClients_l(const ResourceRequestInfo& resourceRequestInfo,
190                                  std::vector<ClientInfo>& clientsInfo);
191 
192     // Gets the client who owns specified resource type from lowest possible priority process.
193     // Returns false if the calling process priority is not higher than the lowest process
194     // priority. The client will remain unchanged if returns false.
195     virtual bool getLowestPriorityBiggestClient_l(
196         const ResourceRequestInfo& resourceRequestInfo,
197         ClientInfo& clientInfo);
198 
199     // override the pid of given process
200     virtual bool overridePid_l(int32_t originalPid, int32_t newPid);
201 
202     // override the process info of given process
203     virtual bool overrideProcessInfo_l(const std::shared_ptr<IResourceManagerClient>& client,
204                                        int pid, int procState, int oomScore);
205 
206     // Get priority from process's pid
207     virtual bool getPriority_l(int pid, int* priority) const;
208 
209     // Gets lowest priority process that has the specified resource type.
210     // Returns false if failed. The output parameters will remain unchanged if failed.
211     virtual bool getLowestPriorityPid_l(MediaResource::Type type, MediaResource::SubType subType,
212                                         int* lowestPriorityPid, int* lowestPriority);
213 
214     // Removes the pid from the override map.
215     virtual void removeProcessInfoOverride(int pid);
216 
217     // Get the client for given pid and the clientId from the map
218     virtual std::shared_ptr<IResourceManagerClient> getClient_l(
219         int pid, const int64_t& clientId) const;
220 
221     // Remove the client for given pid and the clientId from the map
222     virtual bool removeClient_l(int pid, const int64_t& clientId);
223 
224     // Get all the resource status for dump
225     virtual void getResourceDump(std::string& resourceLog) const;
226 
227     // The following utility functions are used only for testing by ResourceManagerServiceTest
228     // START: TEST only functions
229     // Get the peak concurrent pixel count (associated with the video codecs) for the process.
230     long getPeakConcurrentPixelCount(int pid) const;
231     // Get the current concurrent pixel count (associated with the video codecs) for the process.
232     long getCurrentConcurrentPixelCount(int pid) const;
233     // To create object of type ResourceManagerServiceNew
234     static std::shared_ptr<ResourceManagerService> CreateNew(
235         const sp<ProcessInfoInterface>& processInfo,
236         const sp<SystemCallbackInterface>& systemResource);
237     // Returns a unmodifiable reference to the internal resource state as a map
getResourceMap()238     virtual const std::map<int, ResourceInfos>& getResourceMap() const {
239         return mMap;
240     }
241     // enable/disable process priority based reclaim and client importance based reclaim
setReclaimPolicy(bool processPriority,bool clientImportance)242     virtual void setReclaimPolicy(bool processPriority, bool clientImportance) {
243         // Implemented by the refactored/new RMService
244         (void)processPriority;
245         (void)clientImportance;
246     }
247     // END: TEST only functions
248 
249 protected:
250     mutable std::mutex mLock;
251     sp<ProcessInfoInterface> mProcessInfo;
252     sp<SystemCallbackInterface> mSystemCB;
253     sp<ServiceLog> mServiceLog;
254     bool mSupportsMultipleSecureCodecs;
255     bool mSupportsSecureWithNonSecureCodec;
256     int32_t mCpuBoostCount;
257 
258 private:
259     PidResourceInfosMap mMap;
260     struct ProcessInfoOverride {
261         std::shared_ptr<DeathNotifier> deathNotifier = nullptr;
262         std::shared_ptr<IResourceManagerClient> client;
263     };
264     std::map<int, int> mOverridePidMap;
265     std::map<pid_t, ProcessInfoOverride> mProcessInfoOverrideMap;
266     std::shared_ptr<ResourceObserverService> mObserverService;
267     std::unique_ptr<ResourceManagerMetrics> mResourceManagerMetrics;
268 };
269 
270 // ----------------------------------------------------------------------------
271 } // namespace android
272 
273 #endif // ANDROID_MEDIA_RESOURCEMANAGERSERVICE_H
274