1 /*
2  * Copyright (C) 2016 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 #include "SensorDirectConnection.h"
18 #include <android/util/ProtoOutputStream.h>
19 #include <frameworks/base/core/proto/android/service/sensor_service.proto.h>
20 #include <hardware/sensors.h>
21 #include "SensorDevice.h"
22 
23 #define UNUSED(x) (void)(x)
24 
25 namespace android {
26 
27 using util::ProtoOutputStream;
28 
SensorDirectConnection(const sp<SensorService> & service,uid_t uid,const sensors_direct_mem_t * mem,int32_t halChannelHandle,const String16 & opPackageName,int deviceId)29 SensorService::SensorDirectConnection::SensorDirectConnection(const sp<SensorService>& service,
30         uid_t uid, const sensors_direct_mem_t *mem, int32_t halChannelHandle,
31         const String16& opPackageName, int deviceId)
32         : mService(service), mUid(uid), mMem(*mem),
33         mHalChannelHandle(halChannelHandle),
34         mOpPackageName(opPackageName), mDeviceId(deviceId), mDestroyed(false) {
35     mUserId = multiuser_get_user_id(mUid);
36     ALOGD_IF(DEBUG_CONNECTIONS, "Created SensorDirectConnection");
37 }
38 
~SensorDirectConnection()39 SensorService::SensorDirectConnection::~SensorDirectConnection() {
40     ALOGD_IF(DEBUG_CONNECTIONS, "~SensorDirectConnection %p", this);
41     destroy();
42 }
43 
destroy()44 void SensorService::SensorDirectConnection::destroy() {
45     Mutex::Autolock _l(mDestroyLock);
46     // destroy once only
47     if (mDestroyed) {
48         return;
49     }
50 
51     stopAll();
52     mService->cleanupConnection(this);
53     if (mMem.handle != nullptr) {
54         native_handle_close_with_tag(mMem.handle);
55         native_handle_delete(const_cast<struct native_handle*>(mMem.handle));
56     }
57     mDestroyed = true;
58 }
59 
onFirstRef()60 void SensorService::SensorDirectConnection::onFirstRef() {
61 }
62 
dump(String8 & result) const63 void SensorService::SensorDirectConnection::dump(String8& result) const {
64     Mutex::Autolock _l(mConnectionLock);
65     result.appendFormat("\tPackage %s, HAL channel handle %d, total sensor activated %zu\n",
66             String8(mOpPackageName).c_str(), getHalChannelHandle(), mActivated.size());
67     for (auto &i : mActivated) {
68         result.appendFormat("\t\tSensor %#08x, rate %d\n", i.first, i.second);
69     }
70 }
71 
72 /**
73  * Dump debugging information as android.service.SensorDirectConnectionProto protobuf message using
74  * ProtoOutputStream.
75  *
76  * See proto definition and some notes about ProtoOutputStream in
77  * frameworks/base/core/proto/android/service/sensor_service.proto
78  */
dump(ProtoOutputStream * proto) const79 void SensorService::SensorDirectConnection::dump(ProtoOutputStream* proto) const {
80     using namespace service::SensorDirectConnectionProto;
81     Mutex::Autolock _l(mConnectionLock);
82     proto->write(PACKAGE_NAME, std::string(String8(mOpPackageName).c_str()));
83     proto->write(HAL_CHANNEL_HANDLE, getHalChannelHandle());
84     proto->write(NUM_SENSOR_ACTIVATED, int(mActivated.size()));
85     for (auto &i : mActivated) {
86         uint64_t token = proto->start(SENSORS);
87         proto->write(SensorProto::SENSOR, i.first);
88         proto->write(SensorProto::RATE, i.second);
89         proto->end(token);
90     }
91 }
92 
getSensorChannel() const93 sp<BitTube> SensorService::SensorDirectConnection::getSensorChannel() const {
94     return nullptr;
95 }
96 
onSensorAccessChanged(bool hasAccess)97 void SensorService::SensorDirectConnection::onSensorAccessChanged(bool hasAccess) {
98     if (!hasAccess) {
99         stopAll(true /* backupRecord */);
100     } else {
101         recoverAll();
102     }
103 }
104 
onMicSensorAccessChanged(bool isMicToggleOn)105 void SensorService::SensorDirectConnection::onMicSensorAccessChanged(bool isMicToggleOn) {
106     if (isMicToggleOn) {
107         capRates();
108     } else {
109         uncapRates();
110     }
111 }
112 
hasSensorAccess() const113 bool SensorService::SensorDirectConnection::hasSensorAccess() const {
114     return mService->hasSensorAccess(mUid, mOpPackageName);
115 }
116 
enableDisable(int handle,bool enabled,nsecs_t samplingPeriodNs,nsecs_t maxBatchReportLatencyNs,int reservedFlags)117 status_t SensorService::SensorDirectConnection::enableDisable(
118         int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
119         int reservedFlags) {
120     // SensorDirectConnection does not support enableDisable, parameters not used
121     UNUSED(handle);
122     UNUSED(enabled);
123     UNUSED(samplingPeriodNs);
124     UNUSED(maxBatchReportLatencyNs);
125     UNUSED(reservedFlags);
126     return INVALID_OPERATION;
127 }
128 
setEventRate(int handle,nsecs_t samplingPeriodNs)129 status_t SensorService::SensorDirectConnection::setEventRate(
130         int handle, nsecs_t samplingPeriodNs) {
131     // SensorDirectConnection does not support setEventRate, parameters not used
132     UNUSED(handle);
133     UNUSED(samplingPeriodNs);
134     return INVALID_OPERATION;
135 }
136 
flush()137 status_t SensorService::SensorDirectConnection::flush() {
138     // SensorDirectConnection does not support flush
139     return INVALID_OPERATION;
140 }
141 
configureChannel(int handle,int rateLevel)142 int32_t SensorService::SensorDirectConnection::configureChannel(int handle, int rateLevel) {
143 
144     if (handle == -1 && rateLevel == SENSOR_DIRECT_RATE_STOP) {
145         stopAll();
146         mMicRateBackup.clear();
147         return NO_ERROR;
148     }
149 
150     if (!hasSensorAccess()) {
151         return PERMISSION_DENIED;
152     }
153 
154     std::shared_ptr<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
155     if (si == nullptr) {
156         return NAME_NOT_FOUND;
157     }
158 
159     const Sensor& s = si->getSensor();
160     if (!mService->canAccessSensor(s, "config direct channel", mOpPackageName)) {
161         return PERMISSION_DENIED;
162     }
163 
164     if (s.getHighestDirectReportRateLevel() == 0
165             || rateLevel > s.getHighestDirectReportRateLevel()
166             || !s.isDirectChannelTypeSupported(mMem.type)) {
167         return INVALID_OPERATION;
168     }
169 
170     int requestedRateLevel = rateLevel;
171     if (mService->isSensorInCappedSet(s.getType()) && rateLevel != SENSOR_DIRECT_RATE_STOP) {
172         status_t err = mService->adjustRateLevelBasedOnMicAndPermission(&rateLevel, mOpPackageName);
173         if (err != OK) {
174             return err;
175         }
176     }
177 
178     struct sensors_direct_cfg_t config = {
179         .rate_level = rateLevel
180     };
181 
182     Mutex::Autolock _l(mConnectionLock);
183     int ret = configure(handle, &config);
184 
185     if (rateLevel == SENSOR_DIRECT_RATE_STOP) {
186         if (ret == NO_ERROR) {
187             mActivated.erase(handle);
188             mMicRateBackup.erase(handle);
189         } else if (ret > 0) {
190             ret = UNKNOWN_ERROR;
191         }
192     } else {
193         if (ret > 0) {
194             mActivated[handle] = rateLevel;
195             if (mService->isSensorInCappedSet(s.getType())) {
196                 // Back up the rates that the app is allowed to have if the mic toggle is off
197                 // This is used in the uncapRates() function.
198                 if ((requestedRateLevel <= SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL) ||
199                     !isRateCappedBasedOnPermission()) {
200                     mMicRateBackup[handle] = requestedRateLevel;
201                 } else {
202                     mMicRateBackup[handle] = SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL;
203                 }
204             }
205         }
206     }
207 
208     return ret;
209 }
210 
capRates()211 void SensorService::SensorDirectConnection::capRates() {
212     Mutex::Autolock _l(mConnectionLock);
213     const struct sensors_direct_cfg_t capConfig = {
214         .rate_level = SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL
215     };
216 
217     const struct sensors_direct_cfg_t stopConfig = {
218         .rate_level = SENSOR_DIRECT_RATE_STOP
219     };
220 
221     // If our requests are in the backup, then we shouldn't activate sensors from here
222     bool temporarilyStopped = mActivated.empty() && !mActivatedBackup.empty();
223     std::unordered_map<int, int>& existingConnections =
224                     (!temporarilyStopped) ? mActivated : mActivatedBackup;
225 
226     for (auto &i : existingConnections) {
227         int handle = i.first;
228         int rateLevel = i.second;
229         std::shared_ptr<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
230         if (si != nullptr) {
231             const Sensor& s = si->getSensor();
232             if (mService->isSensorInCappedSet(s.getType()) &&
233                         rateLevel > SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL) {
234                 mMicRateBackup[handle] = rateLevel;
235                 // Modify the rate kept by the existing map
236                 existingConnections[handle] = SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL;
237                 // Only reconfigure the channel if it's ongoing
238                 if (!temporarilyStopped) {
239                     // Stopping before reconfiguring is the well-tested path in CTS
240                     configure(handle, &stopConfig);
241                     configure(handle, &capConfig);
242                 }
243             }
244         }
245     }
246 }
247 
uncapRates()248 void SensorService::SensorDirectConnection::uncapRates() {
249     Mutex::Autolock _l(mConnectionLock);
250 
251     // If our requests are in the backup, then we shouldn't activate sensors from here
252     bool temporarilyStopped = mActivated.empty() && !mActivatedBackup.empty();
253     std::unordered_map<int, int>& existingConnections =
254                     (!temporarilyStopped) ? mActivated : mActivatedBackup;
255 
256     const struct sensors_direct_cfg_t stopConfig = {
257         .rate_level = SENSOR_DIRECT_RATE_STOP
258     };
259     for (auto &i : mMicRateBackup) {
260         int handle = i.first;
261         int rateLevel = i.second;
262 
263         const struct sensors_direct_cfg_t config = {
264             .rate_level = rateLevel
265         };
266 
267         // Modify the rate kept by the existing map
268         existingConnections[handle] = rateLevel;
269 
270         // Only reconfigure the channel if it's ongoing
271         if (!temporarilyStopped) {
272             // Stopping before reconfiguring is the well-tested path in CTS
273             configure(handle, &stopConfig);
274             configure(handle, &config);
275         }
276     }
277     mMicRateBackup.clear();
278 }
279 
configure(int handle,const sensors_direct_cfg_t * config)280 int SensorService::SensorDirectConnection::configure(
281         int handle, const sensors_direct_cfg_t* config) {
282     if (mDeviceId == RuntimeSensor::DEFAULT_DEVICE_ID) {
283         SensorDevice& dev(SensorDevice::getInstance());
284         return dev.configureDirectChannel(handle, getHalChannelHandle(), config);
285     } else {
286         return mService->configureRuntimeSensorDirectChannel(handle, this, config);
287     }
288 }
289 
stopAll(bool backupRecord)290 void SensorService::SensorDirectConnection::stopAll(bool backupRecord) {
291     Mutex::Autolock _l(mConnectionLock);
292     stopAllLocked(backupRecord);
293 }
294 
stopAllLocked(bool backupRecord)295 void SensorService::SensorDirectConnection::stopAllLocked(bool backupRecord) {
296     struct sensors_direct_cfg_t config = {
297         .rate_level = SENSOR_DIRECT_RATE_STOP
298     };
299 
300     for (auto &i : mActivated) {
301         configure(i.first, &config);
302     }
303 
304     if (backupRecord && mActivatedBackup.empty()) {
305         mActivatedBackup = mActivated;
306     }
307     mActivated.clear();
308 }
309 
recoverAll()310 void SensorService::SensorDirectConnection::recoverAll() {
311     Mutex::Autolock _l(mConnectionLock);
312     if (!mActivatedBackup.empty()) {
313         stopAllLocked(false);
314 
315         // recover list of report from backup
316         ALOG_ASSERT(mActivated.empty(),
317                     "mActivated must be empty if mActivatedBackup was non-empty");
318         mActivated = mActivatedBackup;
319         mActivatedBackup.clear();
320 
321         // re-enable them
322         for (auto &i : mActivated) {
323             struct sensors_direct_cfg_t config = {
324                 .rate_level = i.second
325             };
326             configure(i.first, &config);
327         }
328     }
329 }
330 
getHalChannelHandle() const331 int32_t SensorService::SensorDirectConnection::getHalChannelHandle() const {
332     return mHalChannelHandle;
333 }
334 
isEquivalent(const sensors_direct_mem_t * mem) const335 bool SensorService::SensorDirectConnection::isEquivalent(const sensors_direct_mem_t *mem) const {
336     bool ret = false;
337 
338     if (mMem.type == mem->type) {
339         switch (mMem.type) {
340             case SENSOR_DIRECT_MEM_TYPE_ASHMEM: {
341                 // there is no known method to test if two ashmem fds are equivalent besides
342                 // trivially comparing the fd values (ino number from fstat() are always the
343                 // same, pointing to "/dev/ashmem").
344                 int fd1 = mMem.handle->data[0];
345                 int fd2 = mem->handle->data[0];
346                 ret = (fd1 == fd2);
347                 break;
348             }
349             case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
350                 // there is no known method to test if two gralloc handle are equivalent
351                 ret = false;
352                 break;
353             default:
354                 // should never happen
355                 ALOGE("Unexpected mem type %d", mMem.type);
356                 ret = true;
357                 break;
358         }
359     }
360     return ret;
361 }
362 
363 } // namespace android
364 
365