xref: /aosp_15_r20/frameworks/av/services/camera/libcameraservice/utils/ClientManager.h (revision ec779b8e0859a360c3d303172224686826e6e0e1)
1 /*
2  * Copyright (C) 2015 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 #ifndef ANDROID_SERVICE_UTILS_EVICTION_POLICY_MANAGER_H
18 #define ANDROID_SERVICE_UTILS_EVICTION_POLICY_MANAGER_H
19 
20 #include <utils/Condition.h>
21 #include <utils/Mutex.h>
22 #include <utils/Timers.h>
23 #include <utils/Log.h>
24 
25 #include <algorithm>
26 #include <utility>
27 #include <vector>
28 #include <set>
29 #include <map>
30 #include <memory>
31 #include <com_android_internal_camera_flags.h>
32 
33 namespace flags = com::android::internal::camera::flags;
34 
35 namespace android {
36 namespace resource_policy {
37 
38 // Values from frameworks/base/services/core/java/com/android/server/am/ProcessList.java
39 const int32_t INVALID_ADJ = -10000;
40 const int32_t UNKNOWN_ADJ = 1001;
41 const int32_t CACHED_APP_MAX_ADJ = 999;
42 const int32_t CACHED_APP_MIN_ADJ = 900;
43 const int32_t CACHED_APP_LMK_FIRST_ADJ = 950;
44 const int32_t CACHED_APP_IMPORTANCE_LEVELS = 5;
45 const int32_t SERVICE_B_ADJ = 800;
46 const int32_t PREVIOUS_APP_ADJ = 700;
47 const int32_t HOME_APP_ADJ = 600;
48 const int32_t SERVICE_ADJ = 500;
49 const int32_t HEAVY_WEIGHT_APP_ADJ = 400;
50 const int32_t BACKUP_APP_ADJ = 300;
51 const int32_t PERCEPTIBLE_LOW_APP_ADJ = 250;
52 const int32_t PERCEPTIBLE_MEDIUM_APP_ADJ = 225;
53 const int32_t PERCEPTIBLE_APP_ADJ = 200;
54 const int32_t VISIBLE_APP_ADJ = 100;
55 const int32_t VISIBLE_APP_LAYER_MAX = PERCEPTIBLE_APP_ADJ - VISIBLE_APP_ADJ - 1;
56 const int32_t PERCEPTIBLE_RECENT_FOREGROUND_APP_ADJ = 50;
57 const int32_t FOREGROUND_APP_ADJ = 0;
58 const int32_t PERSISTENT_SERVICE_ADJ = -700;
59 const int32_t PERSISTENT_PROC_ADJ = -800;
60 const int32_t SYSTEM_ADJ = -900;
61 const int32_t NATIVE_ADJ = -1000;
62 
63 class ClientPriority {
64 public:
65     /**
66      * Choosing to set mIsVendorClient through a parameter instead of calling
67      * getCurrentServingCall() == BinderCallType::HWBINDER to protect against the
68      * case where the construction is offloaded to another thread which isn't a
69      * hwbinder thread.
70      */
71     ClientPriority(int32_t score, int32_t state, bool isVendorClient, int32_t scoreOffset = 0) :
mIsVendorClient(isVendorClient)72             mIsVendorClient(isVendorClient), mScoreOffset(scoreOffset) {
73         setScore(score);
74         setState(state);
75     }
76 
getScore()77     int32_t getScore() const { return mScore; }
getState()78     int32_t getState() const { return mState; }
isVendorClient()79     int32_t isVendorClient() const { return mIsVendorClient; }
80 
setScore(int32_t score)81     void setScore(int32_t score) {
82         // For vendor clients, the score is set once and for all during
83         // construction. Otherwise, it can get reset each time cameraserver
84         // queries ActivityManagerService for oom_adj scores / states .
85         // For clients where the score offset is set by the app, add it to the
86         // score provided by ActivityManagerService.
87         if (score == INVALID_ADJ) {
88             mScore = UNKNOWN_ADJ;
89         } else {
90             mScore = mScoreOffset + score;
91         }
92     }
93 
setState(int32_t state)94     void setState(int32_t state) {
95       // For vendor clients, the score is set once and for all during
96       // construction. Otherwise, it can get reset each time cameraserver
97       // queries ActivityManagerService for oom_adj scores / states
98       // (ActivityManagerService returns a vendor process' state as
99       // PROCESS_STATE_NONEXISTENT.
100       mState = state;
101     }
102 
103     bool operator==(const ClientPriority& rhs) const {
104         return (this->mScore == rhs.mScore) && (this->mState == rhs.mState);
105     }
106 
107     bool operator< (const ClientPriority& rhs)  const {
108         if (this->mScore == rhs.mScore) {
109             return this->mState < rhs.mState;
110         } else {
111             return this->mScore < rhs.mScore;
112         }
113     }
114 
115     bool operator> (const ClientPriority& rhs) const {
116         return rhs < *this;
117     }
118 
119     bool operator<=(const ClientPriority& rhs) const {
120         return !(*this > rhs);
121     }
122 
123     bool operator>=(const ClientPriority& rhs) const {
124         return !(*this < rhs);
125     }
126 
127 private:
128         int32_t mScore;
129         int32_t mState;
130         bool mIsVendorClient = false;
131         int32_t mScoreOffset = 0;
132 };
133 
134 // --------------------------------------------------------------------------------
135 
136 /**
137  * The ClientDescriptor class is a container for a given key/value pair identifying a shared
138  * resource, and the corresponding cost, priority, owner ID, and conflicting keys list used
139  * in determining eviction behavior.
140  *
141  * Aside from the priority, these values are immutable once the ClientDescriptor has been
142  * constructed.
143  */
144 template<class KEY, class VALUE>
145 class ClientDescriptor final {
146 public:
147     ClientDescriptor(const KEY& key, const VALUE& value, int32_t cost,
148             const std::set<KEY>& conflictingKeys, int32_t score, int32_t ownerId, int32_t state,
149             bool isVendorClient, int32_t oomScoreOffset, bool sharedMode = false);
150     ClientDescriptor(KEY&& key, VALUE&& value, int32_t cost, std::set<KEY>&& conflictingKeys,
151             int32_t score, int32_t ownerId, int32_t state, bool isVendorClient,
152             int32_t oomScoreOffset, bool sharedMode = false);
153 
154     ~ClientDescriptor();
155 
156     /**
157      * Return the key for this descriptor.
158      */
159     const KEY& getKey() const;
160 
161     /**
162      * Return the value for this descriptor.
163      */
164     const VALUE& getValue() const;
165 
166     /**
167      * Return the cost for this descriptor.
168      */
169     int32_t getCost() const;
170 
171     /**
172      * Return the priority for this descriptor.
173      */
174     const ClientPriority &getPriority() const;
175 
176     /**
177      * Return the owner ID for this descriptor.
178      */
179     int32_t getOwnerId() const;
180 
181     /**
182      * Return true if the given key is in this descriptor's conflicting keys list.
183      */
184     bool isConflicting(const KEY& key) const;
185 
186     /**
187      * Return the set of all conflicting keys for this descriptor.
188      */
189     std::set<KEY> getConflicting() const;
190 
191     /**
192      * Set the proirity for this descriptor.
193      */
194     void setPriority(const ClientPriority& priority);
195 
196     /**
197      * Returns true when camera is opened in shared mode.
198      */
199     bool getSharedMode() const;
200 
201     // This class is ordered by key
202     template<class K, class V>
203     friend bool operator < (const ClientDescriptor<K, V>& a, const ClientDescriptor<K, V>& b);
204 
205 private:
206     KEY mKey;
207     VALUE mValue;
208     int32_t mCost;
209     std::set<KEY> mConflicting;
210     ClientPriority mPriority;
211     int32_t mOwnerId;
212     bool mSharedMode;
213 }; // class ClientDescriptor
214 
215 template<class K, class V>
216 bool operator < (const ClientDescriptor<K, V>& a, const ClientDescriptor<K, V>& b) {
217     return a.mKey < b.mKey;
218 }
219 
220 template<class KEY, class VALUE>
ClientDescriptor(const KEY & key,const VALUE & value,int32_t cost,const std::set<KEY> & conflictingKeys,int32_t score,int32_t ownerId,int32_t state,bool isVendorClient,int32_t scoreOffset,bool sharedMode)221 ClientDescriptor<KEY, VALUE>::ClientDescriptor(const KEY& key, const VALUE& value, int32_t cost,
222         const std::set<KEY>& conflictingKeys, int32_t score, int32_t ownerId, int32_t state,
223         bool isVendorClient, int32_t scoreOffset, bool sharedMode) :
224         mKey{key}, mValue{value}, mCost{cost}, mConflicting{conflictingKeys},
225         mPriority(score, state, isVendorClient, scoreOffset),
226         mOwnerId{ownerId}, mSharedMode{sharedMode} {}
227 
228 template<class KEY, class VALUE>
ClientDescriptor(KEY && key,VALUE && value,int32_t cost,std::set<KEY> && conflictingKeys,int32_t score,int32_t ownerId,int32_t state,bool isVendorClient,int32_t scoreOffset,bool sharedMode)229 ClientDescriptor<KEY, VALUE>::ClientDescriptor(KEY&& key, VALUE&& value, int32_t cost,
230         std::set<KEY>&& conflictingKeys, int32_t score, int32_t ownerId, int32_t state,
231         bool isVendorClient, int32_t scoreOffset, bool sharedMode) :
232         mKey{std::forward<KEY>(key)}, mValue{std::forward<VALUE>(value)}, mCost{cost},
233         mConflicting{std::forward<std::set<KEY>>(conflictingKeys)},
234         mPriority(score, state, isVendorClient, scoreOffset), mOwnerId{ownerId},
235         mSharedMode{sharedMode} {}
236 
237 template<class KEY, class VALUE>
~ClientDescriptor()238 ClientDescriptor<KEY, VALUE>::~ClientDescriptor() {}
239 
240 template<class KEY, class VALUE>
getKey()241 const KEY& ClientDescriptor<KEY, VALUE>::getKey() const {
242     return mKey;
243 }
244 
245 template<class KEY, class VALUE>
getValue()246 const VALUE& ClientDescriptor<KEY, VALUE>::getValue() const {
247     return mValue;
248 }
249 
250 template<class KEY, class VALUE>
getCost()251 int32_t ClientDescriptor<KEY, VALUE>::getCost() const {
252     return mCost;
253 }
254 
255 template<class KEY, class VALUE>
getPriority()256 const ClientPriority& ClientDescriptor<KEY, VALUE>::getPriority() const {
257     return mPriority;
258 }
259 
260 template<class KEY, class VALUE>
getOwnerId()261 int32_t ClientDescriptor<KEY, VALUE>::getOwnerId() const {
262     return mOwnerId;
263 }
264 
265 template<class KEY, class VALUE>
isConflicting(const KEY & key)266 bool ClientDescriptor<KEY, VALUE>::isConflicting(const KEY& key) const {
267     if (flags::camera_multi_client()) {
268         // In shared mode, there can be more than one client using the camera.
269         // Hence, having more than one client with the same key is not considered as
270         // conflicting.
271         if (!mSharedMode && key == mKey) return true;
272     } else {
273         if (key == mKey) return true;
274     }
275     for (const auto& x : mConflicting) {
276         if (key == x) return true;
277     }
278     return false;
279 }
280 
281 template<class KEY, class VALUE>
getConflicting()282 std::set<KEY> ClientDescriptor<KEY, VALUE>::getConflicting() const {
283     return mConflicting;
284 }
285 
286 template<class KEY, class VALUE>
getSharedMode()287 bool ClientDescriptor<KEY, VALUE>::getSharedMode() const {
288     return mSharedMode;
289 }
290 
291 template<class KEY, class VALUE>
setPriority(const ClientPriority & priority)292 void ClientDescriptor<KEY, VALUE>::setPriority(const ClientPriority& priority) {
293     // We don't use the usual copy constructor here since we want to remember
294     // whether a client is a vendor client or not. This could have been wiped
295     // off in the incoming priority argument since an AIDL thread might have
296     // called getCurrentServingCall() == BinderCallType::HWBINDER after refreshing
297     // priorities for old clients through ProcessInfoService::getProcessStatesScoresFromPids().
298     if (mPriority.isVendorClient()) {
299         return;
300     }
301     mPriority.setScore(priority.getScore());
302     mPriority.setState(priority.getState());
303 }
304 
305 // --------------------------------------------------------------------------------
306 
307 /**
308  * A default class implementing the LISTENER interface used by ClientManager.
309  */
310 template<class KEY, class VALUE>
311 class DefaultEventListener {
312 public:
313     void onClientAdded(const ClientDescriptor<KEY, VALUE>& descriptor);
314     void onClientRemoved(const ClientDescriptor<KEY, VALUE>& descriptor);
315 };
316 
317 template<class KEY, class VALUE>
onClientAdded(const ClientDescriptor<KEY,VALUE> &)318 void DefaultEventListener<KEY, VALUE>::onClientAdded(
319         const ClientDescriptor<KEY, VALUE>& /*descriptor*/) {}
320 
321 template<class KEY, class VALUE>
onClientRemoved(const ClientDescriptor<KEY,VALUE> &)322 void DefaultEventListener<KEY, VALUE>::onClientRemoved(
323         const ClientDescriptor<KEY, VALUE>& /*descriptor*/) {}
324 
325 // --------------------------------------------------------------------------------
326 
327 /**
328  * The ClientManager class wraps an LRU-ordered list of active clients and implements eviction
329  * behavior for handling shared resource access.
330  *
331  * When adding a new descriptor, eviction behavior is as follows:
332  *   - Keys are unique, adding a descriptor with the same key as an existing descriptor will
333  *     result in the lower-priority of the two being removed.  Priority ties result in the
334  *     LRU descriptor being evicted (this means the incoming descriptor be added in this case).
335  *   - Any descriptors with keys that are in the incoming descriptor's 'conflicting keys' list
336  *     will be removed if they have an equal or lower priority than the incoming descriptor;
337  *     if any have a higher priority, the incoming descriptor is removed instead.
338  *   - If the sum of all descriptors' costs, including the incoming descriptor's, is more than
339  *     the max cost allowed for this ClientManager, descriptors with non-zero cost, equal or lower
340  *     priority, and a different owner will be evicted in LRU order until either the cost is less
341  *     than the max cost, or all descriptors meeting this criteria have been evicted and the
342  *     incoming descriptor has the highest priority.  Otherwise, the incoming descriptor is
343  *     removed instead.
344  */
345 template<class KEY, class VALUE, class LISTENER=DefaultEventListener<KEY, VALUE>>
346 class ClientManager {
347 public:
348     // The default maximum "cost" allowed before evicting
349     static constexpr int32_t DEFAULT_MAX_COST = 100;
350 
351     ClientManager();
352     explicit ClientManager(int32_t totalCost);
353 
354     /**
355      * Add a given ClientDescriptor to the managed list.  ClientDescriptors for clients that
356      * are evicted by this action are returned in a vector.
357      *
358      * This may return the ClientDescriptor passed in if it would be evicted.
359      */
360     std::vector<std::shared_ptr<ClientDescriptor<KEY, VALUE>>> addAndEvict(
361             const std::shared_ptr<ClientDescriptor<KEY, VALUE>>& client);
362 
363     /**
364      * Given a map containing owner (pid) -> priority mappings, update the priority of each
365      * ClientDescriptor with an owner in this mapping.
366      */
367     void updatePriorities(const std::map<int32_t,ClientPriority>& ownerPriorityList);
368 
369     /**
370      * Remove all ClientDescriptors.
371      */
372     void removeAll();
373 
374     /**
375      * Remove all ClientDescriptors with a given key.
376      */
377     std::vector<std::shared_ptr<ClientDescriptor<KEY, VALUE>>> removeAll(const KEY& key);
378 
379     /**
380      * Remove and return the ClientDescriptors with a given key.
381      */
382     std::shared_ptr<ClientDescriptor<KEY, VALUE>> remove(const KEY& key);
383 
384     /**
385      * Remove the given ClientDescriptor.
386      */
387     virtual void remove(const std::shared_ptr<ClientDescriptor<KEY, VALUE>>& value);
388 
389     /**
390      * Return a vector of the ClientDescriptors that would be evicted by adding the given
391      * ClientDescriptor.
392      *
393      * This may return the ClientDescriptor passed in if it would be evicted.
394      */
395     std::vector<std::shared_ptr<ClientDescriptor<KEY, VALUE>>> wouldEvict(
396             const std::shared_ptr<ClientDescriptor<KEY, VALUE>>& client) const;
397 
398     /**
399      * Return a vector of active ClientDescriptors that prevent this client from being added.
400      */
401     std::vector<std::shared_ptr<ClientDescriptor<KEY, VALUE>>> getIncompatibleClients(
402             const std::shared_ptr<ClientDescriptor<KEY, VALUE>>& client) const;
403 
404     /**
405      * Return a vector containing all currently active ClientDescriptors.
406      */
407     std::vector<std::shared_ptr<ClientDescriptor<KEY, VALUE>>> getAll() const;
408 
409     /**
410      * Return a vector containing all keys of currently active ClientDescriptors.
411      */
412     std::vector<KEY> getAllKeys() const;
413 
414     /**
415      * Return a vector of the owner tags of all currently active ClientDescriptors (duplicates
416      * will be removed).
417      */
418     std::vector<int32_t> getAllOwners() const;
419 
420     /**
421      * Return the ClientDescriptor corresponding to the given key, or an empty shared pointer
422      * if none exists.
423      */
424     std::shared_ptr<ClientDescriptor<KEY, VALUE>> get(const KEY& key) const;
425 
426     std::shared_ptr<ClientDescriptor<KEY, VALUE>> getPrimaryClient(const KEY& key) const;
427 
428     /**
429      * Block until the given client is no longer in the active clients list, or the timeout
430      * occurred.
431      *
432      * Returns NO_ERROR if this succeeded, -ETIMEDOUT on a timeout, or a negative error code on
433      * failure.
434      */
435     status_t waitUntilRemoved(const std::shared_ptr<ClientDescriptor<KEY, VALUE>> client,
436             nsecs_t timeout) const;
437 
438     /**
439      * Set the current listener for client add/remove events.
440      *
441      * The listener instance must inherit from the LISTENER class and implement the following
442      * methods:
443      *    void onClientRemoved(const ClientDescriptor<KEY, VALUE>& descriptor);
444      *    void onClientAdded(const ClientDescriptor<KEY, VALUE>& descriptor);
445      *
446      * These callback methods will be called with the ClientManager's lock held, and should
447      * not call any further ClientManager methods.
448      *
449      * The onClientRemoved method will be called when the client has been removed or evicted
450      * from the ClientManager that this event listener has been added to. The onClientAdded
451      * method will be called when the client has been added to the ClientManager that this
452      * event listener has been added to.
453      */
454     void setListener(const std::shared_ptr<LISTENER>& listener);
455 
456 protected:
457     ~ClientManager();
458 
459 private:
460 
461     /**
462      * Return a vector of the ClientDescriptors that would be evicted by adding the given
463      * ClientDescriptor.  If returnIncompatibleClients is set to true, instead, return the
464      * vector of ClientDescriptors that are higher priority than the incoming client and
465      * either conflict with this client, or contribute to the resource cost if that would
466      * prevent the incoming client from being added.
467      *
468      * This may return the ClientDescriptor passed in.
469      */
470     std::vector<std::shared_ptr<ClientDescriptor<KEY, VALUE>>> wouldEvictLocked(
471             const std::shared_ptr<ClientDescriptor<KEY, VALUE>>& client,
472             bool returnIncompatibleClients = false) const;
473 
474     int64_t getCurrentCostLocked() const;
475 
476     mutable Mutex mLock;
477     mutable Condition mRemovedCondition;
478     int32_t mMaxCost;
479     // LRU ordered, most recent at end
480     std::vector<std::shared_ptr<ClientDescriptor<KEY, VALUE>>> mClients;
481     std::shared_ptr<LISTENER> mListener;
482 }; // class ClientManager
483 
484 template<class KEY, class VALUE, class LISTENER>
ClientManager()485 ClientManager<KEY, VALUE, LISTENER>::ClientManager() :
486         ClientManager(DEFAULT_MAX_COST) {}
487 
488 template<class KEY, class VALUE, class LISTENER>
ClientManager(int32_t totalCost)489 ClientManager<KEY, VALUE, LISTENER>::ClientManager(int32_t totalCost) : mMaxCost(totalCost) {}
490 
491 template<class KEY, class VALUE, class LISTENER>
~ClientManager()492 ClientManager<KEY, VALUE, LISTENER>::~ClientManager() {}
493 
494 template<class KEY, class VALUE, class LISTENER>
495 std::vector<std::shared_ptr<ClientDescriptor<KEY, VALUE>>>
wouldEvict(const std::shared_ptr<ClientDescriptor<KEY,VALUE>> & client)496 ClientManager<KEY, VALUE, LISTENER>::wouldEvict(
497         const std::shared_ptr<ClientDescriptor<KEY, VALUE>>& client) const {
498     Mutex::Autolock lock(mLock);
499     return wouldEvictLocked(client);
500 }
501 
502 template<class KEY, class VALUE, class LISTENER>
503 std::vector<std::shared_ptr<ClientDescriptor<KEY, VALUE>>>
getIncompatibleClients(const std::shared_ptr<ClientDescriptor<KEY,VALUE>> & client)504 ClientManager<KEY, VALUE, LISTENER>::getIncompatibleClients(
505         const std::shared_ptr<ClientDescriptor<KEY, VALUE>>& client) const {
506     Mutex::Autolock lock(mLock);
507     return wouldEvictLocked(client, /*returnIncompatibleClients*/true);
508 }
509 
510 template<class KEY, class VALUE, class LISTENER>
511 std::vector<std::shared_ptr<ClientDescriptor<KEY, VALUE>>>
wouldEvictLocked(const std::shared_ptr<ClientDescriptor<KEY,VALUE>> & client,bool returnIncompatibleClients)512 ClientManager<KEY, VALUE, LISTENER>::wouldEvictLocked(
513         const std::shared_ptr<ClientDescriptor<KEY, VALUE>>& client,
514         bool returnIncompatibleClients) const {
515 
516     std::vector<std::shared_ptr<ClientDescriptor<KEY, VALUE>>> evictList;
517 
518     // Disallow null clients, return input
519     if (client == nullptr) {
520         evictList.push_back(client);
521         return evictList;
522     }
523 
524     const KEY& key = client->getKey();
525     int32_t cost = client->getCost();
526     ClientPriority priority = client->getPriority();
527     int32_t owner = client->getOwnerId();
528     bool sharedMode = client->getSharedMode();
529 
530 
531     int64_t totalCost = getCurrentCostLocked() + cost;
532 
533     // Determine the MRU of the owners tied for having the highest priority
534     int32_t highestPriorityOwner = owner;
535     ClientPriority highestPriority = priority;
536     for (const auto& i : mClients) {
537         ClientPriority curPriority = i->getPriority();
538         if (curPriority <= highestPriority) {
539             highestPriority = curPriority;
540             highestPriorityOwner = i->getOwnerId();
541         }
542     }
543 
544     if (highestPriority == priority) {
545         // Switch back owner if the incoming client has the highest priority, as it is MRU
546         highestPriorityOwner = owner;
547     }
548 
549     // Build eviction list of clients to remove
550     for (const auto& i : mClients) {
551         const KEY& curKey = i->getKey();
552         int32_t curCost = i->getCost();
553         ClientPriority curPriority = i->getPriority();
554         int32_t curOwner = i->getOwnerId();
555         bool curSharedMode = i->getSharedMode();
556         bool conflicting;
557         if (flags::camera_multi_client()) {
558             conflicting = (((!sharedMode || !curSharedMode) && curKey == key)
559                     || i->isConflicting(key) || client->isConflicting(curKey));
560         } else {
561             conflicting = (curKey == key || i->isConflicting(key) ||
562                     client->isConflicting(curKey));
563         }
564 
565         if (!returnIncompatibleClients) {
566             // Find evicted clients
567 
568             if (conflicting && owner == curOwner) {
569                 // Pre-existing conflicting client with the same client owner exists
570                 // Open the same device twice -> most recent open wins
571                 // Otherwise let the existing client wins to avoid behaviors difference
572                 // due to how HAL advertising conflicting devices (which is hidden from
573                 // application)
574                 if (curKey == key) {
575                     evictList.push_back(i);
576                     totalCost -= curCost;
577                 } else {
578                     evictList.clear();
579                     evictList.push_back(client);
580                     return evictList;
581                 }
582             } else if (conflicting && curPriority < priority) {
583                 // Pre-existing conflicting client with higher priority exists
584                 evictList.clear();
585                 evictList.push_back(client);
586                 return evictList;
587             } else if (conflicting || ((totalCost > mMaxCost && curCost > 0) &&
588                     (curPriority >= priority) &&
589                     !(highestPriorityOwner == owner && owner == curOwner))) {
590                 // Add a pre-existing client to the eviction list if:
591                 // - We are adding a client with higher priority that conflicts with this one.
592                 // - The total cost including the incoming client's is more than the allowable
593                 //   maximum, and the client has a non-zero cost, lower priority, and a different
594                 //   owner than the incoming client when the incoming client has the
595                 //   highest priority.
596                 evictList.push_back(i);
597                 totalCost -= curCost;
598             }
599         } else {
600             // Find clients preventing the incoming client from being added
601 
602             if (curPriority < priority && (conflicting || (totalCost > mMaxCost && curCost > 0))) {
603                 // Pre-existing conflicting client with higher priority exists
604                 evictList.push_back(i);
605             }
606         }
607     }
608 
609     // Immediately return the incompatible clients if we are calculating these instead
610     if (returnIncompatibleClients) {
611         return evictList;
612     }
613 
614     // If the total cost is too high, return the input unless the input has the highest priority
615     if (totalCost > mMaxCost && highestPriorityOwner != owner) {
616         evictList.clear();
617         evictList.push_back(client);
618         return evictList;
619     }
620 
621     return evictList;
622 
623 }
624 
625 template<class KEY, class VALUE, class LISTENER>
626 std::vector<std::shared_ptr<ClientDescriptor<KEY, VALUE>>>
addAndEvict(const std::shared_ptr<ClientDescriptor<KEY,VALUE>> & client)627 ClientManager<KEY, VALUE, LISTENER>::addAndEvict(
628         const std::shared_ptr<ClientDescriptor<KEY, VALUE>>& client) {
629     Mutex::Autolock lock(mLock);
630     auto evicted = wouldEvictLocked(client);
631     auto it = evicted.begin();
632     if (it != evicted.end() && *it == client) {
633         return evicted;
634     }
635 
636     auto iter = evicted.cbegin();
637 
638     if (iter != evicted.cend()) {
639 
640         if (mListener != nullptr) mListener->onClientRemoved(**iter);
641 
642         // Remove evicted clients from list
643         mClients.erase(std::remove_if(mClients.begin(), mClients.end(),
644             [&iter] (std::shared_ptr<ClientDescriptor<KEY, VALUE>>& curClientPtr) {
645                 if (curClientPtr->getKey() == (*iter)->getKey()) {
646                     iter++;
647                     return true;
648                 }
649                 return false;
650             }), mClients.end());
651     }
652 
653     if (mListener != nullptr) mListener->onClientAdded(*client);
654     mClients.push_back(client);
655     mRemovedCondition.broadcast();
656 
657     return evicted;
658 }
659 
660 template<class KEY, class VALUE, class LISTENER>
661 std::vector<std::shared_ptr<ClientDescriptor<KEY, VALUE>>>
getAll()662 ClientManager<KEY, VALUE, LISTENER>::getAll() const {
663     Mutex::Autolock lock(mLock);
664     return mClients;
665 }
666 
667 template<class KEY, class VALUE, class LISTENER>
getAllKeys()668 std::vector<KEY> ClientManager<KEY, VALUE, LISTENER>::getAllKeys() const {
669     Mutex::Autolock lock(mLock);
670     std::vector<KEY> keys(mClients.size());
671     for (const auto& i : mClients) {
672         keys.push_back(i->getKey());
673     }
674     return keys;
675 }
676 
677 template<class KEY, class VALUE, class LISTENER>
getAllOwners()678 std::vector<int32_t> ClientManager<KEY, VALUE, LISTENER>::getAllOwners() const {
679     Mutex::Autolock lock(mLock);
680     std::set<int32_t> owners;
681     for (const auto& i : mClients) {
682         owners.emplace(i->getOwnerId());
683     }
684     return std::vector<int32_t>(owners.begin(), owners.end());
685 }
686 
687 template<class KEY, class VALUE, class LISTENER>
updatePriorities(const std::map<int32_t,ClientPriority> & ownerPriorityList)688 void ClientManager<KEY, VALUE, LISTENER>::updatePriorities(
689         const std::map<int32_t,ClientPriority>& ownerPriorityList) {
690     Mutex::Autolock lock(mLock);
691     for (auto& i : mClients) {
692         auto j = ownerPriorityList.find(i->getOwnerId());
693         if (j != ownerPriorityList.end()) {
694             i->setPriority(j->second);
695         }
696     }
697 }
698 
699 template<class KEY, class VALUE, class LISTENER>
get(const KEY & key)700 std::shared_ptr<ClientDescriptor<KEY, VALUE>> ClientManager<KEY, VALUE, LISTENER>::get(
701         const KEY& key) const {
702     Mutex::Autolock lock(mLock);
703     for (const auto& i : mClients) {
704         if (i->getKey() == key) return i;
705     }
706     return std::shared_ptr<ClientDescriptor<KEY, VALUE>>(nullptr);
707 }
708 
709 template<class KEY, class VALUE, class LISTENER>
getPrimaryClient(const KEY & key)710 std::shared_ptr<ClientDescriptor<KEY, VALUE>> ClientManager<KEY, VALUE, LISTENER>::getPrimaryClient(
711         const KEY& key) const {
712     Mutex::Autolock lock(mLock);
713     if (flags::camera_multi_client()) {
714         for (const auto& i : mClients) {
715             bool sharedMode =  i->getSharedMode();
716             bool primaryClient;
717             status_t ret = i->getValue()->isPrimaryClient(&primaryClient);
718             if (ret == OK) {
719                 if ((i->getKey() == key) && sharedMode && primaryClient) {
720                     return i;
721                 }
722             }
723         }
724     }
725     return std::shared_ptr<ClientDescriptor<KEY, VALUE>>(nullptr);
726 }
727 
728 template<class KEY, class VALUE, class LISTENER>
removeAll()729 void ClientManager<KEY, VALUE, LISTENER>::removeAll() {
730     Mutex::Autolock lock(mLock);
731     if (mListener != nullptr) {
732         for (const auto& i : mClients) {
733             mListener->onClientRemoved(*i);
734         }
735     }
736     mClients.clear();
737     mRemovedCondition.broadcast();
738 }
739 
740 template<class KEY, class VALUE, class LISTENER>
741 std::vector<std::shared_ptr<ClientDescriptor<KEY, VALUE>>>
removeAll(const KEY & key)742         ClientManager<KEY, VALUE, LISTENER>::removeAll(const KEY& key) {
743     Mutex::Autolock lock(mLock);
744     std::vector<std::shared_ptr<ClientDescriptor<KEY, VALUE>>> clients;
745     if (flags::camera_multi_client()) {
746         for (auto it = mClients.begin(); it != mClients.end();)
747         {
748             if ((*it)->getKey() == key) {
749                 if (mListener != nullptr) mListener->onClientRemoved(**it);
750                 clients.push_back(*it);
751                 it = mClients.erase(it);
752             } else {
753                 ++it;
754             }
755         }
756         mRemovedCondition.broadcast();
757     }
758     return clients;
759 }
760 
761 template<class KEY, class VALUE, class LISTENER>
remove(const KEY & key)762 std::shared_ptr<ClientDescriptor<KEY, VALUE>> ClientManager<KEY, VALUE, LISTENER>::remove(
763     const KEY& key) {
764     Mutex::Autolock lock(mLock);
765 
766     std::shared_ptr<ClientDescriptor<KEY, VALUE>> ret;
767 
768     // Remove evicted clients from list
769     mClients.erase(std::remove_if(mClients.begin(), mClients.end(),
770         [this, &key, &ret] (std::shared_ptr<ClientDescriptor<KEY, VALUE>>& curClientPtr) {
771             if (curClientPtr->getKey() == key) {
772                 if (mListener != nullptr) mListener->onClientRemoved(*curClientPtr);
773                 ret = curClientPtr;
774                 return true;
775             }
776             return false;
777         }), mClients.end());
778 
779     mRemovedCondition.broadcast();
780     return ret;
781 }
782 
783 template<class KEY, class VALUE, class LISTENER>
waitUntilRemoved(const std::shared_ptr<ClientDescriptor<KEY,VALUE>> client,nsecs_t timeout)784 status_t ClientManager<KEY, VALUE, LISTENER>::waitUntilRemoved(
785         const std::shared_ptr<ClientDescriptor<KEY, VALUE>> client,
786         nsecs_t timeout) const {
787     status_t ret = NO_ERROR;
788     Mutex::Autolock lock(mLock);
789 
790     bool isRemoved = false;
791 
792     // Figure out what time in the future we should hit the timeout
793     nsecs_t failTime = systemTime(SYSTEM_TIME_MONOTONIC) + timeout;
794 
795     while (!isRemoved) {
796         isRemoved = true;
797         for (const auto& i : mClients) {
798             if (i == client) {
799                 isRemoved = false;
800             }
801         }
802 
803         if (!isRemoved) {
804             ret = mRemovedCondition.waitRelative(mLock, timeout);
805             if (ret != NO_ERROR) {
806                 break;
807             }
808             timeout = failTime - systemTime(SYSTEM_TIME_MONOTONIC);
809         }
810     }
811 
812     return ret;
813 }
814 
815 template<class KEY, class VALUE, class LISTENER>
setListener(const std::shared_ptr<LISTENER> & listener)816 void ClientManager<KEY, VALUE, LISTENER>::setListener(const std::shared_ptr<LISTENER>& listener) {
817     Mutex::Autolock lock(mLock);
818     mListener = listener;
819 }
820 
821 template<class KEY, class VALUE, class LISTENER>
remove(const std::shared_ptr<ClientDescriptor<KEY,VALUE>> & value)822 void ClientManager<KEY, VALUE, LISTENER>::remove(
823         const std::shared_ptr<ClientDescriptor<KEY, VALUE>>& value) {
824     Mutex::Autolock lock(mLock);
825     // Remove evicted clients from list
826     mClients.erase(std::remove_if(mClients.begin(), mClients.end(),
827         [this, &value] (std::shared_ptr<ClientDescriptor<KEY, VALUE>>& curClientPtr) {
828             if (curClientPtr == value) {
829                 if (mListener != nullptr) mListener->onClientRemoved(*curClientPtr);
830                 return true;
831             }
832             return false;
833         }), mClients.end());
834     mRemovedCondition.broadcast();
835 }
836 
837 template<class KEY, class VALUE, class LISTENER>
getCurrentCostLocked()838 int64_t ClientManager<KEY, VALUE, LISTENER>::getCurrentCostLocked() const {
839     int64_t totalCost = 0;
840     for (const auto& x : mClients) {
841             totalCost += x->getCost();
842     }
843     return totalCost;
844 }
845 
846 // --------------------------------------------------------------------------------
847 
848 }; // namespace resource_policy
849 }; // namespace android
850 
851 #endif // ANDROID_SERVICE_UTILS_EVICTION_POLICY_MANAGER_H
852