1 /**
2  * Copyright (c) 2020, 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 "carpowerpolicyd"
18 #define DEBUG false  // STOPSHIP if true.
19 
20 #include "CarPowerPolicyServer.h"
21 
22 #include <aidl/android/hardware/automotive/vehicle/StatusCode.h>
23 #include <aidl/android/hardware/automotive/vehicle/SubscribeOptions.h>
24 #include <aidl/android/hardware/automotive/vehicle/VehicleApPowerStateReport.h>
25 #include <aidl/android/hardware/automotive/vehicle/VehicleProperty.h>
26 #include <android-base/file.h>
27 #include <android-base/stringprintf.h>
28 #include <android/binder_ibinder.h>
29 #include <android/binder_manager.h>
30 #include <android/binder_status.h>
31 #include <binder/IPCThreadState.h>
32 #include <binder/IServiceManager.h>
33 #include <hidl/HidlTransportSupport.h>
34 #include <private/android_filesystem_config.h>
35 #include <utils/String8.h>
36 #include <utils/SystemClock.h>
37 #include <utils/Timers.h>
38 
39 #include <android_car_feature.h>
40 #include <inttypes.h>
41 
42 namespace android {
43 namespace frameworks {
44 namespace automotive {
45 namespace powerpolicy {
46 
47 using ::aidl::android::automotive::powerpolicy::internal::ICarPowerPolicyDelegate;
48 using ::aidl::android::automotive::powerpolicy::internal::ICarPowerPolicyDelegateCallback;
49 using ::aidl::android::automotive::powerpolicy::internal::PowerPolicyFailureReason;
50 using ::aidl::android::automotive::powerpolicy::internal::PowerPolicyInitData;
51 using ::aidl::android::frameworks::automotive::powerpolicy::CarPowerPolicy;
52 using ::aidl::android::frameworks::automotive::powerpolicy::CarPowerPolicyFilter;
53 using ::aidl::android::frameworks::automotive::powerpolicy::ICarPowerPolicyChangeCallback;
54 using ::aidl::android::frameworks::automotive::powerpolicy::PowerComponent;
55 using ::aidl::android::frameworks::automotive::powerpolicy::internal::PolicyState;
56 using ::aidl::android::hardware::automotive::vehicle::StatusCode;
57 using ::aidl::android::hardware::automotive::vehicle::SubscribeOptions;
58 using ::aidl::android::hardware::automotive::vehicle::VehicleApPowerStateReport;
59 using ::aidl::android::hardware::automotive::vehicle::VehicleProperty;
60 
61 using ::android::defaultServiceManager;
62 using ::android::IBinder;
63 using ::android::Looper;
64 using ::android::Mutex;
65 using ::android::status_t;
66 using ::android::String16;
67 using ::android::uptimeMillis;
68 using ::android::Vector;
69 using ::android::wp;
70 using ::android::base::Error;
71 using ::android::base::Result;
72 using ::android::base::StringAppendF;
73 using ::android::base::StringPrintf;
74 using ::android::base::WriteStringToFd;
75 using ::android::car::feature::car_power_policy_refactoring;
76 using ::android::frameworks::automotive::vhal::HalPropError;
77 using ::android::frameworks::automotive::vhal::IHalPropValue;
78 using ::android::frameworks::automotive::vhal::ISubscriptionClient;
79 using ::android::frameworks::automotive::vhal::IVhalClient;
80 using ::android::frameworks::automotive::vhal::VhalClientResult;
81 
82 using ::android::hardware::hidl_vec;
83 using ::android::hardware::interfacesEqual;
84 using ::android::hardware::Return;
85 
86 using ::android::hidl::base::V1_0::IBase;
87 using ::ndk::ScopedAIBinder_DeathRecipient;
88 using ::ndk::ScopedAStatus;
89 using ::ndk::SharedRefBase;
90 using ::ndk::SpAIBinder;
91 
92 namespace {
93 
94 const int32_t MSG_CONNECT_TO_VHAL = 1;  // Message to request of connecting to VHAL.
95 
96 const nsecs_t kConnectionRetryIntervalNs = 200000000;  // 200 milliseconds.
97 const int32_t kMaxConnectionRetry = 5 * 60;                // Retry up to 60 seconds.
98 
99 constexpr const char kCarServiceInterface[] = "car_service";
100 constexpr const char kCarPowerPolicyServerInterface[] =
101         "android.frameworks.automotive.powerpolicy.ICarPowerPolicyServer/default";
102 constexpr const char kCarPowerPolicySystemNotificationInterface[] =
103         "android.frameworks.automotive.powerpolicy.internal.ICarPowerPolicySystemNotification/"
104         "default";
105 constexpr const char kCarPowerPolicyDelegateInterface[] =
106         "android.automotive.powerpolicy.internal.ICarPowerPolicyDelegate/default";
107 
lookupPowerPolicyChangeCallback(const std::vector<CallbackInfo> & callbacks,const AIBinder * binder)108 std::vector<CallbackInfo>::const_iterator lookupPowerPolicyChangeCallback(
109         const std::vector<CallbackInfo>& callbacks, const AIBinder* binder) {
110     for (auto it = callbacks.begin(); it != callbacks.end(); it++) {
111         if (it->binder.get() == binder) {
112             return it;
113         }
114     }
115     return callbacks.end();
116 }
117 
checkSystemPermission()118 ScopedAStatus checkSystemPermission() {
119     if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
120         return ScopedAStatus::fromServiceSpecificErrorWithMessage(EX_SECURITY,
121                                                                   "Calling process does not have "
122                                                                   "proper privilege");
123     }
124     return ScopedAStatus::ok();
125 }
126 
convertErrorToFailureReason(int errorCode)127 PowerPolicyFailureReason convertErrorToFailureReason(int errorCode) {
128     switch (errorCode) {
129         case EX_ILLEGAL_ARGUMENT:
130             return PowerPolicyFailureReason::POWER_POLICY_FAILURE_NOT_REGISTERED_ID;
131         default:
132             return PowerPolicyFailureReason::POWER_POLICY_FAILURE_UNKNOWN;
133     }
134 }
135 
136 }  // namespace
137 
138 std::shared_ptr<CarPowerPolicyServer> CarPowerPolicyServer::sCarPowerPolicyServer = nullptr;
139 
PropertyChangeListener(CarPowerPolicyServer * service)140 PropertyChangeListener::PropertyChangeListener(CarPowerPolicyServer* service) : mService(service) {}
141 
onPropertyEvent(const std::vector<std::unique_ptr<IHalPropValue>> & values)142 void PropertyChangeListener::onPropertyEvent(
143         const std::vector<std::unique_ptr<IHalPropValue>>& values) {
144     for (const auto& value : values) {
145         const std::string stringValue = value->getStringValue();
146         int32_t propId = value->getPropId();
147         if (propId == static_cast<int32_t>(VehicleProperty::POWER_POLICY_GROUP_REQ)) {
148             const auto& ret = mService->setPowerPolicyGroupInternal(stringValue);
149             if (!ret.ok()) {
150                 ALOGW("Failed to set power policy group(%s): %s", stringValue.c_str(),
151                       ret.error().message().c_str());
152             }
153         } else if (propId == static_cast<int32_t>(VehicleProperty::POWER_POLICY_REQ)) {
154             const auto& ret = mService->applyPowerPolicy(stringValue,
155                                                          /*carServiceExpected=*/false,
156                                                          /*force=*/false);
157             if (!ret.ok()) {
158                 ALOGW("Failed to apply power policy(%s): %s", stringValue.c_str(),
159                       ret.error().message().c_str());
160             }
161         }
162     }
163 }
164 
onPropertySetError(const std::vector<HalPropError> & errors)165 void PropertyChangeListener::onPropertySetError(
166         [[maybe_unused]] const std::vector<HalPropError>& errors) {
167     return;
168 }
169 
EventHandler(CarPowerPolicyServer * service)170 EventHandler::EventHandler(CarPowerPolicyServer* service) : mService(service) {}
171 
handleMessage(const Message & message)172 void EventHandler::handleMessage(const Message& message) {
173     switch (message.what) {
174         case MSG_CONNECT_TO_VHAL:
175             mService->connectToVhalHelper();
176             break;
177         default:
178             ALOGW("Unknown message: %d", message.what);
179     }
180 }
181 
RequestIdHandler(CarPowerPolicyServer * service)182 RequestIdHandler::RequestIdHandler(CarPowerPolicyServer* service) : mService(service) {}
183 
handleMessage(const Message & message)184 void RequestIdHandler::handleMessage(const Message& message) {
185     mService->handleApplyPowerPolicyRequest(message.what);
186 }
187 
CarServiceNotificationHandler(CarPowerPolicyServer * service)188 CarServiceNotificationHandler::CarServiceNotificationHandler(CarPowerPolicyServer* service) :
189       mService(service) {}
190 
terminate()191 void CarServiceNotificationHandler::terminate() {
192     std::lock_guard<std::mutex> lock(mMutex);
193     mService = nullptr;
194 }
195 
dump(int fd,const char ** args,uint32_t numArgs)196 binder_status_t CarServiceNotificationHandler::dump(int fd, const char** args, uint32_t numArgs) {
197     std::lock_guard<std::mutex> lock(mMutex);
198     if (mService == nullptr) {
199         ALOGD("Skip dumping, CarPowerPolicyServer is ending");
200         return STATUS_OK;
201     }
202     return mService->dump(fd, args, numArgs);
203 }
204 
notifyCarServiceReady(PolicyState * policyState)205 ScopedAStatus CarServiceNotificationHandler::notifyCarServiceReady(PolicyState* policyState) {
206     std::lock_guard<std::mutex> lock(mMutex);
207     if (mService == nullptr) {
208         ALOGD("Skip notifying CarServiceReady, CarPowerPolicyServer is ending");
209         return ScopedAStatus::ok();
210     }
211     return mService->notifyCarServiceReady(policyState);
212 }
213 
notifyPowerPolicyChange(const std::string & policyId,bool force)214 ScopedAStatus CarServiceNotificationHandler::notifyPowerPolicyChange(const std::string& policyId,
215                                                                      bool force) {
216     std::lock_guard<std::mutex> lock(mMutex);
217     if (mService == nullptr) {
218         ALOGD("Skip notifying PowerPolicyChange, CarPowerPolicyServer is ending");
219         return ScopedAStatus::ok();
220     }
221     return mService->notifyPowerPolicyChange(policyId, force);
222 }
223 
notifyPowerPolicyDefinition(const std::string & policyId,const std::vector<std::string> & enabledComponents,const std::vector<std::string> & disabledComponents)224 ScopedAStatus CarServiceNotificationHandler::notifyPowerPolicyDefinition(
225         const std::string& policyId, const std::vector<std::string>& enabledComponents,
226         const std::vector<std::string>& disabledComponents) {
227     std::lock_guard<std::mutex> lock(mMutex);
228     if (mService == nullptr) {
229         ALOGD("Skip notifying PowerPolicyDefinition, CarPowerPolicyServer is ending");
230         return ScopedAStatus::ok();
231     }
232     return mService->notifyPowerPolicyDefinition(policyId, enabledComponents, disabledComponents);
233 }
234 
CarPowerPolicyDelegate(CarPowerPolicyServer * service)235 CarPowerPolicyDelegate::CarPowerPolicyDelegate(CarPowerPolicyServer* service) : mService(service) {}
236 
terminate()237 void CarPowerPolicyDelegate::terminate() {
238     std::lock_guard<std::mutex> lock(mMutex);
239     mService = nullptr;
240 }
241 
dump(int fd,const char ** args,uint32_t numArgs)242 binder_status_t CarPowerPolicyDelegate::dump(int fd, const char** args, uint32_t numArgs) {
243     std::lock_guard<std::mutex> lock(mMutex);
244     if (mService == nullptr) {
245         ALOGD("Skip dumping, CarPowerPolicyServer is ending");
246         return STATUS_OK;
247     }
248     return mService->dump(fd, args, numArgs);
249 }
250 
notifyCarServiceReady(const std::shared_ptr<ICarPowerPolicyDelegateCallback> & callback,PowerPolicyInitData * aidlReturn)251 ScopedAStatus CarPowerPolicyDelegate::notifyCarServiceReady(
252         const std::shared_ptr<ICarPowerPolicyDelegateCallback>& callback,
253         PowerPolicyInitData* aidlReturn) {
254     return runWithService(
255             [callback, aidlReturn](CarPowerPolicyServer* service) -> ScopedAStatus {
256                 return service->notifyCarServiceReadyInternal(callback, aidlReturn);
257             },
258             "notifyCarServiceReady");
259 }
260 
applyPowerPolicyAsync(int32_t requestId,const std::string & policyId,bool force)261 ScopedAStatus CarPowerPolicyDelegate::applyPowerPolicyAsync(int32_t requestId,
262                                                             const std::string& policyId,
263                                                             bool force) {
264     return runWithService(
265             [requestId, policyId, force](CarPowerPolicyServer* service) -> ScopedAStatus {
266                 return service->applyPowerPolicyAsync(requestId, policyId, force);
267             },
268             "applyPowerPolicyAsync");
269 }
270 
setPowerPolicyGroup(const std::string & policyGroupId)271 ScopedAStatus CarPowerPolicyDelegate::setPowerPolicyGroup(const std::string& policyGroupId) {
272     std::lock_guard<std::mutex> lock(mMutex);
273     if (mService == nullptr) {
274         ALOGD("Skip setting power policy group, CarPowerPolicyServer is ending");
275         return ScopedAStatus::ok();
276     }
277     if (const auto& ret = mService->setPowerPolicyGroupInternal(policyGroupId); !ret.ok()) {
278         return ScopedAStatus::fromExceptionCodeWithMessage(ret.error().code(),
279                                                            ret.error().message().c_str());
280     }
281     return ScopedAStatus::ok();
282 }
283 
notifyPowerPolicyDefinition(const std::string & policyId,const std::vector<std::string> & enabledComponents,const std::vector<std::string> & disabledComponents)284 ScopedAStatus CarPowerPolicyDelegate::notifyPowerPolicyDefinition(
285         const std::string& policyId, const std::vector<std::string>& enabledComponents,
286         const std::vector<std::string>& disabledComponents) {
287     return runWithService(
288             [policyId, enabledComponents,
289              disabledComponents](CarPowerPolicyServer* service) -> ScopedAStatus {
290                 return service->notifyPowerPolicyDefinition(policyId, enabledComponents,
291                                                             disabledComponents);
292             },
293             "notifyPowerPolicyDefinition");
294 }
295 
notifyPowerPolicyGroupDefinition(const std::string & policyGroupId,const std::vector<std::string> & powerPolicyPerState)296 ScopedAStatus CarPowerPolicyDelegate::notifyPowerPolicyGroupDefinition(
297         const std::string& policyGroupId, const std::vector<std::string>& powerPolicyPerState) {
298     return runWithService(
299             [policyGroupId, powerPolicyPerState](CarPowerPolicyServer* service) -> ScopedAStatus {
300                 return service->notifyPowerPolicyGroupDefinition(policyGroupId,
301                                                                  powerPolicyPerState);
302             },
303             "notifyPowerPolicyGroupDefinition");
304 }
305 
applyPowerPolicyPerPowerStateChangeAsync(int32_t requestId,ICarPowerPolicyDelegate::PowerState state)306 ScopedAStatus CarPowerPolicyDelegate::applyPowerPolicyPerPowerStateChangeAsync(
307         int32_t requestId, ICarPowerPolicyDelegate::PowerState state) {
308     return runWithService(
309             [requestId, state](CarPowerPolicyServer* service) -> ScopedAStatus {
310                 return service->applyPowerPolicyPerPowerStateChangeAsync(requestId, state);
311             },
312             "applyPowerPolicyPerPowerStateChangeAsync");
313 }
314 
setSilentMode(const std::string & silentMode)315 ScopedAStatus CarPowerPolicyDelegate::setSilentMode(const std::string& silentMode) {
316     return runWithService([silentMode](CarPowerPolicyServer* service)
317                                   -> ScopedAStatus { return service->setSilentMode(silentMode); },
318                           "setSilentMode");
319 }
320 
runWithService(const std::function<ScopedAStatus (CarPowerPolicyServer *)> & action,const std::string & actionTitle)321 ScopedAStatus CarPowerPolicyDelegate::runWithService(
322         const std::function<ScopedAStatus(CarPowerPolicyServer*)>& action,
323         const std::string& actionTitle) {
324     std::lock_guard<std::mutex> lock(mMutex);
325     if (mService == nullptr) {
326         ALOGD("Skip %s, CarPowerPolicyServer is ending", actionTitle.c_str());
327         return ScopedAStatus::ok();
328     }
329     return action(mService);
330 }
331 
~ISilentModeChangeHandler()332 ISilentModeChangeHandler::~ISilentModeChangeHandler() {}
333 
startService(const sp<Looper> & looper)334 Result<std::shared_ptr<CarPowerPolicyServer>> CarPowerPolicyServer::startService(
335         const sp<Looper>& looper) {
336     if (sCarPowerPolicyServer != nullptr) {
337         return Error(INVALID_OPERATION) << "Cannot start service more than once";
338     }
339     std::shared_ptr<CarPowerPolicyServer> server = SharedRefBase::make<CarPowerPolicyServer>();
340     const auto& ret = server->init(looper);
341     if (!ret.ok()) {
342         return Error(ret.error().code())
343                 << "Failed to start car power policy server: " << ret.error();
344     }
345     sCarPowerPolicyServer = server;
346 
347     return sCarPowerPolicyServer;
348 }
349 
terminateService()350 void CarPowerPolicyServer::terminateService() {
351     if (sCarPowerPolicyServer != nullptr) {
352         sCarPowerPolicyServer->terminate();
353         sCarPowerPolicyServer = nullptr;
354     }
355 }
356 
CarPowerPolicyServer()357 CarPowerPolicyServer::CarPowerPolicyServer() :
358       mSilentModeHandler(this),
359       mIsPowerPolicyLocked(false),
360       mIsCarServiceInOperation(false),
361       mIsFirstConnectionToVhal(true) {
362     mEventHandler = new EventHandler(this);
363     mRequestIdHandler = new RequestIdHandler(this);
364     mClientDeathRecipient = ScopedAIBinder_DeathRecipient(
365             AIBinder_DeathRecipient_new(&CarPowerPolicyServer::onClientBinderDied));
366     mCarServiceDeathRecipient = ScopedAIBinder_DeathRecipient(
367             AIBinder_DeathRecipient_new(&CarPowerPolicyServer::onCarServiceBinderDied));
368     mPropertyChangeListener = std::make_unique<PropertyChangeListener>(this);
369     mLinkUnlinkImpl = std::make_unique<AIBinderLinkUnlinkImpl>();
370 
371     setOnUnlinked();
372 }
373 
~CarPowerPolicyServer()374 CarPowerPolicyServer::~CarPowerPolicyServer() {
375     terminate();
376 
377     // Delete the deathRecipient so that all binders would be unlinked.
378     mLinkUnlinkImpl->deleteDeathRecipient(mClientDeathRecipient.release());
379     mLinkUnlinkImpl->deleteDeathRecipient(mCarServiceDeathRecipient.release());
380 
381     // Wait for all onClientDeathRecipientUnlinked and onCarServiceDeathRecipientUnlinked to be
382     // called.
383     {
384         std::unique_lock lock(mMutex);
385         mResourceReleasedCv.wait(lock, [this] {
386             return mOnClientBinderDiedContexts.empty() && !mCarServiceLinked;
387         });
388     }
389 }
390 
391 // For test-only.
setLinkUnlinkImpl(std::unique_ptr<CarPowerPolicyServer::LinkUnlinkImpl> impl)392 void CarPowerPolicyServer::setLinkUnlinkImpl(
393         std::unique_ptr<CarPowerPolicyServer::LinkUnlinkImpl> impl) {
394     mLinkUnlinkImpl = std::move(impl);
395 
396     setOnUnlinked();
397 }
398 
setOnUnlinked()399 void CarPowerPolicyServer::setOnUnlinked() {
400     mLinkUnlinkImpl->setOnUnlinked(mCarServiceDeathRecipient.get(),
401                                    &CarPowerPolicyServer::onCarServiceDeathRecipientUnlinked);
402     mLinkUnlinkImpl->setOnUnlinked(mClientDeathRecipient.get(),
403                                    &CarPowerPolicyServer::onClientDeathRecipientUnlinked);
404 }
405 
getCurrentPowerPolicy(CarPowerPolicy * aidlReturn)406 ScopedAStatus CarPowerPolicyServer::getCurrentPowerPolicy(CarPowerPolicy* aidlReturn) {
407     std::lock_guard<std::mutex> lock(mMutex);
408     if (!isPowerPolicyAppliedLocked()) {
409         return ScopedAStatus::
410                 fromServiceSpecificErrorWithMessage(EX_ILLEGAL_STATE,
411                                                     "The current power policy is not set");
412     }
413     *aidlReturn = *mCurrentPowerPolicyMeta.powerPolicy;
414     return ScopedAStatus::ok();
415 }
416 
getPowerComponentState(PowerComponent componentId,bool * aidlReturn)417 ScopedAStatus CarPowerPolicyServer::getPowerComponentState(PowerComponent componentId,
418                                                            bool* aidlReturn) {
419     const auto& ret = mComponentHandler.getPowerComponentState(componentId);
420     if (!ret.ok()) {
421         std::string errorMsg = ret.error().message();
422         ALOGW("getPowerComponentState(%s) failed: %s", toString(componentId).c_str(),
423               errorMsg.c_str());
424         return ScopedAStatus::fromServiceSpecificErrorWithMessage(EX_ILLEGAL_ARGUMENT,
425                                                                   errorMsg.c_str());
426     }
427     *aidlReturn = *ret;
428     return ScopedAStatus::ok();
429 }
430 
registerPowerPolicyChangeCallback(const std::shared_ptr<ICarPowerPolicyChangeCallback> & callback,const CarPowerPolicyFilter & filter)431 ScopedAStatus CarPowerPolicyServer::registerPowerPolicyChangeCallback(
432         const std::shared_ptr<ICarPowerPolicyChangeCallback>& callback,
433         const CarPowerPolicyFilter& filter) {
434     if (callback == nullptr) {
435         std::string errorMsg = "Cannot register a null callback";
436         ALOGW("%s", errorMsg.c_str());
437         return ScopedAStatus::fromServiceSpecificErrorWithMessage(EX_ILLEGAL_ARGUMENT,
438                                                                   errorMsg.c_str());
439     }
440     pid_t callingPid = IPCThreadState::self()->getCallingPid();
441     uid_t callingUid = IPCThreadState::self()->getCallingUid();
442     SpAIBinder binder = callback->asBinder();
443     AIBinder* clientId = binder.get();
444     void* contextPtr;
445 
446     {
447         std::lock_guard<std::mutex> lock(mMutex);
448         if (isRegisteredLocked(clientId)) {
449             std::string errorStr =
450                     StringPrintf("The callback(pid: %d, uid: %d) is already registered.",
451                                  callingPid, callingUid);
452             const char* errorCause = errorStr.c_str();
453             ALOGW("Cannot register a callback: %s", errorCause);
454             return ScopedAStatus::fromServiceSpecificErrorWithMessage(EX_ILLEGAL_ARGUMENT,
455                                                                       errorCause);
456         }
457 
458         std::unique_ptr<OnClientBinderDiedContext> context =
459                 std::make_unique<OnClientBinderDiedContext>(
460                         OnClientBinderDiedContext{.server = this, .clientId = clientId});
461         // Get a raw pointer to be passed as cookie to death recipient.
462         contextPtr = static_cast<void*>(context.get());
463         // Insert into a map to keep the context object alive.
464         mOnClientBinderDiedContexts[clientId] = std::move(context);
465         mPolicyChangeCallbacks.emplace_back(binder, filter, callingPid);
466     }
467 
468     // Do not call linkToDeath within a locked scope. handleClientDeathRecipientUnlinked might be
469     // called within which requires a lock.
470     binder_status_t status =
471             mLinkUnlinkImpl->linkToDeath(clientId, mClientDeathRecipient.get(), contextPtr);
472     if (status != STATUS_OK) {
473         // In this case, onBinderDied will not be called and we should clean up registered
474         // policyChangeCallback.
475         handleClientBinderDeath(clientId);
476 
477         std::string errorStr = StringPrintf("The given callback(pid: %d, uid: %d) is dead",
478                                             callingPid, callingUid);
479         const char* errorCause = errorStr.c_str();
480         ALOGW("Cannot register a callback: %s", errorCause);
481         return ScopedAStatus::fromServiceSpecificErrorWithMessage(EX_ILLEGAL_STATE, errorCause);
482     }
483     if (DEBUG) {
484         ALOGD("Power policy change callback(pid: %d, filter: %s) is registered", callingPid,
485               toString(filter.components).c_str());
486     }
487     return ScopedAStatus::ok();
488 }
489 
unregisterPowerPolicyChangeCallback(const std::shared_ptr<ICarPowerPolicyChangeCallback> & callback)490 ScopedAStatus CarPowerPolicyServer::unregisterPowerPolicyChangeCallback(
491         const std::shared_ptr<ICarPowerPolicyChangeCallback>& callback) {
492     pid_t callingPid = IPCThreadState::self()->getCallingPid();
493     uid_t callingUid = IPCThreadState::self()->getCallingUid();
494     if (callback == nullptr) {
495         std::string errorMsg = "Cannot unregister a null callback";
496         ALOGW("%s", errorMsg.c_str());
497         return ScopedAStatus::fromServiceSpecificErrorWithMessage(EX_ILLEGAL_ARGUMENT,
498                                                                   errorMsg.c_str());
499     }
500     AIBinder* clientId = callback->asBinder().get();
501     void* cookie = nullptr;
502 
503     {
504         std::lock_guard<std::mutex> lock(mMutex);
505         auto it = lookupPowerPolicyChangeCallback(mPolicyChangeCallbacks, clientId);
506         if (it == mPolicyChangeCallbacks.end()) {
507             std::string errorStr =
508                     StringPrintf("The callback(pid: %d, uid: %d) has not been registered",
509                                  callingPid, callingUid);
510             const char* errorCause = errorStr.c_str();
511             ALOGW("Cannot unregister a callback: %s", errorCause);
512             return ScopedAStatus::fromServiceSpecificErrorWithMessage(EX_ILLEGAL_ARGUMENT,
513                                                                       errorCause);
514         }
515         if (mOnClientBinderDiedContexts.find(clientId) != mOnClientBinderDiedContexts.end()) {
516             // We don't set a callback for unlinkToDeath but need to call unlinkToDeath to clean up
517             // the registered death recipient.
518             cookie = static_cast<void*>(mOnClientBinderDiedContexts[clientId].get());
519         }
520         mPolicyChangeCallbacks.erase(it);
521     }
522 
523     if (cookie != nullptr) {
524         mLinkUnlinkImpl->unlinkToDeath(clientId, mClientDeathRecipient.get(), cookie);
525     }
526 
527     if (DEBUG) {
528         ALOGD("Power policy change callback(pid: %d, uid: %d) is unregistered", callingPid,
529               callingUid);
530     }
531     return ScopedAStatus::ok();
532 }
533 
applyPowerPolicy(const std::string & policyId)534 ScopedAStatus CarPowerPolicyServer::applyPowerPolicy(const std::string& policyId) {
535     if (!car_power_policy_refactoring()) {
536         ALOGE("Cannot execute applyPowerPolicy: car_power_policy_refactoring flag is not enabled");
537         return ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
538     }
539     if (const auto& ret =
540                 applyPowerPolicyInternal(policyId, /*force=*/false, /*notifyCarService=*/true);
541         !ret.ok()) {
542         return ScopedAStatus::fromExceptionCodeWithMessage(ret.error().code(),
543                                                            ret.error().message().c_str());
544     }
545     return ScopedAStatus::ok();
546 }
547 
setPowerPolicyGroup(const std::string & policyGroupId)548 ScopedAStatus CarPowerPolicyServer::setPowerPolicyGroup(const std::string& policyGroupId) {
549     if (!car_power_policy_refactoring()) {
550         ALOGE("Cannot execute setPowerPolicyGroup: car_power_policy_refactoring flag is not "
551               "enabled");
552         return ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
553     }
554     if (const auto& ret = setPowerPolicyGroupInternal(policyGroupId); !ret.ok()) {
555         return ScopedAStatus::fromExceptionCodeWithMessage(ret.error().code(),
556                                                            ret.error().message().c_str());
557     }
558     return ScopedAStatus::ok();
559 }
560 
notifyCarServiceReady(PolicyState * policyState)561 ScopedAStatus CarPowerPolicyServer::notifyCarServiceReady(PolicyState* policyState) {
562     ScopedAStatus status = checkSystemPermission();
563     if (!status.isOk()) {
564         return status;
565     }
566     mSilentModeHandler.stopMonitoringSilentModeHwState();
567     std::lock_guard<std::mutex> lock(mMutex);
568     policyState->policyId =
569             isPowerPolicyAppliedLocked() ? mCurrentPowerPolicyMeta.powerPolicy->policyId : "";
570     policyState->policyGroupId = mCurrentPolicyGroupId;
571     mIsCarServiceInOperation = true;
572     ALOGI("CarService is now responsible for power policy management");
573     return ScopedAStatus::ok();
574 }
575 
notifyPowerPolicyChange(const std::string & policyId,bool force)576 ScopedAStatus CarPowerPolicyServer::notifyPowerPolicyChange(const std::string& policyId,
577                                                             bool force) {
578     ScopedAStatus status = checkSystemPermission();
579     if (!status.isOk()) {
580         return status;
581     }
582     const auto& ret = applyPowerPolicy(policyId, /*carServiceExpected=*/true, force);
583     if (!ret.ok()) {
584         return ScopedAStatus::
585                 fromServiceSpecificErrorWithMessage(EX_ILLEGAL_STATE,
586                                                     StringPrintf("Failed to notify power policy "
587                                                                  "change: %s",
588                                                                  ret.error().message().c_str())
589                                                             .c_str());
590     }
591     ALOGD("Policy change(%s) is notified by CarService", policyId.c_str());
592     return ScopedAStatus::ok();
593 }
594 
notifyPowerPolicyDefinition(const std::string & policyId,const std::vector<std::string> & enabledComponents,const std::vector<std::string> & disabledComponents)595 ScopedAStatus CarPowerPolicyServer::notifyPowerPolicyDefinition(
596         const std::string& policyId, const std::vector<std::string>& enabledComponents,
597         const std::vector<std::string>& disabledComponents) {
598     ScopedAStatus status = checkSystemPermission();
599     if (!status.isOk()) {
600         return status;
601     }
602     const auto& ret =
603             mPolicyManager.definePowerPolicy(policyId, enabledComponents, disabledComponents);
604     if (!ret.ok()) {
605         return ScopedAStatus::
606                 fromServiceSpecificErrorWithMessage(EX_ILLEGAL_ARGUMENT,
607                                                     StringPrintf("Failed to notify power policy "
608                                                                  "definition: %s",
609                                                                  ret.error().message().c_str())
610                                                             .c_str());
611     }
612     return ScopedAStatus::ok();
613 }
614 
notifyPowerPolicyGroupDefinition(const std::string & policyGroupId,const std::vector<std::string> & powerPolicyPerState)615 ScopedAStatus CarPowerPolicyServer::notifyPowerPolicyGroupDefinition(
616         const std::string& policyGroupId, const std::vector<std::string>& powerPolicyPerState) {
617     ScopedAStatus status = checkSystemPermission();
618     if (!status.isOk()) {
619         return status;
620     }
621     const auto& ret = mPolicyManager.definePowerPolicyGroup(policyGroupId, powerPolicyPerState);
622     if (!ret.ok()) {
623         return ScopedAStatus::
624                 fromServiceSpecificErrorWithMessage(EX_ILLEGAL_ARGUMENT,
625                                                     StringPrintf("Failed to notify power policy "
626                                                                  "group definition: %s",
627                                                                  ret.error().message().c_str())
628                                                             .c_str());
629     }
630     return ScopedAStatus::ok();
631 }
632 
applyPowerPolicyPerPowerStateChangeAsync(int32_t requestId,ICarPowerPolicyDelegate::PowerState state)633 ScopedAStatus CarPowerPolicyServer::applyPowerPolicyPerPowerStateChangeAsync(
634         int32_t requestId, ICarPowerPolicyDelegate::PowerState state) {
635     ScopedAStatus status = checkSystemPermission();
636     if (!status.isOk()) {
637         return status;
638     }
639     VehicleApPowerStateReport apPowerState;
640     std::string defaultPowerPolicyId;
641     // TODO(b/318520417): Power policy should be updated according to SilentMode.
642     // TODO(b/321319532): Create a map for default power policy in PolicyManager.
643     switch (state) {
644         case ICarPowerPolicyDelegate::PowerState::WAIT_FOR_VHAL:
645             apPowerState = VehicleApPowerStateReport::WAIT_FOR_VHAL;
646             defaultPowerPolicyId = kSystemPolicyIdInitialOn;
647             break;
648         case ICarPowerPolicyDelegate::PowerState::ON:
649             apPowerState = VehicleApPowerStateReport::ON;
650             defaultPowerPolicyId = kSystemPolicyIdAllOn;
651             break;
652         default:
653             return ScopedAStatus::
654                     fromServiceSpecificErrorWithMessage(EX_ILLEGAL_ARGUMENT,
655                                                         StringPrintf("Power policy cannot be "
656                                                                      "changed for power state(%d)",
657                                                                      static_cast<int32_t>(state))
658                                                                 .c_str());
659     }
660     std::string powerStateName = toString(apPowerState);
661     ALOGI("Power policy change for new power state(%s) is requested", powerStateName.c_str());
662     std::string currentPolicyGroupId;
663     {
664         std::lock_guard<std::mutex> lock(mMutex);
665         currentPolicyGroupId = mCurrentPolicyGroupId;
666     }
667     const auto& policy =
668             mPolicyManager.getDefaultPowerPolicyForState(currentPolicyGroupId, apPowerState);
669     std::string policyId;
670     if (policy.ok()) {
671         policyId = (*policy)->policyId;
672         ALOGI("Vendor-configured policy(%s) is about to be applied for power state(%s)",
673               policyId.c_str(), powerStateName.c_str());
674     } else {
675         policyId = defaultPowerPolicyId;
676         ALOGI("Default policy(%s) is about to be applied for power state(%s)", policyId.c_str(),
677               powerStateName.c_str());
678     }
679 
680     const bool useForce = !mSilentModeHandler.isSilentMode();
681 
682     if (auto ret = enqueuePowerPolicyRequest(requestId, policyId, useForce); !ret.isOk()) {
683         ALOGW("Failed to apply power policy(%s) for power state(%s) with request ID(%d)",
684               policyId.c_str(), powerStateName.c_str(), requestId);
685         return ret;
686     }
687     return ScopedAStatus::ok();
688 }
689 
setSilentMode(const std::string & silentMode)690 ScopedAStatus CarPowerPolicyServer::setSilentMode(const std::string& silentMode) {
691     ScopedAStatus status = checkSystemPermission();
692     if (!status.isOk()) {
693         return status;
694     }
695     if (auto ret = mSilentModeHandler.setSilentMode(silentMode); !ret.isOk()) {
696         ALOGW("Failed to set Silent Mode(%s)", silentMode.c_str());
697         return ret;
698     }
699     return ScopedAStatus::ok();
700 }
701 
applyPowerPolicyAsync(int32_t requestId,const std::string & policyId,bool force)702 ScopedAStatus CarPowerPolicyServer::applyPowerPolicyAsync(int32_t requestId,
703                                                           const std::string& policyId, bool force) {
704     ScopedAStatus status = checkSystemPermission();
705     if (!status.isOk()) {
706         return status;
707     }
708     if (auto ret = enqueuePowerPolicyRequest(requestId, policyId, force); !ret.isOk()) {
709         ALOGW("Failed to apply power policy(%s) with request ID(%d)", policyId.c_str(), requestId);
710         return ret;
711     }
712     return ScopedAStatus::ok();
713 }
714 
enqueuePowerPolicyRequest(int32_t requestId,const std::string & policyId,bool force)715 ScopedAStatus CarPowerPolicyServer::enqueuePowerPolicyRequest(int32_t requestId,
716                                                               const std::string& policyId,
717                                                               bool force) {
718     std::lock_guard<std::mutex> lock(mMutex);
719     if (mPolicyRequestById.count(requestId) > 0) {
720         return ScopedAStatus::
721                 fromServiceSpecificErrorWithMessage(EX_ILLEGAL_ARGUMENT,
722                                                     StringPrintf("Duplicated request ID(%d)",
723                                                                  requestId)
724                                                             .c_str());
725     }
726     mPolicyRequestById[requestId] = PolicyRequest{.policyId = policyId, .force = force};
727     ALOGI("Queueing request ID(%d) for applying power policy(%s): force=%s", requestId,
728           policyId.c_str(), force ? "true" : "false");
729     mHandlerLooper->sendMessage(mRequestIdHandler, requestId);
730     return ScopedAStatus::ok();
731 }
732 
notifyCarServiceReadyInternal(const std::shared_ptr<ICarPowerPolicyDelegateCallback> & callback,PowerPolicyInitData * aidlReturn)733 ScopedAStatus CarPowerPolicyServer::notifyCarServiceReadyInternal(
734         const std::shared_ptr<ICarPowerPolicyDelegateCallback>& callback,
735         PowerPolicyInitData* aidlReturn) {
736     ScopedAStatus status = checkSystemPermission();
737     if (!status.isOk()) {
738         return status;
739     }
740     if (callback == nullptr) {
741         std::string errorMsg = "Cannot register a null callback for notifyCarServiceReadyInternal";
742         ALOGW("%s", errorMsg.c_str());
743         return ScopedAStatus::fromServiceSpecificErrorWithMessage(EX_ILLEGAL_ARGUMENT,
744                                                                   errorMsg.c_str());
745     }
746 
747     SpAIBinder newCallbackBinder;
748     SpAIBinder oldCallbackBinder;
749     {
750         std::lock_guard<std::mutex> lock(mMutex);
751         // Override with the newer callback.
752         newCallbackBinder = callback->asBinder();
753         // Copy old client binder out so that we can unlink it outside of the lock.
754         oldCallbackBinder = mPowerPolicyDelegateCallback;
755         mPowerPolicyDelegateCallback = newCallbackBinder;
756         mCarServiceLinked = true;
757     }
758 
759     if (oldCallbackBinder != nullptr) {
760         mLinkUnlinkImpl->unlinkToDeath(oldCallbackBinder.get(), mCarServiceDeathRecipient.get(),
761                                        static_cast<void*>(this));
762     }
763 
764     // Do not call linkToDeath within a locked scope. handleCarServiceDeathRecipientUnlinked might
765     // be called within which requires a lock.
766     binder_status_t linkStatus =
767             mLinkUnlinkImpl->linkToDeath(newCallbackBinder.get(), mCarServiceDeathRecipient.get(),
768                                          static_cast<void*>(this));
769     if (linkStatus != STATUS_OK) {
770         pid_t callingPid = IPCThreadState::self()->getCallingPid();
771         uid_t callingUid = IPCThreadState::self()->getCallingUid();
772         std::string errorStr =
773                 StringPrintf("CarService(pid: %d, uid: %d) is dead", callingPid, callingUid);
774         const char* errorCause = errorStr.c_str();
775         ALOGW("Cannot handle notifyCarServiceReady: %s", errorCause);
776         return ScopedAStatus::fromServiceSpecificErrorWithMessage(EX_ILLEGAL_STATE, errorCause);
777     }
778 
779     aidlReturn->registeredCustomComponents = mPolicyManager.getCustomComponents();
780     {
781         std::lock_guard<std::mutex> lock(mMutex);
782         aidlReturn->currentPowerPolicy = *mCurrentPowerPolicyMeta.powerPolicy;
783     }
784     aidlReturn->registeredPolicies = mPolicyManager.getRegisteredPolicies();
785     ALOGI("CarService registers ICarPowerPolicyDelegateCallback");
786     return ScopedAStatus::ok();
787 }
788 
dump(int fd,const char ** args,uint32_t numArgs)789 status_t CarPowerPolicyServer::dump(int fd, const char** args, uint32_t numArgs) {
790     Vector<String16> argsV;
791     for (size_t i = 0; i < numArgs; i++) {
792         argsV.push(String16(args[i]));
793     }
794 
795     {
796         std::lock_guard<std::mutex> lock(mMutex);
797         const char* indent = "  ";
798         const char* doubleIndent = "    ";
799         WriteStringToFd("CAR POWER POLICY DAEMON\n", fd);
800         WriteStringToFd(StringPrintf("%sCarService is in operation: %s\n", indent,
801                                      mIsCarServiceInOperation ? "true" : "false"),
802                         fd);
803         WriteStringToFd(StringPrintf("%sConnection to VHAL: %s\n", indent,
804                                      mVhalService.get() ? "connected" : "disconnected"),
805                         fd);
806         WriteStringToFd(StringPrintf("%sCurrent power policy: %s\n", indent,
807                                      isPowerPolicyAppliedLocked()
808                                              ? mCurrentPowerPolicyMeta.powerPolicy->policyId.c_str()
809                                              : "not set"),
810                         fd);
811         WriteStringToFd(StringPrintf("%sLast uptime of applying power policy: %" PRId64 "ms\n",
812                                      indent, mLastApplyPowerPolicyUptimeMs.value_or(-1)),
813                         fd);
814         WriteStringToFd(StringPrintf("%sPending power policy ID: %s\n", indent,
815                                      mPendingPowerPolicyId.c_str()),
816                         fd);
817         WriteStringToFd(StringPrintf("%sCurrent power policy group ID: %s\n", indent,
818                                      mCurrentPolicyGroupId.empty() ? "not set"
819                                                                    : mCurrentPolicyGroupId.c_str()),
820                         fd);
821         WriteStringToFd(StringPrintf("%sLast uptime of setting default power policy group: "
822                                      "%" PRId64 "ms\n",
823                                      indent, mLastSetDefaultPowerPolicyGroupUptimeMs.value_or(-1)),
824                         fd);
825         WriteStringToFd(StringPrintf("%sPolicy change callbacks:%s\n", indent,
826                                      mPolicyChangeCallbacks.size() ? "" : " none"),
827                         fd);
828         for (auto& callback : mPolicyChangeCallbacks) {
829             WriteStringToFd(StringPrintf("%s- %s\n", doubleIndent,
830                                          callbackToString(callback).c_str()),
831                             fd);
832         }
833     }
834     if (const auto& ret = mPolicyManager.dump(fd, argsV); !ret.ok()) {
835         ALOGW("Failed to dump power policy handler: %s", ret.error().message().c_str());
836         return ret.error().code();
837     }
838     if (const auto& ret = mComponentHandler.dump(fd); !ret.ok()) {
839         ALOGW("Failed to dump power component handler: %s", ret.error().message().c_str());
840         return ret.error().code();
841     }
842     if (const auto& ret = mSilentModeHandler.dump(fd, argsV); !ret.ok()) {
843         ALOGW("Failed to dump Silent Mode handler: %s", ret.error().message().c_str());
844         return ret.error().code();
845     }
846     return OK;
847 }
848 
init(const sp<Looper> & looper)849 Result<void> CarPowerPolicyServer::init(const sp<Looper>& looper) {
850     AIBinder* binderCarService = AServiceManager_checkService(kCarServiceInterface);
851     {
852         std::lock_guard<std::mutex> lock(mMutex);
853         // Before initializing power policy daemon, we need to update mIsCarServiceInOperation
854         // according to whether CPMS is running.
855         mIsCarServiceInOperation = binderCarService != nullptr;
856     }
857     mHandlerLooper = looper;
858     mPolicyManager.init();
859     mComponentHandler.init();
860     mSilentModeHandler.init();
861 
862     binder_exception_t err =
863             AServiceManager_addService(this->asBinder().get(), kCarPowerPolicyServerInterface);
864     if (err != EX_NONE) {
865         return Error(err) << "Failed to add carpowerpolicyd to ServiceManager";
866     }
867 
868     if (car_power_policy_refactoring()) {
869         ALOGI("Registering ICarPowerPolicyDelegate");
870         mCarPowerPolicyDelegate = SharedRefBase::make<CarPowerPolicyDelegate>(this);
871         if (err = AServiceManager_addService(mCarPowerPolicyDelegate->asBinder().get(),
872                                              kCarPowerPolicyDelegateInterface);
873             err != EX_NONE) {
874             return Error(err) << "Failed to add car power policy delegate to ServiceManager";
875         }
876     } else {
877         mCarServiceNotificationHandler = SharedRefBase::make<CarServiceNotificationHandler>(this);
878         if (err = AServiceManager_addService(mCarServiceNotificationHandler->asBinder().get(),
879                                              kCarPowerPolicySystemNotificationInterface);
880             err != EX_NONE) {
881             return Error(err)
882                     << "Failed to add car power policy system notification to ServiceManager";
883         }
884     }
885 
886     connectToVhal();
887     return {};
888 }
889 
terminate()890 void CarPowerPolicyServer::terminate() {
891     ALOGI("CarPowerPolicyServer terminate");
892     std::lock_guard<std::mutex> lock(mMutex);
893     mPolicyChangeCallbacks.clear();
894     if (mVhalService != nullptr) {
895         mSubscriptionClient->unsubscribe(
896                 {static_cast<int32_t>(VehicleProperty::POWER_POLICY_REQ),
897                  static_cast<int32_t>(VehicleProperty::POWER_POLICY_GROUP_REQ)});
898     }
899 
900     if (car_power_policy_refactoring()) {
901         if (mCarPowerPolicyDelegate != nullptr) {
902             mCarPowerPolicyDelegate->terminate();
903             mCarPowerPolicyDelegate = nullptr;
904         }
905     } else {
906         if (mCarServiceNotificationHandler != nullptr) {
907             mCarServiceNotificationHandler->terminate();
908             mCarServiceNotificationHandler = nullptr;
909         }
910     }
911 
912     mSilentModeHandler.release();
913 
914     if (mHandlerLooper != nullptr) {
915         // Remove the messages so that mEventHandler and mRequestIdHandler would no longer be used.
916         mHandlerLooper->removeMessages(mEventHandler);
917         mHandlerLooper->removeMessages(mRequestIdHandler);
918     }
919 }
920 
onCarServiceDeathRecipientUnlinked(void * cookie)921 void CarPowerPolicyServer::onCarServiceDeathRecipientUnlinked(void* cookie) {
922     CarPowerPolicyServer* server = static_cast<CarPowerPolicyServer*>(cookie);
923     server->handleCarServiceDeathRecipientUnlinked();
924 }
925 
onClientDeathRecipientUnlinked(void * cookie)926 void CarPowerPolicyServer::onClientDeathRecipientUnlinked(void* cookie) {
927     OnClientBinderDiedContext* context = static_cast<OnClientBinderDiedContext*>(cookie);
928     context->server->handleClientDeathRecipientUnlinked(context->clientId);
929 }
930 
onClientBinderDied(void * cookie)931 void CarPowerPolicyServer::onClientBinderDied(void* cookie) {
932     OnClientBinderDiedContext* context = static_cast<OnClientBinderDiedContext*>(cookie);
933     context->server->handleClientBinderDeath(context->clientId);
934 }
935 
onCarServiceBinderDied(void * cookie)936 void CarPowerPolicyServer::onCarServiceBinderDied(void* cookie) {
937     CarPowerPolicyServer* server = static_cast<CarPowerPolicyServer*>(cookie);
938     server->handleCarServiceBinderDeath();
939 }
940 
handleClientBinderDeath(const AIBinder * clientId)941 void CarPowerPolicyServer::handleClientBinderDeath(const AIBinder* clientId) {
942     ALOGI("handleClientBinderDeath");
943     std::lock_guard<std::mutex> lock(mMutex);
944     auto it = lookupPowerPolicyChangeCallback(mPolicyChangeCallbacks, clientId);
945     if (it != mPolicyChangeCallbacks.end()) {
946         ALOGW("Power policy callback(pid: %d) died", it->pid);
947         mPolicyChangeCallbacks.erase(it);
948     }
949 }
950 
handleCarServiceDeathRecipientUnlinked()951 void CarPowerPolicyServer::handleCarServiceDeathRecipientUnlinked() {
952     ALOGI("handleCarServiceDeathRecipientUnlinked");
953     std::lock_guard<std::mutex> lock(mMutex);
954     mCarServiceLinked = false;
955     mResourceReleasedCv.notify_all();
956 }
957 
handleClientDeathRecipientUnlinked(const AIBinder * clientId)958 void CarPowerPolicyServer::handleClientDeathRecipientUnlinked(const AIBinder* clientId) {
959     ALOGI("handleClientDeathRecipientUnlinked");
960     std::lock_guard<std::mutex> lock(mMutex);
961     mOnClientBinderDiedContexts.erase(clientId);
962     if (mOnClientBinderDiedContexts.empty()) {
963         mResourceReleasedCv.notify_all();
964     }
965 }
966 
handleCarServiceBinderDeath()967 void CarPowerPolicyServer::handleCarServiceBinderDeath() {
968     ALOGI("handleCarServiceBinderDeath");
969     std::lock_guard<std::mutex> lock(mMutex);
970     mPowerPolicyDelegateCallback = nullptr;
971 }
972 
handleVhalDeath()973 void CarPowerPolicyServer::handleVhalDeath() {
974     {
975         std::lock_guard<std::mutex> lock(mMutex);
976         ALOGW("VHAL has died.");
977         mVhalService = nullptr;
978     }
979     connectToVhal();
980 }
981 
handleApplyPowerPolicyRequest(const int32_t requestId)982 void CarPowerPolicyServer::handleApplyPowerPolicyRequest(const int32_t requestId) {
983     ALOGI("Handling request ID(%d) to apply power policy", requestId);
984     PolicyRequest policyRequest;
985     std::shared_ptr<ICarPowerPolicyDelegateCallback> callback;
986     {
987         std::lock_guard<std::mutex> lock(mMutex);
988         if (mPolicyRequestById.count(requestId) == 0) {
989             ALOGW("Request ID(%d) for applying power policy is not found", requestId);
990             return;
991         }
992         policyRequest = mPolicyRequestById[requestId];
993         mPolicyRequestById.erase(requestId);
994         callback = ICarPowerPolicyDelegateCallback::fromBinder(mPowerPolicyDelegateCallback);
995         if (callback == nullptr) {
996             ALOGW("ICarPowerPolicyDelegateCallback is not set");
997         }
998     }
999     if (const auto& ret = applyPowerPolicyInternal(policyRequest.policyId, policyRequest.force,
1000                                                    /*notifyCarService=*/false);
1001         !ret.ok()) {
1002         ALOGW("%s", ret.error().message().c_str());
1003         if (callback != nullptr) {
1004             callback->onApplyPowerPolicyFailed(requestId,
1005                                                convertErrorToFailureReason(ret.error().code()));
1006         }
1007         return;
1008     } else if (callback != nullptr) {
1009         callback->onApplyPowerPolicySucceeded(requestId, *mComponentHandler.getAccumulatedPolicy(),
1010                                               !*ret);
1011     }
1012 }
1013 
applyPowerPolicy(const std::string & policyId,const bool carServiceInOperation,const bool force)1014 Result<void> CarPowerPolicyServer::applyPowerPolicy(const std::string& policyId,
1015                                                     const bool carServiceInOperation,
1016                                                     const bool force) {
1017     auto policyMeta = mPolicyManager.getPowerPolicy(policyId);
1018     if (!policyMeta.ok()) {
1019         return Error() << "Failed to apply power policy: " << policyMeta.error().message();
1020     }
1021 
1022     std::vector<CallbackInfo> clients;
1023     if (std::lock_guard<std::mutex> lock(mMutex);
1024         mIsCarServiceInOperation != carServiceInOperation) {
1025         return Error() << (mIsCarServiceInOperation
1026                                    ? "After CarService starts serving, power policy cannot be "
1027                                      "managed in car power policy daemon"
1028                                    : "Before CarService starts serving, power policy cannot be "
1029                                      "applied from CarService");
1030     } else {
1031         if (!canApplyPowerPolicyLocked(*policyMeta, force, /*out*/ clients)) {
1032             return {};
1033         }
1034     }
1035     applyAndNotifyPowerPolicy(*policyMeta, clients, /*notifyCarService=*/false);
1036     return {};
1037 }
1038 
canApplyPowerPolicyLocked(const CarPowerPolicyMeta & policyMeta,const bool force,std::vector<CallbackInfo> & outClients)1039 bool CarPowerPolicyServer::canApplyPowerPolicyLocked(const CarPowerPolicyMeta& policyMeta,
1040                                                      const bool force,
1041                                                      std::vector<CallbackInfo>& outClients) {
1042     const std::string& policyId = policyMeta.powerPolicy->policyId;
1043     bool isPolicyApplied = isPowerPolicyAppliedLocked();
1044     if (isPolicyApplied && mCurrentPowerPolicyMeta.powerPolicy->policyId == policyId) {
1045         ALOGI("Applying policy skipped: the given policy(ID: %s) is the current policy",
1046               policyId.c_str());
1047         return false;
1048     }
1049     if (policyMeta.isPreemptive) {
1050         if (isPolicyApplied && !mCurrentPowerPolicyMeta.isPreemptive) {
1051             mPendingPowerPolicyId = mCurrentPowerPolicyMeta.powerPolicy->policyId;
1052         }
1053         mIsPowerPolicyLocked = true;
1054     } else {
1055         if (force) {
1056             mPendingPowerPolicyId.clear();
1057             mIsPowerPolicyLocked = false;
1058         } else if (mIsPowerPolicyLocked) {
1059             ALOGI("%s is queued and will be applied after power policy get unlocked",
1060                   policyId.c_str());
1061             mPendingPowerPolicyId = policyId;
1062             return false;
1063         }
1064     }
1065     mCurrentPowerPolicyMeta = policyMeta;
1066     outClients = mPolicyChangeCallbacks;
1067     mLastApplyPowerPolicyUptimeMs = uptimeMillis();
1068     ALOGD("CurrentPowerPolicyMeta is updated to %s", policyId.c_str());
1069     return true;
1070 }
1071 
applyAndNotifyPowerPolicy(const CarPowerPolicyMeta & policyMeta,const std::vector<CallbackInfo> & clients,const bool notifyCarService)1072 void CarPowerPolicyServer::applyAndNotifyPowerPolicy(const CarPowerPolicyMeta& policyMeta,
1073                                                      const std::vector<CallbackInfo>& clients,
1074                                                      const bool notifyCarService) {
1075     CarPowerPolicyPtr policy = policyMeta.powerPolicy;
1076     const std::string& policyId = policy->policyId;
1077     mComponentHandler.applyPowerPolicy(policy);
1078 
1079     std::shared_ptr<ICarPowerPolicyDelegateCallback> callback = nullptr;
1080     if (car_power_policy_refactoring()) {
1081         {
1082             std::lock_guard<std::mutex> lock(mMutex);
1083             callback = ICarPowerPolicyDelegateCallback::fromBinder(mPowerPolicyDelegateCallback);
1084         }
1085         if (callback != nullptr) {
1086             ALOGD("Asking CPMS to update power components for policy(%s)", policyId.c_str());
1087             callback->updatePowerComponents(*policy);
1088         } else {
1089             ALOGW("CarService isn't ready to update power components for policy(%s)",
1090                   policyId.c_str());
1091         }
1092     }
1093 
1094     if (const auto& ret = notifyVhalNewPowerPolicy(policy->policyId); !ret.ok()) {
1095         ALOGW("Failed to tell VHAL the new power policy(%s): %s", policy->policyId.c_str(),
1096               ret.error().message().c_str());
1097     }
1098     auto accumulatedPolicy = mComponentHandler.getAccumulatedPolicy();
1099     for (auto client : clients) {
1100         ICarPowerPolicyChangeCallback::fromBinder(client.binder)
1101                 ->onPolicyChanged(*accumulatedPolicy);
1102     }
1103     if (notifyCarService && callback != nullptr) {
1104         callback->onPowerPolicyChanged(*accumulatedPolicy);
1105     }
1106     ALOGI("The current power policy is %s", policyId.c_str());
1107 }
1108 
applyPowerPolicyInternal(const std::string & policyId,const bool force,const bool notifyCarService)1109 Result<bool> CarPowerPolicyServer::applyPowerPolicyInternal(const std::string& policyId,
1110                                                             const bool force,
1111                                                             const bool notifyCarService) {
1112     auto policyMeta = mPolicyManager.getPowerPolicy(policyId);
1113     if (!policyMeta.ok()) {
1114         return Error(EX_ILLEGAL_ARGUMENT)
1115                 << "Failed to apply power policy: " << policyMeta.error().message();
1116     }
1117     std::vector<CallbackInfo> clients;
1118     {
1119         std::lock_guard<std::mutex> lock(mMutex);
1120         if (!canApplyPowerPolicyLocked(*policyMeta, force, /*out*/ clients)) {
1121             return false;
1122         }
1123     }
1124     applyAndNotifyPowerPolicy(*policyMeta, clients, notifyCarService);
1125     return true;
1126 }
1127 
setPowerPolicyGroupInternal(const std::string & groupId)1128 Result<void> CarPowerPolicyServer::setPowerPolicyGroupInternal(const std::string& groupId) {
1129     if (!mPolicyManager.isPowerPolicyGroupAvailable(groupId)) {
1130         return Error(EX_ILLEGAL_ARGUMENT)
1131                 << StringPrintf("Power policy group(%s) is not available", groupId.c_str());
1132     }
1133     std::lock_guard<std::mutex> lock(mMutex);
1134     if (!car_power_policy_refactoring() && mIsCarServiceInOperation) {
1135         return Error(EX_ILLEGAL_STATE) << "After CarService starts serving, power policy group "
1136                                           "cannot be set in car power policy daemon";
1137     }
1138     mCurrentPolicyGroupId = groupId;
1139     ALOGI("The current power policy group is |%s|", groupId.c_str());
1140     return {};
1141 }
1142 
notifySilentModeChange(const bool isSilent)1143 void CarPowerPolicyServer::notifySilentModeChange(const bool isSilent) {
1144     if (car_power_policy_refactoring()) {
1145         notifySilentModeChangeInternal(isSilent);
1146     } else {
1147         notifySilentModeChangeLegacy(isSilent);
1148     }
1149 }
1150 
notifySilentModeChangeLegacy(const bool isSilent)1151 void CarPowerPolicyServer::notifySilentModeChangeLegacy(const bool isSilent) {
1152     std::string pendingPowerPolicyId;
1153     if (std::lock_guard<std::mutex> lock(mMutex); mIsCarServiceInOperation) {
1154         return;
1155     } else {
1156         pendingPowerPolicyId = mPendingPowerPolicyId;
1157     }
1158     ALOGI("Silent Mode is set to %s", isSilent ? "silent" : "non-silent");
1159     Result<void> ret;
1160     if (isSilent) {
1161         ret = applyPowerPolicy(kSystemPolicyIdNoUserInteraction,
1162                                /*carServiceExpected=*/false, /*force=*/false);
1163     } else {
1164         ret = applyPowerPolicy(pendingPowerPolicyId,
1165                                /*carServiceExpected=*/false, /*force=*/true);
1166     }
1167     if (!ret.ok()) {
1168         ALOGW("Failed to apply power policy: %s", ret.error().message().c_str());
1169     }
1170 }
1171 
notifySilentModeChangeInternal(const bool isSilent)1172 void CarPowerPolicyServer::notifySilentModeChangeInternal(const bool isSilent) {
1173     std::string pendingPowerPolicyId;
1174     {
1175         std::lock_guard<std::mutex> lock(mMutex);
1176         pendingPowerPolicyId = mPendingPowerPolicyId;
1177     }
1178     ALOGI("Silent Mode is set to %s", isSilent ? "silent" : "non-silent");
1179     Result<bool> ret;
1180     if (isSilent) {
1181         ret = applyPowerPolicyInternal(kSystemPolicyIdNoUserInteraction, /*force=*/false,
1182                                        /*notifyCarService=*/true);
1183     } else {
1184         ret = applyPowerPolicyInternal(pendingPowerPolicyId, /*force=*/true,
1185                                        /*notifyCarService=*/true);
1186     }
1187     if (!ret.ok()) {
1188         ALOGW("Failed to apply power policy: %s", ret.error().message().c_str());
1189     }
1190 }
1191 
isRegisteredLocked(const AIBinder * binder)1192 bool CarPowerPolicyServer::isRegisteredLocked(const AIBinder* binder) {
1193     return lookupPowerPolicyChangeCallback(mPolicyChangeCallbacks, binder) !=
1194             mPolicyChangeCallbacks.end();
1195 }
1196 
1197 // This method ensures that the attempt to connect to VHAL occurs in the main thread.
connectToVhal()1198 void CarPowerPolicyServer::connectToVhal() {
1199     mRemainingConnectionRetryCount = kMaxConnectionRetry;
1200     mHandlerLooper->sendMessage(mEventHandler, MSG_CONNECT_TO_VHAL);
1201 }
1202 
1203 // connectToVhalHelper is always executed in the main thread.
connectToVhalHelper()1204 void CarPowerPolicyServer::connectToVhalHelper() {
1205     {
1206         std::lock_guard<std::mutex> lock(mMutex);
1207         if (mVhalService != nullptr) {
1208             return;
1209         }
1210     }
1211     std::shared_ptr<IVhalClient> vhalService = IVhalClient::tryCreate();
1212     if (vhalService == nullptr) {
1213         ALOGW("Failed to connect to VHAL. Retrying in %" PRId64 " ms.",
1214               nanoseconds_to_milliseconds(kConnectionRetryIntervalNs));
1215         mRemainingConnectionRetryCount--;
1216         if (mRemainingConnectionRetryCount <= 0) {
1217             ALOGE("Failed to connect to VHAL after %d attempt%s. Gave up.", kMaxConnectionRetry,
1218                   kMaxConnectionRetry > 1 ? "s" : "");
1219             return;
1220         }
1221         mHandlerLooper->sendMessageDelayed(kConnectionRetryIntervalNs, mEventHandler,
1222                                            MSG_CONNECT_TO_VHAL);
1223         return;
1224     }
1225     vhalService->addOnBinderDiedCallback(
1226             std::make_shared<IVhalClient::OnBinderDiedCallbackFunc>([this] { handleVhalDeath(); }));
1227     std::string currentPolicyId;
1228     {
1229         std::lock_guard<std::mutex> lock(mMutex);
1230         mVhalService = vhalService;
1231         mSubscriptionClient = mVhalService->getSubscriptionClient(mPropertyChangeListener);
1232         if (isPowerPolicyAppliedLocked()) {
1233             currentPolicyId = mCurrentPowerPolicyMeta.powerPolicy->policyId;
1234         }
1235     }
1236     /*
1237      * When VHAL is first executed, a normal power management goes on. When VHAL is restarted due to
1238      * some reasons, the current policy is notified to VHAL.
1239      */
1240     if (mIsFirstConnectionToVhal) {
1241         applyInitialPowerPolicy();
1242         mIsFirstConnectionToVhal = false;
1243     } else if (!currentPolicyId.empty()) {
1244         notifyVhalNewPowerPolicy(currentPolicyId);
1245     }
1246     subscribeToVhal();
1247     ALOGI("Connected to VHAL");
1248     return;
1249 }
1250 
applyInitialPowerPolicy()1251 void CarPowerPolicyServer::applyInitialPowerPolicy() {
1252     std::string policyId;
1253     std::string currentPolicyGroupId;
1254     CarPowerPolicyPtr powerPolicy;
1255     {
1256         std::lock_guard<std::mutex> lock(mMutex);
1257         if (mIsCarServiceInOperation) {
1258             ALOGI("Skipping initial power policy application because CarService is running");
1259             return;
1260         }
1261         policyId = mPendingPowerPolicyId;
1262         currentPolicyGroupId = mCurrentPolicyGroupId;
1263     }
1264     if (policyId.empty()) {
1265         if (auto policy = mPolicyManager.getDefaultPowerPolicyForState(currentPolicyGroupId,
1266                                                                        VehicleApPowerStateReport::
1267                                                                                WAIT_FOR_VHAL);
1268             policy.ok()) {
1269             policyId = (*policy)->policyId;
1270         } else {
1271             policyId = kSystemPolicyIdInitialOn;
1272         }
1273     }
1274     if (const auto& ret = applyPowerPolicy(policyId, /*carServiceExpected=*/false, /*force=*/false);
1275         !ret.ok()) {
1276         ALOGW("Cannot apply the initial power policy(%s): %s", policyId.c_str(),
1277               ret.error().message().c_str());
1278         return;
1279     }
1280     ALOGD("Policy(%s) is applied as the initial one", policyId.c_str());
1281 }
1282 
subscribeToVhal()1283 void CarPowerPolicyServer::subscribeToVhal() {
1284     subscribeToProperty(static_cast<int32_t>(VehicleProperty::POWER_POLICY_REQ),
1285                         [this](const IHalPropValue& value) {
1286                             std::string stringValue = value.getStringValue();
1287                             if (stringValue.size() > 0) {
1288                                 const auto& ret = applyPowerPolicy(stringValue,
1289                                                                    /*carServiceExpected=*/false,
1290                                                                    /*force=*/false);
1291                                 if (!ret.ok()) {
1292                                     ALOGW("Failed to apply power policy(%s): %s",
1293                                           stringValue.c_str(), ret.error().message().c_str());
1294                                 }
1295                             }
1296                         });
1297     subscribeToProperty(static_cast<int32_t>(VehicleProperty::POWER_POLICY_GROUP_REQ),
1298                         [this](const IHalPropValue& value) {
1299                             std::string stringValue = value.getStringValue();
1300                             if (stringValue.size() > 0) {
1301                                 const auto& ret = setPowerPolicyGroupInternal(stringValue);
1302                                 if (ret.ok()) {
1303                                     std::lock_guard<std::mutex> lock(mMutex);
1304                                     mLastSetDefaultPowerPolicyGroupUptimeMs = value.getTimestamp();
1305                                 } else {
1306                                     ALOGW("Failed to set power policy group(%s): %s",
1307                                           stringValue.c_str(), ret.error().message().c_str());
1308                                 }
1309                             }
1310                         });
1311 }
1312 
subscribeToProperty(int32_t prop,std::function<void (const IHalPropValue &)> processor)1313 void CarPowerPolicyServer::subscribeToProperty(
1314         int32_t prop, std::function<void(const IHalPropValue&)> processor) {
1315     if (!isPropertySupported(prop)) {
1316         ALOGW("Vehicle property(%d) is not supported by VHAL.", prop);
1317         return;
1318     }
1319     std::shared_ptr<IVhalClient> vhalService;
1320     {
1321         std::lock_guard<std::mutex> lock(mMutex);
1322         if (mVhalService == nullptr) {
1323             ALOGW("Failed to subscribe to property(%d): VHAL is not ready", prop);
1324             return;
1325         }
1326         vhalService = mVhalService;
1327     }
1328 
1329     VhalClientResult<std::unique_ptr<IHalPropValue>> result =
1330             vhalService->getValueSync(*vhalService->createHalPropValue(prop));
1331 
1332     if (!result.ok()) {
1333         ALOGW("Failed to get vehicle property(%d) value, error: %s.", prop,
1334               result.error().message().c_str());
1335         return;
1336     }
1337     processor(*result.value());
1338     std::vector<SubscribeOptions> options = {
1339             {.propId = prop, .areaIds = {}},
1340     };
1341 
1342     if (auto result = mSubscriptionClient->subscribe(options); !result.ok()) {
1343         ALOGW("Failed to subscribe to vehicle property(%d), error: %s", prop,
1344               result.error().message().c_str());
1345     }
1346 }
1347 
notifyVhalNewPowerPolicy(const std::string & policyId)1348 Result<void> CarPowerPolicyServer::notifyVhalNewPowerPolicy(const std::string& policyId) {
1349     int32_t prop = static_cast<int32_t>(VehicleProperty::CURRENT_POWER_POLICY);
1350     if (!isPropertySupported(prop)) {
1351         return Error() << StringPrintf("Vehicle property(%d) is not supported by VHAL.", prop);
1352     }
1353     std::shared_ptr<IVhalClient> vhalService;
1354     {
1355         std::lock_guard<std::mutex> lock(mMutex);
1356         if (mVhalService == nullptr) {
1357             return Error() << "VHAL is not ready";
1358         }
1359         vhalService = mVhalService;
1360     }
1361     std::unique_ptr<IHalPropValue> propValue = vhalService->createHalPropValue(prop);
1362     propValue->setStringValue(policyId);
1363 
1364     VhalClientResult<void> result = vhalService->setValueSync(*propValue);
1365     if (!result.ok()) {
1366         return Error() << "Failed to set CURRENT_POWER_POLICY property";
1367     }
1368     ALOGD("Policy(%s) is notified to VHAL", policyId.c_str());
1369     return {};
1370 }
1371 
isPropertySupported(const int32_t prop)1372 bool CarPowerPolicyServer::isPropertySupported(const int32_t prop) {
1373     if (mSupportedProperties.count(prop) > 0) {
1374         return mSupportedProperties[prop];
1375     }
1376     StatusCode status;
1377     hidl_vec<int32_t> props = {prop};
1378     std::shared_ptr<IVhalClient> vhalService;
1379     {
1380         std::lock_guard<std::mutex> lock(mMutex);
1381         if (mVhalService == nullptr) {
1382             ALOGW("Failed to check if property(%d) is supported: VHAL is not ready", prop);
1383             return false;
1384         }
1385         vhalService = mVhalService;
1386     }
1387     auto result = vhalService->getPropConfigs(props);
1388     mSupportedProperties[prop] = result.ok();
1389     return mSupportedProperties[prop];
1390 }
1391 
isPowerPolicyAppliedLocked() const1392 bool CarPowerPolicyServer::isPowerPolicyAppliedLocked() const {
1393     return mCurrentPowerPolicyMeta.powerPolicy != nullptr;
1394 }
1395 
callbackToString(const CallbackInfo & callback)1396 std::string CarPowerPolicyServer::callbackToString(const CallbackInfo& callback) {
1397     const std::vector<PowerComponent>& components = callback.filter.components;
1398     return StringPrintf("callback(pid %d, filter: %s)", callback.pid, toString(components).c_str());
1399 }
1400 
getPolicyChangeCallbacks()1401 std::vector<CallbackInfo> CarPowerPolicyServer::getPolicyChangeCallbacks() {
1402     std::lock_guard<std::mutex> lock(mMutex);
1403     return mPolicyChangeCallbacks;
1404 }
1405 
countOnClientBinderDiedContexts()1406 size_t CarPowerPolicyServer::countOnClientBinderDiedContexts() {
1407     std::lock_guard<std::mutex> lock(mMutex);
1408     return mOnClientBinderDiedContexts.size();
1409 }
1410 
linkToDeath(AIBinder * binder,AIBinder_DeathRecipient * recipient,void * cookie)1411 binder_status_t CarPowerPolicyServer::AIBinderLinkUnlinkImpl::linkToDeath(
1412         AIBinder* binder, AIBinder_DeathRecipient* recipient, void* cookie) {
1413     return AIBinder_linkToDeath(binder, recipient, cookie);
1414 }
1415 
unlinkToDeath(AIBinder * binder,AIBinder_DeathRecipient * recipient,void * cookie)1416 binder_status_t CarPowerPolicyServer::AIBinderLinkUnlinkImpl::unlinkToDeath(
1417         AIBinder* binder, AIBinder_DeathRecipient* recipient, void* cookie) {
1418     return AIBinder_unlinkToDeath(binder, recipient, cookie);
1419 }
1420 
setOnUnlinked(AIBinder_DeathRecipient * recipient,AIBinder_DeathRecipient_onBinderUnlinked onUnlinked)1421 void CarPowerPolicyServer::AIBinderLinkUnlinkImpl::setOnUnlinked(
1422         AIBinder_DeathRecipient* recipient, AIBinder_DeathRecipient_onBinderUnlinked onUnlinked) {
1423     AIBinder_DeathRecipient_setOnUnlinked(recipient, onUnlinked);
1424 }
1425 
deleteDeathRecipient(AIBinder_DeathRecipient * recipient)1426 void CarPowerPolicyServer::AIBinderLinkUnlinkImpl::deleteDeathRecipient(
1427         AIBinder_DeathRecipient* recipient) {
1428     AIBinder_DeathRecipient_delete(recipient);
1429 }
1430 
1431 }  // namespace powerpolicy
1432 }  // namespace automotive
1433 }  // namespace frameworks
1434 }  // namespace android
1435