blob: 143a3c57460b40fa40f8e666e066474d7a8d9d53 [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
Peng Xue36e3472016-11-03 11:57:10 -070024#include <cutils/ashmem.h>
Mathias Agopian907103b2012-04-02 18:38:02 -070025#include <gui/SensorEventQueue.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070026
27#include <hardware/sensors.h>
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070028#include <hardware_legacy/power.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070029
Greg Kaiser53ca2e02016-06-21 16:11:14 -070030#include <openssl/digest.h>
31#include <openssl/hmac.h>
32#include <openssl/rand.h>
33
Mathias Agopian787ac1b2012-09-18 18:49:18 -070034#include "BatteryService.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070035#include "CorrectedGyroSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080036#include "GravitySensor.h"
37#include "LinearAccelerationSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070038#include "OrientationSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080039#include "RotationVectorSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070040#include "SensorFusion.h"
Peng Xu755c4512016-04-07 23:15:14 -070041#include "SensorInterface.h"
Peng Xueb4d6282015-12-10 18:02:41 -080042
Mathias Agopian984826c2011-05-17 22:54:42 -070043#include "SensorService.h"
Peng Xue36e3472016-11-03 11:57:10 -070044#include "SensorDirectConnection.h"
Peng Xueb4d6282015-12-10 18:02:41 -080045#include "SensorEventAckReceiver.h"
Peng Xu6a2d3a02015-12-21 12:00:23 -080046#include "SensorEventConnection.h"
Peng Xueb4d6282015-12-10 18:02:41 -080047#include "SensorRecord.h"
48#include "SensorRegistrationInfo.h"
Peng Xueb4d6282015-12-10 18:02:41 -080049
50#include <inttypes.h>
51#include <math.h>
Peng Xu98d30f62016-08-01 18:12:11 -070052#include <sched.h>
Peng Xueb4d6282015-12-10 18:02:41 -080053#include <stdint.h>
Peng Xueb4d6282015-12-10 18:02:41 -080054#include <sys/socket.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070055#include <sys/stat.h>
56#include <sys/types.h>
57#include <unistd.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070058
59namespace android {
60// ---------------------------------------------------------------------------
61
Mathias Agopian33015422011-05-27 18:18:13 -070062/*
63 * Notes:
64 *
65 * - what about a gyro-corrected magnetic-field sensor?
Mathias Agopian33015422011-05-27 18:18:13 -070066 * - run mag sensor from time to time to force calibration
67 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
68 *
69 */
70
Aravind Akella8ef3c892015-07-10 11:24:28 -070071const char* SensorService::WAKE_LOCK_NAME = "SensorService_wakelock";
Greg Kaiser53ca2e02016-06-21 16:11:14 -070072uint8_t SensorService::sHmacGlobalKey[128] = {};
73bool SensorService::sHmacGlobalKeyIsValid = false;
74
75#define SENSOR_SERVICE_DIR "/data/system/sensor_service"
76#define SENSOR_SERVICE_HMAC_KEY_FILE SENSOR_SERVICE_DIR "/hmac_key"
Peng Xu98d30f62016-08-01 18:12:11 -070077#define SENSOR_SERVICE_SCHED_FIFO_PRIORITY 10
Greg Kaiser53ca2e02016-06-21 16:11:14 -070078
Aravind Akellaa9e6cc32015-04-16 18:57:31 -070079// Permissions.
Aravind Akellaa9e6cc32015-04-16 18:57:31 -070080static const String16 sDump("android.permission.DUMP");
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070081
Mathias Agopianfc328812010-07-14 23:41:37 -070082SensorService::SensorService()
Aravind Akella8a969552014-09-28 17:52:41 -070083 : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
Peng Xu47e96012016-03-28 17:55:56 -070084 mWakeLockAcquired(false) {
Mathias Agopianfc328812010-07-14 23:41:37 -070085}
86
Greg Kaiser53ca2e02016-06-21 16:11:14 -070087bool SensorService::initializeHmacKey() {
88 int fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_RDONLY|O_CLOEXEC);
89 if (fd != -1) {
90 int result = read(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
91 close(fd);
92 if (result == sizeof(sHmacGlobalKey)) {
93 return true;
94 }
95 ALOGW("Unable to read HMAC key; generating new one.");
96 }
97
98 if (RAND_bytes(sHmacGlobalKey, sizeof(sHmacGlobalKey)) == -1) {
99 ALOGW("Can't generate HMAC key; dynamic sensor getId() will be wrong.");
100 return false;
101 }
102
103 // We need to make sure this is only readable to us.
104 bool wroteKey = false;
105 mkdir(SENSOR_SERVICE_DIR, S_IRWXU);
106 fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC,
107 S_IRUSR|S_IWUSR);
108 if (fd != -1) {
109 int result = write(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
110 close(fd);
111 wroteKey = (result == sizeof(sHmacGlobalKey));
112 }
113 if (wroteKey) {
114 ALOGI("Generated new HMAC key.");
115 } else {
116 ALOGW("Unable to write HMAC key; dynamic sensor getId() will change "
117 "after reboot.");
118 }
119 // Even if we failed to write the key we return true, because we did
120 // initialize the HMAC key.
121 return true;
122}
123
Peng Xu98d30f62016-08-01 18:12:11 -0700124// Set main thread to SCHED_FIFO to lower sensor event latency when system is under load
125void SensorService::enableSchedFifoMode() {
126 struct sched_param param = {0};
127 param.sched_priority = SENSOR_SERVICE_SCHED_FIFO_PRIORITY;
128 if (sched_setscheduler(getTid(), SCHED_FIFO | SCHED_RESET_ON_FORK, &param) != 0) {
129 ALOGE("Couldn't set SCHED_FIFO for SensorService thread");
130 }
131}
132
Peng Xu47e96012016-03-28 17:55:56 -0700133void SensorService::onFirstRef() {
Steve Blocka5512372011-12-20 16:23:08 +0000134 ALOGD("nuSensorService starting...");
Mathias Agopianf001c922010-11-11 17:58:51 -0800135 SensorDevice& dev(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700136
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700137 sHmacGlobalKeyIsValid = initializeHmacKey();
138
Mathias Agopianf001c922010-11-11 17:58:51 -0800139 if (dev.initCheck() == NO_ERROR) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800140 sensor_t const* list;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700141 ssize_t count = dev.getSensorList(&list);
142 if (count > 0) {
143 ssize_t orientationIndex = -1;
Aravind Akellaf5047892015-07-20 17:29:33 -0700144 bool hasGyro = false, hasAccel = false, hasMag = false;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700145 uint32_t virtualSensorsNeeds =
146 (1<<SENSOR_TYPE_GRAVITY) |
147 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
Peng Xuf66684a2015-07-23 11:41:53 -0700148 (1<<SENSOR_TYPE_ROTATION_VECTOR) |
149 (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR) |
150 (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700151
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700152 for (ssize_t i=0 ; i<count ; i++) {
Peng Xuf66684a2015-07-23 11:41:53 -0700153 bool useThisSensor=true;
154
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700155 switch (list[i].type) {
Aravind Akellaf5047892015-07-20 17:29:33 -0700156 case SENSOR_TYPE_ACCELEROMETER:
157 hasAccel = true;
158 break;
159 case SENSOR_TYPE_MAGNETIC_FIELD:
160 hasMag = true;
161 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700162 case SENSOR_TYPE_ORIENTATION:
163 orientationIndex = i;
164 break;
165 case SENSOR_TYPE_GYROSCOPE:
Mathias Agopian03193062013-05-10 19:32:39 -0700166 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700167 hasGyro = true;
168 break;
169 case SENSOR_TYPE_GRAVITY:
170 case SENSOR_TYPE_LINEAR_ACCELERATION:
171 case SENSOR_TYPE_ROTATION_VECTOR:
Peng Xuf66684a2015-07-23 11:41:53 -0700172 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
173 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
174 if (IGNORE_HARDWARE_FUSION) {
175 useThisSensor = false;
176 } else {
177 virtualSensorsNeeds &= ~(1<<list[i].type);
178 }
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700179 break;
180 }
Peng Xuf66684a2015-07-23 11:41:53 -0700181 if (useThisSensor) {
182 registerSensor( new HardwareSensor(list[i]) );
183 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700184 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700185
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700186 // it's safe to instantiate the SensorFusion object here
187 // (it wants to be instantiated after h/w sensors have been
188 // registered)
Andreas Gamped4036b62015-07-28 13:49:04 -0700189 SensorFusion::getInstance();
Mathias Agopian984826c2011-05-17 22:54:42 -0700190
Aravind Akellaf5047892015-07-20 17:29:33 -0700191 if (hasGyro && hasAccel && hasMag) {
Mathias Agopian03193062013-05-10 19:32:39 -0700192 // Add Android virtual sensors if they're not already
193 // available in the HAL
Peng Xu0cc8f802016-04-05 23:46:03 -0700194 bool needRotationVector =
195 (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) != 0;
Mathias Agopian03193062013-05-10 19:32:39 -0700196
Peng Xu0cc8f802016-04-05 23:46:03 -0700197 registerSensor(new RotationVectorSensor(), !needRotationVector, true);
198 registerSensor(new OrientationSensor(), !needRotationVector, true);
Mathias Agopian03193062013-05-10 19:32:39 -0700199
Peng Xu0cc8f802016-04-05 23:46:03 -0700200 bool needLinearAcceleration =
201 (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) != 0;
Mathias Agopian03193062013-05-10 19:32:39 -0700202
Peng Xu0cc8f802016-04-05 23:46:03 -0700203 registerSensor(new LinearAccelerationSensor(list, count),
204 !needLinearAcceleration, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700205
Peng Xu0cc8f802016-04-05 23:46:03 -0700206 // virtual debugging sensors are not for user
Peng Xu755c4512016-04-07 23:15:14 -0700207 registerSensor( new CorrectedGyroSensor(list, count), true, true);
208 registerSensor( new GyroDriftSensor(), true, true);
Mathias Agopian33264862012-06-28 19:46:54 -0700209 }
210
Peng Xuf66684a2015-07-23 11:41:53 -0700211 if (hasAccel && hasGyro) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700212 bool needGravitySensor = (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) != 0;
213 registerSensor(new GravitySensor(list, count), !needGravitySensor, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700214
Peng Xu0cc8f802016-04-05 23:46:03 -0700215 bool needGameRotationVector =
216 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) != 0;
217 registerSensor(new GameRotationVectorSensor(), !needGameRotationVector, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700218 }
219
220 if (hasAccel && hasMag) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700221 bool needGeoMagRotationVector =
222 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) != 0;
223 registerSensor(new GeoMagRotationVectorSensor(), !needGeoMagRotationVector, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700224 }
225
Aravind Akella5466c3d2014-08-22 16:11:10 -0700226 // Check if the device really supports batching by looking at the FIFO event
227 // counts for each sensor.
228 bool batchingSupported = false;
Peng Xu0cc8f802016-04-05 23:46:03 -0700229 mSensors.forEachSensor(
230 [&batchingSupported] (const Sensor& s) -> bool {
231 if (s.getFifoMaxEventCount() > 0) {
232 batchingSupported = true;
233 }
234 return !batchingSupported;
235 });
Aravind Akella5466c3d2014-08-22 16:11:10 -0700236
237 if (batchingSupported) {
238 // Increase socket buffer size to a max of 100 KB for batching capabilities.
239 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
240 } else {
241 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
242 }
243
244 // Compare the socketBufferSize value against the system limits and limit
245 // it to maxSystemSocketBufferSize if necessary.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700246 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
247 char line[128];
248 if (fp != NULL && fgets(line, sizeof(line), fp) != NULL) {
249 line[sizeof(line) - 1] = '\0';
Aravind Akella5466c3d2014-08-22 16:11:10 -0700250 size_t maxSystemSocketBufferSize;
251 sscanf(line, "%zu", &maxSystemSocketBufferSize);
252 if (mSocketBufferSize > maxSystemSocketBufferSize) {
253 mSocketBufferSize = maxSystemSocketBufferSize;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700254 }
255 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700256 if (fp) {
257 fclose(fp);
258 }
259
Aravind Akella9a844cf2014-02-11 18:58:52 -0800260 mWakeLockAcquired = false;
Aravind Akella56ae4262014-07-10 16:01:10 -0700261 mLooper = new Looper(false);
Aravind Akella8493b792014-09-08 15:45:47 -0700262 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
263 mSensorEventBuffer = new sensors_event_t[minBufferSize];
264 mSensorEventScratch = new sensors_event_t[minBufferSize];
Peng Xueb059472016-08-12 16:39:44 -0700265 mMapFlushEventsToConnections = new wp<const SensorEventConnection> [minBufferSize];
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700266 mCurrentOperatingMode = NORMAL;
Aravind Akella7830ef32014-10-07 14:13:12 -0700267
Aravind Akella18d6d512015-06-18 14:18:28 -0700268 mNextSensorRegIndex = 0;
269 for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
270 mLastNSensorRegistrations.push();
271 }
272
273 mInitCheck = NO_ERROR;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700274 mAckReceiver = new SensorEventAckReceiver(this);
275 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Aravind Akella7830ef32014-10-07 14:13:12 -0700276 run("SensorService", PRIORITY_URGENT_DISPLAY);
Peng Xu98d30f62016-08-01 18:12:11 -0700277
278 // priority can only be changed after run
279 enableSchedFifoMode();
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700280 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700281 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700282}
283
Peng Xu0cc8f802016-04-05 23:46:03 -0700284const Sensor& SensorService::registerSensor(SensorInterface* s, bool isDebug, bool isVirtual) {
285 int handle = s->getSensor().getHandle();
Peng Xu6a2d3a02015-12-21 12:00:23 -0800286 int type = s->getSensor().getType();
Peng Xu0cc8f802016-04-05 23:46:03 -0700287 if (mSensors.add(handle, s, isDebug, isVirtual)){
Peng Xu6a2d3a02015-12-21 12:00:23 -0800288 mRecentEvent.emplace(handle, new RecentEventLogger(type));
Peng Xu0cc8f802016-04-05 23:46:03 -0700289 return s->getSensor();
290 } else {
291 return mSensors.getNonSensor();
292 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800293}
294
Peng Xu6a2d3a02015-12-21 12:00:23 -0800295const Sensor& SensorService::registerDynamicSensorLocked(SensorInterface* s, bool isDebug) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700296 return registerSensor(s, isDebug);
Peng Xu2576cb62016-01-20 00:22:09 -0800297}
298
Peng Xu6a2d3a02015-12-21 12:00:23 -0800299bool SensorService::unregisterDynamicSensorLocked(int handle) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700300 bool ret = mSensors.remove(handle);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800301
302 const auto i = mRecentEvent.find(handle);
303 if (i != mRecentEvent.end()) {
304 delete i->second;
305 mRecentEvent.erase(i);
Peng Xu2576cb62016-01-20 00:22:09 -0800306 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700307 return ret;
Peng Xu2576cb62016-01-20 00:22:09 -0800308}
309
Peng Xu0cc8f802016-04-05 23:46:03 -0700310const Sensor& SensorService::registerVirtualSensor(SensorInterface* s, bool isDebug) {
311 return registerSensor(s, isDebug, true);
Mathias Agopianfc328812010-07-14 23:41:37 -0700312}
313
Peng Xu47e96012016-03-28 17:55:56 -0700314SensorService::~SensorService() {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800315 for (auto && entry : mRecentEvent) {
316 delete entry.second;
317 }
Peng Xu47e96012016-03-28 17:55:56 -0700318}
319
320status_t SensorService::dump(int fd, const Vector<String16>& args) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700321 String8 result;
Mathias Agopian1cb13462011-06-27 16:05:52 -0700322 if (!PermissionCache::checkCallingPermission(sDump)) {
Peng Xueb4d6282015-12-10 18:02:41 -0800323 result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700324 IPCThreadState::self()->getCallingPid(),
325 IPCThreadState::self()->getCallingUid());
Aravind Akella444f2672015-05-07 12:40:52 -0700326 } else {
Peng Xufba3c112016-09-08 12:36:59 -0700327 bool privileged = IPCThreadState::self()->getCallingUid() == 0;
Aravind Akella841a5922015-06-29 12:37:48 -0700328 if (args.size() > 2) {
Aravind Akella4949c502015-02-11 15:54:35 -0800329 return INVALID_OPERATION;
330 }
331 Mutex::Autolock _l(mLock);
332 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akella841a5922015-06-29 12:37:48 -0700333 if (args.size() == 2 && args[0] == String16("restrict")) {
Aravind Akella444f2672015-05-07 12:40:52 -0700334 // If already in restricted mode. Ignore.
335 if (mCurrentOperatingMode == RESTRICTED) {
336 return status_t(NO_ERROR);
337 }
338 // If in any mode other than normal, ignore.
339 if (mCurrentOperatingMode != NORMAL) {
340 return INVALID_OPERATION;
341 }
Peng Xue36e3472016-11-03 11:57:10 -0700342
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700343 mCurrentOperatingMode = RESTRICTED;
Peng Xue36e3472016-11-03 11:57:10 -0700344 // temporarily stop all sensor direct report
345 for (auto &i : mDirectConnections) {
346 sp<SensorDirectConnection> connection(i.promote());
347 if (connection != nullptr) {
348 connection->stopAll(true /* backupRecord */);
349 }
350 }
351
Aravind Akella4949c502015-02-11 15:54:35 -0800352 dev.disableAllSensors();
353 // Clear all pending flush connections for all active sensors. If one of the active
354 // connections has called flush() and the underlying sensor has been disabled before a
355 // flush complete event is returned, we need to remove the connection from this queue.
356 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
357 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
358 }
Aravind Akella841a5922015-06-29 12:37:48 -0700359 mWhiteListedPackage.setTo(String8(args[1]));
Aravind Akella444f2672015-05-07 12:40:52 -0700360 return status_t(NO_ERROR);
361 } else if (args.size() == 1 && args[0] == String16("enable")) {
362 // If currently in restricted mode, reset back to NORMAL mode else ignore.
363 if (mCurrentOperatingMode == RESTRICTED) {
364 mCurrentOperatingMode = NORMAL;
365 dev.enableAllSensors();
Peng Xue36e3472016-11-03 11:57:10 -0700366 // recover all sensor direct report
367 for (auto &i : mDirectConnections) {
368 sp<SensorDirectConnection> connection(i.promote());
369 if (connection != nullptr) {
370 connection->recoverAll();
371 }
372 }
Aravind Akella444f2672015-05-07 12:40:52 -0700373 }
Aravind Akella841a5922015-06-29 12:37:48 -0700374 if (mCurrentOperatingMode == DATA_INJECTION) {
375 resetToNormalModeLocked();
376 }
377 mWhiteListedPackage.clear();
Aravind Akella444f2672015-05-07 12:40:52 -0700378 return status_t(NO_ERROR);
Aravind Akella841a5922015-06-29 12:37:48 -0700379 } else if (args.size() == 2 && args[0] == String16("data_injection")) {
380 if (mCurrentOperatingMode == NORMAL) {
381 dev.disableAllSensors();
382 status_t err = dev.setMode(DATA_INJECTION);
383 if (err == NO_ERROR) {
384 mCurrentOperatingMode = DATA_INJECTION;
385 } else {
386 // Re-enable sensors.
387 dev.enableAllSensors();
388 }
389 mWhiteListedPackage.setTo(String8(args[1]));
390 return NO_ERROR;
391 } else if (mCurrentOperatingMode == DATA_INJECTION) {
392 // Already in DATA_INJECTION mode. Treat this as a no_op.
393 return NO_ERROR;
394 } else {
395 // Transition to data injection mode supported only from NORMAL mode.
396 return INVALID_OPERATION;
397 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700398 } else if (!mSensors.hasAnySensor()) {
Aravind Akellaee155ca2015-06-24 08:31:32 -0700399 result.append("No Sensors on the device\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700400 } else {
401 // Default dump the sensor list and debugging information.
Peng Xu0cc8f802016-04-05 23:46:03 -0700402 //
Peng Xu6a2d3a02015-12-21 12:00:23 -0800403 result.append("Sensor Device:\n");
404 result.append(SensorDevice::getInstance().dump().c_str());
405
406 result.append("Sensor List:\n");
Peng Xu0cc8f802016-04-05 23:46:03 -0700407 result.append(mSensors.dump().c_str());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700408
Peng Xu6a2d3a02015-12-21 12:00:23 -0800409 result.append("Fusion States:\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700410 SensorFusion::getInstance().dump(result);
Aravind Akella444f2672015-05-07 12:40:52 -0700411
Peng Xu0cc8f802016-04-05 23:46:03 -0700412 result.append("Recent Sensor events:\n");
Peng Xu6a2d3a02015-12-21 12:00:23 -0800413 for (auto&& i : mRecentEvent) {
414 sp<SensorInterface> s = mSensors.getInterface(i.first);
Peng Xufba3c112016-09-08 12:36:59 -0700415 if (!i.second->isEmpty()) {
416 if (privileged || s->getSensor().getRequiredPermission().isEmpty()) {
417 i.second->setFormat("normal");
418 } else {
419 i.second->setFormat("mask_data");
420 }
Peng Xu6a2d3a02015-12-21 12:00:23 -0800421 // if there is events and sensor does not need special permission.
422 result.appendFormat("%s: ", s->getSensor().getName().string());
423 result.append(i.second->dump().c_str());
424 }
425 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700426
Aravind Akella444f2672015-05-07 12:40:52 -0700427 result.append("Active sensors:\n");
428 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
429 int handle = mActiveSensors.keyAt(i);
430 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
431 getSensorName(handle).string(),
432 handle,
433 mActiveSensors.valueAt(i)->getNumConnections());
Aravind Akella6c2664a2014-08-13 12:24:50 -0700434 }
435
Andreas Gamped4036b62015-07-28 13:49:04 -0700436 result.appendFormat("Socket Buffer size = %zd events\n",
Aravind Akella444f2672015-05-07 12:40:52 -0700437 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella18d6d512015-06-18 14:18:28 -0700438 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
439 "not held");
Aravind Akella444f2672015-05-07 12:40:52 -0700440 result.appendFormat("Mode :");
441 switch(mCurrentOperatingMode) {
442 case NORMAL:
443 result.appendFormat(" NORMAL\n");
444 break;
445 case RESTRICTED:
Aravind Akella841a5922015-06-29 12:37:48 -0700446 result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
Aravind Akella444f2672015-05-07 12:40:52 -0700447 break;
448 case DATA_INJECTION:
Aravind Akella841a5922015-06-29 12:37:48 -0700449 result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700450 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700451
Peng Xue36e3472016-11-03 11:57:10 -0700452 result.appendFormat("%zd active connections\n", mActiveConnections.size());
Aravind Akella444f2672015-05-07 12:40:52 -0700453 for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
454 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
455 if (connection != 0) {
456 result.appendFormat("Connection Number: %zu \n", i);
457 connection->dump(result);
458 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700459 }
Aravind Akella18d6d512015-06-18 14:18:28 -0700460
Peng Xue36e3472016-11-03 11:57:10 -0700461 result.appendFormat("%zd direct connections\n", mDirectConnections.size());
462 for (size_t i = 0 ; i < mDirectConnections.size() ; i++) {
463 sp<SensorDirectConnection> connection(mDirectConnections[i].promote());
464 if (connection != nullptr) {
465 result.appendFormat("Direct connection %zu:\n", i);
466 connection->dump(result);
467 }
468 }
469
Aravind Akella18d6d512015-06-18 14:18:28 -0700470 result.appendFormat("Previous Registrations:\n");
471 // Log in the reverse chronological order.
472 int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
473 SENSOR_REGISTRATIONS_BUF_SIZE;
474 const int startIndex = currentIndex;
475 do {
476 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
477 if (SensorRegistrationInfo::isSentinel(reg_info)) {
478 // Ignore sentinel, proceed to next item.
479 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
480 SENSOR_REGISTRATIONS_BUF_SIZE;
481 continue;
482 }
483 if (reg_info.mActivated) {
Peng Xu363b3fd2016-07-07 15:40:08 -0700484 result.appendFormat("%02d:%02d:%02d activated handle=0x%08x "
485 "samplingRate=%dus maxReportLatency=%dus package=%s\n",
486 reg_info.mHour, reg_info.mMin, reg_info.mSec, reg_info.mSensorHandle,
487 reg_info.mSamplingRateUs, reg_info.mMaxReportLatencyUs,
488 reg_info.mPackageName.string());
Aravind Akella18d6d512015-06-18 14:18:28 -0700489 } else {
Peng Xu363b3fd2016-07-07 15:40:08 -0700490 result.appendFormat("%02d:%02d:%02d de-activated handle=0x%08x package=%s\n",
Aravind Akella18d6d512015-06-18 14:18:28 -0700491 reg_info.mHour, reg_info.mMin, reg_info.mSec,
Peng Xu363b3fd2016-07-07 15:40:08 -0700492 reg_info.mSensorHandle, reg_info.mPackageName.string());
Aravind Akella18d6d512015-06-18 14:18:28 -0700493 }
494 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
495 SENSOR_REGISTRATIONS_BUF_SIZE;
496 } while(startIndex != currentIndex);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700497 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700498 }
499 write(fd, result.string(), result.size());
500 return NO_ERROR;
501}
502
Peng Xu0cc8f802016-04-05 23:46:03 -0700503//TODO: move to SensorEventConnection later
Aravind Akella9a844cf2014-02-11 18:58:52 -0800504void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700505 sensors_event_t const* buffer, const int count) {
506 for (int i=0 ; i<count ; i++) {
507 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700508 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
509 handle = buffer[i].meta_data.sensor;
510 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700511 if (connection->hasSensor(handle)) {
Peng Xu755c4512016-04-07 23:15:14 -0700512 sp<SensorInterface> si = getSensorInterfaceFromHandle(handle);
Aravind Akella0e025c52014-06-03 19:19:57 -0700513 // If this buffer has an event from a one_shot sensor and this connection is registered
514 // for this particular one_shot sensor, try cleaning up the connection.
Peng Xu755c4512016-04-07 23:15:14 -0700515 if (si != nullptr &&
Peng Xu0cc8f802016-04-05 23:46:03 -0700516 si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
517 si->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800518 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700519 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700520
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700521 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700522 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700523}
524
Peng Xu47e96012016-03-28 17:55:56 -0700525bool SensorService::threadLoop() {
Steve Blocka5512372011-12-20 16:23:08 +0000526 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700527
Peng Xueb4d6282015-12-10 18:02:41 -0800528 // each virtual sensor could generate an event per "real" event, that's why we need to size
529 // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. in practice, this is too
530 // aggressive, but guaranteed to be enough.
Peng Xu0cc8f802016-04-05 23:46:03 -0700531 const size_t vcount = mSensors.getVirtualSensors().size();
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700532 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
Peng Xu0cc8f802016-04-05 23:46:03 -0700533 const size_t numEventMax = minBufferSize / (1 + vcount);
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700534
Mathias Agopianf001c922010-11-11 17:58:51 -0800535 SensorDevice& device(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700536
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700537 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700538 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700539 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
540 if (count < 0) {
Steve Blockf5a12302012-01-06 19:20:56 +0000541 ALOGE("sensor poll failed (%s)", strerror(-count));
Mathias Agopianfc328812010-07-14 23:41:37 -0700542 break;
543 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700544
545 // Reset sensors_event_t.flags to zero for all events in the buffer.
546 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700547 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700548 }
Aravind Akellae148bc22014-09-24 22:12:58 -0700549
Peng Xueb4d6282015-12-10 18:02:41 -0800550 // Make a copy of the connection vector as some connections may be removed during the course
551 // of this loop (especially when one-shot sensor events are present in the sensor_event
552 // buffer). Promote all connections to StrongPointers before the lock is acquired. If the
553 // destructor of the sp gets called when the lock is acquired, it may result in a deadlock
554 // as ~SensorEventConnection() needs to acquire mLock again for cleanup. So copy all the
555 // strongPointers to a vector before the lock is acquired.
Aravind Akellae148bc22014-09-24 22:12:58 -0700556 SortedVector< sp<SensorEventConnection> > activeConnections;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700557 populateActiveConnections(&activeConnections);
Peng Xueb4d6282015-12-10 18:02:41 -0800558
Aravind Akella9a844cf2014-02-11 18:58:52 -0800559 Mutex::Autolock _l(mLock);
560 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
561 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
562 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
563 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
564 // releasing the wakelock.
565 bool bufferHasWakeUpEvent = false;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700566 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700567 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800568 bufferHasWakeUpEvent = true;
569 break;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700570 }
571 }
572
Aravind Akella9a844cf2014-02-11 18:58:52 -0800573 if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700574 setWakeLockAcquiredLocked(true);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800575 }
Aravind Akella8493b792014-09-08 15:45:47 -0700576 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800577
Mathias Agopianf001c922010-11-11 17:58:51 -0800578 // handle virtual sensors
579 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700580 sensors_event_t const * const event = mSensorEventBuffer;
Peng Xu755c4512016-04-07 23:15:14 -0700581 if (!mActiveVirtualSensors.empty()) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800582 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700583 SensorFusion& fusion(SensorFusion::getInstance());
584 if (fusion.isEnabled()) {
585 for (size_t i=0 ; i<size_t(count) ; i++) {
586 fusion.process(event[i]);
587 }
588 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700589 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Peng Xu755c4512016-04-07 23:15:14 -0700590 for (int handle : mActiveVirtualSensors) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700591 if (count + k >= minBufferSize) {
592 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700593 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700594 count, k, minBufferSize);
595 break;
596 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800597 sensors_event_t out;
Peng Xu755c4512016-04-07 23:15:14 -0700598 sp<SensorInterface> si = mSensors.getInterface(handle);
599 if (si == nullptr) {
600 ALOGE("handle %d is not an valid virtual sensor", handle);
601 continue;
602 }
603
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700604 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700605 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800606 k++;
607 }
608 }
609 }
610 if (k) {
611 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700612 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800613 count += k;
614 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700615 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700616 }
617 }
618 }
619
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700620 // handle backward compatibility for RotationVector sensor
621 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
622 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700623 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700624 // All the 4 components of the quaternion should be available
625 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700626 mSensorEventBuffer[i].data[4] = -1;
627 }
628 }
629 }
630
Aravind Akella8493b792014-09-08 15:45:47 -0700631 for (int i = 0; i < count; ++i) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700632 // Map flush_complete_events in the buffer to SensorEventConnections which called flush
633 // on the hardware sensor. mapFlushEventsToConnections[i] will be the
634 // SensorEventConnection mapped to the corresponding flush_complete_event in
635 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
Aravind Akella8493b792014-09-08 15:45:47 -0700636 mMapFlushEventsToConnections[i] = NULL;
637 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
638 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
639 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
640 if (rec != NULL) {
641 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
642 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700643 }
644 }
Peng Xu2576cb62016-01-20 00:22:09 -0800645
646 // handle dynamic sensor meta events, process registration and unregistration of dynamic
647 // sensor based on content of event.
648 if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
649 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
650 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
651 const sensor_t& dynamicSensor =
652 *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
653 ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
654 handle, dynamicSensor.type, dynamicSensor.name);
655
Peng Xu0cc8f802016-04-05 23:46:03 -0700656 if (mSensors.isNewHandle(handle)) {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800657 const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
Peng Xu47e96012016-03-28 17:55:56 -0700658 sensor_t s = dynamicSensor;
659 // make sure the dynamic sensor flag is set
660 s.flags |= DYNAMIC_SENSOR_MASK;
661 // force the handle to be consistent
662 s.handle = handle;
Peng Xu6a2d3a02015-12-21 12:00:23 -0800663
664 SensorInterface *si = new HardwareSensor(s, uuid);
Peng Xu2576cb62016-01-20 00:22:09 -0800665
Peng Xu0cc8f802016-04-05 23:46:03 -0700666 // This will release hold on dynamic sensor meta, so it should be called
667 // after Sensor object is created.
Peng Xu47e96012016-03-28 17:55:56 -0700668 device.handleDynamicSensorConnection(handle, true /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800669 registerDynamicSensorLocked(si);
Peng Xu47e96012016-03-28 17:55:56 -0700670 } else {
671 ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
672 }
Peng Xu2576cb62016-01-20 00:22:09 -0800673 } else {
674 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
675 ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
676
677 device.handleDynamicSensorConnection(handle, false /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800678 if (!unregisterDynamicSensorLocked(handle)) {
Peng Xu2576cb62016-01-20 00:22:09 -0800679 ALOGE("Dynamic sensor release error.");
680 }
681
682 size_t numConnections = activeConnections.size();
683 for (size_t i=0 ; i < numConnections; ++i) {
684 if (activeConnections[i] != NULL) {
685 activeConnections[i]->removeSensor(handle);
686 }
687 }
688 }
689 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700690 }
691
Peng Xu2576cb62016-01-20 00:22:09 -0800692
Aravind Akella9a844cf2014-02-11 18:58:52 -0800693 // Send our events to clients. Check the state of wake lock for each client and release the
694 // lock if none of the clients need it.
695 bool needsWakeLock = false;
Aravind Akella8493b792014-09-08 15:45:47 -0700696 size_t numConnections = activeConnections.size();
697 for (size_t i=0 ; i < numConnections; ++i) {
Aravind Akellae148bc22014-09-24 22:12:58 -0700698 if (activeConnections[i] != 0) {
699 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
Aravind Akella8493b792014-09-08 15:45:47 -0700700 mMapFlushEventsToConnections);
Aravind Akellae148bc22014-09-24 22:12:58 -0700701 needsWakeLock |= activeConnections[i]->needsWakeLock();
Aravind Akella8493b792014-09-08 15:45:47 -0700702 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
703 // Early check for one-shot sensors.
Aravind Akellae148bc22014-09-24 22:12:58 -0700704 if (activeConnections[i]->hasOneShotSensors()) {
705 cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
706 count);
Aravind Akella8493b792014-09-08 15:45:47 -0700707 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800708 }
709 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700710
Aravind Akella9a844cf2014-02-11 18:58:52 -0800711 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700712 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800713 }
Aravind Akella8493b792014-09-08 15:45:47 -0700714 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -0700715
Steve Block3c20fbe2012-01-05 23:22:43 +0000716 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -0800717 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -0700718 return false;
719}
720
Aravind Akella56ae4262014-07-10 16:01:10 -0700721sp<Looper> SensorService::getLooper() const {
722 return mLooper;
723}
724
Aravind Akellab4373ac2014-10-29 17:55:20 -0700725void SensorService::resetAllWakeLockRefCounts() {
726 SortedVector< sp<SensorEventConnection> > activeConnections;
727 populateActiveConnections(&activeConnections);
728 {
729 Mutex::Autolock _l(mLock);
730 for (size_t i=0 ; i < activeConnections.size(); ++i) {
731 if (activeConnections[i] != 0) {
732 activeConnections[i]->resetWakeLockRefCount();
733 }
734 }
735 setWakeLockAcquiredLocked(false);
736 }
737}
738
739void SensorService::setWakeLockAcquiredLocked(bool acquire) {
740 if (acquire) {
741 if (!mWakeLockAcquired) {
742 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
743 mWakeLockAcquired = true;
744 }
745 mLooper->wake();
746 } else {
747 if (mWakeLockAcquired) {
748 release_wake_lock(WAKE_LOCK_NAME);
749 mWakeLockAcquired = false;
750 }
751 }
752}
753
Aravind Akellab4373ac2014-10-29 17:55:20 -0700754bool SensorService::isWakeLockAcquired() {
755 Mutex::Autolock _l(mLock);
756 return mWakeLockAcquired;
757}
758
Aravind Akella56ae4262014-07-10 16:01:10 -0700759bool SensorService::SensorEventAckReceiver::threadLoop() {
760 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -0700761 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -0700762 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700763 bool wakeLockAcquired = mService->isWakeLockAcquired();
764 int timeout = -1;
765 if (wakeLockAcquired) timeout = 5000;
766 int ret = looper->pollOnce(timeout);
767 if (ret == ALOOPER_POLL_TIMEOUT) {
768 mService->resetAllWakeLockRefCounts();
769 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700770 } while(!Thread::exitPending());
771 return false;
772}
773
Aravind Akella9a844cf2014-02-11 18:58:52 -0800774void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -0800775 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -0800776 for (size_t i = 0; i < count; i++) {
Peng Xu2576cb62016-01-20 00:22:09 -0800777 if (buffer[i].type == SENSOR_TYPE_META_DATA ||
778 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
Peng Xu6a2d3a02015-12-21 12:00:23 -0800779 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) {
Peng Xu2576cb62016-01-20 00:22:09 -0800780 continue;
Mathias Agopian94e8f682010-11-10 17:50:28 -0800781 }
Peng Xu2576cb62016-01-20 00:22:09 -0800782
Peng Xu6a2d3a02015-12-21 12:00:23 -0800783 auto logger = mRecentEvent.find(buffer[i].sensor);
784 if (logger != mRecentEvent.end()) {
785 logger->second->addEvent(buffer[i]);
Peng Xu2576cb62016-01-20 00:22:09 -0800786 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800787 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800788}
789
Peng Xu47e96012016-03-28 17:55:56 -0700790void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800791 struct compar {
792 static int cmp(void const* lhs, void const* rhs) {
793 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
794 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -0700795 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -0800796 }
797 };
798 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
799}
800
Mathias Agopian5d270722010-07-19 15:20:39 -0700801String8 SensorService::getSensorName(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -0700802 return mSensors.getName(handle);
Mathias Agopian5d270722010-07-19 15:20:39 -0700803}
804
Aravind Akellab4099e72013-10-15 15:43:10 -0700805bool SensorService::isVirtualSensor(int handle) const {
Peng Xu755c4512016-04-07 23:15:14 -0700806 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
807 return sensor != nullptr && sensor->isVirtual();
Aravind Akellab4099e72013-10-15 15:43:10 -0700808}
809
Aravind Akella9a844cf2014-02-11 18:58:52 -0800810bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -0700811 int handle = event.sensor;
812 if (event.type == SENSOR_TYPE_META_DATA) {
813 handle = event.meta_data.sensor;
814 }
Peng Xu755c4512016-04-07 23:15:14 -0700815 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
816 return sensor != nullptr && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -0800817}
818
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700819int32_t SensorService::getIdFromUuid(const Sensor::uuid_t &uuid) const {
820 if ((uuid.i64[0] == 0) && (uuid.i64[1] == 0)) {
821 // UUID is not supported for this device.
822 return 0;
823 }
824 if ((uuid.i64[0] == INT64_C(~0)) && (uuid.i64[1] == INT64_C(~0))) {
825 // This sensor can be uniquely identified in the system by
826 // the combination of its type and name.
827 return -1;
828 }
829
830 // We have a dynamic sensor.
831
832 if (!sHmacGlobalKeyIsValid) {
833 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
834 ALOGW("HMAC key failure; dynamic sensor getId() will be wrong.");
835 return 0;
836 }
837
838 // We want each app author/publisher to get a different ID, so that the
839 // same dynamic sensor cannot be tracked across apps by multiple
840 // authors/publishers. So we use both our UUID and our User ID.
841 // Note potential confusion:
842 // UUID => Universally Unique Identifier.
843 // UID => User Identifier.
844 // We refrain from using "uid" except as needed by API to try to
845 // keep this distinction clear.
846
847 auto appUserId = IPCThreadState::self()->getCallingUid();
848 uint8_t uuidAndApp[sizeof(uuid) + sizeof(appUserId)];
849 memcpy(uuidAndApp, &uuid, sizeof(uuid));
850 memcpy(uuidAndApp + sizeof(uuid), &appUserId, sizeof(appUserId));
851
852 // Now we use our key on our UUID/app combo to get the hash.
853 uint8_t hash[EVP_MAX_MD_SIZE];
854 unsigned int hashLen;
855 if (HMAC(EVP_sha256(),
856 sHmacGlobalKey, sizeof(sHmacGlobalKey),
857 uuidAndApp, sizeof(uuidAndApp),
858 hash, &hashLen) == nullptr) {
859 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
860 ALOGW("HMAC failure; dynamic sensor getId() will be wrong.");
861 return 0;
862 }
863
864 int32_t id = 0;
865 if (hashLen < sizeof(id)) {
866 // We never expect this case, but out of paranoia, we handle it.
867 // Our 'id' length is already quite small, we don't want the
868 // effective length of it to be even smaller.
869 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
870 ALOGW("HMAC insufficient; dynamic sensor getId() will be wrong.");
871 return 0;
872 }
873
874 // This is almost certainly less than all of 'hash', but it's as secure
875 // as we can be with our current 'id' length.
876 memcpy(&id, hash, sizeof(id));
877
878 // Note at the beginning of the function that we return the values of
879 // 0 and -1 to represent special cases. As a result, we can't return
880 // those as dynamic sensor IDs. If we happened to hash to one of those
881 // values, we change 'id' so we report as a dynamic sensor, and not as
882 // one of those special cases.
883 if (id == -1) {
884 id = -2;
885 } else if (id == 0) {
886 id = 1;
887 }
888 return id;
889}
890
891void SensorService::makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const {
892 for (auto &sensor : sensorList) {
893 int32_t id = getIdFromUuid(sensor.getUuid());
894 sensor.setId(id);
895 }
896}
897
Nick Vaccaro2c588c52016-11-23 08:44:15 -0800898Vector<Sensor> SensorService::getSensorList(const String16& /* opPackageName */) {
Mathias Agopian33264862012-06-28 19:46:54 -0700899 char value[PROPERTY_VALUE_MAX];
900 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +0000901 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
Peng Xu0cc8f802016-04-05 23:46:03 -0700902 mSensors.getUserDebugSensors() : mSensors.getUserSensors();
Aravind Akella70018042014-04-07 22:52:37 +0000903 Vector<Sensor> accessibleSensorList;
904 for (size_t i = 0; i < initialSensorList.size(); i++) {
905 Sensor sensor = initialSensorList[i];
Nick Vaccaro2c588c52016-11-23 08:44:15 -0800906 accessibleSensorList.add(sensor);
Mathias Agopian33264862012-06-28 19:46:54 -0700907 }
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700908 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Aravind Akella70018042014-04-07 22:52:37 +0000909 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -0700910}
911
Peng Xu47e96012016-03-28 17:55:56 -0700912Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
Peng Xu2576cb62016-01-20 00:22:09 -0800913 Vector<Sensor> accessibleSensorList;
Peng Xu0cc8f802016-04-05 23:46:03 -0700914 mSensors.forEachSensor(
915 [&opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
Peng Xu755c4512016-04-07 23:15:14 -0700916 if (sensor.isDynamicSensor()) {
917 if (canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) {
918 accessibleSensorList.add(sensor);
919 } else {
920 ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
921 sensor.getName().string(),
922 sensor.getRequiredPermission().string(),
923 sensor.getRequiredAppOp());
924 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700925 }
926 return true;
927 });
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700928 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Peng Xu2576cb62016-01-20 00:22:09 -0800929 return accessibleSensorList;
930}
931
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700932sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -0700933 int requestedMode, const String16& opPackageName) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700934 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
935 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
936 return NULL;
937 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700938
939 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700940 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
941 // operating in DI mode.
942 if (requestedMode == DATA_INJECTION) {
943 if (mCurrentOperatingMode != DATA_INJECTION) return NULL;
944 if (!isWhiteListedPackage(packageName)) return NULL;
945 }
946
Mathias Agopian5307d172012-09-18 17:02:43 -0700947 uid_t uid = IPCThreadState::self()->getCallingUid();
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700948 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -0700949 requestedMode == DATA_INJECTION, opPackageName));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700950 if (requestedMode == DATA_INJECTION) {
951 if (mActiveConnections.indexOf(result) < 0) {
952 mActiveConnections.add(result);
953 }
954 // Add the associated file descriptor to the Looper for polling whenever there is data to
955 // be injected.
956 result->updateLooperRegistration(mLooper);
957 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700958 return result;
959}
960
Aravind Akella841a5922015-06-29 12:37:48 -0700961int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700962 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700963 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700964}
965
Peng Xue36e3472016-11-03 11:57:10 -0700966sp<ISensorEventConnection> SensorService::createSensorDirectConnection(
967 const String16& opPackageName, uint32_t size, int32_t type, int32_t format,
968 const native_handle *resource) {
969 Mutex::Autolock _l(mLock);
970
971 struct sensors_direct_mem_t mem = {
972 .type = type,
973 .format = format,
974 .size = size,
975 .handle = resource,
976 };
977 uid_t uid = IPCThreadState::self()->getCallingUid();
978
979 if (mem.handle == nullptr) {
980 ALOGE("Failed to clone resource handle");
981 return nullptr;
982 }
983
984 // check format
985 if (format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
986 ALOGE("Direct channel format %d is unsupported!", format);
987 return nullptr;
988 }
989
990 // check for duplication
991 for (auto &i : mDirectConnections) {
992 sp<SensorDirectConnection> connection(i.promote());
993 if (connection != nullptr && connection->isEquivalent(&mem)) {
994 return nullptr;
995 }
996 }
997
998 // check specific to memory type
999 switch(type) {
1000 case SENSOR_DIRECT_MEM_TYPE_ASHMEM: { // channel backed by ashmem
1001 int fd = resource->data[0];
1002 int size2 = ashmem_get_size_region(fd);
1003 // check size consistency
1004 if (size2 != static_cast<int>(size)) {
1005 ALOGE("Ashmem direct channel size mismatch, %" PRIu32 " vs %d", size, size2);
1006 return nullptr;
1007 }
1008 break;
1009 }
1010 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
1011 LOG_FATAL("%s: Finish implementation of ION and GRALLOC or remove", __FUNCTION__);
1012 break;
1013 default:
1014 ALOGE("Unknown direct connection memory type %d", type);
1015 return nullptr;
1016 }
1017
1018 native_handle_t *clone = native_handle_clone(resource);
1019 if (!clone) {
1020 return nullptr;
1021 }
1022
1023 SensorDirectConnection* conn = nullptr;
1024 SensorDevice& dev(SensorDevice::getInstance());
1025 int channelHandle = dev.registerDirectChannel(&mem);
1026
1027 if (channelHandle <= 0) {
1028 ALOGE("SensorDevice::registerDirectChannel returns %d", channelHandle);
1029 } else {
1030 mem.handle = clone;
1031 conn = new SensorDirectConnection(this, uid, &mem, channelHandle, opPackageName);
1032 }
1033
1034 if (conn == nullptr) {
1035 native_handle_close(clone);
1036 native_handle_delete(clone);
1037 } else {
1038 // add to list of direct connections
1039 // sensor service should never hold pointer or sp of SensorDirectConnection object.
1040 mDirectConnections.add(wp<SensorDirectConnection>(conn));
1041 }
1042 return conn;
1043}
1044
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001045status_t SensorService::resetToNormalMode() {
1046 Mutex::Autolock _l(mLock);
1047 return resetToNormalModeLocked();
1048}
1049
1050status_t SensorService::resetToNormalModeLocked() {
1051 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001052 status_t err = dev.setMode(NORMAL);
Aniroop Mathurbfac17e2016-08-31 22:59:44 +05301053 if (err == NO_ERROR) {
1054 mCurrentOperatingMode = NORMAL;
1055 dev.enableAllSensors();
1056 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001057 return err;
1058}
1059
Peng Xu47e96012016-03-28 17:55:56 -07001060void SensorService::cleanupConnection(SensorEventConnection* c) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001061 Mutex::Autolock _l(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001062 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001063 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -07001064 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001065 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001066 int handle = mActiveSensors.keyAt(i);
1067 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -07001068 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Peng Xu755c4512016-04-07 23:15:14 -07001069 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1070 if (sensor != nullptr) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001071 sensor->activate(c, false);
Peng Xu755c4512016-04-07 23:15:14 -07001072 } else {
1073 ALOGE("sensor interface of handle=0x%08x is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001074 }
Aravind Akella8a969552014-09-28 17:52:41 -07001075 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001076 }
1077 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -07001078 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +00001079 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -07001080 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -07001081 c, i, handle);
1082
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001083 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +00001084 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001085 mActiveSensors.removeItemsAt(i, 1);
Peng Xu755c4512016-04-07 23:15:14 -07001086 mActiveVirtualSensors.erase(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001087 delete rec;
1088 size--;
1089 } else {
1090 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -07001091 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001092 }
Aravind Akella8a969552014-09-28 17:52:41 -07001093 c->updateLooperRegistration(mLooper);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001094 mActiveConnections.remove(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001095 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -08001096 if (c->needsWakeLock()) {
1097 checkWakeLockStateLocked();
1098 }
Peng Xu4f707f82016-09-26 11:28:32 -07001099
1100 SensorDevice& dev(SensorDevice::getInstance());
1101 dev.notifyConnectionDestroyed(c);
Mathias Agopianfc328812010-07-14 23:41:37 -07001102}
1103
Peng Xue36e3472016-11-03 11:57:10 -07001104void SensorService::cleanupConnection(SensorDirectConnection* c) {
1105 Mutex::Autolock _l(mLock);
1106
1107 SensorDevice& dev(SensorDevice::getInstance());
1108 dev.unregisterDirectChannel(c->getHalChannelHandle());
1109 mDirectConnections.remove(c);
1110}
1111
Peng Xu755c4512016-04-07 23:15:14 -07001112sp<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001113 return mSensors.getInterface(handle);
Peng Xu47e96012016-03-28 17:55:56 -07001114}
1115
Mathias Agopianfc328812010-07-14 23:41:37 -07001116status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -07001117 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
Peng Xu47e96012016-03-28 17:55:56 -07001118 const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001119 if (mInitCheck != NO_ERROR)
1120 return mInitCheck;
1121
Peng Xu755c4512016-04-07 23:15:14 -07001122 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1123 if (sensor == nullptr ||
1124 !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001125 return BAD_VALUE;
1126 }
1127
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001128 Mutex::Autolock _l(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001129 if (mCurrentOperatingMode != NORMAL
Aravind Akella841a5922015-06-29 12:37:48 -07001130 && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -08001131 return INVALID_OPERATION;
1132 }
1133
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001134 SensorRecord* rec = mActiveSensors.valueFor(handle);
1135 if (rec == 0) {
1136 rec = new SensorRecord(connection);
1137 mActiveSensors.add(handle, rec);
1138 if (sensor->isVirtual()) {
Peng Xu755c4512016-04-07 23:15:14 -07001139 mActiveVirtualSensors.emplace(handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001140 }
1141 } else {
1142 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001143 // this sensor is already activated, but we are adding a connection that uses it.
1144 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001145 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -07001146 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001147 // NOTE: The wake_up flag of this event may get set to
1148 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Peng Xu6a2d3a02015-12-21 12:00:23 -08001149
1150 auto logger = mRecentEvent.find(handle);
1151 if (logger != mRecentEvent.end()) {
Aravind Akella444f2672015-05-07 12:40:52 -07001152 sensors_event_t event;
Aravind Akella444f2672015-05-07 12:40:52 -07001153 // It is unlikely that this buffer is empty as the sensor is already active.
1154 // One possible corner case may be two applications activating an on-change
1155 // sensor at the same time.
Peng Xu6a2d3a02015-12-21 12:00:23 -08001156 if(logger->second->populateLastEvent(&event)) {
Aravind Akella444f2672015-05-07 12:40:52 -07001157 event.sensor = handle;
1158 if (event.version == sizeof(sensors_event_t)) {
1159 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
1160 setWakeLockAcquiredLocked(true);
1161 }
1162 connection->sendEvents(&event, 1, NULL);
1163 if (!connection->needsWakeLock() && mWakeLockAcquired) {
1164 checkWakeLockStateLocked();
1165 }
1166 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001167 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001168 }
1169 }
1170 }
1171 }
1172
1173 if (connection->addSensor(handle)) {
1174 BatteryService::enableSensor(connection->getUid(), handle);
1175 // the sensor was added (which means it wasn't already there)
1176 // so, see if this connection becomes active
1177 if (mActiveConnections.indexOf(connection) < 0) {
1178 mActiveConnections.add(connection);
1179 }
1180 } else {
1181 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
1182 handle, connection.get());
1183 }
1184
Aravind Akella724d91d2013-06-27 12:04:23 -07001185 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1186 if (samplingPeriodNs < minDelayNs) {
1187 samplingPeriodNs = minDelayNs;
1188 }
1189
Aravind Akella6c2664a2014-08-13 12:24:50 -07001190 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
1191 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -07001192 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
1193
Aravind Akella4949c502015-02-11 15:54:35 -08001194 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -07001195 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001196
Peng Xu20483c42015-10-26 15:14:43 -07001197 // Call flush() before calling activate() on the sensor. Wait for a first
1198 // flush complete event before sending events on this connection. Ignore
1199 // one-shot sensors which don't support flush(). Ignore on-change sensors
1200 // to maintain the on-change logic (any on-change events except the initial
1201 // one should be trigger by a change in value). Also if this sensor isn't
1202 // already active, don't call flush().
1203 if (err == NO_ERROR &&
Peng Xu2576cb62016-01-20 00:22:09 -08001204 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
Aravind Akella5466c3d2014-08-22 16:11:10 -07001205 rec->getNumConnections() > 1) {
1206 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001207 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001208 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001209 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001210 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -07001211 } else {
1212 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001213 }
1214 }
Aravind Akella724d91d2013-06-27 12:04:23 -07001215
1216 if (err == NO_ERROR) {
1217 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
1218 err = sensor->activate(connection.get(), true);
1219 }
1220
Aravind Akella8a969552014-09-28 17:52:41 -07001221 if (err == NO_ERROR) {
1222 connection->updateLooperRegistration(mLooper);
Aravind Akella18d6d512015-06-18 14:18:28 -07001223 SensorRegistrationInfo &reg_info =
1224 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex);
1225 reg_info.mSensorHandle = handle;
1226 reg_info.mSamplingRateUs = samplingPeriodNs/1000;
1227 reg_info.mMaxReportLatencyUs = maxBatchReportLatencyNs/1000;
1228 reg_info.mActivated = true;
1229 reg_info.mPackageName = connection->getPackageName();
1230 time_t rawtime = time(NULL);
1231 struct tm * timeinfo = localtime(&rawtime);
1232 reg_info.mHour = timeinfo->tm_hour;
1233 reg_info.mMin = timeinfo->tm_min;
1234 reg_info.mSec = timeinfo->tm_sec;
1235 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -07001236 }
1237
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001238 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001239 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001240 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001241 }
1242 return err;
1243}
1244
Peng Xu47e96012016-03-28 17:55:56 -07001245status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001246 if (mInitCheck != NO_ERROR)
1247 return mInitCheck;
1248
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001249 Mutex::Autolock _l(mLock);
1250 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001251 if (err == NO_ERROR) {
Peng Xu755c4512016-04-07 23:15:14 -07001252 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1253 err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -07001254
1255 }
1256 if (err == NO_ERROR) {
1257 SensorRegistrationInfo &reg_info =
1258 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex);
1259 reg_info.mActivated = false;
1260 reg_info.mPackageName= connection->getPackageName();
1261 reg_info.mSensorHandle = handle;
1262 time_t rawtime = time(NULL);
1263 struct tm * timeinfo = localtime(&rawtime);
1264 reg_info.mHour = timeinfo->tm_hour;
1265 reg_info.mMin = timeinfo->tm_min;
1266 reg_info.mSec = timeinfo->tm_sec;
1267 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001268 }
1269 return err;
1270}
1271
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001272status_t SensorService::cleanupWithoutDisable(
1273 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001274 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001275 return cleanupWithoutDisableLocked(connection, handle);
1276}
1277
1278status_t SensorService::cleanupWithoutDisableLocked(
1279 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001280 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001281 if (rec) {
1282 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001283 if (connection->removeSensor(handle)) {
1284 BatteryService::disableSensor(connection->getUid(), handle);
1285 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001286 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07001287 connection->updateLooperRegistration(mLooper);
Mathias Agopianfc328812010-07-14 23:41:37 -07001288 mActiveConnections.remove(connection);
1289 }
1290 // see if this sensor becomes inactive
1291 if (rec->removeConnection(connection)) {
1292 mActiveSensors.removeItem(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001293 mActiveVirtualSensors.erase(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001294 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07001295 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001296 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001297 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001298 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07001299}
1300
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001301status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Peng Xu47e96012016-03-28 17:55:56 -07001302 int handle, nsecs_t ns, const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001303 if (mInitCheck != NO_ERROR)
1304 return mInitCheck;
1305
Peng Xu755c4512016-04-07 23:15:14 -07001306 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1307 if (sensor == nullptr ||
1308 !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001309 return BAD_VALUE;
1310 }
1311
Mathias Agopian1cd70002010-07-21 15:59:50 -07001312 if (ns < 0)
1313 return BAD_VALUE;
1314
Mathias Agopian62569ec2011-11-07 21:21:47 -08001315 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1316 if (ns < minDelayNs) {
1317 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07001318 }
1319
Mathias Agopianf001c922010-11-11 17:58:51 -08001320 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07001321}
1322
Svetoslavb412f6e2015-04-29 16:50:41 -07001323status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1324 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00001325 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001326 SensorDevice& dev(SensorDevice::getInstance());
1327 const int halVersion = dev.getHalDeviceVersion();
1328 status_t err(NO_ERROR);
1329 Mutex::Autolock _l(mLock);
1330 // Loop through all sensors for this connection and call flush on each of them.
1331 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
1332 const int handle = connection->mSensorInfo.keyAt(i);
Peng Xu755c4512016-04-07 23:15:14 -07001333 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1334 if (sensor == nullptr) {
1335 continue;
1336 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001337 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1338 ALOGE("flush called on a one-shot sensor");
1339 err = INVALID_OPERATION;
1340 continue;
1341 }
Aravind Akella8493b792014-09-08 15:45:47 -07001342 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001343 // For older devices just increment pending flush count which will send a trivial
1344 // flush complete event.
Aravind Akella8a969552014-09-28 17:52:41 -07001345 connection->incrementPendingFlushCount(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001346 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001347 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1348 err = INVALID_OPERATION;
1349 continue;
1350 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001351 status_t err_flush = sensor->flush(connection.get(), handle);
1352 if (err_flush == NO_ERROR) {
1353 SensorRecord* rec = mActiveSensors.valueFor(handle);
1354 if (rec != NULL) rec->addPendingFlushConnection(connection);
1355 }
1356 err = (err_flush != NO_ERROR) ? err_flush : err;
1357 }
Aravind Akella70018042014-04-07 22:52:37 +00001358 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001359 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001360}
Aravind Akella70018042014-04-07 22:52:37 +00001361
Svetoslavb412f6e2015-04-29 16:50:41 -07001362bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1363 const String16& opPackageName) {
1364 const String8& requiredPermission = sensor.getRequiredPermission();
Aravind Akella70018042014-04-07 22:52:37 +00001365
Svetoslavb412f6e2015-04-29 16:50:41 -07001366 if (requiredPermission.length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00001367 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07001368 }
1369
1370 bool hasPermission = false;
1371
1372 // Runtime permissions can't use the cache as they may change.
1373 if (sensor.isRequiredPermissionRuntime()) {
1374 hasPermission = checkPermission(String16(requiredPermission),
1375 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Aravind Akella70018042014-04-07 22:52:37 +00001376 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001377 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1378 }
1379
1380 if (!hasPermission) {
1381 ALOGE("%s a sensor (%s) without holding its required permission: %s",
1382 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
Aravind Akella70018042014-04-07 22:52:37 +00001383 return false;
1384 }
Svetoslavb412f6e2015-04-29 16:50:41 -07001385
1386 const int32_t opCode = sensor.getRequiredAppOp();
1387 if (opCode >= 0) {
1388 AppOpsManager appOps;
1389 if (appOps.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName)
1390 != AppOpsManager::MODE_ALLOWED) {
Andreas Gamped4036b62015-07-28 13:49:04 -07001391 ALOGE("%s a sensor (%s) without enabled required app op: %d",
Svetoslavb412f6e2015-04-29 16:50:41 -07001392 operation, sensor.getName().string(), opCode);
1393 return false;
1394 }
1395 }
1396
1397 return true;
Aravind Akella70018042014-04-07 22:52:37 +00001398}
1399
Aravind Akella9a844cf2014-02-11 18:58:52 -08001400void SensorService::checkWakeLockState() {
1401 Mutex::Autolock _l(mLock);
1402 checkWakeLockStateLocked();
1403}
1404
1405void SensorService::checkWakeLockStateLocked() {
1406 if (!mWakeLockAcquired) {
1407 return;
1408 }
1409 bool releaseLock = true;
1410 for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
1411 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1412 if (connection != 0) {
1413 if (connection->needsWakeLock()) {
1414 releaseLock = false;
1415 break;
1416 }
1417 }
1418 }
1419 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001420 setWakeLockAcquiredLocked(false);
1421 }
1422}
1423
1424void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1425 Mutex::Autolock _l(mLock);
1426 connection->writeToSocketFromCache();
1427 if (connection->needsWakeLock()) {
1428 setWakeLockAcquiredLocked(true);
1429 }
1430}
1431
1432void SensorService::populateActiveConnections(
1433 SortedVector< sp<SensorEventConnection> >* activeConnections) {
1434 Mutex::Autolock _l(mLock);
1435 for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
1436 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1437 if (connection != 0) {
1438 activeConnections->add(connection);
1439 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001440 }
1441}
Aravind Akella6c2664a2014-08-13 12:24:50 -07001442
Aravind Akella4949c502015-02-11 15:54:35 -08001443bool SensorService::isWhiteListedPackage(const String8& packageName) {
Aravind Akella841a5922015-06-29 12:37:48 -07001444 return (packageName.contains(mWhiteListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08001445}
1446
Peng Xue36e3472016-11-03 11:57:10 -07001447bool SensorService::isOperationRestricted(const String16& opPackageName) {
1448 Mutex::Autolock _l(mLock);
1449 if (mCurrentOperatingMode != RESTRICTED) {
1450 String8 package(opPackageName);
1451 return !isWhiteListedPackage(package);
1452 }
1453 return false;
1454}
1455
Mathias Agopianfc328812010-07-14 23:41:37 -07001456}; // namespace android
1457