blob: fd72b2312ffa1ee25231d988e699d71b3a2fbef4 [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
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -070017#include <inttypes.h>
Mathias Agopianf001c922010-11-11 17:58:51 -080018#include <math.h>
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -070019#include <stdint.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070020#include <sys/types.h>
Aravind Akella56ae4262014-07-10 16:01:10 -070021#include <sys/socket.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070022
Mathias Agopian33015422011-05-27 18:18:13 -070023#include <cutils/properties.h>
24
Mathias Agopianfc328812010-07-14 23:41:37 -070025#include <utils/SortedVector.h>
26#include <utils/KeyedVector.h>
27#include <utils/threads.h>
28#include <utils/Atomic.h>
29#include <utils/Errors.h>
30#include <utils/RefBase.h>
Mathias Agopian451beee2010-07-19 15:03:55 -070031#include <utils/Singleton.h>
Mathias Agopianc4a930d2010-07-22 22:19:43 -070032#include <utils/String16.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070033
Svetoslavb412f6e2015-04-29 16:50:41 -070034#include <binder/AppOpsManager.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070035#include <binder/BinderService.h>
Mathias Agopian451beee2010-07-19 15:03:55 -070036#include <binder/IServiceManager.h>
Mathias Agopian1cb13462011-06-27 16:05:52 -070037#include <binder/PermissionCache.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070038
39#include <gui/ISensorServer.h>
40#include <gui/ISensorEventConnection.h>
Mathias Agopian907103b2012-04-02 18:38:02 -070041#include <gui/SensorEventQueue.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070042
43#include <hardware/sensors.h>
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070044#include <hardware_legacy/power.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070045
Mathias Agopian787ac1b2012-09-18 18:49:18 -070046#include "BatteryService.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070047#include "CorrectedGyroSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080048#include "GravitySensor.h"
49#include "LinearAccelerationSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070050#include "OrientationSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080051#include "RotationVectorSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070052#include "SensorFusion.h"
53#include "SensorService.h"
Mathias Agopianfc328812010-07-14 23:41:37 -070054
55namespace android {
56// ---------------------------------------------------------------------------
57
Mathias Agopian33015422011-05-27 18:18:13 -070058/*
59 * Notes:
60 *
61 * - what about a gyro-corrected magnetic-field sensor?
Mathias Agopian33015422011-05-27 18:18:13 -070062 * - run mag sensor from time to time to force calibration
63 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
64 *
65 */
66
Aravind Akella8ef3c892015-07-10 11:24:28 -070067const char* SensorService::WAKE_LOCK_NAME = "SensorService_wakelock";
Aravind Akellaa9e6cc32015-04-16 18:57:31 -070068// Permissions.
Aravind Akellaa9e6cc32015-04-16 18:57:31 -070069static const String16 sDump("android.permission.DUMP");
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070070
Mathias Agopianfc328812010-07-14 23:41:37 -070071SensorService::SensorService()
Aravind Akella8a969552014-09-28 17:52:41 -070072 : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
73 mWakeLockAcquired(false)
Mathias Agopianfc328812010-07-14 23:41:37 -070074{
75}
76
77void SensorService::onFirstRef()
78{
Steve Blocka5512372011-12-20 16:23:08 +000079 ALOGD("nuSensorService starting...");
Mathias Agopianf001c922010-11-11 17:58:51 -080080 SensorDevice& dev(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -070081
Mathias Agopianf001c922010-11-11 17:58:51 -080082 if (dev.initCheck() == NO_ERROR) {
Mathias Agopianf001c922010-11-11 17:58:51 -080083 sensor_t const* list;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070084 ssize_t count = dev.getSensorList(&list);
85 if (count > 0) {
86 ssize_t orientationIndex = -1;
Aravind Akellaf5047892015-07-20 17:29:33 -070087 bool hasGyro = false, hasAccel = false, hasMag = false;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070088 uint32_t virtualSensorsNeeds =
89 (1<<SENSOR_TYPE_GRAVITY) |
90 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
91 (1<<SENSOR_TYPE_ROTATION_VECTOR);
92
93 mLastEventSeen.setCapacity(count);
94 for (ssize_t i=0 ; i<count ; i++) {
95 registerSensor( new HardwareSensor(list[i]) );
96 switch (list[i].type) {
Aravind Akellaf5047892015-07-20 17:29:33 -070097 case SENSOR_TYPE_ACCELEROMETER:
98 hasAccel = true;
99 break;
100 case SENSOR_TYPE_MAGNETIC_FIELD:
101 hasMag = true;
102 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700103 case SENSOR_TYPE_ORIENTATION:
104 orientationIndex = i;
105 break;
106 case SENSOR_TYPE_GYROSCOPE:
Mathias Agopian03193062013-05-10 19:32:39 -0700107 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700108 hasGyro = true;
109 break;
110 case SENSOR_TYPE_GRAVITY:
111 case SENSOR_TYPE_LINEAR_ACCELERATION:
112 case SENSOR_TYPE_ROTATION_VECTOR:
113 virtualSensorsNeeds &= ~(1<<list[i].type);
114 break;
115 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700116 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700117
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700118 // it's safe to instantiate the SensorFusion object here
119 // (it wants to be instantiated after h/w sensors have been
120 // registered)
121 const SensorFusion& fusion(SensorFusion::getInstance());
Mathias Agopian984826c2011-05-17 22:54:42 -0700122
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700123 // build the sensor list returned to users
124 mUserSensorList = mSensorList;
Mathias Agopian33264862012-06-28 19:46:54 -0700125
Aravind Akellaf5047892015-07-20 17:29:33 -0700126 if (hasGyro && hasAccel && hasMag) {
Mathias Agopian03193062013-05-10 19:32:39 -0700127 Sensor aSensor;
128
129 // Add Android virtual sensors if they're not already
130 // available in the HAL
131
132 aSensor = registerVirtualSensor( new RotationVectorSensor() );
133 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
134 mUserSensorList.add(aSensor);
135 }
136
137 aSensor = registerVirtualSensor( new GravitySensor(list, count) );
138 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) {
139 mUserSensorList.add(aSensor);
140 }
141
142 aSensor = registerVirtualSensor( new LinearAccelerationSensor(list, count) );
143 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) {
144 mUserSensorList.add(aSensor);
145 }
146
147 aSensor = registerVirtualSensor( new OrientationSensor() );
148 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
149 // if we are doing our own rotation-vector, also add
150 // the orientation sensor and remove the HAL provided one.
151 mUserSensorList.replaceAt(aSensor, orientationIndex);
152 }
153
Mathias Agopian33264862012-06-28 19:46:54 -0700154 // virtual debugging sensors are not added to mUserSensorList
Mathias Agopian03193062013-05-10 19:32:39 -0700155 registerVirtualSensor( new CorrectedGyroSensor(list, count) );
Mathias Agopian33264862012-06-28 19:46:54 -0700156 registerVirtualSensor( new GyroDriftSensor() );
157 }
158
Mathias Agopian33264862012-06-28 19:46:54 -0700159 // debugging sensor list
Mathias Agopian03193062013-05-10 19:32:39 -0700160 mUserSensorListDebug = mSensorList;
Mathias Agopian33264862012-06-28 19:46:54 -0700161
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;
Svetoslavb412f6e2015-04-29 16:50:41 -0700165 for (size_t i = 0; i < mSensorList.size(); ++i) {
Aravind Akella5466c3d2014-08-22 16:11:10 -0700166 if (mSensorList[i].getFifoMaxEventCount() > 0) {
167 batchingSupported = true;
168 break;
169 }
170 }
171
172 if (batchingSupported) {
173 // Increase socket buffer size to a max of 100 KB for batching capabilities.
174 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
175 } else {
176 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
177 }
178
179 // Compare the socketBufferSize value against the system limits and limit
180 // it to maxSystemSocketBufferSize if necessary.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700181 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
182 char line[128];
183 if (fp != NULL && fgets(line, sizeof(line), fp) != NULL) {
184 line[sizeof(line) - 1] = '\0';
Aravind Akella5466c3d2014-08-22 16:11:10 -0700185 size_t maxSystemSocketBufferSize;
186 sscanf(line, "%zu", &maxSystemSocketBufferSize);
187 if (mSocketBufferSize > maxSystemSocketBufferSize) {
188 mSocketBufferSize = maxSystemSocketBufferSize;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700189 }
190 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700191 if (fp) {
192 fclose(fp);
193 }
194
Aravind Akella9a844cf2014-02-11 18:58:52 -0800195 mWakeLockAcquired = false;
Aravind Akella56ae4262014-07-10 16:01:10 -0700196 mLooper = new Looper(false);
Aravind Akella8493b792014-09-08 15:45:47 -0700197 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
198 mSensorEventBuffer = new sensors_event_t[minBufferSize];
199 mSensorEventScratch = new sensors_event_t[minBufferSize];
200 mMapFlushEventsToConnections = new SensorEventConnection const * [minBufferSize];
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700201 mCurrentOperatingMode = NORMAL;
Aravind Akella7830ef32014-10-07 14:13:12 -0700202
Aravind Akella18d6d512015-06-18 14:18:28 -0700203 mNextSensorRegIndex = 0;
204 for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
205 mLastNSensorRegistrations.push();
206 }
207
208 mInitCheck = NO_ERROR;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700209 mAckReceiver = new SensorEventAckReceiver(this);
210 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Aravind Akella7830ef32014-10-07 14:13:12 -0700211 run("SensorService", PRIORITY_URGENT_DISPLAY);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700212 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700213 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700214}
215
Mathias Agopian03193062013-05-10 19:32:39 -0700216Sensor SensorService::registerSensor(SensorInterface* s)
Mathias Agopianf001c922010-11-11 17:58:51 -0800217{
218 sensors_event_t event;
219 memset(&event, 0, sizeof(event));
220
221 const Sensor sensor(s->getSensor());
222 // add to the sensor list (returned to clients)
223 mSensorList.add(sensor);
224 // add to our handle->SensorInterface mapping
225 mSensorMap.add(sensor.getHandle(), s);
226 // create an entry in the mLastEventSeen array
Aravind Akella444f2672015-05-07 12:40:52 -0700227 mLastEventSeen.add(sensor.getHandle(), NULL);
Mathias Agopian03193062013-05-10 19:32:39 -0700228
229 return sensor;
Mathias Agopianf001c922010-11-11 17:58:51 -0800230}
231
Mathias Agopian03193062013-05-10 19:32:39 -0700232Sensor SensorService::registerVirtualSensor(SensorInterface* s)
Mathias Agopianf001c922010-11-11 17:58:51 -0800233{
Mathias Agopian03193062013-05-10 19:32:39 -0700234 Sensor sensor = registerSensor(s);
Mathias Agopianf001c922010-11-11 17:58:51 -0800235 mVirtualSensorList.add( s );
Mathias Agopian03193062013-05-10 19:32:39 -0700236 return sensor;
Mathias Agopianf001c922010-11-11 17:58:51 -0800237}
238
Mathias Agopianfc328812010-07-14 23:41:37 -0700239SensorService::~SensorService()
240{
Mathias Agopianf001c922010-11-11 17:58:51 -0800241 for (size_t i=0 ; i<mSensorMap.size() ; i++)
242 delete mSensorMap.valueAt(i);
Mathias Agopianfc328812010-07-14 23:41:37 -0700243}
244
Aravind Akella4949c502015-02-11 15:54:35 -0800245status_t SensorService::dump(int fd, const Vector<String16>& args)
Mathias Agopianfc328812010-07-14 23:41:37 -0700246{
Mathias Agopianfc328812010-07-14 23:41:37 -0700247 String8 result;
Mathias Agopian1cb13462011-06-27 16:05:52 -0700248 if (!PermissionCache::checkCallingPermission(sDump)) {
Mathias Agopianba02cd22013-07-03 16:20:57 -0700249 result.appendFormat("Permission Denial: "
Aravind Akella70018042014-04-07 22:52:37 +0000250 "can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700251 IPCThreadState::self()->getCallingPid(),
252 IPCThreadState::self()->getCallingUid());
Aravind Akella444f2672015-05-07 12:40:52 -0700253 } else {
Aravind Akella841a5922015-06-29 12:37:48 -0700254 if (args.size() > 2) {
Aravind Akella4949c502015-02-11 15:54:35 -0800255 return INVALID_OPERATION;
256 }
257 Mutex::Autolock _l(mLock);
258 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akella841a5922015-06-29 12:37:48 -0700259 if (args.size() == 2 && args[0] == String16("restrict")) {
Aravind Akella444f2672015-05-07 12:40:52 -0700260 // If already in restricted mode. Ignore.
261 if (mCurrentOperatingMode == RESTRICTED) {
262 return status_t(NO_ERROR);
263 }
264 // If in any mode other than normal, ignore.
265 if (mCurrentOperatingMode != NORMAL) {
266 return INVALID_OPERATION;
267 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700268 mCurrentOperatingMode = RESTRICTED;
Aravind Akella4949c502015-02-11 15:54:35 -0800269 dev.disableAllSensors();
270 // Clear all pending flush connections for all active sensors. If one of the active
271 // connections has called flush() and the underlying sensor has been disabled before a
272 // flush complete event is returned, we need to remove the connection from this queue.
273 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
274 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
275 }
Aravind Akella841a5922015-06-29 12:37:48 -0700276 mWhiteListedPackage.setTo(String8(args[1]));
Aravind Akella444f2672015-05-07 12:40:52 -0700277 return status_t(NO_ERROR);
278 } else if (args.size() == 1 && args[0] == String16("enable")) {
279 // If currently in restricted mode, reset back to NORMAL mode else ignore.
280 if (mCurrentOperatingMode == RESTRICTED) {
281 mCurrentOperatingMode = NORMAL;
282 dev.enableAllSensors();
283 }
Aravind Akella841a5922015-06-29 12:37:48 -0700284 if (mCurrentOperatingMode == DATA_INJECTION) {
285 resetToNormalModeLocked();
286 }
287 mWhiteListedPackage.clear();
Aravind Akella444f2672015-05-07 12:40:52 -0700288 return status_t(NO_ERROR);
Aravind Akella841a5922015-06-29 12:37:48 -0700289 } else if (args.size() == 2 && args[0] == String16("data_injection")) {
290 if (mCurrentOperatingMode == NORMAL) {
291 dev.disableAllSensors();
292 status_t err = dev.setMode(DATA_INJECTION);
293 if (err == NO_ERROR) {
294 mCurrentOperatingMode = DATA_INJECTION;
295 } else {
296 // Re-enable sensors.
297 dev.enableAllSensors();
298 }
299 mWhiteListedPackage.setTo(String8(args[1]));
300 return NO_ERROR;
301 } else if (mCurrentOperatingMode == DATA_INJECTION) {
302 // Already in DATA_INJECTION mode. Treat this as a no_op.
303 return NO_ERROR;
304 } else {
305 // Transition to data injection mode supported only from NORMAL mode.
306 return INVALID_OPERATION;
307 }
Aravind Akellaee155ca2015-06-24 08:31:32 -0700308 } else if (mSensorList.size() == 0) {
309 result.append("No Sensors on the device\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700310 } else {
311 // Default dump the sensor list and debugging information.
312 result.append("Sensor List:\n");
313 for (size_t i=0 ; i<mSensorList.size() ; i++) {
314 const Sensor& s(mSensorList[i]);
315 result.appendFormat(
316 "%-15s| %-10s| version=%d |%-20s| 0x%08x | \"%s\" | type=%d |",
317 s.getName().string(),
318 s.getVendor().string(),
319 s.getVersion(),
320 s.getStringType().string(),
321 s.getHandle(),
322 s.getRequiredPermission().string(),
323 s.getType());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700324
Aravind Akella444f2672015-05-07 12:40:52 -0700325 const int reportingMode = s.getReportingMode();
326 if (reportingMode == AREPORTING_MODE_CONTINUOUS) {
327 result.append(" continuous | ");
328 } else if (reportingMode == AREPORTING_MODE_ON_CHANGE) {
329 result.append(" on-change | ");
330 } else if (reportingMode == AREPORTING_MODE_ONE_SHOT) {
331 result.append(" one-shot | ");
332 } else {
333 result.append(" special-trigger | ");
334 }
335
336 if (s.getMaxDelay() > 0) {
337 result.appendFormat("minRate=%.2fHz | ", 1e6f / s.getMaxDelay());
338 } else {
339 result.appendFormat("maxDelay=%dus |", s.getMaxDelay());
340 }
341
342 if (s.getMinDelay() > 0) {
343 result.appendFormat("maxRate=%.2fHz | ", 1e6f / s.getMinDelay());
344 } else {
345 result.appendFormat("minDelay=%dus |", s.getMinDelay());
346 }
347
348 if (s.getFifoMaxEventCount() > 0) {
349 result.appendFormat("FifoMax=%d events | ",
350 s.getFifoMaxEventCount());
351 } else {
352 result.append("no batching | ");
353 }
354
355 if (s.isWakeUpSensor()) {
356 result.appendFormat("wakeUp | ");
357 } else {
358 result.appendFormat("non-wakeUp | ");
359 }
360
Aravind Akella18d6d512015-06-18 14:18:28 -0700361 int bufIndex = mLastEventSeen.indexOfKey(s.getHandle());
362 if (bufIndex >= 0) {
363 const CircularBuffer* buf = mLastEventSeen.valueAt(bufIndex);
364 if (buf != NULL && s.getRequiredPermission().isEmpty()) {
365 buf->printBuffer(result);
366 } else {
367 result.append("last=<> \n");
368 }
Aravind Akella444f2672015-05-07 12:40:52 -0700369 }
370 result.append("\n");
371 }
372 SensorFusion::getInstance().dump(result);
373 SensorDevice::getInstance().dump(result);
374
375 result.append("Active sensors:\n");
376 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
377 int handle = mActiveSensors.keyAt(i);
378 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
379 getSensorName(handle).string(),
380 handle,
381 mActiveSensors.valueAt(i)->getNumConnections());
Aravind Akella6c2664a2014-08-13 12:24:50 -0700382 }
383
Aravind Akella444f2672015-05-07 12:40:52 -0700384 result.appendFormat("Socket Buffer size = %d events\n",
385 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella18d6d512015-06-18 14:18:28 -0700386 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
387 "not held");
Aravind Akella444f2672015-05-07 12:40:52 -0700388 result.appendFormat("Mode :");
389 switch(mCurrentOperatingMode) {
390 case NORMAL:
391 result.appendFormat(" NORMAL\n");
392 break;
393 case RESTRICTED:
Aravind Akella841a5922015-06-29 12:37:48 -0700394 result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
Aravind Akella444f2672015-05-07 12:40:52 -0700395 break;
396 case DATA_INJECTION:
Aravind Akella841a5922015-06-29 12:37:48 -0700397 result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700398 }
Aravind Akella444f2672015-05-07 12:40:52 -0700399 result.appendFormat("%zd active connections\n", mActiveConnections.size());
Aravind Akella0e025c52014-06-03 19:19:57 -0700400
Aravind Akella444f2672015-05-07 12:40:52 -0700401 for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
402 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
403 if (connection != 0) {
404 result.appendFormat("Connection Number: %zu \n", i);
405 connection->dump(result);
406 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700407 }
Aravind Akella18d6d512015-06-18 14:18:28 -0700408
409 result.appendFormat("Previous Registrations:\n");
410 // Log in the reverse chronological order.
411 int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
412 SENSOR_REGISTRATIONS_BUF_SIZE;
413 const int startIndex = currentIndex;
414 do {
415 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
416 if (SensorRegistrationInfo::isSentinel(reg_info)) {
417 // Ignore sentinel, proceed to next item.
418 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
419 SENSOR_REGISTRATIONS_BUF_SIZE;
420 continue;
421 }
422 if (reg_info.mActivated) {
423 result.appendFormat("%02d:%02d:%02d activated package=%s handle=0x%08x "
424 "samplingRate=%dus maxReportLatency=%dus\n",
425 reg_info.mHour, reg_info.mMin, reg_info.mSec,
426 reg_info.mPackageName.string(), reg_info.mSensorHandle,
427 reg_info.mSamplingRateUs, reg_info.mMaxReportLatencyUs);
428 } else {
429 result.appendFormat("%02d:%02d:%02d de-activated package=%s handle=0x%08x\n",
430 reg_info.mHour, reg_info.mMin, reg_info.mSec,
431 reg_info.mPackageName.string(), reg_info.mSensorHandle);
432 }
433 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
434 SENSOR_REGISTRATIONS_BUF_SIZE;
435 } while(startIndex != currentIndex);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700436 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700437 }
438 write(fd, result.string(), result.size());
439 return NO_ERROR;
440}
441
Aravind Akella9a844cf2014-02-11 18:58:52 -0800442void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700443 sensors_event_t const* buffer, const int count) {
444 for (int i=0 ; i<count ; i++) {
445 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700446 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
447 handle = buffer[i].meta_data.sensor;
448 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700449 if (connection->hasSensor(handle)) {
450 SensorInterface* sensor = mSensorMap.valueFor(handle);
451 // If this buffer has an event from a one_shot sensor and this connection is registered
452 // for this particular one_shot sensor, try cleaning up the connection.
453 if (sensor != NULL &&
454 sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
455 sensor->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800456 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700457 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700458
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700459 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700460 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700461}
462
Mathias Agopianfc328812010-07-14 23:41:37 -0700463bool SensorService::threadLoop()
464{
Steve Blocka5512372011-12-20 16:23:08 +0000465 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700466
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700467 // each virtual sensor could generate an event per "real" event, that's why we need
468 // to size numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT.
469 // in practice, this is too aggressive, but guaranteed to be enough.
470 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
471 const size_t numEventMax = minBufferSize / (1 + mVirtualSensorList.size());
472
Mathias Agopianf001c922010-11-11 17:58:51 -0800473 SensorDevice& device(SensorDevice::getInstance());
474 const size_t vcount = mVirtualSensorList.size();
Mathias Agopianfc328812010-07-14 23:41:37 -0700475
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700476 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700477 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700478 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
479 if (count < 0) {
Steve Blockf5a12302012-01-06 19:20:56 +0000480 ALOGE("sensor poll failed (%s)", strerror(-count));
Mathias Agopianfc328812010-07-14 23:41:37 -0700481 break;
482 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700483
484 // Reset sensors_event_t.flags to zero for all events in the buffer.
485 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700486 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700487 }
Aravind Akellae148bc22014-09-24 22:12:58 -0700488
489 // Make a copy of the connection vector as some connections may be removed during the
490 // course of this loop (especially when one-shot sensor events are present in the
491 // sensor_event buffer). Promote all connections to StrongPointers before the lock is
492 // acquired. If the destructor of the sp gets called when the lock is acquired, it may
493 // result in a deadlock as ~SensorEventConnection() needs to acquire mLock again for
494 // cleanup. So copy all the strongPointers to a vector before the lock is acquired.
495 SortedVector< sp<SensorEventConnection> > activeConnections;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700496 populateActiveConnections(&activeConnections);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800497 Mutex::Autolock _l(mLock);
498 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
499 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
500 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
501 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
502 // releasing the wakelock.
503 bool bufferHasWakeUpEvent = false;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700504 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700505 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800506 bufferHasWakeUpEvent = true;
507 break;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700508 }
509 }
510
Aravind Akella9a844cf2014-02-11 18:58:52 -0800511 if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700512 setWakeLockAcquiredLocked(true);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800513 }
Aravind Akella8493b792014-09-08 15:45:47 -0700514 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800515
Mathias Agopianf001c922010-11-11 17:58:51 -0800516 // handle virtual sensors
517 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700518 sensors_event_t const * const event = mSensorEventBuffer;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800519 const size_t activeVirtualSensorCount = mActiveVirtualSensors.size();
Mathias Agopianf001c922010-11-11 17:58:51 -0800520 if (activeVirtualSensorCount) {
521 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700522 SensorFusion& fusion(SensorFusion::getInstance());
523 if (fusion.isEnabled()) {
524 for (size_t i=0 ; i<size_t(count) ; i++) {
525 fusion.process(event[i]);
526 }
527 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700528 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800529 for (size_t j=0 ; j<activeVirtualSensorCount ; j++) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700530 if (count + k >= minBufferSize) {
531 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700532 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700533 count, k, minBufferSize);
534 break;
535 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800536 sensors_event_t out;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800537 SensorInterface* si = mActiveVirtualSensors.valueAt(j);
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700538 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700539 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800540 k++;
541 }
542 }
543 }
544 if (k) {
545 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700546 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800547 count += k;
548 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700549 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700550 }
551 }
552 }
553
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700554 // handle backward compatibility for RotationVector sensor
555 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
556 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700557 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700558 // All the 4 components of the quaternion should be available
559 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700560 mSensorEventBuffer[i].data[4] = -1;
561 }
562 }
563 }
564
565 // Map flush_complete_events in the buffer to SensorEventConnections which called
566 // flush on the hardware sensor. mapFlushEventsToConnections[i] will be the
567 // SensorEventConnection mapped to the corresponding flush_complete_event in
568 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
569 for (int i = 0; i < count; ++i) {
570 mMapFlushEventsToConnections[i] = NULL;
571 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
572 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
573 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
574 if (rec != NULL) {
575 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
576 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700577 }
578 }
579 }
580
Aravind Akella9a844cf2014-02-11 18:58:52 -0800581 // Send our events to clients. Check the state of wake lock for each client and release the
582 // lock if none of the clients need it.
583 bool needsWakeLock = false;
Aravind Akella8493b792014-09-08 15:45:47 -0700584 size_t numConnections = activeConnections.size();
585 for (size_t i=0 ; i < numConnections; ++i) {
Aravind Akellae148bc22014-09-24 22:12:58 -0700586 if (activeConnections[i] != 0) {
587 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
Aravind Akella8493b792014-09-08 15:45:47 -0700588 mMapFlushEventsToConnections);
Aravind Akellae148bc22014-09-24 22:12:58 -0700589 needsWakeLock |= activeConnections[i]->needsWakeLock();
Aravind Akella8493b792014-09-08 15:45:47 -0700590 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
591 // Early check for one-shot sensors.
Aravind Akellae148bc22014-09-24 22:12:58 -0700592 if (activeConnections[i]->hasOneShotSensors()) {
593 cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
594 count);
Aravind Akella8493b792014-09-08 15:45:47 -0700595 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800596 }
597 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700598
Aravind Akella9a844cf2014-02-11 18:58:52 -0800599 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700600 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800601 }
Aravind Akella8493b792014-09-08 15:45:47 -0700602 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -0700603
Steve Block3c20fbe2012-01-05 23:22:43 +0000604 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -0800605 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -0700606 return false;
607}
608
Aravind Akella56ae4262014-07-10 16:01:10 -0700609sp<Looper> SensorService::getLooper() const {
610 return mLooper;
611}
612
Aravind Akellab4373ac2014-10-29 17:55:20 -0700613void SensorService::resetAllWakeLockRefCounts() {
614 SortedVector< sp<SensorEventConnection> > activeConnections;
615 populateActiveConnections(&activeConnections);
616 {
617 Mutex::Autolock _l(mLock);
618 for (size_t i=0 ; i < activeConnections.size(); ++i) {
619 if (activeConnections[i] != 0) {
620 activeConnections[i]->resetWakeLockRefCount();
621 }
622 }
623 setWakeLockAcquiredLocked(false);
624 }
625}
626
627void SensorService::setWakeLockAcquiredLocked(bool acquire) {
628 if (acquire) {
629 if (!mWakeLockAcquired) {
630 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
631 mWakeLockAcquired = true;
632 }
633 mLooper->wake();
634 } else {
635 if (mWakeLockAcquired) {
636 release_wake_lock(WAKE_LOCK_NAME);
637 mWakeLockAcquired = false;
638 }
639 }
640}
641
Aravind Akellab4373ac2014-10-29 17:55:20 -0700642bool SensorService::isWakeLockAcquired() {
643 Mutex::Autolock _l(mLock);
644 return mWakeLockAcquired;
645}
646
Aravind Akella56ae4262014-07-10 16:01:10 -0700647bool SensorService::SensorEventAckReceiver::threadLoop() {
648 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -0700649 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -0700650 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700651 bool wakeLockAcquired = mService->isWakeLockAcquired();
652 int timeout = -1;
653 if (wakeLockAcquired) timeout = 5000;
654 int ret = looper->pollOnce(timeout);
655 if (ret == ALOOPER_POLL_TIMEOUT) {
656 mService->resetAllWakeLockRefCounts();
657 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700658 } while(!Thread::exitPending());
659 return false;
660}
661
Aravind Akella9a844cf2014-02-11 18:58:52 -0800662void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -0800663 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -0800664 for (size_t i = 0; i < count; i++) {
Aravind Akella444f2672015-05-07 12:40:52 -0700665 if (buffer[i].type != SENSOR_TYPE_META_DATA) {
666 CircularBuffer* &circular_buf = mLastEventSeen.editValueFor(buffer[i].sensor);
667 if (circular_buf == NULL) {
668 circular_buf = new CircularBuffer(buffer[i].type);
Aravind Akella4b847042014-03-03 19:02:46 -0800669 }
Aravind Akella444f2672015-05-07 12:40:52 -0700670 circular_buf->addEvent(buffer[i]);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800671 }
672 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800673}
674
Mathias Agopianf001c922010-11-11 17:58:51 -0800675void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count)
676{
677 struct compar {
678 static int cmp(void const* lhs, void const* rhs) {
679 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
680 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -0700681 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -0800682 }
683 };
684 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
685}
686
Mathias Agopian5d270722010-07-19 15:20:39 -0700687String8 SensorService::getSensorName(int handle) const {
Mathias Agopian010e4222011-06-08 20:06:50 -0700688 size_t count = mUserSensorList.size();
Mathias Agopian5d270722010-07-19 15:20:39 -0700689 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian010e4222011-06-08 20:06:50 -0700690 const Sensor& sensor(mUserSensorList[i]);
Mathias Agopian5d270722010-07-19 15:20:39 -0700691 if (sensor.getHandle() == handle) {
692 return sensor.getName();
693 }
694 }
695 String8 result("unknown");
696 return result;
697}
698
Aravind Akellab4099e72013-10-15 15:43:10 -0700699bool SensorService::isVirtualSensor(int handle) const {
700 SensorInterface* sensor = mSensorMap.valueFor(handle);
701 return sensor->isVirtual();
702}
703
Aravind Akella9a844cf2014-02-11 18:58:52 -0800704bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -0700705 int handle = event.sensor;
706 if (event.type == SENSOR_TYPE_META_DATA) {
707 handle = event.meta_data.sensor;
708 }
709 SensorInterface* sensor = mSensorMap.valueFor(handle);
710 return sensor != NULL && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -0800711}
712
Aravind Akella6c2664a2014-08-13 12:24:50 -0700713SensorService::SensorRecord * SensorService::getSensorRecord(int handle) {
714 return mActiveSensors.valueFor(handle);
715}
716
Svetoslavb412f6e2015-04-29 16:50:41 -0700717Vector<Sensor> SensorService::getSensorList(const String16& opPackageName)
Mathias Agopianfc328812010-07-14 23:41:37 -0700718{
Mathias Agopian33264862012-06-28 19:46:54 -0700719 char value[PROPERTY_VALUE_MAX];
720 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +0000721 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
722 mUserSensorListDebug : mUserSensorList;
723 Vector<Sensor> accessibleSensorList;
724 for (size_t i = 0; i < initialSensorList.size(); i++) {
725 Sensor sensor = initialSensorList[i];
Svetoslavb412f6e2015-04-29 16:50:41 -0700726 if (canAccessSensor(sensor, "getSensorList", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +0000727 accessibleSensorList.add(sensor);
728 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -0700729 ALOGI("Skipped sensor %s because it requires permission %s and app op %d",
Bernhard Rosenkränzer5f619932014-11-17 21:06:20 +0100730 sensor.getName().string(),
Svetoslavb412f6e2015-04-29 16:50:41 -0700731 sensor.getRequiredPermission().string(),
732 sensor.getRequiredAppOp());
Aravind Akella70018042014-04-07 22:52:37 +0000733 }
Mathias Agopian33264862012-06-28 19:46:54 -0700734 }
Aravind Akella70018042014-04-07 22:52:37 +0000735 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -0700736}
737
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700738sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -0700739 int requestedMode, const String16& opPackageName) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700740 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
741 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
742 return NULL;
743 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700744
745 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700746 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
747 // operating in DI mode.
748 if (requestedMode == DATA_INJECTION) {
749 if (mCurrentOperatingMode != DATA_INJECTION) return NULL;
750 if (!isWhiteListedPackage(packageName)) return NULL;
751 }
752
Mathias Agopian5307d172012-09-18 17:02:43 -0700753 uid_t uid = IPCThreadState::self()->getCallingUid();
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700754 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -0700755 requestedMode == DATA_INJECTION, opPackageName));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700756 if (requestedMode == DATA_INJECTION) {
757 if (mActiveConnections.indexOf(result) < 0) {
758 mActiveConnections.add(result);
759 }
760 // Add the associated file descriptor to the Looper for polling whenever there is data to
761 // be injected.
762 result->updateLooperRegistration(mLooper);
763 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700764 return result;
765}
766
Aravind Akella841a5922015-06-29 12:37:48 -0700767int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700768 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700769 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700770}
771
772status_t SensorService::resetToNormalMode() {
773 Mutex::Autolock _l(mLock);
774 return resetToNormalModeLocked();
775}
776
777status_t SensorService::resetToNormalModeLocked() {
778 SensorDevice& dev(SensorDevice::getInstance());
779 dev.enableAllSensors();
780 status_t err = dev.setMode(NORMAL);
781 mCurrentOperatingMode = NORMAL;
782 return err;
783}
784
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800785void SensorService::cleanupConnection(SensorEventConnection* c)
Mathias Agopianfc328812010-07-14 23:41:37 -0700786{
787 Mutex::Autolock _l(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800788 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700789 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -0700790 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700791 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800792 int handle = mActiveSensors.keyAt(i);
793 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -0700794 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800795 SensorInterface* sensor = mSensorMap.valueFor( handle );
Steve Blockf5a12302012-01-06 19:20:56 +0000796 ALOGE_IF(!sensor, "mSensorMap[handle=0x%08x] is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800797 if (sensor) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800798 sensor->activate(c, false);
Mathias Agopianf001c922010-11-11 17:58:51 -0800799 }
Aravind Akella8a969552014-09-28 17:52:41 -0700800 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800801 }
802 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -0700803 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +0000804 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -0700805 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700806 c, i, handle);
807
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800808 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +0000809 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700810 mActiveSensors.removeItemsAt(i, 1);
Mathias Agopianf001c922010-11-11 17:58:51 -0800811 mActiveVirtualSensors.removeItem(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700812 delete rec;
813 size--;
814 } else {
815 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -0700816 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700817 }
Aravind Akella8a969552014-09-28 17:52:41 -0700818 c->updateLooperRegistration(mLooper);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700819 mActiveConnections.remove(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -0700820 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -0800821 if (c->needsWakeLock()) {
822 checkWakeLockStateLocked();
823 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700824}
825
Aravind Akella70018042014-04-07 22:52:37 +0000826Sensor SensorService::getSensorFromHandle(int handle) const {
827 return mSensorMap.valueFor(handle)->getSensor();
828}
829
Mathias Agopianfc328812010-07-14 23:41:37 -0700830status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -0700831 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
832 const String16& opPackageName)
Mathias Agopianfc328812010-07-14 23:41:37 -0700833{
Mathias Agopian50df2952010-07-19 19:09:10 -0700834 if (mInitCheck != NO_ERROR)
835 return mInitCheck;
836
Mathias Agopianf001c922010-11-11 17:58:51 -0800837 SensorInterface* sensor = mSensorMap.valueFor(handle);
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700838 if (sensor == NULL) {
839 return BAD_VALUE;
840 }
Aravind Akella70018042014-04-07 22:52:37 +0000841
Svetoslavb412f6e2015-04-29 16:50:41 -0700842 if (!canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +0000843 return BAD_VALUE;
844 }
845
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700846 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700847 if ((mCurrentOperatingMode == RESTRICTED || mCurrentOperatingMode == DATA_INJECTION)
848 && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -0800849 return INVALID_OPERATION;
850 }
851
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700852 SensorRecord* rec = mActiveSensors.valueFor(handle);
853 if (rec == 0) {
854 rec = new SensorRecord(connection);
855 mActiveSensors.add(handle, rec);
856 if (sensor->isVirtual()) {
857 mActiveVirtualSensors.add(handle, sensor);
858 }
859 } else {
860 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800861 // this sensor is already activated, but we are adding a connection that uses it.
862 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700863 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -0700864 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800865 // NOTE: The wake_up flag of this event may get set to
866 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Aravind Akella444f2672015-05-07 12:40:52 -0700867 CircularBuffer *circular_buf = mLastEventSeen.valueFor(handle);
868 if (circular_buf) {
869 sensors_event_t event;
870 memset(&event, 0, sizeof(event));
871 // It is unlikely that this buffer is empty as the sensor is already active.
872 // One possible corner case may be two applications activating an on-change
873 // sensor at the same time.
874 if(circular_buf->populateLastEvent(&event)) {
875 event.sensor = handle;
876 if (event.version == sizeof(sensors_event_t)) {
877 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
878 setWakeLockAcquiredLocked(true);
879 }
880 connection->sendEvents(&event, 1, NULL);
881 if (!connection->needsWakeLock() && mWakeLockAcquired) {
882 checkWakeLockStateLocked();
883 }
884 }
Aravind Akella9a844cf2014-02-11 18:58:52 -0800885 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700886 }
887 }
888 }
889 }
890
891 if (connection->addSensor(handle)) {
892 BatteryService::enableSensor(connection->getUid(), handle);
893 // the sensor was added (which means it wasn't already there)
894 // so, see if this connection becomes active
895 if (mActiveConnections.indexOf(connection) < 0) {
896 mActiveConnections.add(connection);
897 }
898 } else {
899 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
900 handle, connection.get());
901 }
902
Aravind Akella724d91d2013-06-27 12:04:23 -0700903 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
904 if (samplingPeriodNs < minDelayNs) {
905 samplingPeriodNs = minDelayNs;
906 }
907
Aravind Akella6c2664a2014-08-13 12:24:50 -0700908 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
909 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -0700910 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
911
Aravind Akella4949c502015-02-11 15:54:35 -0800912 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -0700913 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -0700914
Peng Xu20483c42015-10-26 15:14:43 -0700915 // Call flush() before calling activate() on the sensor. Wait for a first
916 // flush complete event before sending events on this connection. Ignore
917 // one-shot sensors which don't support flush(). Ignore on-change sensors
918 // to maintain the on-change logic (any on-change events except the initial
919 // one should be trigger by a change in value). Also if this sensor isn't
920 // already active, don't call flush().
921 if (err == NO_ERROR &&
922 sensor->getSensor().getReportingMode() != AREPORTING_MODE_ONE_SHOT &&
923 sensor->getSensor().getReportingMode() != AREPORTING_MODE_ON_CHANGE &&
Aravind Akella5466c3d2014-08-22 16:11:10 -0700924 rec->getNumConnections() > 1) {
925 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700926 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -0700927 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -0700928 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700929 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -0700930 } else {
931 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700932 }
933 }
Aravind Akella724d91d2013-06-27 12:04:23 -0700934
935 if (err == NO_ERROR) {
936 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
937 err = sensor->activate(connection.get(), true);
938 }
939
Aravind Akella8a969552014-09-28 17:52:41 -0700940 if (err == NO_ERROR) {
941 connection->updateLooperRegistration(mLooper);
Aravind Akella18d6d512015-06-18 14:18:28 -0700942 SensorRegistrationInfo &reg_info =
943 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex);
944 reg_info.mSensorHandle = handle;
945 reg_info.mSamplingRateUs = samplingPeriodNs/1000;
946 reg_info.mMaxReportLatencyUs = maxBatchReportLatencyNs/1000;
947 reg_info.mActivated = true;
948 reg_info.mPackageName = connection->getPackageName();
949 time_t rawtime = time(NULL);
950 struct tm * timeinfo = localtime(&rawtime);
951 reg_info.mHour = timeinfo->tm_hour;
952 reg_info.mMin = timeinfo->tm_min;
953 reg_info.mSec = timeinfo->tm_sec;
954 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -0700955 }
956
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700957 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -0700958 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700959 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700960 }
961 return err;
962}
963
964status_t SensorService::disable(const sp<SensorEventConnection>& connection,
965 int handle)
966{
Mathias Agopian50df2952010-07-19 19:09:10 -0700967 if (mInitCheck != NO_ERROR)
968 return mInitCheck;
969
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700970 Mutex::Autolock _l(mLock);
971 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700972 if (err == NO_ERROR) {
973 SensorInterface* sensor = mSensorMap.valueFor(handle);
974 err = sensor ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -0700975
976 }
977 if (err == NO_ERROR) {
978 SensorRegistrationInfo &reg_info =
979 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex);
980 reg_info.mActivated = false;
981 reg_info.mPackageName= connection->getPackageName();
982 reg_info.mSensorHandle = handle;
983 time_t rawtime = time(NULL);
984 struct tm * timeinfo = localtime(&rawtime);
985 reg_info.mHour = timeinfo->tm_hour;
986 reg_info.mMin = timeinfo->tm_min;
987 reg_info.mSec = timeinfo->tm_sec;
988 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700989 }
990 return err;
991}
992
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700993status_t SensorService::cleanupWithoutDisable(
994 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700995 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700996 return cleanupWithoutDisableLocked(connection, handle);
997}
998
999status_t SensorService::cleanupWithoutDisableLocked(
1000 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001001 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001002 if (rec) {
1003 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001004 if (connection->removeSensor(handle)) {
1005 BatteryService::disableSensor(connection->getUid(), handle);
1006 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001007 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07001008 connection->updateLooperRegistration(mLooper);
Mathias Agopianfc328812010-07-14 23:41:37 -07001009 mActiveConnections.remove(connection);
1010 }
1011 // see if this sensor becomes inactive
1012 if (rec->removeConnection(connection)) {
1013 mActiveSensors.removeItem(handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001014 mActiveVirtualSensors.removeItem(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001015 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07001016 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001017 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001018 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001019 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07001020}
1021
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001022status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -07001023 int handle, nsecs_t ns, const String16& opPackageName)
Mathias Agopianfc328812010-07-14 23:41:37 -07001024{
Mathias Agopian50df2952010-07-19 19:09:10 -07001025 if (mInitCheck != NO_ERROR)
1026 return mInitCheck;
1027
Mathias Agopianae09d652011-11-01 17:37:49 -07001028 SensorInterface* sensor = mSensorMap.valueFor(handle);
1029 if (!sensor)
1030 return BAD_VALUE;
1031
Svetoslavb412f6e2015-04-29 16:50:41 -07001032 if (!canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001033 return BAD_VALUE;
1034 }
1035
Mathias Agopian1cd70002010-07-21 15:59:50 -07001036 if (ns < 0)
1037 return BAD_VALUE;
1038
Mathias Agopian62569ec2011-11-07 21:21:47 -08001039 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1040 if (ns < minDelayNs) {
1041 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07001042 }
1043
Mathias Agopianf001c922010-11-11 17:58:51 -08001044 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07001045}
1046
Svetoslavb412f6e2015-04-29 16:50:41 -07001047status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1048 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00001049 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001050 SensorDevice& dev(SensorDevice::getInstance());
1051 const int halVersion = dev.getHalDeviceVersion();
1052 status_t err(NO_ERROR);
1053 Mutex::Autolock _l(mLock);
1054 // Loop through all sensors for this connection and call flush on each of them.
1055 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
1056 const int handle = connection->mSensorInfo.keyAt(i);
1057 SensorInterface* sensor = mSensorMap.valueFor(handle);
1058 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1059 ALOGE("flush called on a one-shot sensor");
1060 err = INVALID_OPERATION;
1061 continue;
1062 }
Aravind Akella8493b792014-09-08 15:45:47 -07001063 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001064 // For older devices just increment pending flush count which will send a trivial
1065 // flush complete event.
Aravind Akella8a969552014-09-28 17:52:41 -07001066 connection->incrementPendingFlushCount(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001067 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001068 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1069 err = INVALID_OPERATION;
1070 continue;
1071 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001072 status_t err_flush = sensor->flush(connection.get(), handle);
1073 if (err_flush == NO_ERROR) {
1074 SensorRecord* rec = mActiveSensors.valueFor(handle);
1075 if (rec != NULL) rec->addPendingFlushConnection(connection);
1076 }
1077 err = (err_flush != NO_ERROR) ? err_flush : err;
1078 }
Aravind Akella70018042014-04-07 22:52:37 +00001079 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001080 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001081}
Aravind Akella70018042014-04-07 22:52:37 +00001082
Svetoslavb412f6e2015-04-29 16:50:41 -07001083bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1084 const String16& opPackageName) {
1085 const String8& requiredPermission = sensor.getRequiredPermission();
Aravind Akella70018042014-04-07 22:52:37 +00001086
Svetoslavb412f6e2015-04-29 16:50:41 -07001087 if (requiredPermission.length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00001088 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07001089 }
1090
1091 bool hasPermission = false;
1092
1093 // Runtime permissions can't use the cache as they may change.
1094 if (sensor.isRequiredPermissionRuntime()) {
1095 hasPermission = checkPermission(String16(requiredPermission),
1096 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Aravind Akella70018042014-04-07 22:52:37 +00001097 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001098 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1099 }
1100
1101 if (!hasPermission) {
1102 ALOGE("%s a sensor (%s) without holding its required permission: %s",
1103 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
Aravind Akella70018042014-04-07 22:52:37 +00001104 return false;
1105 }
Svetoslavb412f6e2015-04-29 16:50:41 -07001106
1107 const int32_t opCode = sensor.getRequiredAppOp();
1108 if (opCode >= 0) {
1109 AppOpsManager appOps;
1110 if (appOps.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName)
1111 != AppOpsManager::MODE_ALLOWED) {
1112 ALOGE("%s a sensor (%s) without enabled required app op: %D",
1113 operation, sensor.getName().string(), opCode);
1114 return false;
1115 }
1116 }
1117
1118 return true;
Aravind Akella70018042014-04-07 22:52:37 +00001119}
1120
Aravind Akella9a844cf2014-02-11 18:58:52 -08001121void SensorService::checkWakeLockState() {
1122 Mutex::Autolock _l(mLock);
1123 checkWakeLockStateLocked();
1124}
1125
1126void SensorService::checkWakeLockStateLocked() {
1127 if (!mWakeLockAcquired) {
1128 return;
1129 }
1130 bool releaseLock = true;
1131 for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
1132 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1133 if (connection != 0) {
1134 if (connection->needsWakeLock()) {
1135 releaseLock = false;
1136 break;
1137 }
1138 }
1139 }
1140 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001141 setWakeLockAcquiredLocked(false);
1142 }
1143}
1144
1145void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1146 Mutex::Autolock _l(mLock);
1147 connection->writeToSocketFromCache();
1148 if (connection->needsWakeLock()) {
1149 setWakeLockAcquiredLocked(true);
1150 }
1151}
1152
1153void SensorService::populateActiveConnections(
1154 SortedVector< sp<SensorEventConnection> >* activeConnections) {
1155 Mutex::Autolock _l(mLock);
1156 for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
1157 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1158 if (connection != 0) {
1159 activeConnections->add(connection);
1160 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001161 }
1162}
Aravind Akella6c2664a2014-08-13 12:24:50 -07001163
Aravind Akella4949c502015-02-11 15:54:35 -08001164bool SensorService::isWhiteListedPackage(const String8& packageName) {
Aravind Akella841a5922015-06-29 12:37:48 -07001165 return (packageName.contains(mWhiteListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08001166}
1167
Aravind Akella444f2672015-05-07 12:40:52 -07001168int SensorService::getNumEventsForSensorType(int sensor_event_type) {
1169 switch (sensor_event_type) {
1170 case SENSOR_TYPE_ROTATION_VECTOR:
1171 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
1172 return 5;
1173
1174 case SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED:
1175 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
1176 return 6;
1177
1178 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
1179 return 4;
1180
1181 case SENSOR_TYPE_SIGNIFICANT_MOTION:
1182 case SENSOR_TYPE_STEP_DETECTOR:
1183 case SENSOR_TYPE_STEP_COUNTER:
1184 return 1;
1185
1186 default:
1187 return 3;
1188 }
1189}
1190
Mathias Agopianfc328812010-07-14 23:41:37 -07001191// ---------------------------------------------------------------------------
Mathias Agopianfc328812010-07-14 23:41:37 -07001192SensorService::SensorRecord::SensorRecord(
1193 const sp<SensorEventConnection>& connection)
1194{
1195 mConnections.add(connection);
1196}
1197
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001198bool SensorService::SensorRecord::addConnection(
Mathias Agopianfc328812010-07-14 23:41:37 -07001199 const sp<SensorEventConnection>& connection)
1200{
1201 if (mConnections.indexOf(connection) < 0) {
1202 mConnections.add(connection);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001203 return true;
Mathias Agopianfc328812010-07-14 23:41:37 -07001204 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001205 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -07001206}
1207
1208bool SensorService::SensorRecord::removeConnection(
1209 const wp<SensorEventConnection>& connection)
1210{
1211 ssize_t index = mConnections.indexOf(connection);
1212 if (index >= 0) {
1213 mConnections.removeItemsAt(index, 1);
1214 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001215 // Remove this connections from the queue of flush() calls made on this sensor.
1216 for (Vector< wp<SensorEventConnection> >::iterator it =
1217 mPendingFlushConnections.begin(); it != mPendingFlushConnections.end();) {
Aravind Akella8a969552014-09-28 17:52:41 -07001218
Aravind Akella6c2664a2014-08-13 12:24:50 -07001219 if (it->unsafe_get() == connection.unsafe_get()) {
1220 it = mPendingFlushConnections.erase(it);
1221 } else {
1222 ++it;
1223 }
1224 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001225 return mConnections.size() ? false : true;
1226}
1227
Aravind Akella6c2664a2014-08-13 12:24:50 -07001228void SensorService::SensorRecord::addPendingFlushConnection(
1229 const sp<SensorEventConnection>& connection) {
1230 mPendingFlushConnections.add(connection);
1231}
1232
1233void SensorService::SensorRecord::removeFirstPendingFlushConnection() {
1234 if (mPendingFlushConnections.size() > 0) {
1235 mPendingFlushConnections.removeAt(0);
1236 }
1237}
1238
1239SensorService::SensorEventConnection *
1240SensorService::SensorRecord::getFirstPendingFlushConnection() {
1241 if (mPendingFlushConnections.size() > 0) {
1242 return mPendingFlushConnections[0].unsafe_get();
1243 }
1244 return NULL;
1245}
1246
Aravind Akella4949c502015-02-11 15:54:35 -08001247void SensorService::SensorRecord::clearAllPendingFlushConnections() {
1248 mPendingFlushConnections.clear();
1249}
1250
Aravind Akella18d6d512015-06-18 14:18:28 -07001251
1252// ---------------------------------------------------------------------------
1253SensorService::TrimmedSensorEvent::TrimmedSensorEvent(int sensorType) {
1254 mTimestamp = -1;
1255 const int numData = SensorService::getNumEventsForSensorType(sensorType);
1256 if (sensorType == SENSOR_TYPE_STEP_COUNTER) {
1257 mStepCounter = 0;
1258 } else {
1259 mData = new float[numData];
1260 for (int i = 0; i < numData; ++i) {
1261 mData[i] = -1.0;
1262 }
1263 }
1264 mHour = mMin = mSec = INT32_MIN;
1265}
1266
1267bool SensorService::TrimmedSensorEvent::isSentinel(const TrimmedSensorEvent& event) {
1268 return (event.mHour == INT32_MIN && event.mMin == INT32_MIN && event.mSec == INT32_MIN);
1269}
Aravind Akella444f2672015-05-07 12:40:52 -07001270// --------------------------------------------------------------------------
1271SensorService::CircularBuffer::CircularBuffer(int sensor_event_type) {
1272 mNextInd = 0;
Aravind Akella18d6d512015-06-18 14:18:28 -07001273 mBufSize = CIRCULAR_BUF_SIZE;
1274 if (sensor_event_type == SENSOR_TYPE_STEP_COUNTER ||
1275 sensor_event_type == SENSOR_TYPE_SIGNIFICANT_MOTION ||
1276 sensor_event_type == SENSOR_TYPE_ACCELEROMETER) {
1277 mBufSize = CIRCULAR_BUF_SIZE * 5;
1278 }
1279 mTrimmedSensorEventArr = new TrimmedSensorEvent *[mBufSize];
Aravind Akella444f2672015-05-07 12:40:52 -07001280 mSensorType = sensor_event_type;
Aravind Akella18d6d512015-06-18 14:18:28 -07001281 for (int i = 0; i < mBufSize; ++i) {
1282 mTrimmedSensorEventArr[i] = new TrimmedSensorEvent(mSensorType);
Aravind Akella444f2672015-05-07 12:40:52 -07001283 }
1284}
1285
1286void SensorService::CircularBuffer::addEvent(const sensors_event_t& sensor_event) {
1287 TrimmedSensorEvent *curr_event = mTrimmedSensorEventArr[mNextInd];
1288 curr_event->mTimestamp = sensor_event.timestamp;
1289 if (mSensorType == SENSOR_TYPE_STEP_COUNTER) {
1290 curr_event->mStepCounter = sensor_event.u64.step_counter;
1291 } else {
1292 memcpy(curr_event->mData, sensor_event.data,
1293 sizeof(float) * SensorService::getNumEventsForSensorType(mSensorType));
1294 }
1295 time_t rawtime = time(NULL);
1296 struct tm * timeinfo = localtime(&rawtime);
1297 curr_event->mHour = timeinfo->tm_hour;
1298 curr_event->mMin = timeinfo->tm_min;
1299 curr_event->mSec = timeinfo->tm_sec;
Aravind Akella18d6d512015-06-18 14:18:28 -07001300 mNextInd = (mNextInd + 1) % mBufSize;
Aravind Akella444f2672015-05-07 12:40:52 -07001301}
1302
1303void SensorService::CircularBuffer::printBuffer(String8& result) const {
1304 const int numData = SensorService::getNumEventsForSensorType(mSensorType);
1305 int i = mNextInd, eventNum = 1;
Aravind Akella18d6d512015-06-18 14:18:28 -07001306 result.appendFormat("last %d events = < ", mBufSize);
Aravind Akella444f2672015-05-07 12:40:52 -07001307 do {
Aravind Akella18d6d512015-06-18 14:18:28 -07001308 if (TrimmedSensorEvent::isSentinel(*mTrimmedSensorEventArr[i])) {
Aravind Akella444f2672015-05-07 12:40:52 -07001309 // Sentinel, ignore.
Aravind Akella18d6d512015-06-18 14:18:28 -07001310 i = (i + 1) % mBufSize;
Aravind Akella444f2672015-05-07 12:40:52 -07001311 continue;
1312 }
1313 result.appendFormat("%d) ", eventNum++);
1314 if (mSensorType == SENSOR_TYPE_STEP_COUNTER) {
1315 result.appendFormat("%llu,", mTrimmedSensorEventArr[i]->mStepCounter);
1316 } else {
1317 for (int j = 0; j < numData; ++j) {
1318 result.appendFormat("%5.1f,", mTrimmedSensorEventArr[i]->mData[j]);
1319 }
1320 }
1321 result.appendFormat("%lld %02d:%02d:%02d ", mTrimmedSensorEventArr[i]->mTimestamp,
1322 mTrimmedSensorEventArr[i]->mHour, mTrimmedSensorEventArr[i]->mMin,
1323 mTrimmedSensorEventArr[i]->mSec);
Aravind Akella18d6d512015-06-18 14:18:28 -07001324 i = (i + 1) % mBufSize;
Aravind Akella444f2672015-05-07 12:40:52 -07001325 } while (i != mNextInd);
1326 result.appendFormat(">\n");
1327}
1328
1329bool SensorService::CircularBuffer::populateLastEvent(sensors_event_t *event) {
Aravind Akella18d6d512015-06-18 14:18:28 -07001330 int lastEventInd = (mNextInd - 1 + mBufSize) % mBufSize;
Aravind Akella444f2672015-05-07 12:40:52 -07001331 // Check if the buffer is empty.
Aravind Akella18d6d512015-06-18 14:18:28 -07001332 if (TrimmedSensorEvent::isSentinel(*mTrimmedSensorEventArr[lastEventInd])) {
Aravind Akella444f2672015-05-07 12:40:52 -07001333 return false;
1334 }
1335 event->version = sizeof(sensors_event_t);
1336 event->type = mSensorType;
1337 event->timestamp = mTrimmedSensorEventArr[lastEventInd]->mTimestamp;
1338 if (mSensorType == SENSOR_TYPE_STEP_COUNTER) {
1339 event->u64.step_counter = mTrimmedSensorEventArr[lastEventInd]->mStepCounter;
1340 } else {
1341 memcpy(event->data, mTrimmedSensorEventArr[lastEventInd]->mData,
1342 sizeof(float) * SensorService::getNumEventsForSensorType(mSensorType));
1343 }
1344 return true;
1345}
1346
1347SensorService::CircularBuffer::~CircularBuffer() {
Aravind Akella18d6d512015-06-18 14:18:28 -07001348 for (int i = 0; i < mBufSize; ++i) {
Aravind Akella444f2672015-05-07 12:40:52 -07001349 delete mTrimmedSensorEventArr[i];
1350 }
1351 delete [] mTrimmedSensorEventArr;
1352}
1353
Mathias Agopianfc328812010-07-14 23:41:37 -07001354// ---------------------------------------------------------------------------
1355
1356SensorService::SensorEventConnection::SensorEventConnection(
Svetoslavb412f6e2015-04-29 16:50:41 -07001357 const sp<SensorService>& service, uid_t uid, String8 packageName, bool isDataInjectionMode,
1358 const String16& opPackageName)
Aravind Akella8a969552014-09-28 17:52:41 -07001359 : mService(service), mUid(uid), mWakeLockRefCount(0), mHasLooperCallbacks(false),
Svetoslavb412f6e2015-04-29 16:50:41 -07001360 mDead(false), mDataInjectionMode(isDataInjectionMode), mEventCache(NULL),
1361 mCacheSize(0), mMaxCacheSize(0), mPackageName(packageName), mOpPackageName(opPackageName) {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001362 mChannel = new BitTube(mService->mSocketBufferSize);
Aravind Akella56ae4262014-07-10 16:01:10 -07001363#if DEBUG_CONNECTIONS
1364 mEventsReceived = mEventsSentFromCache = mEventsSent = 0;
Aravind Akellae74baf62014-08-21 12:28:35 -07001365 mTotalAcksNeeded = mTotalAcksReceived = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -07001366#endif
Mathias Agopianfc328812010-07-14 23:41:37 -07001367}
1368
Aravind Akella56ae4262014-07-10 16:01:10 -07001369SensorService::SensorEventConnection::~SensorEventConnection() {
Steve Blocka5512372011-12-20 16:23:08 +00001370 ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this);
Aravind Akellae148bc22014-09-24 22:12:58 -07001371 mService->cleanupConnection(this);
Aravind Akella56ae4262014-07-10 16:01:10 -07001372 if (mEventCache != NULL) {
1373 delete mEventCache;
1374 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001375}
1376
Aravind Akella56ae4262014-07-10 16:01:10 -07001377void SensorService::SensorEventConnection::onFirstRef() {
1378 LooperCallback::onFirstRef();
Mathias Agopianfc328812010-07-14 23:41:37 -07001379}
1380
Aravind Akella9a844cf2014-02-11 18:58:52 -08001381bool SensorService::SensorEventConnection::needsWakeLock() {
1382 Mutex::Autolock _l(mConnectionLock);
Aravind Akella8a969552014-09-28 17:52:41 -07001383 return !mDead && mWakeLockRefCount > 0;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001384}
1385
Aravind Akellab4373ac2014-10-29 17:55:20 -07001386void SensorService::SensorEventConnection::resetWakeLockRefCount() {
1387 Mutex::Autolock _l(mConnectionLock);
1388 mWakeLockRefCount = 0;
1389}
1390
Aravind Akella4c8b9512013-09-05 17:03:38 -07001391void SensorService::SensorEventConnection::dump(String8& result) {
1392 Mutex::Autolock _l(mConnectionLock);
Aravind Akella8ef3c892015-07-10 11:24:28 -07001393 result.appendFormat("\tOperating Mode: %s\n",mDataInjectionMode ? "DATA_INJECTION" : "NORMAL");
Aravind Akella18d6d512015-06-18 14:18:28 -07001394 result.appendFormat("\t %s | WakeLockRefCount %d | uid %d | cache size %d | "
1395 "max cache size %d\n", mPackageName.string(), mWakeLockRefCount, mUid, mCacheSize,
1396 mMaxCacheSize);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001397 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1398 const FlushInfo& flushInfo = mSensorInfo.valueAt(i);
Aravind Akella0ec20662014-09-14 17:29:48 -07001399 result.appendFormat("\t %s 0x%08x | status: %s | pending flush events %d \n",
Aravind Akella4c8b9512013-09-05 17:03:38 -07001400 mService->getSensorName(mSensorInfo.keyAt(i)).string(),
Aravind Akella6c2664a2014-08-13 12:24:50 -07001401 mSensorInfo.keyAt(i),
Aravind Akella4c8b9512013-09-05 17:03:38 -07001402 flushInfo.mFirstFlushPending ? "First flush pending" :
1403 "active",
Aravind Akella0ec20662014-09-14 17:29:48 -07001404 flushInfo.mPendingFlushEventsToSend);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001405 }
Aravind Akella0ec20662014-09-14 17:29:48 -07001406#if DEBUG_CONNECTIONS
1407 result.appendFormat("\t events recvd: %d | sent %d | cache %d | dropped %d |"
1408 " total_acks_needed %d | total_acks_recvd %d\n",
1409 mEventsReceived,
1410 mEventsSent,
1411 mEventsSentFromCache,
1412 mEventsReceived - (mEventsSentFromCache + mEventsSent + mCacheSize),
1413 mTotalAcksNeeded,
1414 mTotalAcksReceived);
1415#endif
Aravind Akella4c8b9512013-09-05 17:03:38 -07001416}
1417
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001418bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001419 Mutex::Autolock _l(mConnectionLock);
Svetoslavb412f6e2015-04-29 16:50:41 -07001420 if (!canAccessSensor(mService->getSensorFromHandle(handle),
1421 "Tried adding", mOpPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001422 return false;
1423 }
Aravind Akella4c8b9512013-09-05 17:03:38 -07001424 if (mSensorInfo.indexOfKey(handle) < 0) {
1425 mSensorInfo.add(handle, FlushInfo());
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001426 return true;
Mathias Agopianfc328812010-07-14 23:41:37 -07001427 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001428 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -07001429}
1430
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001431bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001432 Mutex::Autolock _l(mConnectionLock);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001433 if (mSensorInfo.removeItem(handle) >= 0) {
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001434 return true;
1435 }
1436 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -07001437}
1438
1439bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001440 Mutex::Autolock _l(mConnectionLock);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001441 return mSensorInfo.indexOfKey(handle) >= 0;
Mathias Agopianfc328812010-07-14 23:41:37 -07001442}
1443
1444bool SensorService::SensorEventConnection::hasAnySensor() const {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001445 Mutex::Autolock _l(mConnectionLock);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001446 return mSensorInfo.size() ? true : false;
1447}
1448
Aravind Akella8493b792014-09-08 15:45:47 -07001449bool SensorService::SensorEventConnection::hasOneShotSensors() const {
1450 Mutex::Autolock _l(mConnectionLock);
1451 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1452 const int handle = mSensorInfo.keyAt(i);
1453 if (mService->getSensorFromHandle(handle).getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1454 return true;
1455 }
1456 }
1457 return false;
1458}
1459
Aravind Akella4949c502015-02-11 15:54:35 -08001460String8 SensorService::SensorEventConnection::getPackageName() const {
1461 return mPackageName;
1462}
1463
Aravind Akella4c8b9512013-09-05 17:03:38 -07001464void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle,
1465 bool value) {
1466 Mutex::Autolock _l(mConnectionLock);
1467 ssize_t index = mSensorInfo.indexOfKey(handle);
1468 if (index >= 0) {
1469 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
1470 flushInfo.mFirstFlushPending = value;
1471 }
1472}
1473
Aravind Akella8a969552014-09-28 17:52:41 -07001474void SensorService::SensorEventConnection::updateLooperRegistration(const sp<Looper>& looper) {
1475 Mutex::Autolock _l(mConnectionLock);
1476 updateLooperRegistrationLocked(looper);
1477}
1478
1479void SensorService::SensorEventConnection::updateLooperRegistrationLocked(
1480 const sp<Looper>& looper) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001481 bool isConnectionActive = (mSensorInfo.size() > 0 && !mDataInjectionMode) ||
1482 mDataInjectionMode;
Aravind Akella8a969552014-09-28 17:52:41 -07001483 // If all sensors are unregistered OR Looper has encountered an error, we
1484 // can remove the Fd from the Looper if it has been previously added.
1485 if (!isConnectionActive || mDead) {
1486 if (mHasLooperCallbacks) {
1487 ALOGD_IF(DEBUG_CONNECTIONS, "%p removeFd fd=%d", this, mChannel->getSendFd());
1488 looper->removeFd(mChannel->getSendFd());
1489 mHasLooperCallbacks = false;
1490 }
1491 return;
1492 }
1493
1494 int looper_flags = 0;
1495 if (mCacheSize > 0) looper_flags |= ALOOPER_EVENT_OUTPUT;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001496 if (mDataInjectionMode) looper_flags |= ALOOPER_EVENT_INPUT;
Aravind Akella8a969552014-09-28 17:52:41 -07001497 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1498 const int handle = mSensorInfo.keyAt(i);
1499 if (mService->getSensorFromHandle(handle).isWakeUpSensor()) {
1500 looper_flags |= ALOOPER_EVENT_INPUT;
1501 break;
1502 }
1503 }
1504 // If flags is still set to zero, we don't need to add this fd to the Looper, if
1505 // the fd has already been added, remove it. This is likely to happen when ALL the
1506 // events stored in the cache have been sent to the corresponding app.
1507 if (looper_flags == 0) {
1508 if (mHasLooperCallbacks) {
1509 ALOGD_IF(DEBUG_CONNECTIONS, "removeFd fd=%d", mChannel->getSendFd());
1510 looper->removeFd(mChannel->getSendFd());
1511 mHasLooperCallbacks = false;
1512 }
1513 return;
1514 }
1515 // Add the file descriptor to the Looper for receiving acknowledegments if the app has
1516 // registered for wake-up sensors OR for sending events in the cache.
1517 int ret = looper->addFd(mChannel->getSendFd(), 0, looper_flags, this, NULL);
1518 if (ret == 1) {
1519 ALOGD_IF(DEBUG_CONNECTIONS, "%p addFd fd=%d", this, mChannel->getSendFd());
1520 mHasLooperCallbacks = true;
1521 } else {
1522 ALOGE("Looper::addFd failed ret=%d fd=%d", ret, mChannel->getSendFd());
1523 }
1524}
1525
1526void SensorService::SensorEventConnection::incrementPendingFlushCount(int32_t handle) {
1527 Mutex::Autolock _l(mConnectionLock);
1528 ssize_t index = mSensorInfo.indexOfKey(handle);
1529 if (index >= 0) {
1530 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
1531 flushInfo.mPendingFlushEventsToSend++;
1532 }
1533}
1534
Mathias Agopianfc328812010-07-14 23:41:37 -07001535status_t SensorService::SensorEventConnection::sendEvents(
Aravind Akella0ec20662014-09-14 17:29:48 -07001536 sensors_event_t const* buffer, size_t numEvents,
Aravind Akella8493b792014-09-08 15:45:47 -07001537 sensors_event_t* scratch,
1538 SensorEventConnection const * const * mapFlushEventsToConnections) {
Mathias Agopiancf510012010-07-22 16:18:10 -07001539 // filter out events not for this connection
Svetoslavb412f6e2015-04-29 16:50:41 -07001540 int count = 0;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001541 Mutex::Autolock _l(mConnectionLock);
Mathias Agopian3560fb22010-07-22 21:24:39 -07001542 if (scratch) {
1543 size_t i=0;
1544 while (i<numEvents) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001545 int32_t sensor_handle = buffer[i].sensor;
Aravind Akella724d91d2013-06-27 12:04:23 -07001546 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
1547 ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ",
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001548 buffer[i].meta_data.sensor);
Aravind Akella8a969552014-09-28 17:52:41 -07001549 // Setting sensor_handle to the correct sensor to ensure the sensor events per
1550 // connection are filtered correctly. buffer[i].sensor is zero for meta_data
1551 // events.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001552 sensor_handle = buffer[i].meta_data.sensor;
Aravind Akella724d91d2013-06-27 12:04:23 -07001553 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001554 ssize_t index = mSensorInfo.indexOfKey(sensor_handle);
Aravind Akella56ae4262014-07-10 16:01:10 -07001555 // Check if this connection has registered for this sensor. If not continue to the
1556 // next sensor_event.
1557 if (index < 0) {
1558 ++i;
1559 continue;
Aravind Akella4c8b9512013-09-05 17:03:38 -07001560 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001561
Aravind Akella56ae4262014-07-10 16:01:10 -07001562 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001563 // Check if there is a pending flush_complete event for this sensor on this connection.
Aravind Akella8493b792014-09-08 15:45:47 -07001564 if (buffer[i].type == SENSOR_TYPE_META_DATA && flushInfo.mFirstFlushPending == true &&
1565 this == mapFlushEventsToConnections[i]) {
1566 flushInfo.mFirstFlushPending = false;
1567 ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ",
1568 buffer[i].meta_data.sensor);
1569 ++i;
1570 continue;
Aravind Akella56ae4262014-07-10 16:01:10 -07001571 }
1572
1573 // If there is a pending flush complete event for this sensor on this connection,
1574 // ignore the event and proceed to the next.
1575 if (flushInfo.mFirstFlushPending) {
1576 ++i;
1577 continue;
1578 }
1579
1580 do {
Aravind Akella8493b792014-09-08 15:45:47 -07001581 // Keep copying events into the scratch buffer as long as they are regular
1582 // sensor_events are from the same sensor_handle OR they are flush_complete_events
1583 // from the same sensor_handle AND the current connection is mapped to the
1584 // corresponding flush_complete_event.
Aravind Akella56ae4262014-07-10 16:01:10 -07001585 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
Aravind Akella8493b792014-09-08 15:45:47 -07001586 if (this == mapFlushEventsToConnections[i]) {
Aravind Akella56ae4262014-07-10 16:01:10 -07001587 scratch[count++] = buffer[i];
Aravind Akella56ae4262014-07-10 16:01:10 -07001588 }
1589 ++i;
1590 } else {
1591 // Regular sensor event, just copy it to the scratch buffer.
Aravind Akella4c8b9512013-09-05 17:03:38 -07001592 scratch[count++] = buffer[i++];
Aravind Akella56ae4262014-07-10 16:01:10 -07001593 }
Aravind Akella8493b792014-09-08 15:45:47 -07001594 } while ((i<numEvents) && ((buffer[i].sensor == sensor_handle &&
1595 buffer[i].type != SENSOR_TYPE_META_DATA) ||
Aravind Akella56ae4262014-07-10 16:01:10 -07001596 (buffer[i].type == SENSOR_TYPE_META_DATA &&
Aravind Akella6c2664a2014-08-13 12:24:50 -07001597 buffer[i].meta_data.sensor == sensor_handle)));
Mathias Agopiancf510012010-07-22 16:18:10 -07001598 }
Mathias Agopian3560fb22010-07-22 21:24:39 -07001599 } else {
1600 scratch = const_cast<sensors_event_t *>(buffer);
1601 count = numEvents;
Mathias Agopiancf510012010-07-22 16:18:10 -07001602 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001603
Aravind Akella6c2664a2014-08-13 12:24:50 -07001604 sendPendingFlushEventsLocked();
Aravind Akella56ae4262014-07-10 16:01:10 -07001605 // Early return if there are no events for this connection.
1606 if (count == 0) {
1607 return status_t(NO_ERROR);
1608 }
1609
1610#if DEBUG_CONNECTIONS
1611 mEventsReceived += count;
1612#endif
1613 if (mCacheSize != 0) {
1614 // There are some events in the cache which need to be sent first. Copy this buffer to
1615 // the end of cache.
1616 if (mCacheSize + count <= mMaxCacheSize) {
1617 memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
1618 mCacheSize += count;
1619 } else {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001620 // Check if any new sensors have registered on this connection which may have increased
1621 // the max cache size that is desired.
1622 if (mCacheSize + count < computeMaxCacheSizeLocked()) {
1623 reAllocateCacheLocked(scratch, count);
1624 return status_t(NO_ERROR);
1625 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001626 // Some events need to be dropped.
1627 int remaningCacheSize = mMaxCacheSize - mCacheSize;
1628 if (remaningCacheSize != 0) {
1629 memcpy(&mEventCache[mCacheSize], scratch,
1630 remaningCacheSize * sizeof(sensors_event_t));
1631 }
1632 int numEventsDropped = count - remaningCacheSize;
1633 countFlushCompleteEventsLocked(mEventCache, numEventsDropped);
1634 // Drop the first "numEventsDropped" in the cache.
1635 memmove(mEventCache, &mEventCache[numEventsDropped],
1636 (mCacheSize - numEventsDropped) * sizeof(sensors_event_t));
1637
1638 // Copy the remainingEvents in scratch buffer to the end of cache.
1639 memcpy(&mEventCache[mCacheSize - numEventsDropped], scratch + remaningCacheSize,
1640 numEventsDropped * sizeof(sensors_event_t));
1641 }
1642 return status_t(NO_ERROR);
1643 }
1644
Aravind Akella6c2664a2014-08-13 12:24:50 -07001645 int index_wake_up_event = findWakeUpSensorEventLocked(scratch, count);
1646 if (index_wake_up_event >= 0) {
1647 scratch[index_wake_up_event].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1648 ++mWakeLockRefCount;
Aravind Akellae74baf62014-08-21 12:28:35 -07001649#if DEBUG_CONNECTIONS
1650 ++mTotalAcksNeeded;
1651#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001652 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001653
1654 // NOTE: ASensorEvent and sensors_event_t are the same type.
1655 ssize_t size = SensorEventQueue::write(mChannel,
1656 reinterpret_cast<ASensorEvent const*>(scratch), count);
1657 if (size < 0) {
1658 // Write error, copy events to local cache.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001659 if (index_wake_up_event >= 0) {
1660 // If there was a wake_up sensor_event, reset the flag.
1661 scratch[index_wake_up_event].flags &= ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
Aravind Akella0ec20662014-09-14 17:29:48 -07001662 if (mWakeLockRefCount > 0) {
1663 --mWakeLockRefCount;
1664 }
Aravind Akellae74baf62014-08-21 12:28:35 -07001665#if DEBUG_CONNECTIONS
1666 --mTotalAcksNeeded;
1667#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001668 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001669 if (mEventCache == NULL) {
1670 mMaxCacheSize = computeMaxCacheSizeLocked();
1671 mEventCache = new sensors_event_t[mMaxCacheSize];
1672 mCacheSize = 0;
1673 }
1674 memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
1675 mCacheSize += count;
1676
1677 // Add this file descriptor to the looper to get a callback when this fd is available for
1678 // writing.
Aravind Akella8a969552014-09-28 17:52:41 -07001679 updateLooperRegistrationLocked(mService->getLooper());
Aravind Akella56ae4262014-07-10 16:01:10 -07001680 return size;
1681 }
1682
1683#if DEBUG_CONNECTIONS
1684 if (size > 0) {
1685 mEventsSent += count;
1686 }
1687#endif
1688
1689 return size < 0 ? status_t(size) : status_t(NO_ERROR);
1690}
1691
Aravind Akella6c2664a2014-08-13 12:24:50 -07001692void SensorService::SensorEventConnection::reAllocateCacheLocked(sensors_event_t const* scratch,
1693 int count) {
1694 sensors_event_t *eventCache_new;
1695 const int new_cache_size = computeMaxCacheSizeLocked();
1696 // Allocate new cache, copy over events from the old cache & scratch, free up memory.
1697 eventCache_new = new sensors_event_t[new_cache_size];
1698 memcpy(eventCache_new, mEventCache, mCacheSize * sizeof(sensors_event_t));
1699 memcpy(&eventCache_new[mCacheSize], scratch, count * sizeof(sensors_event_t));
1700
1701 ALOGD_IF(DEBUG_CONNECTIONS, "reAllocateCacheLocked maxCacheSize=%d %d", mMaxCacheSize,
1702 new_cache_size);
1703
1704 delete mEventCache;
1705 mEventCache = eventCache_new;
1706 mCacheSize += count;
1707 mMaxCacheSize = new_cache_size;
1708}
1709
1710void SensorService::SensorEventConnection::sendPendingFlushEventsLocked() {
1711 ASensorEvent flushCompleteEvent;
Aravind Akella0ec20662014-09-14 17:29:48 -07001712 memset(&flushCompleteEvent, 0, sizeof(flushCompleteEvent));
Aravind Akella6c2664a2014-08-13 12:24:50 -07001713 flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
Aravind Akella6c2664a2014-08-13 12:24:50 -07001714 // Loop through all the sensors for this connection and check if there are any pending
1715 // flush complete events to be sent.
1716 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1717 FlushInfo& flushInfo = mSensorInfo.editValueAt(i);
1718 while (flushInfo.mPendingFlushEventsToSend > 0) {
Aravind Akella0ec20662014-09-14 17:29:48 -07001719 const int sensor_handle = mSensorInfo.keyAt(i);
1720 flushCompleteEvent.meta_data.sensor = sensor_handle;
Aravind Akellab4373ac2014-10-29 17:55:20 -07001721 bool wakeUpSensor = mService->getSensorFromHandle(sensor_handle).isWakeUpSensor();
1722 if (wakeUpSensor) {
1723 ++mWakeLockRefCount;
Aravind Akella0ec20662014-09-14 17:29:48 -07001724 flushCompleteEvent.flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1725 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001726 ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
1727 if (size < 0) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001728 if (wakeUpSensor) --mWakeLockRefCount;
Aravind Akella6c2664a2014-08-13 12:24:50 -07001729 return;
1730 }
1731 ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
1732 flushCompleteEvent.meta_data.sensor);
1733 flushInfo.mPendingFlushEventsToSend--;
1734 }
1735 }
1736}
1737
Aravind Akellab4373ac2014-10-29 17:55:20 -07001738void SensorService::SensorEventConnection::writeToSocketFromCache() {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001739 // At a time write at most half the size of the receiver buffer in SensorEventQueue OR
1740 // half the size of the socket buffer allocated in BitTube whichever is smaller.
1741 const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
1742 int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
Aravind Akellab4373ac2014-10-29 17:55:20 -07001743 Mutex::Autolock _l(mConnectionLock);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001744 // Send pending flush complete events (if any)
Aravind Akella6c2664a2014-08-13 12:24:50 -07001745 sendPendingFlushEventsLocked();
Aravind Akella56ae4262014-07-10 16:01:10 -07001746 for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001747 const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001748 int index_wake_up_event =
1749 findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite);
1750 if (index_wake_up_event >= 0) {
1751 mEventCache[index_wake_up_event + numEventsSent].flags |=
1752 WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1753 ++mWakeLockRefCount;
Aravind Akellae74baf62014-08-21 12:28:35 -07001754#if DEBUG_CONNECTIONS
1755 ++mTotalAcksNeeded;
1756#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001757 }
Aravind Akella4c8b9512013-09-05 17:03:38 -07001758
Aravind Akella56ae4262014-07-10 16:01:10 -07001759 ssize_t size = SensorEventQueue::write(mChannel,
1760 reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent),
Aravind Akella6c2664a2014-08-13 12:24:50 -07001761 numEventsToWrite);
Aravind Akella56ae4262014-07-10 16:01:10 -07001762 if (size < 0) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001763 if (index_wake_up_event >= 0) {
1764 // If there was a wake_up sensor_event, reset the flag.
1765 mEventCache[index_wake_up_event + numEventsSent].flags &=
1766 ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
Aravind Akella0ec20662014-09-14 17:29:48 -07001767 if (mWakeLockRefCount > 0) {
1768 --mWakeLockRefCount;
1769 }
Aravind Akellae74baf62014-08-21 12:28:35 -07001770#if DEBUG_CONNECTIONS
1771 --mTotalAcksNeeded;
1772#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001773 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001774 memmove(mEventCache, &mEventCache[numEventsSent],
1775 (mCacheSize - numEventsSent) * sizeof(sensors_event_t));
1776 ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ",
Aravind Akella6c2664a2014-08-13 12:24:50 -07001777 numEventsSent, mCacheSize);
Aravind Akella56ae4262014-07-10 16:01:10 -07001778 mCacheSize -= numEventsSent;
Aravind Akella56ae4262014-07-10 16:01:10 -07001779 return;
1780 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001781 numEventsSent += numEventsToWrite;
Aravind Akella56ae4262014-07-10 16:01:10 -07001782#if DEBUG_CONNECTIONS
Aravind Akella6c2664a2014-08-13 12:24:50 -07001783 mEventsSentFromCache += numEventsToWrite;
Aravind Akella56ae4262014-07-10 16:01:10 -07001784#endif
Aravind Akellab4099e72013-10-15 15:43:10 -07001785 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001786 ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize);
1787 // All events from the cache have been sent. Reset cache size to zero.
1788 mCacheSize = 0;
Aravind Akella8a969552014-09-28 17:52:41 -07001789 // There are no more events in the cache. We don't need to poll for write on the fd.
1790 // Update Looper registration.
1791 updateLooperRegistrationLocked(mService->getLooper());
Mathias Agopianfc328812010-07-14 23:41:37 -07001792}
1793
Aravind Akellac551eac2013-10-14 17:04:42 -07001794void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
Aravind Akella0ec20662014-09-14 17:29:48 -07001795 sensors_event_t const* scratch, const int numEventsDropped) {
Aravind Akella4c8b9512013-09-05 17:03:38 -07001796 ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001797 // Count flushComplete events in the events that are about to the dropped. These will be sent
1798 // separately before the next batch of events.
1799 for (int j = 0; j < numEventsDropped; ++j) {
1800 if (scratch[j].type == SENSOR_TYPE_META_DATA) {
1801 FlushInfo& flushInfo = mSensorInfo.editValueFor(scratch[j].meta_data.sensor);
1802 flushInfo.mPendingFlushEventsToSend++;
1803 ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
1804 flushInfo.mPendingFlushEventsToSend);
1805 }
1806 }
1807 return;
1808}
1809
Aravind Akella6c2664a2014-08-13 12:24:50 -07001810int SensorService::SensorEventConnection::findWakeUpSensorEventLocked(
1811 sensors_event_t const* scratch, const int count) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001812 for (int i = 0; i < count; ++i) {
1813 if (mService->isWakeUpSensorEvent(scratch[i])) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001814 return i;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001815 }
1816 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001817 return -1;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001818}
1819
Mathias Agopianb3989272011-10-20 18:42:02 -07001820sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
Mathias Agopianfc328812010-07-14 23:41:37 -07001821{
1822 return mChannel;
1823}
1824
1825status_t SensorService::SensorEventConnection::enableDisable(
Aravind Akella724d91d2013-06-27 12:04:23 -07001826 int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
1827 int reservedFlags)
Mathias Agopianfc328812010-07-14 23:41:37 -07001828{
1829 status_t err;
1830 if (enabled) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001831 err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
Svetoslavb412f6e2015-04-29 16:50:41 -07001832 reservedFlags, mOpPackageName);
Aravind Akella56ae4262014-07-10 16:01:10 -07001833
Mathias Agopianfc328812010-07-14 23:41:37 -07001834 } else {
1835 err = mService->disable(this, handle);
1836 }
1837 return err;
1838}
1839
1840status_t SensorService::SensorEventConnection::setEventRate(
Aravind Akella724d91d2013-06-27 12:04:23 -07001841 int handle, nsecs_t samplingPeriodNs)
Mathias Agopianfc328812010-07-14 23:41:37 -07001842{
Svetoslavb412f6e2015-04-29 16:50:41 -07001843 return mService->setEventRate(this, handle, samplingPeriodNs, mOpPackageName);
Mathias Agopianfc328812010-07-14 23:41:37 -07001844}
1845
Aravind Akella701166d2013-10-08 14:59:26 -07001846status_t SensorService::SensorEventConnection::flush() {
Svetoslavb412f6e2015-04-29 16:50:41 -07001847 return mService->flushSensor(this, mOpPackageName);
Aravind Akella724d91d2013-06-27 12:04:23 -07001848}
Aravind Akella4c8b9512013-09-05 17:03:38 -07001849
Aravind Akella8a969552014-09-28 17:52:41 -07001850int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* /*data*/) {
Aravind Akella56ae4262014-07-10 16:01:10 -07001851 if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) {
Aravind Akella8a969552014-09-28 17:52:41 -07001852 {
1853 // If the Looper encounters some error, set the flag mDead, reset mWakeLockRefCount,
1854 // and remove the fd from Looper. Call checkWakeLockState to know if SensorService
1855 // can release the wake-lock.
1856 ALOGD_IF(DEBUG_CONNECTIONS, "%p Looper error %d", this, fd);
1857 Mutex::Autolock _l(mConnectionLock);
1858 mDead = true;
1859 mWakeLockRefCount = 0;
1860 updateLooperRegistrationLocked(mService->getLooper());
1861 }
1862 mService->checkWakeLockState();
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001863 if (mDataInjectionMode) {
1864 // If the Looper has encountered some error in data injection mode, reset SensorService
1865 // back to normal mode.
1866 mService->resetToNormalMode();
1867 mDataInjectionMode = false;
1868 }
Aravind Akella8a969552014-09-28 17:52:41 -07001869 return 1;
Aravind Akella56ae4262014-07-10 16:01:10 -07001870 }
1871
1872 if (events & ALOOPER_EVENT_INPUT) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001873 unsigned char buf[sizeof(sensors_event_t)];
1874 ssize_t numBytesRead = ::recv(fd, buf, sizeof(buf), MSG_DONTWAIT);
Aravind Akella56ae4262014-07-10 16:01:10 -07001875 {
1876 Mutex::Autolock _l(mConnectionLock);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001877 if (numBytesRead == sizeof(sensors_event_t)) {
1878 if (!mDataInjectionMode) {
1879 ALOGE("Data injected in normal mode, dropping event"
1880 "package=%s uid=%d", mPackageName.string(), mUid);
1881 // Unregister call backs.
1882 return 0;
1883 }
1884 SensorDevice& dev(SensorDevice::getInstance());
1885 sensors_event_t sensor_event;
1886 memset(&sensor_event, 0, sizeof(sensor_event));
1887 memcpy(&sensor_event, buf, sizeof(sensors_event_t));
1888 Sensor sensor = mService->getSensorFromHandle(sensor_event.sensor);
1889 sensor_event.type = sensor.getType();
Svetoslavb412f6e2015-04-29 16:50:41 -07001890 dev.injectSensorData(&sensor_event);
Aravind Akellae74baf62014-08-21 12:28:35 -07001891#if DEBUG_CONNECTIONS
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001892 ++mEventsReceived;
Aravind Akellae74baf62014-08-21 12:28:35 -07001893#endif
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001894 } else if (numBytesRead == sizeof(uint32_t)) {
1895 uint32_t numAcks = 0;
Aravind Akella08f04bf2015-05-08 15:59:23 -07001896 memcpy(&numAcks, buf, numBytesRead);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001897 // Sanity check to ensure there are no read errors in recv, numAcks is always
1898 // within the range and not zero. If any of the above don't hold reset
1899 // mWakeLockRefCount to zero.
1900 if (numAcks > 0 && numAcks < mWakeLockRefCount) {
1901 mWakeLockRefCount -= numAcks;
1902 } else {
1903 mWakeLockRefCount = 0;
1904 }
1905#if DEBUG_CONNECTIONS
1906 mTotalAcksReceived += numAcks;
1907#endif
1908 } else {
1909 // Read error, reset wakelock refcount.
1910 mWakeLockRefCount = 0;
1911 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001912 }
1913 // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released
1914 // here as checkWakeLockState() will need it.
1915 if (mWakeLockRefCount == 0) {
1916 mService->checkWakeLockState();
1917 }
1918 // continue getting callbacks.
1919 return 1;
1920 }
1921
1922 if (events & ALOOPER_EVENT_OUTPUT) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001923 // send sensor data that is stored in mEventCache for this connection.
1924 mService->sendEventsFromCache(this);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001925 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001926 return 1;
1927}
1928
1929int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
Svetoslavb412f6e2015-04-29 16:50:41 -07001930 size_t fifoWakeUpSensors = 0;
1931 size_t fifoNonWakeUpSensors = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -07001932 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1933 const Sensor& sensor = mService->getSensorFromHandle(mSensorInfo.keyAt(i));
1934 if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) {
1935 // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and
1936 // non wake_up sensors.
1937 if (sensor.isWakeUpSensor()) {
1938 fifoWakeUpSensors += sensor.getFifoReservedEventCount();
1939 } else {
1940 fifoNonWakeUpSensors += sensor.getFifoReservedEventCount();
1941 }
1942 } else {
1943 // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors.
1944 if (sensor.isWakeUpSensor()) {
1945 fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ?
1946 fifoWakeUpSensors : sensor.getFifoMaxEventCount();
1947
1948 } else {
1949 fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ?
1950 fifoNonWakeUpSensors : sensor.getFifoMaxEventCount();
1951
1952 }
1953 }
1954 }
1955 if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) {
1956 // It is extremely unlikely that there is a write failure in non batch mode. Return a cache
Aravind Akella6c2664a2014-08-13 12:24:50 -07001957 // size that is equal to that of the batch mode.
Aravind Akellae74baf62014-08-21 12:28:35 -07001958 // ALOGW("Write failure in non-batch mode");
Aravind Akella6c2664a2014-08-13 12:24:50 -07001959 return MAX_SOCKET_BUFFER_SIZE_BATCHED/sizeof(sensors_event_t);
Aravind Akella56ae4262014-07-10 16:01:10 -07001960 }
1961 return fifoWakeUpSensors + fifoNonWakeUpSensors;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001962}
1963
Mathias Agopianfc328812010-07-14 23:41:37 -07001964// ---------------------------------------------------------------------------
1965}; // namespace android
1966