blob: 6caa85bff8a9b9e295d2c3d0a7e4521555cf650e [file] [log] [blame]
Mathias Agopianfc328812010-07-14 23:41:37 -07001/*
2 * Copyright (C) 2010 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
Mathias Agopian33015422011-05-27 18:18:13 -070017#include <cutils/properties.h>
18
Svetoslavb412f6e2015-04-29 16:50:41 -070019#include <binder/AppOpsManager.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070020#include <binder/BinderService.h>
Mathias Agopian451beee2010-07-19 15:03:55 -070021#include <binder/IServiceManager.h>
Mathias Agopian1cb13462011-06-27 16:05:52 -070022#include <binder/PermissionCache.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070023
Mathias Agopian907103b2012-04-02 18:38:02 -070024#include <gui/SensorEventQueue.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070025
26#include <hardware/sensors.h>
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070027#include <hardware_legacy/power.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070028
Mathias Agopian787ac1b2012-09-18 18:49:18 -070029#include "BatteryService.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070030#include "CorrectedGyroSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080031#include "GravitySensor.h"
32#include "LinearAccelerationSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070033#include "OrientationSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080034#include "RotationVectorSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070035#include "SensorFusion.h"
Peng Xu755c4512016-04-07 23:15:14 -070036#include "SensorInterface.h"
Peng Xueb4d6282015-12-10 18:02:41 -080037
Mathias Agopian984826c2011-05-17 22:54:42 -070038#include "SensorService.h"
Peng Xueb4d6282015-12-10 18:02:41 -080039#include "SensorEventAckReceiver.h"
Peng Xu6a2d3a02015-12-21 12:00:23 -080040#include "SensorEventConnection.h"
Peng Xueb4d6282015-12-10 18:02:41 -080041#include "SensorRecord.h"
42#include "SensorRegistrationInfo.h"
Peng Xueb4d6282015-12-10 18:02:41 -080043
44#include <inttypes.h>
45#include <math.h>
46#include <stdint.h>
47#include <sys/types.h>
48#include <sys/socket.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070049
50namespace android {
51// ---------------------------------------------------------------------------
52
Mathias Agopian33015422011-05-27 18:18:13 -070053/*
54 * Notes:
55 *
56 * - what about a gyro-corrected magnetic-field sensor?
Mathias Agopian33015422011-05-27 18:18:13 -070057 * - run mag sensor from time to time to force calibration
58 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
59 *
60 */
61
Aravind Akella8ef3c892015-07-10 11:24:28 -070062const char* SensorService::WAKE_LOCK_NAME = "SensorService_wakelock";
Aravind Akellaa9e6cc32015-04-16 18:57:31 -070063// Permissions.
Aravind Akellaa9e6cc32015-04-16 18:57:31 -070064static const String16 sDump("android.permission.DUMP");
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070065
Mathias Agopianfc328812010-07-14 23:41:37 -070066SensorService::SensorService()
Aravind Akella8a969552014-09-28 17:52:41 -070067 : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
Peng Xu47e96012016-03-28 17:55:56 -070068 mWakeLockAcquired(false) {
Mathias Agopianfc328812010-07-14 23:41:37 -070069}
70
Peng Xu47e96012016-03-28 17:55:56 -070071void SensorService::onFirstRef() {
Steve Blocka5512372011-12-20 16:23:08 +000072 ALOGD("nuSensorService starting...");
Mathias Agopianf001c922010-11-11 17:58:51 -080073 SensorDevice& dev(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -070074
Mathias Agopianf001c922010-11-11 17:58:51 -080075 if (dev.initCheck() == NO_ERROR) {
Mathias Agopianf001c922010-11-11 17:58:51 -080076 sensor_t const* list;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070077 ssize_t count = dev.getSensorList(&list);
78 if (count > 0) {
79 ssize_t orientationIndex = -1;
Aravind Akellaf5047892015-07-20 17:29:33 -070080 bool hasGyro = false, hasAccel = false, hasMag = false;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070081 uint32_t virtualSensorsNeeds =
82 (1<<SENSOR_TYPE_GRAVITY) |
83 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
Peng Xuf66684a2015-07-23 11:41:53 -070084 (1<<SENSOR_TYPE_ROTATION_VECTOR) |
85 (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR) |
86 (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070087
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070088 for (ssize_t i=0 ; i<count ; i++) {
Peng Xuf66684a2015-07-23 11:41:53 -070089 bool useThisSensor=true;
90
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070091 switch (list[i].type) {
Aravind Akellaf5047892015-07-20 17:29:33 -070092 case SENSOR_TYPE_ACCELEROMETER:
93 hasAccel = true;
94 break;
95 case SENSOR_TYPE_MAGNETIC_FIELD:
96 hasMag = true;
97 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070098 case SENSOR_TYPE_ORIENTATION:
99 orientationIndex = i;
100 break;
101 case SENSOR_TYPE_GYROSCOPE:
Mathias Agopian03193062013-05-10 19:32:39 -0700102 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700103 hasGyro = true;
104 break;
105 case SENSOR_TYPE_GRAVITY:
106 case SENSOR_TYPE_LINEAR_ACCELERATION:
107 case SENSOR_TYPE_ROTATION_VECTOR:
Peng Xuf66684a2015-07-23 11:41:53 -0700108 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
109 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
110 if (IGNORE_HARDWARE_FUSION) {
111 useThisSensor = false;
112 } else {
113 virtualSensorsNeeds &= ~(1<<list[i].type);
114 }
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700115 break;
116 }
Peng Xuf66684a2015-07-23 11:41:53 -0700117 if (useThisSensor) {
118 registerSensor( new HardwareSensor(list[i]) );
119 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700120 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700121
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700122 // it's safe to instantiate the SensorFusion object here
123 // (it wants to be instantiated after h/w sensors have been
124 // registered)
Andreas Gamped4036b62015-07-28 13:49:04 -0700125 SensorFusion::getInstance();
Mathias Agopian984826c2011-05-17 22:54:42 -0700126
Aravind Akellaf5047892015-07-20 17:29:33 -0700127 if (hasGyro && hasAccel && hasMag) {
Mathias Agopian03193062013-05-10 19:32:39 -0700128 // Add Android virtual sensors if they're not already
129 // available in the HAL
Peng Xu0cc8f802016-04-05 23:46:03 -0700130 bool needRotationVector =
131 (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) != 0;
Mathias Agopian03193062013-05-10 19:32:39 -0700132
Peng Xu0cc8f802016-04-05 23:46:03 -0700133 registerSensor(new RotationVectorSensor(), !needRotationVector, true);
134 registerSensor(new OrientationSensor(), !needRotationVector, true);
Mathias Agopian03193062013-05-10 19:32:39 -0700135
Peng Xu0cc8f802016-04-05 23:46:03 -0700136 bool needLinearAcceleration =
137 (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) != 0;
Mathias Agopian03193062013-05-10 19:32:39 -0700138
Peng Xu0cc8f802016-04-05 23:46:03 -0700139 registerSensor(new LinearAccelerationSensor(list, count),
140 !needLinearAcceleration, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700141
Peng Xu0cc8f802016-04-05 23:46:03 -0700142 // virtual debugging sensors are not for user
Peng Xu755c4512016-04-07 23:15:14 -0700143 registerSensor( new CorrectedGyroSensor(list, count), true, true);
144 registerSensor( new GyroDriftSensor(), true, true);
Mathias Agopian33264862012-06-28 19:46:54 -0700145 }
146
Peng Xuf66684a2015-07-23 11:41:53 -0700147 if (hasAccel && hasGyro) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700148 bool needGravitySensor = (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) != 0;
149 registerSensor(new GravitySensor(list, count), !needGravitySensor, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700150
Peng Xu0cc8f802016-04-05 23:46:03 -0700151 bool needGameRotationVector =
152 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) != 0;
153 registerSensor(new GameRotationVectorSensor(), !needGameRotationVector, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700154 }
155
156 if (hasAccel && hasMag) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700157 bool needGeoMagRotationVector =
158 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) != 0;
159 registerSensor(new GeoMagRotationVectorSensor(), !needGeoMagRotationVector, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700160 }
161
Aravind Akella5466c3d2014-08-22 16:11:10 -0700162 // Check if the device really supports batching by looking at the FIFO event
163 // counts for each sensor.
164 bool batchingSupported = false;
Peng Xu0cc8f802016-04-05 23:46:03 -0700165 mSensors.forEachSensor(
166 [&batchingSupported] (const Sensor& s) -> bool {
167 if (s.getFifoMaxEventCount() > 0) {
168 batchingSupported = true;
169 }
170 return !batchingSupported;
171 });
Aravind Akella5466c3d2014-08-22 16:11:10 -0700172
173 if (batchingSupported) {
174 // Increase socket buffer size to a max of 100 KB for batching capabilities.
175 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
176 } else {
177 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
178 }
179
180 // Compare the socketBufferSize value against the system limits and limit
181 // it to maxSystemSocketBufferSize if necessary.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700182 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
183 char line[128];
184 if (fp != NULL && fgets(line, sizeof(line), fp) != NULL) {
185 line[sizeof(line) - 1] = '\0';
Aravind Akella5466c3d2014-08-22 16:11:10 -0700186 size_t maxSystemSocketBufferSize;
187 sscanf(line, "%zu", &maxSystemSocketBufferSize);
188 if (mSocketBufferSize > maxSystemSocketBufferSize) {
189 mSocketBufferSize = maxSystemSocketBufferSize;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700190 }
191 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700192 if (fp) {
193 fclose(fp);
194 }
195
Aravind Akella9a844cf2014-02-11 18:58:52 -0800196 mWakeLockAcquired = false;
Aravind Akella56ae4262014-07-10 16:01:10 -0700197 mLooper = new Looper(false);
Aravind Akella8493b792014-09-08 15:45:47 -0700198 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
199 mSensorEventBuffer = new sensors_event_t[minBufferSize];
200 mSensorEventScratch = new sensors_event_t[minBufferSize];
201 mMapFlushEventsToConnections = new SensorEventConnection const * [minBufferSize];
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700202 mCurrentOperatingMode = NORMAL;
Aravind Akella7830ef32014-10-07 14:13:12 -0700203
Aravind Akella18d6d512015-06-18 14:18:28 -0700204 mNextSensorRegIndex = 0;
205 for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
206 mLastNSensorRegistrations.push();
207 }
208
209 mInitCheck = NO_ERROR;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700210 mAckReceiver = new SensorEventAckReceiver(this);
211 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Aravind Akella7830ef32014-10-07 14:13:12 -0700212 run("SensorService", PRIORITY_URGENT_DISPLAY);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700213 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700214 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700215}
216
Peng Xu0cc8f802016-04-05 23:46:03 -0700217const Sensor& SensorService::registerSensor(SensorInterface* s, bool isDebug, bool isVirtual) {
218 int handle = s->getSensor().getHandle();
Peng Xu6a2d3a02015-12-21 12:00:23 -0800219 int type = s->getSensor().getType();
Peng Xu0cc8f802016-04-05 23:46:03 -0700220 if (mSensors.add(handle, s, isDebug, isVirtual)){
Peng Xu6a2d3a02015-12-21 12:00:23 -0800221 mRecentEvent.emplace(handle, new RecentEventLogger(type));
Peng Xu0cc8f802016-04-05 23:46:03 -0700222 return s->getSensor();
223 } else {
224 return mSensors.getNonSensor();
225 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800226}
227
Peng Xu6a2d3a02015-12-21 12:00:23 -0800228const Sensor& SensorService::registerDynamicSensorLocked(SensorInterface* s, bool isDebug) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700229 return registerSensor(s, isDebug);
Peng Xu2576cb62016-01-20 00:22:09 -0800230}
231
Peng Xu6a2d3a02015-12-21 12:00:23 -0800232bool SensorService::unregisterDynamicSensorLocked(int handle) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700233 bool ret = mSensors.remove(handle);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800234
235 const auto i = mRecentEvent.find(handle);
236 if (i != mRecentEvent.end()) {
237 delete i->second;
238 mRecentEvent.erase(i);
Peng Xu2576cb62016-01-20 00:22:09 -0800239 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700240 return ret;
Peng Xu2576cb62016-01-20 00:22:09 -0800241}
242
Peng Xu0cc8f802016-04-05 23:46:03 -0700243const Sensor& SensorService::registerVirtualSensor(SensorInterface* s, bool isDebug) {
244 return registerSensor(s, isDebug, true);
Mathias Agopianfc328812010-07-14 23:41:37 -0700245}
246
Peng Xu47e96012016-03-28 17:55:56 -0700247SensorService::~SensorService() {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800248 for (auto && entry : mRecentEvent) {
249 delete entry.second;
250 }
Peng Xu47e96012016-03-28 17:55:56 -0700251}
252
253status_t SensorService::dump(int fd, const Vector<String16>& args) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700254 String8 result;
Mathias Agopian1cb13462011-06-27 16:05:52 -0700255 if (!PermissionCache::checkCallingPermission(sDump)) {
Peng Xueb4d6282015-12-10 18:02:41 -0800256 result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700257 IPCThreadState::self()->getCallingPid(),
258 IPCThreadState::self()->getCallingUid());
Aravind Akella444f2672015-05-07 12:40:52 -0700259 } else {
Aravind Akella841a5922015-06-29 12:37:48 -0700260 if (args.size() > 2) {
Aravind Akella4949c502015-02-11 15:54:35 -0800261 return INVALID_OPERATION;
262 }
263 Mutex::Autolock _l(mLock);
264 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akella841a5922015-06-29 12:37:48 -0700265 if (args.size() == 2 && args[0] == String16("restrict")) {
Aravind Akella444f2672015-05-07 12:40:52 -0700266 // If already in restricted mode. Ignore.
267 if (mCurrentOperatingMode == RESTRICTED) {
268 return status_t(NO_ERROR);
269 }
270 // If in any mode other than normal, ignore.
271 if (mCurrentOperatingMode != NORMAL) {
272 return INVALID_OPERATION;
273 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700274 mCurrentOperatingMode = RESTRICTED;
Aravind Akella4949c502015-02-11 15:54:35 -0800275 dev.disableAllSensors();
276 // Clear all pending flush connections for all active sensors. If one of the active
277 // connections has called flush() and the underlying sensor has been disabled before a
278 // flush complete event is returned, we need to remove the connection from this queue.
279 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
280 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
281 }
Aravind Akella841a5922015-06-29 12:37:48 -0700282 mWhiteListedPackage.setTo(String8(args[1]));
Aravind Akella444f2672015-05-07 12:40:52 -0700283 return status_t(NO_ERROR);
284 } else if (args.size() == 1 && args[0] == String16("enable")) {
285 // If currently in restricted mode, reset back to NORMAL mode else ignore.
286 if (mCurrentOperatingMode == RESTRICTED) {
287 mCurrentOperatingMode = NORMAL;
288 dev.enableAllSensors();
289 }
Aravind Akella841a5922015-06-29 12:37:48 -0700290 if (mCurrentOperatingMode == DATA_INJECTION) {
291 resetToNormalModeLocked();
292 }
293 mWhiteListedPackage.clear();
Aravind Akella444f2672015-05-07 12:40:52 -0700294 return status_t(NO_ERROR);
Aravind Akella841a5922015-06-29 12:37:48 -0700295 } else if (args.size() == 2 && args[0] == String16("data_injection")) {
296 if (mCurrentOperatingMode == NORMAL) {
297 dev.disableAllSensors();
298 status_t err = dev.setMode(DATA_INJECTION);
299 if (err == NO_ERROR) {
300 mCurrentOperatingMode = DATA_INJECTION;
301 } else {
302 // Re-enable sensors.
303 dev.enableAllSensors();
304 }
305 mWhiteListedPackage.setTo(String8(args[1]));
306 return NO_ERROR;
307 } else if (mCurrentOperatingMode == DATA_INJECTION) {
308 // Already in DATA_INJECTION mode. Treat this as a no_op.
309 return NO_ERROR;
310 } else {
311 // Transition to data injection mode supported only from NORMAL mode.
312 return INVALID_OPERATION;
313 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700314 } else if (!mSensors.hasAnySensor()) {
Aravind Akellaee155ca2015-06-24 08:31:32 -0700315 result.append("No Sensors on the device\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700316 } else {
317 // Default dump the sensor list and debugging information.
Peng Xu0cc8f802016-04-05 23:46:03 -0700318 //
Peng Xu6a2d3a02015-12-21 12:00:23 -0800319 result.append("Sensor Device:\n");
320 result.append(SensorDevice::getInstance().dump().c_str());
321
322 result.append("Sensor List:\n");
Peng Xu0cc8f802016-04-05 23:46:03 -0700323 result.append(mSensors.dump().c_str());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700324
Peng Xu6a2d3a02015-12-21 12:00:23 -0800325 result.append("Fusion States:\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700326 SensorFusion::getInstance().dump(result);
Aravind Akella444f2672015-05-07 12:40:52 -0700327
Peng Xu0cc8f802016-04-05 23:46:03 -0700328 result.append("Recent Sensor events:\n");
Peng Xu6a2d3a02015-12-21 12:00:23 -0800329 for (auto&& i : mRecentEvent) {
330 sp<SensorInterface> s = mSensors.getInterface(i.first);
331 if (!i.second->isEmpty() &&
332 s->getSensor().getRequiredPermission().isEmpty()) {
333 // if there is events and sensor does not need special permission.
334 result.appendFormat("%s: ", s->getSensor().getName().string());
335 result.append(i.second->dump().c_str());
336 }
337 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700338
Aravind Akella444f2672015-05-07 12:40:52 -0700339 result.append("Active sensors:\n");
340 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
341 int handle = mActiveSensors.keyAt(i);
342 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
343 getSensorName(handle).string(),
344 handle,
345 mActiveSensors.valueAt(i)->getNumConnections());
Aravind Akella6c2664a2014-08-13 12:24:50 -0700346 }
347
Andreas Gamped4036b62015-07-28 13:49:04 -0700348 result.appendFormat("Socket Buffer size = %zd events\n",
Aravind Akella444f2672015-05-07 12:40:52 -0700349 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella18d6d512015-06-18 14:18:28 -0700350 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
351 "not held");
Aravind Akella444f2672015-05-07 12:40:52 -0700352 result.appendFormat("Mode :");
353 switch(mCurrentOperatingMode) {
354 case NORMAL:
355 result.appendFormat(" NORMAL\n");
356 break;
357 case RESTRICTED:
Aravind Akella841a5922015-06-29 12:37:48 -0700358 result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
Aravind Akella444f2672015-05-07 12:40:52 -0700359 break;
360 case DATA_INJECTION:
Aravind Akella841a5922015-06-29 12:37:48 -0700361 result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700362 }
Aravind Akella444f2672015-05-07 12:40:52 -0700363 result.appendFormat("%zd active connections\n", mActiveConnections.size());
Aravind Akella0e025c52014-06-03 19:19:57 -0700364
Aravind Akella444f2672015-05-07 12:40:52 -0700365 for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
366 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
367 if (connection != 0) {
368 result.appendFormat("Connection Number: %zu \n", i);
369 connection->dump(result);
370 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700371 }
Aravind Akella18d6d512015-06-18 14:18:28 -0700372
373 result.appendFormat("Previous Registrations:\n");
374 // Log in the reverse chronological order.
375 int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
376 SENSOR_REGISTRATIONS_BUF_SIZE;
377 const int startIndex = currentIndex;
378 do {
379 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
380 if (SensorRegistrationInfo::isSentinel(reg_info)) {
381 // Ignore sentinel, proceed to next item.
382 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
383 SENSOR_REGISTRATIONS_BUF_SIZE;
384 continue;
385 }
386 if (reg_info.mActivated) {
387 result.appendFormat("%02d:%02d:%02d activated package=%s handle=0x%08x "
388 "samplingRate=%dus maxReportLatency=%dus\n",
389 reg_info.mHour, reg_info.mMin, reg_info.mSec,
390 reg_info.mPackageName.string(), reg_info.mSensorHandle,
391 reg_info.mSamplingRateUs, reg_info.mMaxReportLatencyUs);
392 } else {
393 result.appendFormat("%02d:%02d:%02d de-activated package=%s handle=0x%08x\n",
394 reg_info.mHour, reg_info.mMin, reg_info.mSec,
395 reg_info.mPackageName.string(), reg_info.mSensorHandle);
396 }
397 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
398 SENSOR_REGISTRATIONS_BUF_SIZE;
399 } while(startIndex != currentIndex);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700400 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700401 }
402 write(fd, result.string(), result.size());
403 return NO_ERROR;
404}
405
Peng Xu0cc8f802016-04-05 23:46:03 -0700406//TODO: move to SensorEventConnection later
Aravind Akella9a844cf2014-02-11 18:58:52 -0800407void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700408 sensors_event_t const* buffer, const int count) {
409 for (int i=0 ; i<count ; i++) {
410 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700411 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
412 handle = buffer[i].meta_data.sensor;
413 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700414 if (connection->hasSensor(handle)) {
Peng Xu755c4512016-04-07 23:15:14 -0700415 sp<SensorInterface> si = getSensorInterfaceFromHandle(handle);
Aravind Akella0e025c52014-06-03 19:19:57 -0700416 // If this buffer has an event from a one_shot sensor and this connection is registered
417 // for this particular one_shot sensor, try cleaning up the connection.
Peng Xu755c4512016-04-07 23:15:14 -0700418 if (si != nullptr &&
Peng Xu0cc8f802016-04-05 23:46:03 -0700419 si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
420 si->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800421 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700422 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700423
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700424 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700425 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700426}
427
Peng Xu47e96012016-03-28 17:55:56 -0700428bool SensorService::threadLoop() {
Steve Blocka5512372011-12-20 16:23:08 +0000429 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700430
Peng Xueb4d6282015-12-10 18:02:41 -0800431 // each virtual sensor could generate an event per "real" event, that's why we need to size
432 // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. in practice, this is too
433 // aggressive, but guaranteed to be enough.
Peng Xu0cc8f802016-04-05 23:46:03 -0700434 const size_t vcount = mSensors.getVirtualSensors().size();
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700435 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
Peng Xu0cc8f802016-04-05 23:46:03 -0700436 const size_t numEventMax = minBufferSize / (1 + vcount);
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700437
Mathias Agopianf001c922010-11-11 17:58:51 -0800438 SensorDevice& device(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700439
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700440 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700441 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700442 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
443 if (count < 0) {
Steve Blockf5a12302012-01-06 19:20:56 +0000444 ALOGE("sensor poll failed (%s)", strerror(-count));
Mathias Agopianfc328812010-07-14 23:41:37 -0700445 break;
446 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700447
448 // Reset sensors_event_t.flags to zero for all events in the buffer.
449 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700450 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700451 }
Aravind Akellae148bc22014-09-24 22:12:58 -0700452
Peng Xueb4d6282015-12-10 18:02:41 -0800453 // Make a copy of the connection vector as some connections may be removed during the course
454 // of this loop (especially when one-shot sensor events are present in the sensor_event
455 // buffer). Promote all connections to StrongPointers before the lock is acquired. If the
456 // destructor of the sp gets called when the lock is acquired, it may result in a deadlock
457 // as ~SensorEventConnection() needs to acquire mLock again for cleanup. So copy all the
458 // strongPointers to a vector before the lock is acquired.
Aravind Akellae148bc22014-09-24 22:12:58 -0700459 SortedVector< sp<SensorEventConnection> > activeConnections;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700460 populateActiveConnections(&activeConnections);
Peng Xueb4d6282015-12-10 18:02:41 -0800461
Aravind Akella9a844cf2014-02-11 18:58:52 -0800462 Mutex::Autolock _l(mLock);
463 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
464 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
465 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
466 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
467 // releasing the wakelock.
468 bool bufferHasWakeUpEvent = false;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700469 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700470 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800471 bufferHasWakeUpEvent = true;
472 break;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700473 }
474 }
475
Aravind Akella9a844cf2014-02-11 18:58:52 -0800476 if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700477 setWakeLockAcquiredLocked(true);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800478 }
Aravind Akella8493b792014-09-08 15:45:47 -0700479 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800480
Mathias Agopianf001c922010-11-11 17:58:51 -0800481 // handle virtual sensors
482 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700483 sensors_event_t const * const event = mSensorEventBuffer;
Peng Xu755c4512016-04-07 23:15:14 -0700484 if (!mActiveVirtualSensors.empty()) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800485 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700486 SensorFusion& fusion(SensorFusion::getInstance());
487 if (fusion.isEnabled()) {
488 for (size_t i=0 ; i<size_t(count) ; i++) {
489 fusion.process(event[i]);
490 }
491 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700492 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Peng Xu755c4512016-04-07 23:15:14 -0700493 for (int handle : mActiveVirtualSensors) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700494 if (count + k >= minBufferSize) {
495 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700496 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700497 count, k, minBufferSize);
498 break;
499 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800500 sensors_event_t out;
Peng Xu755c4512016-04-07 23:15:14 -0700501 sp<SensorInterface> si = mSensors.getInterface(handle);
502 if (si == nullptr) {
503 ALOGE("handle %d is not an valid virtual sensor", handle);
504 continue;
505 }
506
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700507 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700508 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800509 k++;
510 }
511 }
512 }
513 if (k) {
514 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700515 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800516 count += k;
517 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700518 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700519 }
520 }
521 }
522
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700523 // handle backward compatibility for RotationVector sensor
524 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
525 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700526 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700527 // All the 4 components of the quaternion should be available
528 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700529 mSensorEventBuffer[i].data[4] = -1;
530 }
531 }
532 }
533
Aravind Akella8493b792014-09-08 15:45:47 -0700534 for (int i = 0; i < count; ++i) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700535 // Map flush_complete_events in the buffer to SensorEventConnections which called flush
536 // on the hardware sensor. mapFlushEventsToConnections[i] will be the
537 // SensorEventConnection mapped to the corresponding flush_complete_event in
538 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
Aravind Akella8493b792014-09-08 15:45:47 -0700539 mMapFlushEventsToConnections[i] = NULL;
540 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
541 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
542 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
543 if (rec != NULL) {
544 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
545 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700546 }
547 }
Peng Xu2576cb62016-01-20 00:22:09 -0800548
549 // handle dynamic sensor meta events, process registration and unregistration of dynamic
550 // sensor based on content of event.
551 if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
552 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
553 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
554 const sensor_t& dynamicSensor =
555 *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
556 ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
557 handle, dynamicSensor.type, dynamicSensor.name);
558
Peng Xu0cc8f802016-04-05 23:46:03 -0700559 if (mSensors.isNewHandle(handle)) {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800560 const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
Peng Xu47e96012016-03-28 17:55:56 -0700561 sensor_t s = dynamicSensor;
562 // make sure the dynamic sensor flag is set
563 s.flags |= DYNAMIC_SENSOR_MASK;
564 // force the handle to be consistent
565 s.handle = handle;
Peng Xu6a2d3a02015-12-21 12:00:23 -0800566
567 SensorInterface *si = new HardwareSensor(s, uuid);
Peng Xu2576cb62016-01-20 00:22:09 -0800568
Peng Xu0cc8f802016-04-05 23:46:03 -0700569 // This will release hold on dynamic sensor meta, so it should be called
570 // after Sensor object is created.
Peng Xu47e96012016-03-28 17:55:56 -0700571 device.handleDynamicSensorConnection(handle, true /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800572 registerDynamicSensorLocked(si);
Peng Xu47e96012016-03-28 17:55:56 -0700573 } else {
574 ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
575 }
Peng Xu2576cb62016-01-20 00:22:09 -0800576 } else {
577 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
578 ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
579
580 device.handleDynamicSensorConnection(handle, false /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800581 if (!unregisterDynamicSensorLocked(handle)) {
Peng Xu2576cb62016-01-20 00:22:09 -0800582 ALOGE("Dynamic sensor release error.");
583 }
584
585 size_t numConnections = activeConnections.size();
586 for (size_t i=0 ; i < numConnections; ++i) {
587 if (activeConnections[i] != NULL) {
588 activeConnections[i]->removeSensor(handle);
589 }
590 }
591 }
592 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700593 }
594
Peng Xu2576cb62016-01-20 00:22:09 -0800595
Aravind Akella9a844cf2014-02-11 18:58:52 -0800596 // Send our events to clients. Check the state of wake lock for each client and release the
597 // lock if none of the clients need it.
598 bool needsWakeLock = false;
Aravind Akella8493b792014-09-08 15:45:47 -0700599 size_t numConnections = activeConnections.size();
600 for (size_t i=0 ; i < numConnections; ++i) {
Aravind Akellae148bc22014-09-24 22:12:58 -0700601 if (activeConnections[i] != 0) {
602 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
Aravind Akella8493b792014-09-08 15:45:47 -0700603 mMapFlushEventsToConnections);
Aravind Akellae148bc22014-09-24 22:12:58 -0700604 needsWakeLock |= activeConnections[i]->needsWakeLock();
Aravind Akella8493b792014-09-08 15:45:47 -0700605 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
606 // Early check for one-shot sensors.
Aravind Akellae148bc22014-09-24 22:12:58 -0700607 if (activeConnections[i]->hasOneShotSensors()) {
608 cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
609 count);
Aravind Akella8493b792014-09-08 15:45:47 -0700610 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800611 }
612 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700613
Aravind Akella9a844cf2014-02-11 18:58:52 -0800614 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700615 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800616 }
Aravind Akella8493b792014-09-08 15:45:47 -0700617 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -0700618
Steve Block3c20fbe2012-01-05 23:22:43 +0000619 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -0800620 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -0700621 return false;
622}
623
Aravind Akella56ae4262014-07-10 16:01:10 -0700624sp<Looper> SensorService::getLooper() const {
625 return mLooper;
626}
627
Aravind Akellab4373ac2014-10-29 17:55:20 -0700628void SensorService::resetAllWakeLockRefCounts() {
629 SortedVector< sp<SensorEventConnection> > activeConnections;
630 populateActiveConnections(&activeConnections);
631 {
632 Mutex::Autolock _l(mLock);
633 for (size_t i=0 ; i < activeConnections.size(); ++i) {
634 if (activeConnections[i] != 0) {
635 activeConnections[i]->resetWakeLockRefCount();
636 }
637 }
638 setWakeLockAcquiredLocked(false);
639 }
640}
641
642void SensorService::setWakeLockAcquiredLocked(bool acquire) {
643 if (acquire) {
644 if (!mWakeLockAcquired) {
645 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
646 mWakeLockAcquired = true;
647 }
648 mLooper->wake();
649 } else {
650 if (mWakeLockAcquired) {
651 release_wake_lock(WAKE_LOCK_NAME);
652 mWakeLockAcquired = false;
653 }
654 }
655}
656
Aravind Akellab4373ac2014-10-29 17:55:20 -0700657bool SensorService::isWakeLockAcquired() {
658 Mutex::Autolock _l(mLock);
659 return mWakeLockAcquired;
660}
661
Aravind Akella56ae4262014-07-10 16:01:10 -0700662bool SensorService::SensorEventAckReceiver::threadLoop() {
663 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -0700664 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -0700665 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700666 bool wakeLockAcquired = mService->isWakeLockAcquired();
667 int timeout = -1;
668 if (wakeLockAcquired) timeout = 5000;
669 int ret = looper->pollOnce(timeout);
670 if (ret == ALOOPER_POLL_TIMEOUT) {
671 mService->resetAllWakeLockRefCounts();
672 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700673 } while(!Thread::exitPending());
674 return false;
675}
676
Aravind Akella9a844cf2014-02-11 18:58:52 -0800677void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -0800678 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -0800679 for (size_t i = 0; i < count; i++) {
Peng Xu2576cb62016-01-20 00:22:09 -0800680 if (buffer[i].type == SENSOR_TYPE_META_DATA ||
681 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
Peng Xu6a2d3a02015-12-21 12:00:23 -0800682 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) {
Peng Xu2576cb62016-01-20 00:22:09 -0800683 continue;
Mathias Agopian94e8f682010-11-10 17:50:28 -0800684 }
Peng Xu2576cb62016-01-20 00:22:09 -0800685
Peng Xu6a2d3a02015-12-21 12:00:23 -0800686 auto logger = mRecentEvent.find(buffer[i].sensor);
687 if (logger != mRecentEvent.end()) {
688 logger->second->addEvent(buffer[i]);
Peng Xu2576cb62016-01-20 00:22:09 -0800689 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800690 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800691}
692
Peng Xu47e96012016-03-28 17:55:56 -0700693void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800694 struct compar {
695 static int cmp(void const* lhs, void const* rhs) {
696 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
697 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -0700698 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -0800699 }
700 };
701 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
702}
703
Mathias Agopian5d270722010-07-19 15:20:39 -0700704String8 SensorService::getSensorName(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -0700705 return mSensors.getName(handle);
Mathias Agopian5d270722010-07-19 15:20:39 -0700706}
707
Aravind Akellab4099e72013-10-15 15:43:10 -0700708bool SensorService::isVirtualSensor(int handle) const {
Peng Xu755c4512016-04-07 23:15:14 -0700709 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
710 return sensor != nullptr && sensor->isVirtual();
Aravind Akellab4099e72013-10-15 15:43:10 -0700711}
712
Aravind Akella9a844cf2014-02-11 18:58:52 -0800713bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -0700714 int handle = event.sensor;
715 if (event.type == SENSOR_TYPE_META_DATA) {
716 handle = event.meta_data.sensor;
717 }
Peng Xu755c4512016-04-07 23:15:14 -0700718 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
719 return sensor != nullptr && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -0800720}
721
Peng Xu47e96012016-03-28 17:55:56 -0700722Vector<Sensor> SensorService::getSensorList(const String16& opPackageName) {
Mathias Agopian33264862012-06-28 19:46:54 -0700723 char value[PROPERTY_VALUE_MAX];
724 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +0000725 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
Peng Xu0cc8f802016-04-05 23:46:03 -0700726 mSensors.getUserDebugSensors() : mSensors.getUserSensors();
Aravind Akella70018042014-04-07 22:52:37 +0000727 Vector<Sensor> accessibleSensorList;
728 for (size_t i = 0; i < initialSensorList.size(); i++) {
729 Sensor sensor = initialSensorList[i];
Svetoslavb412f6e2015-04-29 16:50:41 -0700730 if (canAccessSensor(sensor, "getSensorList", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +0000731 accessibleSensorList.add(sensor);
732 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -0700733 ALOGI("Skipped sensor %s because it requires permission %s and app op %d",
Bernhard Rosenkränzer5f619932014-11-17 21:06:20 +0100734 sensor.getName().string(),
Svetoslavb412f6e2015-04-29 16:50:41 -0700735 sensor.getRequiredPermission().string(),
736 sensor.getRequiredAppOp());
Aravind Akella70018042014-04-07 22:52:37 +0000737 }
Mathias Agopian33264862012-06-28 19:46:54 -0700738 }
Aravind Akella70018042014-04-07 22:52:37 +0000739 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -0700740}
741
Peng Xu47e96012016-03-28 17:55:56 -0700742Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
Peng Xu2576cb62016-01-20 00:22:09 -0800743 Vector<Sensor> accessibleSensorList;
Peng Xu0cc8f802016-04-05 23:46:03 -0700744 mSensors.forEachSensor(
745 [&opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
Peng Xu755c4512016-04-07 23:15:14 -0700746 if (sensor.isDynamicSensor()) {
747 if (canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) {
748 accessibleSensorList.add(sensor);
749 } else {
750 ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
751 sensor.getName().string(),
752 sensor.getRequiredPermission().string(),
753 sensor.getRequiredAppOp());
754 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700755 }
756 return true;
757 });
Peng Xu2576cb62016-01-20 00:22:09 -0800758 return accessibleSensorList;
759}
760
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700761sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -0700762 int requestedMode, const String16& opPackageName) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700763 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
764 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
765 return NULL;
766 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700767
768 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700769 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
770 // operating in DI mode.
771 if (requestedMode == DATA_INJECTION) {
772 if (mCurrentOperatingMode != DATA_INJECTION) return NULL;
773 if (!isWhiteListedPackage(packageName)) return NULL;
774 }
775
Mathias Agopian5307d172012-09-18 17:02:43 -0700776 uid_t uid = IPCThreadState::self()->getCallingUid();
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700777 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -0700778 requestedMode == DATA_INJECTION, opPackageName));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700779 if (requestedMode == DATA_INJECTION) {
780 if (mActiveConnections.indexOf(result) < 0) {
781 mActiveConnections.add(result);
782 }
783 // Add the associated file descriptor to the Looper for polling whenever there is data to
784 // be injected.
785 result->updateLooperRegistration(mLooper);
786 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700787 return result;
788}
789
Aravind Akella841a5922015-06-29 12:37:48 -0700790int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700791 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700792 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700793}
794
795status_t SensorService::resetToNormalMode() {
796 Mutex::Autolock _l(mLock);
797 return resetToNormalModeLocked();
798}
799
800status_t SensorService::resetToNormalModeLocked() {
801 SensorDevice& dev(SensorDevice::getInstance());
802 dev.enableAllSensors();
803 status_t err = dev.setMode(NORMAL);
804 mCurrentOperatingMode = NORMAL;
805 return err;
806}
807
Peng Xu47e96012016-03-28 17:55:56 -0700808void SensorService::cleanupConnection(SensorEventConnection* c) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700809 Mutex::Autolock _l(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800810 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700811 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -0700812 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700813 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800814 int handle = mActiveSensors.keyAt(i);
815 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -0700816 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Peng Xu755c4512016-04-07 23:15:14 -0700817 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
818 if (sensor != nullptr) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800819 sensor->activate(c, false);
Peng Xu755c4512016-04-07 23:15:14 -0700820 } else {
821 ALOGE("sensor interface of handle=0x%08x is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800822 }
Aravind Akella8a969552014-09-28 17:52:41 -0700823 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800824 }
825 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -0700826 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +0000827 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -0700828 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700829 c, i, handle);
830
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800831 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +0000832 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700833 mActiveSensors.removeItemsAt(i, 1);
Peng Xu755c4512016-04-07 23:15:14 -0700834 mActiveVirtualSensors.erase(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700835 delete rec;
836 size--;
837 } else {
838 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -0700839 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700840 }
Aravind Akella8a969552014-09-28 17:52:41 -0700841 c->updateLooperRegistration(mLooper);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700842 mActiveConnections.remove(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -0700843 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -0800844 if (c->needsWakeLock()) {
845 checkWakeLockStateLocked();
846 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700847}
848
Peng Xu755c4512016-04-07 23:15:14 -0700849sp<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -0700850 return mSensors.getInterface(handle);
Peng Xu47e96012016-03-28 17:55:56 -0700851}
852
Aravind Akella70018042014-04-07 22:52:37 +0000853
Mathias Agopianfc328812010-07-14 23:41:37 -0700854status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -0700855 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
Peng Xu47e96012016-03-28 17:55:56 -0700856 const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -0700857 if (mInitCheck != NO_ERROR)
858 return mInitCheck;
859
Peng Xu755c4512016-04-07 23:15:14 -0700860 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
861 if (sensor == nullptr ||
862 !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +0000863 return BAD_VALUE;
864 }
865
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700866 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700867 if ((mCurrentOperatingMode == RESTRICTED || mCurrentOperatingMode == DATA_INJECTION)
868 && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -0800869 return INVALID_OPERATION;
870 }
871
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700872 SensorRecord* rec = mActiveSensors.valueFor(handle);
873 if (rec == 0) {
874 rec = new SensorRecord(connection);
875 mActiveSensors.add(handle, rec);
876 if (sensor->isVirtual()) {
Peng Xu755c4512016-04-07 23:15:14 -0700877 mActiveVirtualSensors.emplace(handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700878 }
879 } else {
880 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800881 // this sensor is already activated, but we are adding a connection that uses it.
882 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700883 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -0700884 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800885 // NOTE: The wake_up flag of this event may get set to
886 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Peng Xu6a2d3a02015-12-21 12:00:23 -0800887
888 auto logger = mRecentEvent.find(handle);
889 if (logger != mRecentEvent.end()) {
Aravind Akella444f2672015-05-07 12:40:52 -0700890 sensors_event_t event;
Aravind Akella444f2672015-05-07 12:40:52 -0700891 // It is unlikely that this buffer is empty as the sensor is already active.
892 // One possible corner case may be two applications activating an on-change
893 // sensor at the same time.
Peng Xu6a2d3a02015-12-21 12:00:23 -0800894 if(logger->second->populateLastEvent(&event)) {
Aravind Akella444f2672015-05-07 12:40:52 -0700895 event.sensor = handle;
896 if (event.version == sizeof(sensors_event_t)) {
897 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
898 setWakeLockAcquiredLocked(true);
899 }
900 connection->sendEvents(&event, 1, NULL);
901 if (!connection->needsWakeLock() && mWakeLockAcquired) {
902 checkWakeLockStateLocked();
903 }
904 }
Aravind Akella9a844cf2014-02-11 18:58:52 -0800905 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700906 }
907 }
908 }
909 }
910
911 if (connection->addSensor(handle)) {
912 BatteryService::enableSensor(connection->getUid(), handle);
913 // the sensor was added (which means it wasn't already there)
914 // so, see if this connection becomes active
915 if (mActiveConnections.indexOf(connection) < 0) {
916 mActiveConnections.add(connection);
917 }
918 } else {
919 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
920 handle, connection.get());
921 }
922
Aravind Akella724d91d2013-06-27 12:04:23 -0700923 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
924 if (samplingPeriodNs < minDelayNs) {
925 samplingPeriodNs = minDelayNs;
926 }
927
Aravind Akella6c2664a2014-08-13 12:24:50 -0700928 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
929 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -0700930 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
931
Aravind Akella4949c502015-02-11 15:54:35 -0800932 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -0700933 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -0700934
Peng Xu20483c42015-10-26 15:14:43 -0700935 // Call flush() before calling activate() on the sensor. Wait for a first
936 // flush complete event before sending events on this connection. Ignore
937 // one-shot sensors which don't support flush(). Ignore on-change sensors
938 // to maintain the on-change logic (any on-change events except the initial
939 // one should be trigger by a change in value). Also if this sensor isn't
940 // already active, don't call flush().
941 if (err == NO_ERROR &&
Peng Xu2576cb62016-01-20 00:22:09 -0800942 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
Aravind Akella5466c3d2014-08-22 16:11:10 -0700943 rec->getNumConnections() > 1) {
944 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700945 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -0700946 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -0700947 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700948 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -0700949 } else {
950 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700951 }
952 }
Aravind Akella724d91d2013-06-27 12:04:23 -0700953
954 if (err == NO_ERROR) {
955 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
956 err = sensor->activate(connection.get(), true);
957 }
958
Aravind Akella8a969552014-09-28 17:52:41 -0700959 if (err == NO_ERROR) {
960 connection->updateLooperRegistration(mLooper);
Aravind Akella18d6d512015-06-18 14:18:28 -0700961 SensorRegistrationInfo &reg_info =
962 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex);
963 reg_info.mSensorHandle = handle;
964 reg_info.mSamplingRateUs = samplingPeriodNs/1000;
965 reg_info.mMaxReportLatencyUs = maxBatchReportLatencyNs/1000;
966 reg_info.mActivated = true;
967 reg_info.mPackageName = connection->getPackageName();
968 time_t rawtime = time(NULL);
969 struct tm * timeinfo = localtime(&rawtime);
970 reg_info.mHour = timeinfo->tm_hour;
971 reg_info.mMin = timeinfo->tm_min;
972 reg_info.mSec = timeinfo->tm_sec;
973 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -0700974 }
975
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700976 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -0700977 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700978 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700979 }
980 return err;
981}
982
Peng Xu47e96012016-03-28 17:55:56 -0700983status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopian50df2952010-07-19 19:09:10 -0700984 if (mInitCheck != NO_ERROR)
985 return mInitCheck;
986
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700987 Mutex::Autolock _l(mLock);
988 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700989 if (err == NO_ERROR) {
Peng Xu755c4512016-04-07 23:15:14 -0700990 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
991 err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -0700992
993 }
994 if (err == NO_ERROR) {
995 SensorRegistrationInfo &reg_info =
996 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex);
997 reg_info.mActivated = false;
998 reg_info.mPackageName= connection->getPackageName();
999 reg_info.mSensorHandle = handle;
1000 time_t rawtime = time(NULL);
1001 struct tm * timeinfo = localtime(&rawtime);
1002 reg_info.mHour = timeinfo->tm_hour;
1003 reg_info.mMin = timeinfo->tm_min;
1004 reg_info.mSec = timeinfo->tm_sec;
1005 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001006 }
1007 return err;
1008}
1009
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001010status_t SensorService::cleanupWithoutDisable(
1011 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001012 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001013 return cleanupWithoutDisableLocked(connection, handle);
1014}
1015
1016status_t SensorService::cleanupWithoutDisableLocked(
1017 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001018 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001019 if (rec) {
1020 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001021 if (connection->removeSensor(handle)) {
1022 BatteryService::disableSensor(connection->getUid(), handle);
1023 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001024 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07001025 connection->updateLooperRegistration(mLooper);
Mathias Agopianfc328812010-07-14 23:41:37 -07001026 mActiveConnections.remove(connection);
1027 }
1028 // see if this sensor becomes inactive
1029 if (rec->removeConnection(connection)) {
1030 mActiveSensors.removeItem(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001031 mActiveVirtualSensors.erase(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001032 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07001033 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001034 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001035 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001036 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07001037}
1038
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001039status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Peng Xu47e96012016-03-28 17:55:56 -07001040 int handle, nsecs_t ns, const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001041 if (mInitCheck != NO_ERROR)
1042 return mInitCheck;
1043
Peng Xu755c4512016-04-07 23:15:14 -07001044 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1045 if (sensor == nullptr ||
1046 !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001047 return BAD_VALUE;
1048 }
1049
Mathias Agopian1cd70002010-07-21 15:59:50 -07001050 if (ns < 0)
1051 return BAD_VALUE;
1052
Mathias Agopian62569ec2011-11-07 21:21:47 -08001053 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1054 if (ns < minDelayNs) {
1055 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07001056 }
1057
Mathias Agopianf001c922010-11-11 17:58:51 -08001058 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07001059}
1060
Svetoslavb412f6e2015-04-29 16:50:41 -07001061status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1062 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00001063 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001064 SensorDevice& dev(SensorDevice::getInstance());
1065 const int halVersion = dev.getHalDeviceVersion();
1066 status_t err(NO_ERROR);
1067 Mutex::Autolock _l(mLock);
1068 // Loop through all sensors for this connection and call flush on each of them.
1069 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
1070 const int handle = connection->mSensorInfo.keyAt(i);
Peng Xu755c4512016-04-07 23:15:14 -07001071 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1072 if (sensor == nullptr) {
1073 continue;
1074 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001075 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1076 ALOGE("flush called on a one-shot sensor");
1077 err = INVALID_OPERATION;
1078 continue;
1079 }
Aravind Akella8493b792014-09-08 15:45:47 -07001080 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001081 // For older devices just increment pending flush count which will send a trivial
1082 // flush complete event.
Aravind Akella8a969552014-09-28 17:52:41 -07001083 connection->incrementPendingFlushCount(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001084 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001085 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1086 err = INVALID_OPERATION;
1087 continue;
1088 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001089 status_t err_flush = sensor->flush(connection.get(), handle);
1090 if (err_flush == NO_ERROR) {
1091 SensorRecord* rec = mActiveSensors.valueFor(handle);
1092 if (rec != NULL) rec->addPendingFlushConnection(connection);
1093 }
1094 err = (err_flush != NO_ERROR) ? err_flush : err;
1095 }
Aravind Akella70018042014-04-07 22:52:37 +00001096 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001097 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001098}
Aravind Akella70018042014-04-07 22:52:37 +00001099
Svetoslavb412f6e2015-04-29 16:50:41 -07001100bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1101 const String16& opPackageName) {
1102 const String8& requiredPermission = sensor.getRequiredPermission();
Aravind Akella70018042014-04-07 22:52:37 +00001103
Svetoslavb412f6e2015-04-29 16:50:41 -07001104 if (requiredPermission.length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00001105 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07001106 }
1107
1108 bool hasPermission = false;
1109
1110 // Runtime permissions can't use the cache as they may change.
1111 if (sensor.isRequiredPermissionRuntime()) {
1112 hasPermission = checkPermission(String16(requiredPermission),
1113 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Aravind Akella70018042014-04-07 22:52:37 +00001114 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001115 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1116 }
1117
1118 if (!hasPermission) {
1119 ALOGE("%s a sensor (%s) without holding its required permission: %s",
1120 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
Aravind Akella70018042014-04-07 22:52:37 +00001121 return false;
1122 }
Svetoslavb412f6e2015-04-29 16:50:41 -07001123
1124 const int32_t opCode = sensor.getRequiredAppOp();
1125 if (opCode >= 0) {
1126 AppOpsManager appOps;
1127 if (appOps.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName)
1128 != AppOpsManager::MODE_ALLOWED) {
Andreas Gamped4036b62015-07-28 13:49:04 -07001129 ALOGE("%s a sensor (%s) without enabled required app op: %d",
Svetoslavb412f6e2015-04-29 16:50:41 -07001130 operation, sensor.getName().string(), opCode);
1131 return false;
1132 }
1133 }
1134
1135 return true;
Aravind Akella70018042014-04-07 22:52:37 +00001136}
1137
Aravind Akella9a844cf2014-02-11 18:58:52 -08001138void SensorService::checkWakeLockState() {
1139 Mutex::Autolock _l(mLock);
1140 checkWakeLockStateLocked();
1141}
1142
1143void SensorService::checkWakeLockStateLocked() {
1144 if (!mWakeLockAcquired) {
1145 return;
1146 }
1147 bool releaseLock = true;
1148 for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
1149 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1150 if (connection != 0) {
1151 if (connection->needsWakeLock()) {
1152 releaseLock = false;
1153 break;
1154 }
1155 }
1156 }
1157 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001158 setWakeLockAcquiredLocked(false);
1159 }
1160}
1161
1162void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1163 Mutex::Autolock _l(mLock);
1164 connection->writeToSocketFromCache();
1165 if (connection->needsWakeLock()) {
1166 setWakeLockAcquiredLocked(true);
1167 }
1168}
1169
1170void SensorService::populateActiveConnections(
1171 SortedVector< sp<SensorEventConnection> >* activeConnections) {
1172 Mutex::Autolock _l(mLock);
1173 for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
1174 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1175 if (connection != 0) {
1176 activeConnections->add(connection);
1177 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001178 }
1179}
Aravind Akella6c2664a2014-08-13 12:24:50 -07001180
Aravind Akella4949c502015-02-11 15:54:35 -08001181bool SensorService::isWhiteListedPackage(const String8& packageName) {
Aravind Akella841a5922015-06-29 12:37:48 -07001182 return (packageName.contains(mWhiteListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08001183}
1184
Mathias Agopianfc328812010-07-14 23:41:37 -07001185}; // namespace android
1186