blob: 71aa16039ffa171e402465725f0d99ba48d24f5b [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
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070067const char* SensorService::WAKE_LOCK_NAME = "SensorService";
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;
87 bool hasGyro = false;
88 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) {
97 case SENSOR_TYPE_ORIENTATION:
98 orientationIndex = i;
99 break;
100 case SENSOR_TYPE_GYROSCOPE:
Mathias Agopian03193062013-05-10 19:32:39 -0700101 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700102 hasGyro = true;
103 break;
104 case SENSOR_TYPE_GRAVITY:
105 case SENSOR_TYPE_LINEAR_ACCELERATION:
106 case SENSOR_TYPE_ROTATION_VECTOR:
107 virtualSensorsNeeds &= ~(1<<list[i].type);
108 break;
109 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700110 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700111
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700112 // it's safe to instantiate the SensorFusion object here
113 // (it wants to be instantiated after h/w sensors have been
114 // registered)
115 const SensorFusion& fusion(SensorFusion::getInstance());
Mathias Agopian984826c2011-05-17 22:54:42 -0700116
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700117 // build the sensor list returned to users
118 mUserSensorList = mSensorList;
Mathias Agopian33264862012-06-28 19:46:54 -0700119
120 if (hasGyro) {
Mathias Agopian03193062013-05-10 19:32:39 -0700121 Sensor aSensor;
122
123 // Add Android virtual sensors if they're not already
124 // available in the HAL
125
126 aSensor = registerVirtualSensor( new RotationVectorSensor() );
127 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
128 mUserSensorList.add(aSensor);
129 }
130
131 aSensor = registerVirtualSensor( new GravitySensor(list, count) );
132 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) {
133 mUserSensorList.add(aSensor);
134 }
135
136 aSensor = registerVirtualSensor( new LinearAccelerationSensor(list, count) );
137 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) {
138 mUserSensorList.add(aSensor);
139 }
140
141 aSensor = registerVirtualSensor( new OrientationSensor() );
142 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
143 // if we are doing our own rotation-vector, also add
144 // the orientation sensor and remove the HAL provided one.
145 mUserSensorList.replaceAt(aSensor, orientationIndex);
146 }
147
Mathias Agopian33264862012-06-28 19:46:54 -0700148 // virtual debugging sensors are not added to mUserSensorList
Mathias Agopian03193062013-05-10 19:32:39 -0700149 registerVirtualSensor( new CorrectedGyroSensor(list, count) );
Mathias Agopian33264862012-06-28 19:46:54 -0700150 registerVirtualSensor( new GyroDriftSensor() );
151 }
152
Mathias Agopian33264862012-06-28 19:46:54 -0700153 // debugging sensor list
Mathias Agopian03193062013-05-10 19:32:39 -0700154 mUserSensorListDebug = mSensorList;
Mathias Agopian33264862012-06-28 19:46:54 -0700155
Aravind Akella5466c3d2014-08-22 16:11:10 -0700156 // Check if the device really supports batching by looking at the FIFO event
157 // counts for each sensor.
158 bool batchingSupported = false;
Svetoslavb412f6e2015-04-29 16:50:41 -0700159 for (size_t i = 0; i < mSensorList.size(); ++i) {
Aravind Akella5466c3d2014-08-22 16:11:10 -0700160 if (mSensorList[i].getFifoMaxEventCount() > 0) {
161 batchingSupported = true;
162 break;
163 }
164 }
165
166 if (batchingSupported) {
167 // Increase socket buffer size to a max of 100 KB for batching capabilities.
168 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
169 } else {
170 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
171 }
172
173 // Compare the socketBufferSize value against the system limits and limit
174 // it to maxSystemSocketBufferSize if necessary.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700175 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
176 char line[128];
177 if (fp != NULL && fgets(line, sizeof(line), fp) != NULL) {
178 line[sizeof(line) - 1] = '\0';
Aravind Akella5466c3d2014-08-22 16:11:10 -0700179 size_t maxSystemSocketBufferSize;
180 sscanf(line, "%zu", &maxSystemSocketBufferSize);
181 if (mSocketBufferSize > maxSystemSocketBufferSize) {
182 mSocketBufferSize = maxSystemSocketBufferSize;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700183 }
184 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700185 if (fp) {
186 fclose(fp);
187 }
188
Aravind Akella9a844cf2014-02-11 18:58:52 -0800189 mWakeLockAcquired = false;
Aravind Akella56ae4262014-07-10 16:01:10 -0700190 mLooper = new Looper(false);
Aravind Akella8493b792014-09-08 15:45:47 -0700191 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
192 mSensorEventBuffer = new sensors_event_t[minBufferSize];
193 mSensorEventScratch = new sensors_event_t[minBufferSize];
194 mMapFlushEventsToConnections = new SensorEventConnection const * [minBufferSize];
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700195 mCurrentOperatingMode = NORMAL;
Aravind Akella7830ef32014-10-07 14:13:12 -0700196
Aravind Akella18d6d512015-06-18 14:18:28 -0700197 mNextSensorRegIndex = 0;
198 for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
199 mLastNSensorRegistrations.push();
200 }
201
202 mInitCheck = NO_ERROR;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700203 mAckReceiver = new SensorEventAckReceiver(this);
204 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Aravind Akella7830ef32014-10-07 14:13:12 -0700205 run("SensorService", PRIORITY_URGENT_DISPLAY);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700206 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700207 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700208}
209
Mathias Agopian03193062013-05-10 19:32:39 -0700210Sensor SensorService::registerSensor(SensorInterface* s)
Mathias Agopianf001c922010-11-11 17:58:51 -0800211{
212 sensors_event_t event;
213 memset(&event, 0, sizeof(event));
214
215 const Sensor sensor(s->getSensor());
216 // add to the sensor list (returned to clients)
217 mSensorList.add(sensor);
218 // add to our handle->SensorInterface mapping
219 mSensorMap.add(sensor.getHandle(), s);
220 // create an entry in the mLastEventSeen array
Aravind Akella444f2672015-05-07 12:40:52 -0700221 mLastEventSeen.add(sensor.getHandle(), NULL);
Mathias Agopian03193062013-05-10 19:32:39 -0700222
223 return sensor;
Mathias Agopianf001c922010-11-11 17:58:51 -0800224}
225
Mathias Agopian03193062013-05-10 19:32:39 -0700226Sensor SensorService::registerVirtualSensor(SensorInterface* s)
Mathias Agopianf001c922010-11-11 17:58:51 -0800227{
Mathias Agopian03193062013-05-10 19:32:39 -0700228 Sensor sensor = registerSensor(s);
Mathias Agopianf001c922010-11-11 17:58:51 -0800229 mVirtualSensorList.add( s );
Mathias Agopian03193062013-05-10 19:32:39 -0700230 return sensor;
Mathias Agopianf001c922010-11-11 17:58:51 -0800231}
232
Mathias Agopianfc328812010-07-14 23:41:37 -0700233SensorService::~SensorService()
234{
Mathias Agopianf001c922010-11-11 17:58:51 -0800235 for (size_t i=0 ; i<mSensorMap.size() ; i++)
236 delete mSensorMap.valueAt(i);
Mathias Agopianfc328812010-07-14 23:41:37 -0700237}
238
Aravind Akella4949c502015-02-11 15:54:35 -0800239status_t SensorService::dump(int fd, const Vector<String16>& args)
Mathias Agopianfc328812010-07-14 23:41:37 -0700240{
Mathias Agopianfc328812010-07-14 23:41:37 -0700241 String8 result;
Mathias Agopian1cb13462011-06-27 16:05:52 -0700242 if (!PermissionCache::checkCallingPermission(sDump)) {
Mathias Agopianba02cd22013-07-03 16:20:57 -0700243 result.appendFormat("Permission Denial: "
Aravind Akella70018042014-04-07 22:52:37 +0000244 "can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700245 IPCThreadState::self()->getCallingPid(),
246 IPCThreadState::self()->getCallingUid());
Aravind Akella444f2672015-05-07 12:40:52 -0700247 } else {
Aravind Akella841a5922015-06-29 12:37:48 -0700248 if (args.size() > 2) {
Aravind Akella4949c502015-02-11 15:54:35 -0800249 return INVALID_OPERATION;
250 }
251 Mutex::Autolock _l(mLock);
252 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akella841a5922015-06-29 12:37:48 -0700253 if (args.size() == 2 && args[0] == String16("restrict")) {
Aravind Akella444f2672015-05-07 12:40:52 -0700254 // If already in restricted mode. Ignore.
255 if (mCurrentOperatingMode == RESTRICTED) {
256 return status_t(NO_ERROR);
257 }
258 // If in any mode other than normal, ignore.
259 if (mCurrentOperatingMode != NORMAL) {
260 return INVALID_OPERATION;
261 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700262 mCurrentOperatingMode = RESTRICTED;
Aravind Akella4949c502015-02-11 15:54:35 -0800263 dev.disableAllSensors();
264 // Clear all pending flush connections for all active sensors. If one of the active
265 // connections has called flush() and the underlying sensor has been disabled before a
266 // flush complete event is returned, we need to remove the connection from this queue.
267 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
268 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
269 }
Aravind Akella841a5922015-06-29 12:37:48 -0700270 mWhiteListedPackage.setTo(String8(args[1]));
Aravind Akella444f2672015-05-07 12:40:52 -0700271 return status_t(NO_ERROR);
272 } else if (args.size() == 1 && args[0] == String16("enable")) {
273 // If currently in restricted mode, reset back to NORMAL mode else ignore.
274 if (mCurrentOperatingMode == RESTRICTED) {
275 mCurrentOperatingMode = NORMAL;
276 dev.enableAllSensors();
277 }
Aravind Akella841a5922015-06-29 12:37:48 -0700278 if (mCurrentOperatingMode == DATA_INJECTION) {
279 resetToNormalModeLocked();
280 }
281 mWhiteListedPackage.clear();
Aravind Akella444f2672015-05-07 12:40:52 -0700282 return status_t(NO_ERROR);
Aravind Akella841a5922015-06-29 12:37:48 -0700283 } else if (args.size() == 2 && args[0] == String16("data_injection")) {
284 if (mCurrentOperatingMode == NORMAL) {
285 dev.disableAllSensors();
286 status_t err = dev.setMode(DATA_INJECTION);
287 if (err == NO_ERROR) {
288 mCurrentOperatingMode = DATA_INJECTION;
289 } else {
290 // Re-enable sensors.
291 dev.enableAllSensors();
292 }
293 mWhiteListedPackage.setTo(String8(args[1]));
294 return NO_ERROR;
295 } else if (mCurrentOperatingMode == DATA_INJECTION) {
296 // Already in DATA_INJECTION mode. Treat this as a no_op.
297 return NO_ERROR;
298 } else {
299 // Transition to data injection mode supported only from NORMAL mode.
300 return INVALID_OPERATION;
301 }
Aravind Akellaee155ca2015-06-24 08:31:32 -0700302 } else if (mSensorList.size() == 0) {
303 result.append("No Sensors on the device\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700304 } else {
305 // Default dump the sensor list and debugging information.
306 result.append("Sensor List:\n");
307 for (size_t i=0 ; i<mSensorList.size() ; i++) {
308 const Sensor& s(mSensorList[i]);
309 result.appendFormat(
310 "%-15s| %-10s| version=%d |%-20s| 0x%08x | \"%s\" | type=%d |",
311 s.getName().string(),
312 s.getVendor().string(),
313 s.getVersion(),
314 s.getStringType().string(),
315 s.getHandle(),
316 s.getRequiredPermission().string(),
317 s.getType());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700318
Aravind Akella444f2672015-05-07 12:40:52 -0700319 const int reportingMode = s.getReportingMode();
320 if (reportingMode == AREPORTING_MODE_CONTINUOUS) {
321 result.append(" continuous | ");
322 } else if (reportingMode == AREPORTING_MODE_ON_CHANGE) {
323 result.append(" on-change | ");
324 } else if (reportingMode == AREPORTING_MODE_ONE_SHOT) {
325 result.append(" one-shot | ");
326 } else {
327 result.append(" special-trigger | ");
328 }
329
330 if (s.getMaxDelay() > 0) {
331 result.appendFormat("minRate=%.2fHz | ", 1e6f / s.getMaxDelay());
332 } else {
333 result.appendFormat("maxDelay=%dus |", s.getMaxDelay());
334 }
335
336 if (s.getMinDelay() > 0) {
337 result.appendFormat("maxRate=%.2fHz | ", 1e6f / s.getMinDelay());
338 } else {
339 result.appendFormat("minDelay=%dus |", s.getMinDelay());
340 }
341
342 if (s.getFifoMaxEventCount() > 0) {
343 result.appendFormat("FifoMax=%d events | ",
344 s.getFifoMaxEventCount());
345 } else {
346 result.append("no batching | ");
347 }
348
349 if (s.isWakeUpSensor()) {
350 result.appendFormat("wakeUp | ");
351 } else {
352 result.appendFormat("non-wakeUp | ");
353 }
354
Aravind Akella18d6d512015-06-18 14:18:28 -0700355 int bufIndex = mLastEventSeen.indexOfKey(s.getHandle());
356 if (bufIndex >= 0) {
357 const CircularBuffer* buf = mLastEventSeen.valueAt(bufIndex);
358 if (buf != NULL && s.getRequiredPermission().isEmpty()) {
359 buf->printBuffer(result);
360 } else {
361 result.append("last=<> \n");
362 }
Aravind Akella444f2672015-05-07 12:40:52 -0700363 }
364 result.append("\n");
365 }
366 SensorFusion::getInstance().dump(result);
367 SensorDevice::getInstance().dump(result);
368
369 result.append("Active sensors:\n");
370 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
371 int handle = mActiveSensors.keyAt(i);
372 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
373 getSensorName(handle).string(),
374 handle,
375 mActiveSensors.valueAt(i)->getNumConnections());
Aravind Akella6c2664a2014-08-13 12:24:50 -0700376 }
377
Aravind Akella444f2672015-05-07 12:40:52 -0700378 result.appendFormat("Socket Buffer size = %d events\n",
379 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella18d6d512015-06-18 14:18:28 -0700380 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
381 "not held");
Aravind Akella444f2672015-05-07 12:40:52 -0700382 result.appendFormat("Mode :");
383 switch(mCurrentOperatingMode) {
384 case NORMAL:
385 result.appendFormat(" NORMAL\n");
386 break;
387 case RESTRICTED:
Aravind Akella841a5922015-06-29 12:37:48 -0700388 result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
Aravind Akella444f2672015-05-07 12:40:52 -0700389 break;
390 case DATA_INJECTION:
Aravind Akella841a5922015-06-29 12:37:48 -0700391 result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700392 }
Aravind Akella444f2672015-05-07 12:40:52 -0700393 result.appendFormat("%zd active connections\n", mActiveConnections.size());
Aravind Akella0e025c52014-06-03 19:19:57 -0700394
Aravind Akella444f2672015-05-07 12:40:52 -0700395 for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
396 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
397 if (connection != 0) {
398 result.appendFormat("Connection Number: %zu \n", i);
399 connection->dump(result);
400 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700401 }
Aravind Akella18d6d512015-06-18 14:18:28 -0700402
403 result.appendFormat("Previous Registrations:\n");
404 // Log in the reverse chronological order.
405 int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
406 SENSOR_REGISTRATIONS_BUF_SIZE;
407 const int startIndex = currentIndex;
408 do {
409 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
410 if (SensorRegistrationInfo::isSentinel(reg_info)) {
411 // Ignore sentinel, proceed to next item.
412 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
413 SENSOR_REGISTRATIONS_BUF_SIZE;
414 continue;
415 }
416 if (reg_info.mActivated) {
417 result.appendFormat("%02d:%02d:%02d activated package=%s handle=0x%08x "
418 "samplingRate=%dus maxReportLatency=%dus\n",
419 reg_info.mHour, reg_info.mMin, reg_info.mSec,
420 reg_info.mPackageName.string(), reg_info.mSensorHandle,
421 reg_info.mSamplingRateUs, reg_info.mMaxReportLatencyUs);
422 } else {
423 result.appendFormat("%02d:%02d:%02d de-activated package=%s handle=0x%08x\n",
424 reg_info.mHour, reg_info.mMin, reg_info.mSec,
425 reg_info.mPackageName.string(), reg_info.mSensorHandle);
426 }
427 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
428 SENSOR_REGISTRATIONS_BUF_SIZE;
429 } while(startIndex != currentIndex);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700430 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700431 }
432 write(fd, result.string(), result.size());
433 return NO_ERROR;
434}
435
Aravind Akella9a844cf2014-02-11 18:58:52 -0800436void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700437 sensors_event_t const* buffer, const int count) {
438 for (int i=0 ; i<count ; i++) {
439 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700440 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
441 handle = buffer[i].meta_data.sensor;
442 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700443 if (connection->hasSensor(handle)) {
444 SensorInterface* sensor = mSensorMap.valueFor(handle);
445 // If this buffer has an event from a one_shot sensor and this connection is registered
446 // for this particular one_shot sensor, try cleaning up the connection.
447 if (sensor != NULL &&
448 sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
449 sensor->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800450 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700451 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700452
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700453 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700454 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700455}
456
Mathias Agopianfc328812010-07-14 23:41:37 -0700457bool SensorService::threadLoop()
458{
Steve Blocka5512372011-12-20 16:23:08 +0000459 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700460
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700461 // each virtual sensor could generate an event per "real" event, that's why we need
462 // to size numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT.
463 // in practice, this is too aggressive, but guaranteed to be enough.
464 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
465 const size_t numEventMax = minBufferSize / (1 + mVirtualSensorList.size());
466
Mathias Agopianf001c922010-11-11 17:58:51 -0800467 SensorDevice& device(SensorDevice::getInstance());
468 const size_t vcount = mVirtualSensorList.size();
Mathias Agopianfc328812010-07-14 23:41:37 -0700469
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700470 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700471 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700472 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
473 if (count < 0) {
Steve Blockf5a12302012-01-06 19:20:56 +0000474 ALOGE("sensor poll failed (%s)", strerror(-count));
Mathias Agopianfc328812010-07-14 23:41:37 -0700475 break;
476 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700477
478 // Reset sensors_event_t.flags to zero for all events in the buffer.
479 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700480 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700481 }
Aravind Akellae148bc22014-09-24 22:12:58 -0700482
483 // Make a copy of the connection vector as some connections may be removed during the
484 // course of this loop (especially when one-shot sensor events are present in the
485 // sensor_event buffer). Promote all connections to StrongPointers before the lock is
486 // acquired. If the destructor of the sp gets called when the lock is acquired, it may
487 // result in a deadlock as ~SensorEventConnection() needs to acquire mLock again for
488 // cleanup. So copy all the strongPointers to a vector before the lock is acquired.
489 SortedVector< sp<SensorEventConnection> > activeConnections;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700490 populateActiveConnections(&activeConnections);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800491 Mutex::Autolock _l(mLock);
492 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
493 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
494 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
495 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
496 // releasing the wakelock.
497 bool bufferHasWakeUpEvent = false;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700498 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700499 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800500 bufferHasWakeUpEvent = true;
501 break;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700502 }
503 }
504
Aravind Akella9a844cf2014-02-11 18:58:52 -0800505 if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700506 setWakeLockAcquiredLocked(true);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800507 }
Aravind Akella8493b792014-09-08 15:45:47 -0700508 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800509
Mathias Agopianf001c922010-11-11 17:58:51 -0800510 // handle virtual sensors
511 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700512 sensors_event_t const * const event = mSensorEventBuffer;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800513 const size_t activeVirtualSensorCount = mActiveVirtualSensors.size();
Mathias Agopianf001c922010-11-11 17:58:51 -0800514 if (activeVirtualSensorCount) {
515 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700516 SensorFusion& fusion(SensorFusion::getInstance());
517 if (fusion.isEnabled()) {
518 for (size_t i=0 ; i<size_t(count) ; i++) {
519 fusion.process(event[i]);
520 }
521 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700522 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800523 for (size_t j=0 ; j<activeVirtualSensorCount ; j++) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700524 if (count + k >= minBufferSize) {
525 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700526 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700527 count, k, minBufferSize);
528 break;
529 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800530 sensors_event_t out;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800531 SensorInterface* si = mActiveVirtualSensors.valueAt(j);
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700532 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700533 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800534 k++;
535 }
536 }
537 }
538 if (k) {
539 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700540 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800541 count += k;
542 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700543 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700544 }
545 }
546 }
547
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700548 // handle backward compatibility for RotationVector sensor
549 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
550 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700551 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700552 // All the 4 components of the quaternion should be available
553 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700554 mSensorEventBuffer[i].data[4] = -1;
555 }
556 }
557 }
558
559 // Map flush_complete_events in the buffer to SensorEventConnections which called
560 // flush on the hardware sensor. mapFlushEventsToConnections[i] will be the
561 // SensorEventConnection mapped to the corresponding flush_complete_event in
562 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
563 for (int i = 0; i < count; ++i) {
564 mMapFlushEventsToConnections[i] = NULL;
565 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
566 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
567 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
568 if (rec != NULL) {
569 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
570 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700571 }
572 }
573 }
574
Aravind Akella9a844cf2014-02-11 18:58:52 -0800575 // Send our events to clients. Check the state of wake lock for each client and release the
576 // lock if none of the clients need it.
577 bool needsWakeLock = false;
Aravind Akella8493b792014-09-08 15:45:47 -0700578 size_t numConnections = activeConnections.size();
579 for (size_t i=0 ; i < numConnections; ++i) {
Aravind Akellae148bc22014-09-24 22:12:58 -0700580 if (activeConnections[i] != 0) {
581 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
Aravind Akella8493b792014-09-08 15:45:47 -0700582 mMapFlushEventsToConnections);
Aravind Akellae148bc22014-09-24 22:12:58 -0700583 needsWakeLock |= activeConnections[i]->needsWakeLock();
Aravind Akella8493b792014-09-08 15:45:47 -0700584 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
585 // Early check for one-shot sensors.
Aravind Akellae148bc22014-09-24 22:12:58 -0700586 if (activeConnections[i]->hasOneShotSensors()) {
587 cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
588 count);
Aravind Akella8493b792014-09-08 15:45:47 -0700589 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800590 }
591 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700592
Aravind Akella9a844cf2014-02-11 18:58:52 -0800593 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700594 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800595 }
Aravind Akella8493b792014-09-08 15:45:47 -0700596 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -0700597
Steve Block3c20fbe2012-01-05 23:22:43 +0000598 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -0800599 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -0700600 return false;
601}
602
Aravind Akella56ae4262014-07-10 16:01:10 -0700603sp<Looper> SensorService::getLooper() const {
604 return mLooper;
605}
606
Aravind Akellab4373ac2014-10-29 17:55:20 -0700607void SensorService::resetAllWakeLockRefCounts() {
608 SortedVector< sp<SensorEventConnection> > activeConnections;
609 populateActiveConnections(&activeConnections);
610 {
611 Mutex::Autolock _l(mLock);
612 for (size_t i=0 ; i < activeConnections.size(); ++i) {
613 if (activeConnections[i] != 0) {
614 activeConnections[i]->resetWakeLockRefCount();
615 }
616 }
617 setWakeLockAcquiredLocked(false);
618 }
619}
620
621void SensorService::setWakeLockAcquiredLocked(bool acquire) {
622 if (acquire) {
623 if (!mWakeLockAcquired) {
624 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
625 mWakeLockAcquired = true;
626 }
627 mLooper->wake();
628 } else {
629 if (mWakeLockAcquired) {
630 release_wake_lock(WAKE_LOCK_NAME);
631 mWakeLockAcquired = false;
632 }
633 }
634}
635
Aravind Akellab4373ac2014-10-29 17:55:20 -0700636bool SensorService::isWakeLockAcquired() {
637 Mutex::Autolock _l(mLock);
638 return mWakeLockAcquired;
639}
640
Aravind Akella56ae4262014-07-10 16:01:10 -0700641bool SensorService::SensorEventAckReceiver::threadLoop() {
642 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -0700643 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -0700644 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700645 bool wakeLockAcquired = mService->isWakeLockAcquired();
646 int timeout = -1;
647 if (wakeLockAcquired) timeout = 5000;
648 int ret = looper->pollOnce(timeout);
649 if (ret == ALOOPER_POLL_TIMEOUT) {
650 mService->resetAllWakeLockRefCounts();
651 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700652 } while(!Thread::exitPending());
653 return false;
654}
655
Aravind Akella9a844cf2014-02-11 18:58:52 -0800656void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -0800657 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -0800658 for (size_t i = 0; i < count; i++) {
Aravind Akella444f2672015-05-07 12:40:52 -0700659 if (buffer[i].type != SENSOR_TYPE_META_DATA) {
660 CircularBuffer* &circular_buf = mLastEventSeen.editValueFor(buffer[i].sensor);
661 if (circular_buf == NULL) {
662 circular_buf = new CircularBuffer(buffer[i].type);
Aravind Akella4b847042014-03-03 19:02:46 -0800663 }
Aravind Akella444f2672015-05-07 12:40:52 -0700664 circular_buf->addEvent(buffer[i]);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800665 }
666 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800667}
668
Mathias Agopianf001c922010-11-11 17:58:51 -0800669void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count)
670{
671 struct compar {
672 static int cmp(void const* lhs, void const* rhs) {
673 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
674 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -0700675 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -0800676 }
677 };
678 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
679}
680
Mathias Agopian5d270722010-07-19 15:20:39 -0700681String8 SensorService::getSensorName(int handle) const {
Mathias Agopian010e4222011-06-08 20:06:50 -0700682 size_t count = mUserSensorList.size();
Mathias Agopian5d270722010-07-19 15:20:39 -0700683 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian010e4222011-06-08 20:06:50 -0700684 const Sensor& sensor(mUserSensorList[i]);
Mathias Agopian5d270722010-07-19 15:20:39 -0700685 if (sensor.getHandle() == handle) {
686 return sensor.getName();
687 }
688 }
689 String8 result("unknown");
690 return result;
691}
692
Aravind Akellab4099e72013-10-15 15:43:10 -0700693bool SensorService::isVirtualSensor(int handle) const {
694 SensorInterface* sensor = mSensorMap.valueFor(handle);
695 return sensor->isVirtual();
696}
697
Aravind Akella9a844cf2014-02-11 18:58:52 -0800698bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -0700699 int handle = event.sensor;
700 if (event.type == SENSOR_TYPE_META_DATA) {
701 handle = event.meta_data.sensor;
702 }
703 SensorInterface* sensor = mSensorMap.valueFor(handle);
704 return sensor != NULL && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -0800705}
706
Aravind Akella6c2664a2014-08-13 12:24:50 -0700707SensorService::SensorRecord * SensorService::getSensorRecord(int handle) {
708 return mActiveSensors.valueFor(handle);
709}
710
Svetoslavb412f6e2015-04-29 16:50:41 -0700711Vector<Sensor> SensorService::getSensorList(const String16& opPackageName)
Mathias Agopianfc328812010-07-14 23:41:37 -0700712{
Mathias Agopian33264862012-06-28 19:46:54 -0700713 char value[PROPERTY_VALUE_MAX];
714 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +0000715 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
716 mUserSensorListDebug : mUserSensorList;
717 Vector<Sensor> accessibleSensorList;
718 for (size_t i = 0; i < initialSensorList.size(); i++) {
719 Sensor sensor = initialSensorList[i];
Svetoslavb412f6e2015-04-29 16:50:41 -0700720 if (canAccessSensor(sensor, "getSensorList", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +0000721 accessibleSensorList.add(sensor);
722 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -0700723 ALOGI("Skipped sensor %s because it requires permission %s and app op %d",
Bernhard Rosenkränzer5f619932014-11-17 21:06:20 +0100724 sensor.getName().string(),
Svetoslavb412f6e2015-04-29 16:50:41 -0700725 sensor.getRequiredPermission().string(),
726 sensor.getRequiredAppOp());
Aravind Akella70018042014-04-07 22:52:37 +0000727 }
Mathias Agopian33264862012-06-28 19:46:54 -0700728 }
Aravind Akella70018042014-04-07 22:52:37 +0000729 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -0700730}
731
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700732sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -0700733 int requestedMode, const String16& opPackageName) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700734 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
735 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
736 return NULL;
737 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700738
739 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700740 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
741 // operating in DI mode.
742 if (requestedMode == DATA_INJECTION) {
743 if (mCurrentOperatingMode != DATA_INJECTION) return NULL;
744 if (!isWhiteListedPackage(packageName)) return NULL;
745 }
746
Mathias Agopian5307d172012-09-18 17:02:43 -0700747 uid_t uid = IPCThreadState::self()->getCallingUid();
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700748 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -0700749 requestedMode == DATA_INJECTION, opPackageName));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700750 if (requestedMode == DATA_INJECTION) {
751 if (mActiveConnections.indexOf(result) < 0) {
752 mActiveConnections.add(result);
753 }
754 // Add the associated file descriptor to the Looper for polling whenever there is data to
755 // be injected.
756 result->updateLooperRegistration(mLooper);
757 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700758 return result;
759}
760
Aravind Akella841a5922015-06-29 12:37:48 -0700761int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700762 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700763 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700764}
765
766status_t SensorService::resetToNormalMode() {
767 Mutex::Autolock _l(mLock);
768 return resetToNormalModeLocked();
769}
770
771status_t SensorService::resetToNormalModeLocked() {
772 SensorDevice& dev(SensorDevice::getInstance());
773 dev.enableAllSensors();
774 status_t err = dev.setMode(NORMAL);
775 mCurrentOperatingMode = NORMAL;
776 return err;
777}
778
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800779void SensorService::cleanupConnection(SensorEventConnection* c)
Mathias Agopianfc328812010-07-14 23:41:37 -0700780{
781 Mutex::Autolock _l(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800782 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700783 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -0700784 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700785 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800786 int handle = mActiveSensors.keyAt(i);
787 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -0700788 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800789 SensorInterface* sensor = mSensorMap.valueFor( handle );
Steve Blockf5a12302012-01-06 19:20:56 +0000790 ALOGE_IF(!sensor, "mSensorMap[handle=0x%08x] is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800791 if (sensor) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800792 sensor->activate(c, false);
Mathias Agopianf001c922010-11-11 17:58:51 -0800793 }
Aravind Akella8a969552014-09-28 17:52:41 -0700794 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800795 }
796 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -0700797 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +0000798 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -0700799 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700800 c, i, handle);
801
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800802 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +0000803 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700804 mActiveSensors.removeItemsAt(i, 1);
Mathias Agopianf001c922010-11-11 17:58:51 -0800805 mActiveVirtualSensors.removeItem(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700806 delete rec;
807 size--;
808 } else {
809 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -0700810 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700811 }
Aravind Akella8a969552014-09-28 17:52:41 -0700812 c->updateLooperRegistration(mLooper);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700813 mActiveConnections.remove(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -0700814 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -0800815 if (c->needsWakeLock()) {
816 checkWakeLockStateLocked();
817 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700818}
819
Aravind Akella70018042014-04-07 22:52:37 +0000820Sensor SensorService::getSensorFromHandle(int handle) const {
821 return mSensorMap.valueFor(handle)->getSensor();
822}
823
Mathias Agopianfc328812010-07-14 23:41:37 -0700824status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -0700825 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
826 const String16& opPackageName)
Mathias Agopianfc328812010-07-14 23:41:37 -0700827{
Mathias Agopian50df2952010-07-19 19:09:10 -0700828 if (mInitCheck != NO_ERROR)
829 return mInitCheck;
830
Mathias Agopianf001c922010-11-11 17:58:51 -0800831 SensorInterface* sensor = mSensorMap.valueFor(handle);
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700832 if (sensor == NULL) {
833 return BAD_VALUE;
834 }
Aravind Akella70018042014-04-07 22:52:37 +0000835
Svetoslavb412f6e2015-04-29 16:50:41 -0700836 if (!canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +0000837 return BAD_VALUE;
838 }
839
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700840 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700841 if ((mCurrentOperatingMode == RESTRICTED || mCurrentOperatingMode == DATA_INJECTION)
842 && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -0800843 return INVALID_OPERATION;
844 }
845
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700846 SensorRecord* rec = mActiveSensors.valueFor(handle);
847 if (rec == 0) {
848 rec = new SensorRecord(connection);
849 mActiveSensors.add(handle, rec);
850 if (sensor->isVirtual()) {
851 mActiveVirtualSensors.add(handle, sensor);
852 }
853 } else {
854 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800855 // this sensor is already activated, but we are adding a connection that uses it.
856 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700857 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -0700858 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800859 // NOTE: The wake_up flag of this event may get set to
860 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Aravind Akella444f2672015-05-07 12:40:52 -0700861 CircularBuffer *circular_buf = mLastEventSeen.valueFor(handle);
862 if (circular_buf) {
863 sensors_event_t event;
864 memset(&event, 0, sizeof(event));
865 // It is unlikely that this buffer is empty as the sensor is already active.
866 // One possible corner case may be two applications activating an on-change
867 // sensor at the same time.
868 if(circular_buf->populateLastEvent(&event)) {
869 event.sensor = handle;
870 if (event.version == sizeof(sensors_event_t)) {
871 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
872 setWakeLockAcquiredLocked(true);
873 }
874 connection->sendEvents(&event, 1, NULL);
875 if (!connection->needsWakeLock() && mWakeLockAcquired) {
876 checkWakeLockStateLocked();
877 }
878 }
Aravind Akella9a844cf2014-02-11 18:58:52 -0800879 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700880 }
881 }
882 }
883 }
884
885 if (connection->addSensor(handle)) {
886 BatteryService::enableSensor(connection->getUid(), handle);
887 // the sensor was added (which means it wasn't already there)
888 // so, see if this connection becomes active
889 if (mActiveConnections.indexOf(connection) < 0) {
890 mActiveConnections.add(connection);
891 }
892 } else {
893 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
894 handle, connection.get());
895 }
896
Aravind Akella724d91d2013-06-27 12:04:23 -0700897 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
898 if (samplingPeriodNs < minDelayNs) {
899 samplingPeriodNs = minDelayNs;
900 }
901
Aravind Akella6c2664a2014-08-13 12:24:50 -0700902 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
903 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -0700904 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
905
Aravind Akella4949c502015-02-11 15:54:35 -0800906 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -0700907 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -0700908
Aravind Akella5466c3d2014-08-22 16:11:10 -0700909 // Call flush() before calling activate() on the sensor. Wait for a first flush complete
910 // event before sending events on this connection. Ignore one-shot sensors which don't
911 // support flush(). Also if this sensor isn't already active, don't call flush().
912 if (err == NO_ERROR && sensor->getSensor().getReportingMode() != AREPORTING_MODE_ONE_SHOT &&
913 rec->getNumConnections() > 1) {
914 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700915 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -0700916 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -0700917 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700918 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -0700919 } else {
920 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700921 }
922 }
Aravind Akella724d91d2013-06-27 12:04:23 -0700923
924 if (err == NO_ERROR) {
925 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
926 err = sensor->activate(connection.get(), true);
927 }
928
Aravind Akella8a969552014-09-28 17:52:41 -0700929 if (err == NO_ERROR) {
930 connection->updateLooperRegistration(mLooper);
Aravind Akella18d6d512015-06-18 14:18:28 -0700931 SensorRegistrationInfo &reg_info =
932 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex);
933 reg_info.mSensorHandle = handle;
934 reg_info.mSamplingRateUs = samplingPeriodNs/1000;
935 reg_info.mMaxReportLatencyUs = maxBatchReportLatencyNs/1000;
936 reg_info.mActivated = true;
937 reg_info.mPackageName = connection->getPackageName();
938 time_t rawtime = time(NULL);
939 struct tm * timeinfo = localtime(&rawtime);
940 reg_info.mHour = timeinfo->tm_hour;
941 reg_info.mMin = timeinfo->tm_min;
942 reg_info.mSec = timeinfo->tm_sec;
943 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -0700944 }
945
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700946 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -0700947 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700948 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700949 }
950 return err;
951}
952
953status_t SensorService::disable(const sp<SensorEventConnection>& connection,
954 int handle)
955{
Mathias Agopian50df2952010-07-19 19:09:10 -0700956 if (mInitCheck != NO_ERROR)
957 return mInitCheck;
958
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700959 Mutex::Autolock _l(mLock);
960 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700961 if (err == NO_ERROR) {
962 SensorInterface* sensor = mSensorMap.valueFor(handle);
963 err = sensor ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -0700964
965 }
966 if (err == NO_ERROR) {
967 SensorRegistrationInfo &reg_info =
968 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex);
969 reg_info.mActivated = false;
970 reg_info.mPackageName= connection->getPackageName();
971 reg_info.mSensorHandle = handle;
972 time_t rawtime = time(NULL);
973 struct tm * timeinfo = localtime(&rawtime);
974 reg_info.mHour = timeinfo->tm_hour;
975 reg_info.mMin = timeinfo->tm_min;
976 reg_info.mSec = timeinfo->tm_sec;
977 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700978 }
979 return err;
980}
981
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700982status_t SensorService::cleanupWithoutDisable(
983 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700984 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700985 return cleanupWithoutDisableLocked(connection, handle);
986}
987
988status_t SensorService::cleanupWithoutDisableLocked(
989 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700990 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700991 if (rec) {
992 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -0700993 if (connection->removeSensor(handle)) {
994 BatteryService::disableSensor(connection->getUid(), handle);
995 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700996 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -0700997 connection->updateLooperRegistration(mLooper);
Mathias Agopianfc328812010-07-14 23:41:37 -0700998 mActiveConnections.remove(connection);
999 }
1000 // see if this sensor becomes inactive
1001 if (rec->removeConnection(connection)) {
1002 mActiveSensors.removeItem(handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001003 mActiveVirtualSensors.removeItem(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001004 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07001005 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001006 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001007 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001008 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07001009}
1010
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001011status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -07001012 int handle, nsecs_t ns, const String16& opPackageName)
Mathias Agopianfc328812010-07-14 23:41:37 -07001013{
Mathias Agopian50df2952010-07-19 19:09:10 -07001014 if (mInitCheck != NO_ERROR)
1015 return mInitCheck;
1016
Mathias Agopianae09d652011-11-01 17:37:49 -07001017 SensorInterface* sensor = mSensorMap.valueFor(handle);
1018 if (!sensor)
1019 return BAD_VALUE;
1020
Svetoslavb412f6e2015-04-29 16:50:41 -07001021 if (!canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001022 return BAD_VALUE;
1023 }
1024
Mathias Agopian1cd70002010-07-21 15:59:50 -07001025 if (ns < 0)
1026 return BAD_VALUE;
1027
Mathias Agopian62569ec2011-11-07 21:21:47 -08001028 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1029 if (ns < minDelayNs) {
1030 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07001031 }
1032
Mathias Agopianf001c922010-11-11 17:58:51 -08001033 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07001034}
1035
Svetoslavb412f6e2015-04-29 16:50:41 -07001036status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1037 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00001038 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001039 SensorDevice& dev(SensorDevice::getInstance());
1040 const int halVersion = dev.getHalDeviceVersion();
1041 status_t err(NO_ERROR);
1042 Mutex::Autolock _l(mLock);
1043 // Loop through all sensors for this connection and call flush on each of them.
1044 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
1045 const int handle = connection->mSensorInfo.keyAt(i);
1046 SensorInterface* sensor = mSensorMap.valueFor(handle);
1047 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1048 ALOGE("flush called on a one-shot sensor");
1049 err = INVALID_OPERATION;
1050 continue;
1051 }
Aravind Akella8493b792014-09-08 15:45:47 -07001052 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001053 // For older devices just increment pending flush count which will send a trivial
1054 // flush complete event.
Aravind Akella8a969552014-09-28 17:52:41 -07001055 connection->incrementPendingFlushCount(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001056 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001057 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1058 err = INVALID_OPERATION;
1059 continue;
1060 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001061 status_t err_flush = sensor->flush(connection.get(), handle);
1062 if (err_flush == NO_ERROR) {
1063 SensorRecord* rec = mActiveSensors.valueFor(handle);
1064 if (rec != NULL) rec->addPendingFlushConnection(connection);
1065 }
1066 err = (err_flush != NO_ERROR) ? err_flush : err;
1067 }
Aravind Akella70018042014-04-07 22:52:37 +00001068 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001069 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001070}
Aravind Akella70018042014-04-07 22:52:37 +00001071
Svetoslavb412f6e2015-04-29 16:50:41 -07001072bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1073 const String16& opPackageName) {
1074 const String8& requiredPermission = sensor.getRequiredPermission();
Aravind Akella70018042014-04-07 22:52:37 +00001075
Svetoslavb412f6e2015-04-29 16:50:41 -07001076 if (requiredPermission.length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00001077 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07001078 }
1079
1080 bool hasPermission = false;
1081
1082 // Runtime permissions can't use the cache as they may change.
1083 if (sensor.isRequiredPermissionRuntime()) {
1084 hasPermission = checkPermission(String16(requiredPermission),
1085 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Aravind Akella70018042014-04-07 22:52:37 +00001086 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001087 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1088 }
1089
1090 if (!hasPermission) {
1091 ALOGE("%s a sensor (%s) without holding its required permission: %s",
1092 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
Aravind Akella70018042014-04-07 22:52:37 +00001093 return false;
1094 }
Svetoslavb412f6e2015-04-29 16:50:41 -07001095
1096 const int32_t opCode = sensor.getRequiredAppOp();
1097 if (opCode >= 0) {
1098 AppOpsManager appOps;
1099 if (appOps.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName)
1100 != AppOpsManager::MODE_ALLOWED) {
1101 ALOGE("%s a sensor (%s) without enabled required app op: %D",
1102 operation, sensor.getName().string(), opCode);
1103 return false;
1104 }
1105 }
1106
1107 return true;
Aravind Akella70018042014-04-07 22:52:37 +00001108}
1109
Aravind Akella9a844cf2014-02-11 18:58:52 -08001110void SensorService::checkWakeLockState() {
1111 Mutex::Autolock _l(mLock);
1112 checkWakeLockStateLocked();
1113}
1114
1115void SensorService::checkWakeLockStateLocked() {
1116 if (!mWakeLockAcquired) {
1117 return;
1118 }
1119 bool releaseLock = true;
1120 for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
1121 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1122 if (connection != 0) {
1123 if (connection->needsWakeLock()) {
1124 releaseLock = false;
1125 break;
1126 }
1127 }
1128 }
1129 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001130 setWakeLockAcquiredLocked(false);
1131 }
1132}
1133
1134void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1135 Mutex::Autolock _l(mLock);
1136 connection->writeToSocketFromCache();
1137 if (connection->needsWakeLock()) {
1138 setWakeLockAcquiredLocked(true);
1139 }
1140}
1141
1142void SensorService::populateActiveConnections(
1143 SortedVector< sp<SensorEventConnection> >* activeConnections) {
1144 Mutex::Autolock _l(mLock);
1145 for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
1146 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1147 if (connection != 0) {
1148 activeConnections->add(connection);
1149 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001150 }
1151}
Aravind Akella6c2664a2014-08-13 12:24:50 -07001152
Aravind Akella4949c502015-02-11 15:54:35 -08001153bool SensorService::isWhiteListedPackage(const String8& packageName) {
Aravind Akella841a5922015-06-29 12:37:48 -07001154 return (packageName.contains(mWhiteListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08001155}
1156
Aravind Akella444f2672015-05-07 12:40:52 -07001157int SensorService::getNumEventsForSensorType(int sensor_event_type) {
1158 switch (sensor_event_type) {
1159 case SENSOR_TYPE_ROTATION_VECTOR:
1160 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
1161 return 5;
1162
1163 case SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED:
1164 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
1165 return 6;
1166
1167 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
1168 return 4;
1169
1170 case SENSOR_TYPE_SIGNIFICANT_MOTION:
1171 case SENSOR_TYPE_STEP_DETECTOR:
1172 case SENSOR_TYPE_STEP_COUNTER:
1173 return 1;
1174
1175 default:
1176 return 3;
1177 }
1178}
1179
Mathias Agopianfc328812010-07-14 23:41:37 -07001180// ---------------------------------------------------------------------------
Mathias Agopianfc328812010-07-14 23:41:37 -07001181SensorService::SensorRecord::SensorRecord(
1182 const sp<SensorEventConnection>& connection)
1183{
1184 mConnections.add(connection);
1185}
1186
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001187bool SensorService::SensorRecord::addConnection(
Mathias Agopianfc328812010-07-14 23:41:37 -07001188 const sp<SensorEventConnection>& connection)
1189{
1190 if (mConnections.indexOf(connection) < 0) {
1191 mConnections.add(connection);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001192 return true;
Mathias Agopianfc328812010-07-14 23:41:37 -07001193 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001194 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -07001195}
1196
1197bool SensorService::SensorRecord::removeConnection(
1198 const wp<SensorEventConnection>& connection)
1199{
1200 ssize_t index = mConnections.indexOf(connection);
1201 if (index >= 0) {
1202 mConnections.removeItemsAt(index, 1);
1203 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001204 // Remove this connections from the queue of flush() calls made on this sensor.
1205 for (Vector< wp<SensorEventConnection> >::iterator it =
1206 mPendingFlushConnections.begin(); it != mPendingFlushConnections.end();) {
Aravind Akella8a969552014-09-28 17:52:41 -07001207
Aravind Akella6c2664a2014-08-13 12:24:50 -07001208 if (it->unsafe_get() == connection.unsafe_get()) {
1209 it = mPendingFlushConnections.erase(it);
1210 } else {
1211 ++it;
1212 }
1213 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001214 return mConnections.size() ? false : true;
1215}
1216
Aravind Akella6c2664a2014-08-13 12:24:50 -07001217void SensorService::SensorRecord::addPendingFlushConnection(
1218 const sp<SensorEventConnection>& connection) {
1219 mPendingFlushConnections.add(connection);
1220}
1221
1222void SensorService::SensorRecord::removeFirstPendingFlushConnection() {
1223 if (mPendingFlushConnections.size() > 0) {
1224 mPendingFlushConnections.removeAt(0);
1225 }
1226}
1227
1228SensorService::SensorEventConnection *
1229SensorService::SensorRecord::getFirstPendingFlushConnection() {
1230 if (mPendingFlushConnections.size() > 0) {
1231 return mPendingFlushConnections[0].unsafe_get();
1232 }
1233 return NULL;
1234}
1235
Aravind Akella4949c502015-02-11 15:54:35 -08001236void SensorService::SensorRecord::clearAllPendingFlushConnections() {
1237 mPendingFlushConnections.clear();
1238}
1239
Aravind Akella18d6d512015-06-18 14:18:28 -07001240
1241// ---------------------------------------------------------------------------
1242SensorService::TrimmedSensorEvent::TrimmedSensorEvent(int sensorType) {
1243 mTimestamp = -1;
1244 const int numData = SensorService::getNumEventsForSensorType(sensorType);
1245 if (sensorType == SENSOR_TYPE_STEP_COUNTER) {
1246 mStepCounter = 0;
1247 } else {
1248 mData = new float[numData];
1249 for (int i = 0; i < numData; ++i) {
1250 mData[i] = -1.0;
1251 }
1252 }
1253 mHour = mMin = mSec = INT32_MIN;
1254}
1255
1256bool SensorService::TrimmedSensorEvent::isSentinel(const TrimmedSensorEvent& event) {
1257 return (event.mHour == INT32_MIN && event.mMin == INT32_MIN && event.mSec == INT32_MIN);
1258}
Aravind Akella444f2672015-05-07 12:40:52 -07001259// --------------------------------------------------------------------------
1260SensorService::CircularBuffer::CircularBuffer(int sensor_event_type) {
1261 mNextInd = 0;
Aravind Akella18d6d512015-06-18 14:18:28 -07001262 mBufSize = CIRCULAR_BUF_SIZE;
1263 if (sensor_event_type == SENSOR_TYPE_STEP_COUNTER ||
1264 sensor_event_type == SENSOR_TYPE_SIGNIFICANT_MOTION ||
1265 sensor_event_type == SENSOR_TYPE_ACCELEROMETER) {
1266 mBufSize = CIRCULAR_BUF_SIZE * 5;
1267 }
1268 mTrimmedSensorEventArr = new TrimmedSensorEvent *[mBufSize];
Aravind Akella444f2672015-05-07 12:40:52 -07001269 mSensorType = sensor_event_type;
Aravind Akella18d6d512015-06-18 14:18:28 -07001270 for (int i = 0; i < mBufSize; ++i) {
1271 mTrimmedSensorEventArr[i] = new TrimmedSensorEvent(mSensorType);
Aravind Akella444f2672015-05-07 12:40:52 -07001272 }
1273}
1274
1275void SensorService::CircularBuffer::addEvent(const sensors_event_t& sensor_event) {
1276 TrimmedSensorEvent *curr_event = mTrimmedSensorEventArr[mNextInd];
1277 curr_event->mTimestamp = sensor_event.timestamp;
1278 if (mSensorType == SENSOR_TYPE_STEP_COUNTER) {
1279 curr_event->mStepCounter = sensor_event.u64.step_counter;
1280 } else {
1281 memcpy(curr_event->mData, sensor_event.data,
1282 sizeof(float) * SensorService::getNumEventsForSensorType(mSensorType));
1283 }
1284 time_t rawtime = time(NULL);
1285 struct tm * timeinfo = localtime(&rawtime);
1286 curr_event->mHour = timeinfo->tm_hour;
1287 curr_event->mMin = timeinfo->tm_min;
1288 curr_event->mSec = timeinfo->tm_sec;
Aravind Akella18d6d512015-06-18 14:18:28 -07001289 mNextInd = (mNextInd + 1) % mBufSize;
Aravind Akella444f2672015-05-07 12:40:52 -07001290}
1291
1292void SensorService::CircularBuffer::printBuffer(String8& result) const {
1293 const int numData = SensorService::getNumEventsForSensorType(mSensorType);
1294 int i = mNextInd, eventNum = 1;
Aravind Akella18d6d512015-06-18 14:18:28 -07001295 result.appendFormat("last %d events = < ", mBufSize);
Aravind Akella444f2672015-05-07 12:40:52 -07001296 do {
Aravind Akella18d6d512015-06-18 14:18:28 -07001297 if (TrimmedSensorEvent::isSentinel(*mTrimmedSensorEventArr[i])) {
Aravind Akella444f2672015-05-07 12:40:52 -07001298 // Sentinel, ignore.
Aravind Akella18d6d512015-06-18 14:18:28 -07001299 i = (i + 1) % mBufSize;
Aravind Akella444f2672015-05-07 12:40:52 -07001300 continue;
1301 }
1302 result.appendFormat("%d) ", eventNum++);
1303 if (mSensorType == SENSOR_TYPE_STEP_COUNTER) {
1304 result.appendFormat("%llu,", mTrimmedSensorEventArr[i]->mStepCounter);
1305 } else {
1306 for (int j = 0; j < numData; ++j) {
1307 result.appendFormat("%5.1f,", mTrimmedSensorEventArr[i]->mData[j]);
1308 }
1309 }
1310 result.appendFormat("%lld %02d:%02d:%02d ", mTrimmedSensorEventArr[i]->mTimestamp,
1311 mTrimmedSensorEventArr[i]->mHour, mTrimmedSensorEventArr[i]->mMin,
1312 mTrimmedSensorEventArr[i]->mSec);
Aravind Akella18d6d512015-06-18 14:18:28 -07001313 i = (i + 1) % mBufSize;
Aravind Akella444f2672015-05-07 12:40:52 -07001314 } while (i != mNextInd);
1315 result.appendFormat(">\n");
1316}
1317
1318bool SensorService::CircularBuffer::populateLastEvent(sensors_event_t *event) {
Aravind Akella18d6d512015-06-18 14:18:28 -07001319 int lastEventInd = (mNextInd - 1 + mBufSize) % mBufSize;
Aravind Akella444f2672015-05-07 12:40:52 -07001320 // Check if the buffer is empty.
Aravind Akella18d6d512015-06-18 14:18:28 -07001321 if (TrimmedSensorEvent::isSentinel(*mTrimmedSensorEventArr[lastEventInd])) {
Aravind Akella444f2672015-05-07 12:40:52 -07001322 return false;
1323 }
1324 event->version = sizeof(sensors_event_t);
1325 event->type = mSensorType;
1326 event->timestamp = mTrimmedSensorEventArr[lastEventInd]->mTimestamp;
1327 if (mSensorType == SENSOR_TYPE_STEP_COUNTER) {
1328 event->u64.step_counter = mTrimmedSensorEventArr[lastEventInd]->mStepCounter;
1329 } else {
1330 memcpy(event->data, mTrimmedSensorEventArr[lastEventInd]->mData,
1331 sizeof(float) * SensorService::getNumEventsForSensorType(mSensorType));
1332 }
1333 return true;
1334}
1335
1336SensorService::CircularBuffer::~CircularBuffer() {
Aravind Akella18d6d512015-06-18 14:18:28 -07001337 for (int i = 0; i < mBufSize; ++i) {
Aravind Akella444f2672015-05-07 12:40:52 -07001338 delete mTrimmedSensorEventArr[i];
1339 }
1340 delete [] mTrimmedSensorEventArr;
1341}
1342
Mathias Agopianfc328812010-07-14 23:41:37 -07001343// ---------------------------------------------------------------------------
1344
1345SensorService::SensorEventConnection::SensorEventConnection(
Svetoslavb412f6e2015-04-29 16:50:41 -07001346 const sp<SensorService>& service, uid_t uid, String8 packageName, bool isDataInjectionMode,
1347 const String16& opPackageName)
Aravind Akella8a969552014-09-28 17:52:41 -07001348 : mService(service), mUid(uid), mWakeLockRefCount(0), mHasLooperCallbacks(false),
Svetoslavb412f6e2015-04-29 16:50:41 -07001349 mDead(false), mDataInjectionMode(isDataInjectionMode), mEventCache(NULL),
1350 mCacheSize(0), mMaxCacheSize(0), mPackageName(packageName), mOpPackageName(opPackageName) {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001351 mChannel = new BitTube(mService->mSocketBufferSize);
Aravind Akella56ae4262014-07-10 16:01:10 -07001352#if DEBUG_CONNECTIONS
1353 mEventsReceived = mEventsSentFromCache = mEventsSent = 0;
Aravind Akellae74baf62014-08-21 12:28:35 -07001354 mTotalAcksNeeded = mTotalAcksReceived = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -07001355#endif
Mathias Agopianfc328812010-07-14 23:41:37 -07001356}
1357
Aravind Akella56ae4262014-07-10 16:01:10 -07001358SensorService::SensorEventConnection::~SensorEventConnection() {
Steve Blocka5512372011-12-20 16:23:08 +00001359 ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this);
Aravind Akellae148bc22014-09-24 22:12:58 -07001360 mService->cleanupConnection(this);
Aravind Akella56ae4262014-07-10 16:01:10 -07001361 if (mEventCache != NULL) {
1362 delete mEventCache;
1363 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001364}
1365
Aravind Akella56ae4262014-07-10 16:01:10 -07001366void SensorService::SensorEventConnection::onFirstRef() {
1367 LooperCallback::onFirstRef();
Mathias Agopianfc328812010-07-14 23:41:37 -07001368}
1369
Aravind Akella9a844cf2014-02-11 18:58:52 -08001370bool SensorService::SensorEventConnection::needsWakeLock() {
1371 Mutex::Autolock _l(mConnectionLock);
Aravind Akella8a969552014-09-28 17:52:41 -07001372 return !mDead && mWakeLockRefCount > 0;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001373}
1374
Aravind Akellab4373ac2014-10-29 17:55:20 -07001375void SensorService::SensorEventConnection::resetWakeLockRefCount() {
1376 Mutex::Autolock _l(mConnectionLock);
1377 mWakeLockRefCount = 0;
1378}
1379
Aravind Akella4c8b9512013-09-05 17:03:38 -07001380void SensorService::SensorEventConnection::dump(String8& result) {
1381 Mutex::Autolock _l(mConnectionLock);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001382 result.appendFormat("Operating Mode: %s\n", mDataInjectionMode ? "DATA_INJECTION" : "NORMAL");
Aravind Akella18d6d512015-06-18 14:18:28 -07001383 result.appendFormat("\t %s | WakeLockRefCount %d | uid %d | cache size %d | "
1384 "max cache size %d\n", mPackageName.string(), mWakeLockRefCount, mUid, mCacheSize,
1385 mMaxCacheSize);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001386 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1387 const FlushInfo& flushInfo = mSensorInfo.valueAt(i);
Aravind Akella0ec20662014-09-14 17:29:48 -07001388 result.appendFormat("\t %s 0x%08x | status: %s | pending flush events %d \n",
Aravind Akella4c8b9512013-09-05 17:03:38 -07001389 mService->getSensorName(mSensorInfo.keyAt(i)).string(),
Aravind Akella6c2664a2014-08-13 12:24:50 -07001390 mSensorInfo.keyAt(i),
Aravind Akella4c8b9512013-09-05 17:03:38 -07001391 flushInfo.mFirstFlushPending ? "First flush pending" :
1392 "active",
Aravind Akella0ec20662014-09-14 17:29:48 -07001393 flushInfo.mPendingFlushEventsToSend);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001394 }
Aravind Akella0ec20662014-09-14 17:29:48 -07001395#if DEBUG_CONNECTIONS
1396 result.appendFormat("\t events recvd: %d | sent %d | cache %d | dropped %d |"
1397 " total_acks_needed %d | total_acks_recvd %d\n",
1398 mEventsReceived,
1399 mEventsSent,
1400 mEventsSentFromCache,
1401 mEventsReceived - (mEventsSentFromCache + mEventsSent + mCacheSize),
1402 mTotalAcksNeeded,
1403 mTotalAcksReceived);
1404#endif
Aravind Akella4c8b9512013-09-05 17:03:38 -07001405}
1406
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001407bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001408 Mutex::Autolock _l(mConnectionLock);
Svetoslavb412f6e2015-04-29 16:50:41 -07001409 if (!canAccessSensor(mService->getSensorFromHandle(handle),
1410 "Tried adding", mOpPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001411 return false;
1412 }
Aravind Akella4c8b9512013-09-05 17:03:38 -07001413 if (mSensorInfo.indexOfKey(handle) < 0) {
1414 mSensorInfo.add(handle, FlushInfo());
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001415 return true;
Mathias Agopianfc328812010-07-14 23:41:37 -07001416 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001417 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -07001418}
1419
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001420bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001421 Mutex::Autolock _l(mConnectionLock);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001422 if (mSensorInfo.removeItem(handle) >= 0) {
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001423 return true;
1424 }
1425 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -07001426}
1427
1428bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001429 Mutex::Autolock _l(mConnectionLock);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001430 return mSensorInfo.indexOfKey(handle) >= 0;
Mathias Agopianfc328812010-07-14 23:41:37 -07001431}
1432
1433bool SensorService::SensorEventConnection::hasAnySensor() const {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001434 Mutex::Autolock _l(mConnectionLock);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001435 return mSensorInfo.size() ? true : false;
1436}
1437
Aravind Akella8493b792014-09-08 15:45:47 -07001438bool SensorService::SensorEventConnection::hasOneShotSensors() const {
1439 Mutex::Autolock _l(mConnectionLock);
1440 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1441 const int handle = mSensorInfo.keyAt(i);
1442 if (mService->getSensorFromHandle(handle).getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1443 return true;
1444 }
1445 }
1446 return false;
1447}
1448
Aravind Akella4949c502015-02-11 15:54:35 -08001449String8 SensorService::SensorEventConnection::getPackageName() const {
1450 return mPackageName;
1451}
1452
Aravind Akella4c8b9512013-09-05 17:03:38 -07001453void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle,
1454 bool value) {
1455 Mutex::Autolock _l(mConnectionLock);
1456 ssize_t index = mSensorInfo.indexOfKey(handle);
1457 if (index >= 0) {
1458 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
1459 flushInfo.mFirstFlushPending = value;
1460 }
1461}
1462
Aravind Akella8a969552014-09-28 17:52:41 -07001463void SensorService::SensorEventConnection::updateLooperRegistration(const sp<Looper>& looper) {
1464 Mutex::Autolock _l(mConnectionLock);
1465 updateLooperRegistrationLocked(looper);
1466}
1467
1468void SensorService::SensorEventConnection::updateLooperRegistrationLocked(
1469 const sp<Looper>& looper) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001470 bool isConnectionActive = (mSensorInfo.size() > 0 && !mDataInjectionMode) ||
1471 mDataInjectionMode;
Aravind Akella8a969552014-09-28 17:52:41 -07001472 // If all sensors are unregistered OR Looper has encountered an error, we
1473 // can remove the Fd from the Looper if it has been previously added.
1474 if (!isConnectionActive || mDead) {
1475 if (mHasLooperCallbacks) {
1476 ALOGD_IF(DEBUG_CONNECTIONS, "%p removeFd fd=%d", this, mChannel->getSendFd());
1477 looper->removeFd(mChannel->getSendFd());
1478 mHasLooperCallbacks = false;
1479 }
1480 return;
1481 }
1482
1483 int looper_flags = 0;
1484 if (mCacheSize > 0) looper_flags |= ALOOPER_EVENT_OUTPUT;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001485 if (mDataInjectionMode) looper_flags |= ALOOPER_EVENT_INPUT;
Aravind Akella8a969552014-09-28 17:52:41 -07001486 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1487 const int handle = mSensorInfo.keyAt(i);
1488 if (mService->getSensorFromHandle(handle).isWakeUpSensor()) {
1489 looper_flags |= ALOOPER_EVENT_INPUT;
1490 break;
1491 }
1492 }
1493 // If flags is still set to zero, we don't need to add this fd to the Looper, if
1494 // the fd has already been added, remove it. This is likely to happen when ALL the
1495 // events stored in the cache have been sent to the corresponding app.
1496 if (looper_flags == 0) {
1497 if (mHasLooperCallbacks) {
1498 ALOGD_IF(DEBUG_CONNECTIONS, "removeFd fd=%d", mChannel->getSendFd());
1499 looper->removeFd(mChannel->getSendFd());
1500 mHasLooperCallbacks = false;
1501 }
1502 return;
1503 }
1504 // Add the file descriptor to the Looper for receiving acknowledegments if the app has
1505 // registered for wake-up sensors OR for sending events in the cache.
1506 int ret = looper->addFd(mChannel->getSendFd(), 0, looper_flags, this, NULL);
1507 if (ret == 1) {
1508 ALOGD_IF(DEBUG_CONNECTIONS, "%p addFd fd=%d", this, mChannel->getSendFd());
1509 mHasLooperCallbacks = true;
1510 } else {
1511 ALOGE("Looper::addFd failed ret=%d fd=%d", ret, mChannel->getSendFd());
1512 }
1513}
1514
1515void SensorService::SensorEventConnection::incrementPendingFlushCount(int32_t handle) {
1516 Mutex::Autolock _l(mConnectionLock);
1517 ssize_t index = mSensorInfo.indexOfKey(handle);
1518 if (index >= 0) {
1519 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
1520 flushInfo.mPendingFlushEventsToSend++;
1521 }
1522}
1523
Mathias Agopianfc328812010-07-14 23:41:37 -07001524status_t SensorService::SensorEventConnection::sendEvents(
Aravind Akella0ec20662014-09-14 17:29:48 -07001525 sensors_event_t const* buffer, size_t numEvents,
Aravind Akella8493b792014-09-08 15:45:47 -07001526 sensors_event_t* scratch,
1527 SensorEventConnection const * const * mapFlushEventsToConnections) {
Mathias Agopiancf510012010-07-22 16:18:10 -07001528 // filter out events not for this connection
Svetoslavb412f6e2015-04-29 16:50:41 -07001529 int count = 0;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001530 Mutex::Autolock _l(mConnectionLock);
Mathias Agopian3560fb22010-07-22 21:24:39 -07001531 if (scratch) {
1532 size_t i=0;
1533 while (i<numEvents) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001534 int32_t sensor_handle = buffer[i].sensor;
Aravind Akella724d91d2013-06-27 12:04:23 -07001535 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
1536 ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ",
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001537 buffer[i].meta_data.sensor);
Aravind Akella8a969552014-09-28 17:52:41 -07001538 // Setting sensor_handle to the correct sensor to ensure the sensor events per
1539 // connection are filtered correctly. buffer[i].sensor is zero for meta_data
1540 // events.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001541 sensor_handle = buffer[i].meta_data.sensor;
Aravind Akella724d91d2013-06-27 12:04:23 -07001542 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001543 ssize_t index = mSensorInfo.indexOfKey(sensor_handle);
Aravind Akella56ae4262014-07-10 16:01:10 -07001544 // Check if this connection has registered for this sensor. If not continue to the
1545 // next sensor_event.
1546 if (index < 0) {
1547 ++i;
1548 continue;
Aravind Akella4c8b9512013-09-05 17:03:38 -07001549 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001550
Aravind Akella56ae4262014-07-10 16:01:10 -07001551 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001552 // Check if there is a pending flush_complete event for this sensor on this connection.
Aravind Akella8493b792014-09-08 15:45:47 -07001553 if (buffer[i].type == SENSOR_TYPE_META_DATA && flushInfo.mFirstFlushPending == true &&
1554 this == mapFlushEventsToConnections[i]) {
1555 flushInfo.mFirstFlushPending = false;
1556 ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ",
1557 buffer[i].meta_data.sensor);
1558 ++i;
1559 continue;
Aravind Akella56ae4262014-07-10 16:01:10 -07001560 }
1561
1562 // If there is a pending flush complete event for this sensor on this connection,
1563 // ignore the event and proceed to the next.
1564 if (flushInfo.mFirstFlushPending) {
1565 ++i;
1566 continue;
1567 }
1568
1569 do {
Aravind Akella8493b792014-09-08 15:45:47 -07001570 // Keep copying events into the scratch buffer as long as they are regular
1571 // sensor_events are from the same sensor_handle OR they are flush_complete_events
1572 // from the same sensor_handle AND the current connection is mapped to the
1573 // corresponding flush_complete_event.
Aravind Akella56ae4262014-07-10 16:01:10 -07001574 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
Aravind Akella8493b792014-09-08 15:45:47 -07001575 if (this == mapFlushEventsToConnections[i]) {
Aravind Akella56ae4262014-07-10 16:01:10 -07001576 scratch[count++] = buffer[i];
Aravind Akella56ae4262014-07-10 16:01:10 -07001577 }
1578 ++i;
1579 } else {
1580 // Regular sensor event, just copy it to the scratch buffer.
Aravind Akella4c8b9512013-09-05 17:03:38 -07001581 scratch[count++] = buffer[i++];
Aravind Akella56ae4262014-07-10 16:01:10 -07001582 }
Aravind Akella8493b792014-09-08 15:45:47 -07001583 } while ((i<numEvents) && ((buffer[i].sensor == sensor_handle &&
1584 buffer[i].type != SENSOR_TYPE_META_DATA) ||
Aravind Akella56ae4262014-07-10 16:01:10 -07001585 (buffer[i].type == SENSOR_TYPE_META_DATA &&
Aravind Akella6c2664a2014-08-13 12:24:50 -07001586 buffer[i].meta_data.sensor == sensor_handle)));
Mathias Agopiancf510012010-07-22 16:18:10 -07001587 }
Mathias Agopian3560fb22010-07-22 21:24:39 -07001588 } else {
1589 scratch = const_cast<sensors_event_t *>(buffer);
1590 count = numEvents;
Mathias Agopiancf510012010-07-22 16:18:10 -07001591 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001592
Aravind Akella6c2664a2014-08-13 12:24:50 -07001593 sendPendingFlushEventsLocked();
Aravind Akella56ae4262014-07-10 16:01:10 -07001594 // Early return if there are no events for this connection.
1595 if (count == 0) {
1596 return status_t(NO_ERROR);
1597 }
1598
1599#if DEBUG_CONNECTIONS
1600 mEventsReceived += count;
1601#endif
1602 if (mCacheSize != 0) {
1603 // There are some events in the cache which need to be sent first. Copy this buffer to
1604 // the end of cache.
1605 if (mCacheSize + count <= mMaxCacheSize) {
1606 memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
1607 mCacheSize += count;
1608 } else {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001609 // Check if any new sensors have registered on this connection which may have increased
1610 // the max cache size that is desired.
1611 if (mCacheSize + count < computeMaxCacheSizeLocked()) {
1612 reAllocateCacheLocked(scratch, count);
1613 return status_t(NO_ERROR);
1614 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001615 // Some events need to be dropped.
1616 int remaningCacheSize = mMaxCacheSize - mCacheSize;
1617 if (remaningCacheSize != 0) {
1618 memcpy(&mEventCache[mCacheSize], scratch,
1619 remaningCacheSize * sizeof(sensors_event_t));
1620 }
1621 int numEventsDropped = count - remaningCacheSize;
1622 countFlushCompleteEventsLocked(mEventCache, numEventsDropped);
1623 // Drop the first "numEventsDropped" in the cache.
1624 memmove(mEventCache, &mEventCache[numEventsDropped],
1625 (mCacheSize - numEventsDropped) * sizeof(sensors_event_t));
1626
1627 // Copy the remainingEvents in scratch buffer to the end of cache.
1628 memcpy(&mEventCache[mCacheSize - numEventsDropped], scratch + remaningCacheSize,
1629 numEventsDropped * sizeof(sensors_event_t));
1630 }
1631 return status_t(NO_ERROR);
1632 }
1633
Aravind Akella6c2664a2014-08-13 12:24:50 -07001634 int index_wake_up_event = findWakeUpSensorEventLocked(scratch, count);
1635 if (index_wake_up_event >= 0) {
1636 scratch[index_wake_up_event].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1637 ++mWakeLockRefCount;
Aravind Akellae74baf62014-08-21 12:28:35 -07001638#if DEBUG_CONNECTIONS
1639 ++mTotalAcksNeeded;
1640#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001641 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001642
1643 // NOTE: ASensorEvent and sensors_event_t are the same type.
1644 ssize_t size = SensorEventQueue::write(mChannel,
1645 reinterpret_cast<ASensorEvent const*>(scratch), count);
1646 if (size < 0) {
1647 // Write error, copy events to local cache.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001648 if (index_wake_up_event >= 0) {
1649 // If there was a wake_up sensor_event, reset the flag.
1650 scratch[index_wake_up_event].flags &= ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
Aravind Akella0ec20662014-09-14 17:29:48 -07001651 if (mWakeLockRefCount > 0) {
1652 --mWakeLockRefCount;
1653 }
Aravind Akellae74baf62014-08-21 12:28:35 -07001654#if DEBUG_CONNECTIONS
1655 --mTotalAcksNeeded;
1656#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001657 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001658 if (mEventCache == NULL) {
1659 mMaxCacheSize = computeMaxCacheSizeLocked();
1660 mEventCache = new sensors_event_t[mMaxCacheSize];
1661 mCacheSize = 0;
1662 }
1663 memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
1664 mCacheSize += count;
1665
1666 // Add this file descriptor to the looper to get a callback when this fd is available for
1667 // writing.
Aravind Akella8a969552014-09-28 17:52:41 -07001668 updateLooperRegistrationLocked(mService->getLooper());
Aravind Akella56ae4262014-07-10 16:01:10 -07001669 return size;
1670 }
1671
1672#if DEBUG_CONNECTIONS
1673 if (size > 0) {
1674 mEventsSent += count;
1675 }
1676#endif
1677
1678 return size < 0 ? status_t(size) : status_t(NO_ERROR);
1679}
1680
Aravind Akella6c2664a2014-08-13 12:24:50 -07001681void SensorService::SensorEventConnection::reAllocateCacheLocked(sensors_event_t const* scratch,
1682 int count) {
1683 sensors_event_t *eventCache_new;
1684 const int new_cache_size = computeMaxCacheSizeLocked();
1685 // Allocate new cache, copy over events from the old cache & scratch, free up memory.
1686 eventCache_new = new sensors_event_t[new_cache_size];
1687 memcpy(eventCache_new, mEventCache, mCacheSize * sizeof(sensors_event_t));
1688 memcpy(&eventCache_new[mCacheSize], scratch, count * sizeof(sensors_event_t));
1689
1690 ALOGD_IF(DEBUG_CONNECTIONS, "reAllocateCacheLocked maxCacheSize=%d %d", mMaxCacheSize,
1691 new_cache_size);
1692
1693 delete mEventCache;
1694 mEventCache = eventCache_new;
1695 mCacheSize += count;
1696 mMaxCacheSize = new_cache_size;
1697}
1698
1699void SensorService::SensorEventConnection::sendPendingFlushEventsLocked() {
1700 ASensorEvent flushCompleteEvent;
Aravind Akella0ec20662014-09-14 17:29:48 -07001701 memset(&flushCompleteEvent, 0, sizeof(flushCompleteEvent));
Aravind Akella6c2664a2014-08-13 12:24:50 -07001702 flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
Aravind Akella6c2664a2014-08-13 12:24:50 -07001703 // Loop through all the sensors for this connection and check if there are any pending
1704 // flush complete events to be sent.
1705 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1706 FlushInfo& flushInfo = mSensorInfo.editValueAt(i);
1707 while (flushInfo.mPendingFlushEventsToSend > 0) {
Aravind Akella0ec20662014-09-14 17:29:48 -07001708 const int sensor_handle = mSensorInfo.keyAt(i);
1709 flushCompleteEvent.meta_data.sensor = sensor_handle;
Aravind Akellab4373ac2014-10-29 17:55:20 -07001710 bool wakeUpSensor = mService->getSensorFromHandle(sensor_handle).isWakeUpSensor();
1711 if (wakeUpSensor) {
1712 ++mWakeLockRefCount;
Aravind Akella0ec20662014-09-14 17:29:48 -07001713 flushCompleteEvent.flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1714 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001715 ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
1716 if (size < 0) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001717 if (wakeUpSensor) --mWakeLockRefCount;
Aravind Akella6c2664a2014-08-13 12:24:50 -07001718 return;
1719 }
1720 ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
1721 flushCompleteEvent.meta_data.sensor);
1722 flushInfo.mPendingFlushEventsToSend--;
1723 }
1724 }
1725}
1726
Aravind Akellab4373ac2014-10-29 17:55:20 -07001727void SensorService::SensorEventConnection::writeToSocketFromCache() {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001728 // At a time write at most half the size of the receiver buffer in SensorEventQueue OR
1729 // half the size of the socket buffer allocated in BitTube whichever is smaller.
1730 const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
1731 int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
Aravind Akellab4373ac2014-10-29 17:55:20 -07001732 Mutex::Autolock _l(mConnectionLock);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001733 // Send pending flush complete events (if any)
Aravind Akella6c2664a2014-08-13 12:24:50 -07001734 sendPendingFlushEventsLocked();
Aravind Akella56ae4262014-07-10 16:01:10 -07001735 for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001736 const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001737 int index_wake_up_event =
1738 findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite);
1739 if (index_wake_up_event >= 0) {
1740 mEventCache[index_wake_up_event + numEventsSent].flags |=
1741 WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1742 ++mWakeLockRefCount;
Aravind Akellae74baf62014-08-21 12:28:35 -07001743#if DEBUG_CONNECTIONS
1744 ++mTotalAcksNeeded;
1745#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001746 }
Aravind Akella4c8b9512013-09-05 17:03:38 -07001747
Aravind Akella56ae4262014-07-10 16:01:10 -07001748 ssize_t size = SensorEventQueue::write(mChannel,
1749 reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent),
Aravind Akella6c2664a2014-08-13 12:24:50 -07001750 numEventsToWrite);
Aravind Akella56ae4262014-07-10 16:01:10 -07001751 if (size < 0) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001752 if (index_wake_up_event >= 0) {
1753 // If there was a wake_up sensor_event, reset the flag.
1754 mEventCache[index_wake_up_event + numEventsSent].flags &=
1755 ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
Aravind Akella0ec20662014-09-14 17:29:48 -07001756 if (mWakeLockRefCount > 0) {
1757 --mWakeLockRefCount;
1758 }
Aravind Akellae74baf62014-08-21 12:28:35 -07001759#if DEBUG_CONNECTIONS
1760 --mTotalAcksNeeded;
1761#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001762 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001763 memmove(mEventCache, &mEventCache[numEventsSent],
1764 (mCacheSize - numEventsSent) * sizeof(sensors_event_t));
1765 ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ",
Aravind Akella6c2664a2014-08-13 12:24:50 -07001766 numEventsSent, mCacheSize);
Aravind Akella56ae4262014-07-10 16:01:10 -07001767 mCacheSize -= numEventsSent;
Aravind Akella56ae4262014-07-10 16:01:10 -07001768 return;
1769 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001770 numEventsSent += numEventsToWrite;
Aravind Akella56ae4262014-07-10 16:01:10 -07001771#if DEBUG_CONNECTIONS
Aravind Akella6c2664a2014-08-13 12:24:50 -07001772 mEventsSentFromCache += numEventsToWrite;
Aravind Akella56ae4262014-07-10 16:01:10 -07001773#endif
Aravind Akellab4099e72013-10-15 15:43:10 -07001774 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001775 ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize);
1776 // All events from the cache have been sent. Reset cache size to zero.
1777 mCacheSize = 0;
Aravind Akella8a969552014-09-28 17:52:41 -07001778 // There are no more events in the cache. We don't need to poll for write on the fd.
1779 // Update Looper registration.
1780 updateLooperRegistrationLocked(mService->getLooper());
Mathias Agopianfc328812010-07-14 23:41:37 -07001781}
1782
Aravind Akellac551eac2013-10-14 17:04:42 -07001783void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
Aravind Akella0ec20662014-09-14 17:29:48 -07001784 sensors_event_t const* scratch, const int numEventsDropped) {
Aravind Akella4c8b9512013-09-05 17:03:38 -07001785 ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001786 // Count flushComplete events in the events that are about to the dropped. These will be sent
1787 // separately before the next batch of events.
1788 for (int j = 0; j < numEventsDropped; ++j) {
1789 if (scratch[j].type == SENSOR_TYPE_META_DATA) {
1790 FlushInfo& flushInfo = mSensorInfo.editValueFor(scratch[j].meta_data.sensor);
1791 flushInfo.mPendingFlushEventsToSend++;
1792 ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
1793 flushInfo.mPendingFlushEventsToSend);
1794 }
1795 }
1796 return;
1797}
1798
Aravind Akella6c2664a2014-08-13 12:24:50 -07001799int SensorService::SensorEventConnection::findWakeUpSensorEventLocked(
1800 sensors_event_t const* scratch, const int count) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001801 for (int i = 0; i < count; ++i) {
1802 if (mService->isWakeUpSensorEvent(scratch[i])) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001803 return i;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001804 }
1805 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001806 return -1;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001807}
1808
Mathias Agopianb3989272011-10-20 18:42:02 -07001809sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
Mathias Agopianfc328812010-07-14 23:41:37 -07001810{
1811 return mChannel;
1812}
1813
1814status_t SensorService::SensorEventConnection::enableDisable(
Aravind Akella724d91d2013-06-27 12:04:23 -07001815 int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
1816 int reservedFlags)
Mathias Agopianfc328812010-07-14 23:41:37 -07001817{
1818 status_t err;
1819 if (enabled) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001820 err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
Svetoslavb412f6e2015-04-29 16:50:41 -07001821 reservedFlags, mOpPackageName);
Aravind Akella56ae4262014-07-10 16:01:10 -07001822
Mathias Agopianfc328812010-07-14 23:41:37 -07001823 } else {
1824 err = mService->disable(this, handle);
1825 }
1826 return err;
1827}
1828
1829status_t SensorService::SensorEventConnection::setEventRate(
Aravind Akella724d91d2013-06-27 12:04:23 -07001830 int handle, nsecs_t samplingPeriodNs)
Mathias Agopianfc328812010-07-14 23:41:37 -07001831{
Svetoslavb412f6e2015-04-29 16:50:41 -07001832 return mService->setEventRate(this, handle, samplingPeriodNs, mOpPackageName);
Mathias Agopianfc328812010-07-14 23:41:37 -07001833}
1834
Aravind Akella701166d2013-10-08 14:59:26 -07001835status_t SensorService::SensorEventConnection::flush() {
Svetoslavb412f6e2015-04-29 16:50:41 -07001836 return mService->flushSensor(this, mOpPackageName);
Aravind Akella724d91d2013-06-27 12:04:23 -07001837}
Aravind Akella4c8b9512013-09-05 17:03:38 -07001838
Aravind Akella8a969552014-09-28 17:52:41 -07001839int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* /*data*/) {
Aravind Akella56ae4262014-07-10 16:01:10 -07001840 if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) {
Aravind Akella8a969552014-09-28 17:52:41 -07001841 {
1842 // If the Looper encounters some error, set the flag mDead, reset mWakeLockRefCount,
1843 // and remove the fd from Looper. Call checkWakeLockState to know if SensorService
1844 // can release the wake-lock.
1845 ALOGD_IF(DEBUG_CONNECTIONS, "%p Looper error %d", this, fd);
1846 Mutex::Autolock _l(mConnectionLock);
1847 mDead = true;
1848 mWakeLockRefCount = 0;
1849 updateLooperRegistrationLocked(mService->getLooper());
1850 }
1851 mService->checkWakeLockState();
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001852 if (mDataInjectionMode) {
1853 // If the Looper has encountered some error in data injection mode, reset SensorService
1854 // back to normal mode.
1855 mService->resetToNormalMode();
1856 mDataInjectionMode = false;
1857 }
Aravind Akella8a969552014-09-28 17:52:41 -07001858 return 1;
Aravind Akella56ae4262014-07-10 16:01:10 -07001859 }
1860
1861 if (events & ALOOPER_EVENT_INPUT) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001862 unsigned char buf[sizeof(sensors_event_t)];
1863 ssize_t numBytesRead = ::recv(fd, buf, sizeof(buf), MSG_DONTWAIT);
Aravind Akella56ae4262014-07-10 16:01:10 -07001864 {
1865 Mutex::Autolock _l(mConnectionLock);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001866 if (numBytesRead == sizeof(sensors_event_t)) {
1867 if (!mDataInjectionMode) {
1868 ALOGE("Data injected in normal mode, dropping event"
1869 "package=%s uid=%d", mPackageName.string(), mUid);
1870 // Unregister call backs.
1871 return 0;
1872 }
1873 SensorDevice& dev(SensorDevice::getInstance());
1874 sensors_event_t sensor_event;
1875 memset(&sensor_event, 0, sizeof(sensor_event));
1876 memcpy(&sensor_event, buf, sizeof(sensors_event_t));
1877 Sensor sensor = mService->getSensorFromHandle(sensor_event.sensor);
1878 sensor_event.type = sensor.getType();
Svetoslavb412f6e2015-04-29 16:50:41 -07001879 dev.injectSensorData(&sensor_event);
Aravind Akellae74baf62014-08-21 12:28:35 -07001880#if DEBUG_CONNECTIONS
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001881 ++mEventsReceived;
Aravind Akellae74baf62014-08-21 12:28:35 -07001882#endif
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001883 } else if (numBytesRead == sizeof(uint32_t)) {
1884 uint32_t numAcks = 0;
Aravind Akella08f04bf2015-05-08 15:59:23 -07001885 memcpy(&numAcks, buf, numBytesRead);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001886 // Sanity check to ensure there are no read errors in recv, numAcks is always
1887 // within the range and not zero. If any of the above don't hold reset
1888 // mWakeLockRefCount to zero.
1889 if (numAcks > 0 && numAcks < mWakeLockRefCount) {
1890 mWakeLockRefCount -= numAcks;
1891 } else {
1892 mWakeLockRefCount = 0;
1893 }
1894#if DEBUG_CONNECTIONS
1895 mTotalAcksReceived += numAcks;
1896#endif
1897 } else {
1898 // Read error, reset wakelock refcount.
1899 mWakeLockRefCount = 0;
1900 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001901 }
1902 // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released
1903 // here as checkWakeLockState() will need it.
1904 if (mWakeLockRefCount == 0) {
1905 mService->checkWakeLockState();
1906 }
1907 // continue getting callbacks.
1908 return 1;
1909 }
1910
1911 if (events & ALOOPER_EVENT_OUTPUT) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001912 // send sensor data that is stored in mEventCache for this connection.
1913 mService->sendEventsFromCache(this);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001914 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001915 return 1;
1916}
1917
1918int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
Svetoslavb412f6e2015-04-29 16:50:41 -07001919 size_t fifoWakeUpSensors = 0;
1920 size_t fifoNonWakeUpSensors = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -07001921 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1922 const Sensor& sensor = mService->getSensorFromHandle(mSensorInfo.keyAt(i));
1923 if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) {
1924 // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and
1925 // non wake_up sensors.
1926 if (sensor.isWakeUpSensor()) {
1927 fifoWakeUpSensors += sensor.getFifoReservedEventCount();
1928 } else {
1929 fifoNonWakeUpSensors += sensor.getFifoReservedEventCount();
1930 }
1931 } else {
1932 // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors.
1933 if (sensor.isWakeUpSensor()) {
1934 fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ?
1935 fifoWakeUpSensors : sensor.getFifoMaxEventCount();
1936
1937 } else {
1938 fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ?
1939 fifoNonWakeUpSensors : sensor.getFifoMaxEventCount();
1940
1941 }
1942 }
1943 }
1944 if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) {
1945 // It is extremely unlikely that there is a write failure in non batch mode. Return a cache
Aravind Akella6c2664a2014-08-13 12:24:50 -07001946 // size that is equal to that of the batch mode.
Aravind Akellae74baf62014-08-21 12:28:35 -07001947 // ALOGW("Write failure in non-batch mode");
Aravind Akella6c2664a2014-08-13 12:24:50 -07001948 return MAX_SOCKET_BUFFER_SIZE_BATCHED/sizeof(sensors_event_t);
Aravind Akella56ae4262014-07-10 16:01:10 -07001949 }
1950 return fifoWakeUpSensors + fifoNonWakeUpSensors;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001951}
1952
Mathias Agopianfc328812010-07-14 23:41:37 -07001953// ---------------------------------------------------------------------------
1954}; // namespace android
1955