• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "SensorDevice.h"
18 #include "SensorDirectConnection.h"
19 #include <android/util/ProtoOutputStream.h>
20 #include <frameworks/base/core/proto/android/service/sensor_service.proto.h>
21 #include <hardware/sensors.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)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)
32         : mService(service), mUid(uid), mMem(*mem),
33         mHalChannelHandle(halChannelHandle),
34         mOpPackageName(opPackageName), 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(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).string(), 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).string()));
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     sp<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     SensorDevice& dev(SensorDevice::getInstance());
184     int ret = dev.configureDirectChannel(handle, getHalChannelHandle(), &config);
185 
186     if (rateLevel == SENSOR_DIRECT_RATE_STOP) {
187         if (ret == NO_ERROR) {
188             mActivated.erase(handle);
189             mMicRateBackup.erase(handle);
190         } else if (ret > 0) {
191             ret = UNKNOWN_ERROR;
192         }
193     } else {
194         if (ret > 0) {
195             mActivated[handle] = rateLevel;
196             if (mService->isSensorInCappedSet(s.getType())) {
197                 // Back up the rates that the app is allowed to have if the mic toggle is off
198                 // This is used in the uncapRates() function.
199                 if ((requestedRateLevel <= SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL) ||
200                     !isRateCappedBasedOnPermission()) {
201                     mMicRateBackup[handle] = requestedRateLevel;
202                 } else {
203                     mMicRateBackup[handle] = SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL;
204                 }
205             }
206         }
207     }
208 
209     return ret;
210 }
211 
capRates()212 void SensorService::SensorDirectConnection::capRates() {
213     Mutex::Autolock _l(mConnectionLock);
214     const struct sensors_direct_cfg_t capConfig = {
215         .rate_level = SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL
216     };
217 
218     const struct sensors_direct_cfg_t stopConfig = {
219         .rate_level = SENSOR_DIRECT_RATE_STOP
220     };
221 
222     // If our requests are in the backup, then we shouldn't activate sensors from here
223     bool temporarilyStopped = mActivated.empty() && !mActivatedBackup.empty();
224     std::unordered_map<int, int>& existingConnections =
225                     (!temporarilyStopped) ? mActivated : mActivatedBackup;
226 
227     SensorDevice& dev(SensorDevice::getInstance());
228     for (auto &i : existingConnections) {
229         int handle = i.first;
230         int rateLevel = i.second;
231         sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
232         if (si != nullptr) {
233             const Sensor& s = si->getSensor();
234             if (mService->isSensorInCappedSet(s.getType()) &&
235                         rateLevel > SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL) {
236                 mMicRateBackup[handle] = rateLevel;
237                 // Modify the rate kept by the existing map
238                 existingConnections[handle] = SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL;
239                 // Only reconfigure the channel if it's ongoing
240                 if (!temporarilyStopped) {
241                     // Stopping before reconfiguring is the well-tested path in CTS
242                     dev.configureDirectChannel(handle, getHalChannelHandle(), &stopConfig);
243                     dev.configureDirectChannel(handle, getHalChannelHandle(), &capConfig);
244                 }
245             }
246         }
247     }
248 }
249 
uncapRates()250 void SensorService::SensorDirectConnection::uncapRates() {
251     Mutex::Autolock _l(mConnectionLock);
252 
253     // If our requests are in the backup, then we shouldn't activate sensors from here
254     bool temporarilyStopped = mActivated.empty() && !mActivatedBackup.empty();
255     std::unordered_map<int, int>& existingConnections =
256                     (!temporarilyStopped) ? mActivated : mActivatedBackup;
257 
258     const struct sensors_direct_cfg_t stopConfig = {
259         .rate_level = SENSOR_DIRECT_RATE_STOP
260     };
261     SensorDevice& dev(SensorDevice::getInstance());
262     for (auto &i : mMicRateBackup) {
263         int handle = i.first;
264         int rateLevel = i.second;
265 
266         const struct sensors_direct_cfg_t config = {
267             .rate_level = rateLevel
268         };
269 
270         // Modify the rate kept by the existing map
271         existingConnections[handle] = rateLevel;
272 
273         // Only reconfigure the channel if it's ongoing
274         if (!temporarilyStopped) {
275             // Stopping before reconfiguring is the well-tested path in CTS
276             dev.configureDirectChannel(handle, getHalChannelHandle(), &stopConfig);
277             dev.configureDirectChannel(handle, getHalChannelHandle(), &config);
278         }
279     }
280     mMicRateBackup.clear();
281 }
282 
stopAll(bool backupRecord)283 void SensorService::SensorDirectConnection::stopAll(bool backupRecord) {
284     Mutex::Autolock _l(mConnectionLock);
285     stopAllLocked(backupRecord);
286 }
287 
stopAllLocked(bool backupRecord)288 void SensorService::SensorDirectConnection::stopAllLocked(bool backupRecord) {
289     struct sensors_direct_cfg_t config = {
290         .rate_level = SENSOR_DIRECT_RATE_STOP
291     };
292 
293     SensorDevice& dev(SensorDevice::getInstance());
294     for (auto &i : mActivated) {
295         dev.configureDirectChannel(i.first, getHalChannelHandle(), &config);
296     }
297 
298     if (backupRecord && mActivatedBackup.empty()) {
299         mActivatedBackup = mActivated;
300     }
301     mActivated.clear();
302 }
303 
recoverAll()304 void SensorService::SensorDirectConnection::recoverAll() {
305     Mutex::Autolock _l(mConnectionLock);
306     if (!mActivatedBackup.empty()) {
307         stopAllLocked(false);
308 
309         SensorDevice& dev(SensorDevice::getInstance());
310 
311         // recover list of report from backup
312         ALOG_ASSERT(mActivated.empty(),
313                     "mActivated must be empty if mActivatedBackup was non-empty");
314         mActivated = mActivatedBackup;
315         mActivatedBackup.clear();
316 
317         // re-enable them
318         for (auto &i : mActivated) {
319             struct sensors_direct_cfg_t config = {
320                 .rate_level = i.second
321             };
322             dev.configureDirectChannel(i.first, getHalChannelHandle(), &config);
323         }
324     }
325 }
326 
getHalChannelHandle() const327 int32_t SensorService::SensorDirectConnection::getHalChannelHandle() const {
328     return mHalChannelHandle;
329 }
330 
isEquivalent(const sensors_direct_mem_t * mem) const331 bool SensorService::SensorDirectConnection::isEquivalent(const sensors_direct_mem_t *mem) const {
332     bool ret = false;
333 
334     if (mMem.type == mem->type) {
335         switch (mMem.type) {
336             case SENSOR_DIRECT_MEM_TYPE_ASHMEM: {
337                 // there is no known method to test if two ashmem fds are equivalent besides
338                 // trivially comparing the fd values (ino number from fstat() are always the
339                 // same, pointing to "/dev/ashmem").
340                 int fd1 = mMem.handle->data[0];
341                 int fd2 = mem->handle->data[0];
342                 ret = (fd1 == fd2);
343                 break;
344             }
345             case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
346                 // there is no known method to test if two gralloc handle are equivalent
347                 ret = false;
348                 break;
349             default:
350                 // should never happen
351                 ALOGE("Unexpected mem type %d", mMem.type);
352                 ret = true;
353                 break;
354         }
355     }
356     return ret;
357 }
358 
359 } // namespace android
360 
361