blob: 3d985dcebb1559f9aab676f6107db3e312f32f10 [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
34#include <binder/BinderService.h>
Mathias Agopian451beee2010-07-19 15:03:55 -070035#include <binder/IServiceManager.h>
Mathias Agopian1cb13462011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070037
38#include <gui/ISensorServer.h>
39#include <gui/ISensorEventConnection.h>
Mathias Agopian907103b2012-04-02 18:38:02 -070040#include <gui/SensorEventQueue.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070041
42#include <hardware/sensors.h>
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070043#include <hardware_legacy/power.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070044
Mathias Agopian787ac1b2012-09-18 18:49:18 -070045#include "BatteryService.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070046#include "CorrectedGyroSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080047#include "GravitySensor.h"
48#include "LinearAccelerationSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070049#include "OrientationSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080050#include "RotationVectorSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070051#include "SensorFusion.h"
52#include "SensorService.h"
Mathias Agopianfc328812010-07-14 23:41:37 -070053
54namespace android {
55// ---------------------------------------------------------------------------
56
Mathias Agopian33015422011-05-27 18:18:13 -070057/*
58 * Notes:
59 *
60 * - what about a gyro-corrected magnetic-field sensor?
Mathias Agopian33015422011-05-27 18:18:13 -070061 * - run mag sensor from time to time to force calibration
62 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
63 *
64 */
65
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070066const char* SensorService::WAKE_LOCK_NAME = "SensorService";
Aravind Akellaa9e6cc32015-04-16 18:57:31 -070067// Permissions.
68static const String16 sDataInjectionPermission("android.permission.HARDWARE_TEST");
69static 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;
159 for (int i = 0; i < mSensorList.size(); ++i) {
160 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 Akellab4373ac2014-10-29 17:55:20 -0700197 mAckReceiver = new SensorEventAckReceiver(this);
198 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700199 mInitCheck = NO_ERROR;
Aravind Akella7830ef32014-10-07 14:13:12 -0700200 run("SensorService", PRIORITY_URGENT_DISPLAY);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700201 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700202 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700203}
204
Mathias Agopian03193062013-05-10 19:32:39 -0700205Sensor SensorService::registerSensor(SensorInterface* s)
Mathias Agopianf001c922010-11-11 17:58:51 -0800206{
207 sensors_event_t event;
208 memset(&event, 0, sizeof(event));
209
210 const Sensor sensor(s->getSensor());
211 // add to the sensor list (returned to clients)
212 mSensorList.add(sensor);
213 // add to our handle->SensorInterface mapping
214 mSensorMap.add(sensor.getHandle(), s);
215 // create an entry in the mLastEventSeen array
Aravind Akella444f2672015-05-07 12:40:52 -0700216 mLastEventSeen.add(sensor.getHandle(), NULL);
Mathias Agopian03193062013-05-10 19:32:39 -0700217
218 return sensor;
Mathias Agopianf001c922010-11-11 17:58:51 -0800219}
220
Mathias Agopian03193062013-05-10 19:32:39 -0700221Sensor SensorService::registerVirtualSensor(SensorInterface* s)
Mathias Agopianf001c922010-11-11 17:58:51 -0800222{
Mathias Agopian03193062013-05-10 19:32:39 -0700223 Sensor sensor = registerSensor(s);
Mathias Agopianf001c922010-11-11 17:58:51 -0800224 mVirtualSensorList.add( s );
Mathias Agopian03193062013-05-10 19:32:39 -0700225 return sensor;
Mathias Agopianf001c922010-11-11 17:58:51 -0800226}
227
Mathias Agopianfc328812010-07-14 23:41:37 -0700228SensorService::~SensorService()
229{
Mathias Agopianf001c922010-11-11 17:58:51 -0800230 for (size_t i=0 ; i<mSensorMap.size() ; i++)
231 delete mSensorMap.valueAt(i);
Mathias Agopianfc328812010-07-14 23:41:37 -0700232}
233
Aravind Akella4949c502015-02-11 15:54:35 -0800234status_t SensorService::dump(int fd, const Vector<String16>& args)
Mathias Agopianfc328812010-07-14 23:41:37 -0700235{
Mathias Agopianfc328812010-07-14 23:41:37 -0700236 String8 result;
Mathias Agopian1cb13462011-06-27 16:05:52 -0700237 if (!PermissionCache::checkCallingPermission(sDump)) {
Mathias Agopianba02cd22013-07-03 16:20:57 -0700238 result.appendFormat("Permission Denial: "
Aravind Akella70018042014-04-07 22:52:37 +0000239 "can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700240 IPCThreadState::self()->getCallingPid(),
241 IPCThreadState::self()->getCallingUid());
Aravind Akella444f2672015-05-07 12:40:52 -0700242 } else {
Aravind Akella4949c502015-02-11 15:54:35 -0800243 if (args.size() > 1) {
244 return INVALID_OPERATION;
245 }
246 Mutex::Autolock _l(mLock);
247 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akella444f2672015-05-07 12:40:52 -0700248 if (args.size() == 1 && args[0] == String16("restrict")) {
249 // If already in restricted mode. Ignore.
250 if (mCurrentOperatingMode == RESTRICTED) {
251 return status_t(NO_ERROR);
252 }
253 // If in any mode other than normal, ignore.
254 if (mCurrentOperatingMode != NORMAL) {
255 return INVALID_OPERATION;
256 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700257 mCurrentOperatingMode = RESTRICTED;
Aravind Akella4949c502015-02-11 15:54:35 -0800258 dev.disableAllSensors();
259 // Clear all pending flush connections for all active sensors. If one of the active
260 // connections has called flush() and the underlying sensor has been disabled before a
261 // flush complete event is returned, we need to remove the connection from this queue.
262 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
263 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
264 }
Aravind Akella444f2672015-05-07 12:40:52 -0700265 return status_t(NO_ERROR);
266 } else if (args.size() == 1 && args[0] == String16("enable")) {
267 // If currently in restricted mode, reset back to NORMAL mode else ignore.
268 if (mCurrentOperatingMode == RESTRICTED) {
269 mCurrentOperatingMode = NORMAL;
270 dev.enableAllSensors();
271 }
272 return status_t(NO_ERROR);
273 } else {
274 // Default dump the sensor list and debugging information.
275 result.append("Sensor List:\n");
276 for (size_t i=0 ; i<mSensorList.size() ; i++) {
277 const Sensor& s(mSensorList[i]);
278 result.appendFormat(
279 "%-15s| %-10s| version=%d |%-20s| 0x%08x | \"%s\" | type=%d |",
280 s.getName().string(),
281 s.getVendor().string(),
282 s.getVersion(),
283 s.getStringType().string(),
284 s.getHandle(),
285 s.getRequiredPermission().string(),
286 s.getType());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700287
Aravind Akella444f2672015-05-07 12:40:52 -0700288 const int reportingMode = s.getReportingMode();
289 if (reportingMode == AREPORTING_MODE_CONTINUOUS) {
290 result.append(" continuous | ");
291 } else if (reportingMode == AREPORTING_MODE_ON_CHANGE) {
292 result.append(" on-change | ");
293 } else if (reportingMode == AREPORTING_MODE_ONE_SHOT) {
294 result.append(" one-shot | ");
295 } else {
296 result.append(" special-trigger | ");
297 }
298
299 if (s.getMaxDelay() > 0) {
300 result.appendFormat("minRate=%.2fHz | ", 1e6f / s.getMaxDelay());
301 } else {
302 result.appendFormat("maxDelay=%dus |", s.getMaxDelay());
303 }
304
305 if (s.getMinDelay() > 0) {
306 result.appendFormat("maxRate=%.2fHz | ", 1e6f / s.getMinDelay());
307 } else {
308 result.appendFormat("minDelay=%dus |", s.getMinDelay());
309 }
310
311 if (s.getFifoMaxEventCount() > 0) {
312 result.appendFormat("FifoMax=%d events | ",
313 s.getFifoMaxEventCount());
314 } else {
315 result.append("no batching | ");
316 }
317
318 if (s.isWakeUpSensor()) {
319 result.appendFormat("wakeUp | ");
320 } else {
321 result.appendFormat("non-wakeUp | ");
322 }
323
324 const CircularBuffer* buf = mLastEventSeen.valueFor(s.getHandle());
325 if (buf != NULL && s.getRequiredPermission().isEmpty()) {
326 buf->printBuffer(result);
327 } else {
328 result.append("last=<> \n");
329 }
330 result.append("\n");
331 }
332 SensorFusion::getInstance().dump(result);
333 SensorDevice::getInstance().dump(result);
334
335 result.append("Active sensors:\n");
336 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
337 int handle = mActiveSensors.keyAt(i);
338 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
339 getSensorName(handle).string(),
340 handle,
341 mActiveSensors.valueAt(i)->getNumConnections());
Aravind Akella6c2664a2014-08-13 12:24:50 -0700342 }
343
Aravind Akella444f2672015-05-07 12:40:52 -0700344 result.appendFormat("Socket Buffer size = %d events\n",
345 mSocketBufferSize/sizeof(sensors_event_t));
346 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" : "not held");
347 result.appendFormat("Mode :");
348 switch(mCurrentOperatingMode) {
349 case NORMAL:
350 result.appendFormat(" NORMAL\n");
351 break;
352 case RESTRICTED:
353 result.appendFormat(" RESTRICTED\n");
354 break;
355 case DATA_INJECTION:
356 result.appendFormat(" DATA_INJECTION\n");
Mathias Agopianba02cd22013-07-03 16:20:57 -0700357 }
Aravind Akella444f2672015-05-07 12:40:52 -0700358 result.appendFormat("%zd active connections\n", mActiveConnections.size());
Aravind Akella0e025c52014-06-03 19:19:57 -0700359
Aravind Akella444f2672015-05-07 12:40:52 -0700360 for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
361 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
362 if (connection != 0) {
363 result.appendFormat("Connection Number: %zu \n", i);
364 connection->dump(result);
365 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700366 }
367 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700368 }
369 write(fd, result.string(), result.size());
370 return NO_ERROR;
371}
372
Aravind Akella9a844cf2014-02-11 18:58:52 -0800373void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700374 sensors_event_t const* buffer, const int count) {
375 for (int i=0 ; i<count ; i++) {
376 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700377 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
378 handle = buffer[i].meta_data.sensor;
379 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700380 if (connection->hasSensor(handle)) {
381 SensorInterface* sensor = mSensorMap.valueFor(handle);
382 // If this buffer has an event from a one_shot sensor and this connection is registered
383 // for this particular one_shot sensor, try cleaning up the connection.
384 if (sensor != NULL &&
385 sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
386 sensor->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800387 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700388 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700389
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700390 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700391 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700392}
393
Mathias Agopianfc328812010-07-14 23:41:37 -0700394bool SensorService::threadLoop()
395{
Steve Blocka5512372011-12-20 16:23:08 +0000396 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700397
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700398 // each virtual sensor could generate an event per "real" event, that's why we need
399 // to size numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT.
400 // in practice, this is too aggressive, but guaranteed to be enough.
401 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
402 const size_t numEventMax = minBufferSize / (1 + mVirtualSensorList.size());
403
Mathias Agopianf001c922010-11-11 17:58:51 -0800404 SensorDevice& device(SensorDevice::getInstance());
405 const size_t vcount = mVirtualSensorList.size();
Mathias Agopianfc328812010-07-14 23:41:37 -0700406
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700407 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700408 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700409 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
410 if (count < 0) {
Steve Blockf5a12302012-01-06 19:20:56 +0000411 ALOGE("sensor poll failed (%s)", strerror(-count));
Mathias Agopianfc328812010-07-14 23:41:37 -0700412 break;
413 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700414
415 // Reset sensors_event_t.flags to zero for all events in the buffer.
416 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700417 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700418 }
Aravind Akellae148bc22014-09-24 22:12:58 -0700419
420 // Make a copy of the connection vector as some connections may be removed during the
421 // course of this loop (especially when one-shot sensor events are present in the
422 // sensor_event buffer). Promote all connections to StrongPointers before the lock is
423 // acquired. If the destructor of the sp gets called when the lock is acquired, it may
424 // result in a deadlock as ~SensorEventConnection() needs to acquire mLock again for
425 // cleanup. So copy all the strongPointers to a vector before the lock is acquired.
426 SortedVector< sp<SensorEventConnection> > activeConnections;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700427 populateActiveConnections(&activeConnections);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800428 Mutex::Autolock _l(mLock);
429 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
430 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
431 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
432 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
433 // releasing the wakelock.
434 bool bufferHasWakeUpEvent = false;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700435 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700436 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800437 bufferHasWakeUpEvent = true;
438 break;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700439 }
440 }
441
Aravind Akella9a844cf2014-02-11 18:58:52 -0800442 if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700443 setWakeLockAcquiredLocked(true);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800444 }
Aravind Akella8493b792014-09-08 15:45:47 -0700445 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800446
Mathias Agopianf001c922010-11-11 17:58:51 -0800447 // handle virtual sensors
448 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700449 sensors_event_t const * const event = mSensorEventBuffer;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800450 const size_t activeVirtualSensorCount = mActiveVirtualSensors.size();
Mathias Agopianf001c922010-11-11 17:58:51 -0800451 if (activeVirtualSensorCount) {
452 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700453 SensorFusion& fusion(SensorFusion::getInstance());
454 if (fusion.isEnabled()) {
455 for (size_t i=0 ; i<size_t(count) ; i++) {
456 fusion.process(event[i]);
457 }
458 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700459 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800460 for (size_t j=0 ; j<activeVirtualSensorCount ; j++) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700461 if (count + k >= minBufferSize) {
462 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700463 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700464 count, k, minBufferSize);
465 break;
466 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800467 sensors_event_t out;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800468 SensorInterface* si = mActiveVirtualSensors.valueAt(j);
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700469 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700470 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800471 k++;
472 }
473 }
474 }
475 if (k) {
476 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700477 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800478 count += k;
479 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700480 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700481 }
482 }
483 }
484
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700485 // handle backward compatibility for RotationVector sensor
486 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
487 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700488 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700489 // All the 4 components of the quaternion should be available
490 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700491 mSensorEventBuffer[i].data[4] = -1;
492 }
493 }
494 }
495
496 // Map flush_complete_events in the buffer to SensorEventConnections which called
497 // flush on the hardware sensor. mapFlushEventsToConnections[i] will be the
498 // SensorEventConnection mapped to the corresponding flush_complete_event in
499 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
500 for (int i = 0; i < count; ++i) {
501 mMapFlushEventsToConnections[i] = NULL;
502 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
503 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
504 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
505 if (rec != NULL) {
506 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
507 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700508 }
509 }
510 }
511
Aravind Akella9a844cf2014-02-11 18:58:52 -0800512 // Send our events to clients. Check the state of wake lock for each client and release the
513 // lock if none of the clients need it.
514 bool needsWakeLock = false;
Aravind Akella8493b792014-09-08 15:45:47 -0700515 size_t numConnections = activeConnections.size();
516 for (size_t i=0 ; i < numConnections; ++i) {
Aravind Akellae148bc22014-09-24 22:12:58 -0700517 if (activeConnections[i] != 0) {
518 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
Aravind Akella8493b792014-09-08 15:45:47 -0700519 mMapFlushEventsToConnections);
Aravind Akellae148bc22014-09-24 22:12:58 -0700520 needsWakeLock |= activeConnections[i]->needsWakeLock();
Aravind Akella8493b792014-09-08 15:45:47 -0700521 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
522 // Early check for one-shot sensors.
Aravind Akellae148bc22014-09-24 22:12:58 -0700523 if (activeConnections[i]->hasOneShotSensors()) {
524 cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
525 count);
Aravind Akella8493b792014-09-08 15:45:47 -0700526 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800527 }
528 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700529
Aravind Akella9a844cf2014-02-11 18:58:52 -0800530 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700531 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800532 }
Aravind Akella8493b792014-09-08 15:45:47 -0700533 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -0700534
Steve Block3c20fbe2012-01-05 23:22:43 +0000535 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -0800536 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -0700537 return false;
538}
539
Aravind Akella56ae4262014-07-10 16:01:10 -0700540sp<Looper> SensorService::getLooper() const {
541 return mLooper;
542}
543
Aravind Akellab4373ac2014-10-29 17:55:20 -0700544void SensorService::resetAllWakeLockRefCounts() {
545 SortedVector< sp<SensorEventConnection> > activeConnections;
546 populateActiveConnections(&activeConnections);
547 {
548 Mutex::Autolock _l(mLock);
549 for (size_t i=0 ; i < activeConnections.size(); ++i) {
550 if (activeConnections[i] != 0) {
551 activeConnections[i]->resetWakeLockRefCount();
552 }
553 }
554 setWakeLockAcquiredLocked(false);
555 }
556}
557
558void SensorService::setWakeLockAcquiredLocked(bool acquire) {
559 if (acquire) {
560 if (!mWakeLockAcquired) {
561 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
562 mWakeLockAcquired = true;
563 }
564 mLooper->wake();
565 } else {
566 if (mWakeLockAcquired) {
567 release_wake_lock(WAKE_LOCK_NAME);
568 mWakeLockAcquired = false;
569 }
570 }
571}
572
Aravind Akellab4373ac2014-10-29 17:55:20 -0700573bool SensorService::isWakeLockAcquired() {
574 Mutex::Autolock _l(mLock);
575 return mWakeLockAcquired;
576}
577
Aravind Akella56ae4262014-07-10 16:01:10 -0700578bool SensorService::SensorEventAckReceiver::threadLoop() {
579 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -0700580 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -0700581 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700582 bool wakeLockAcquired = mService->isWakeLockAcquired();
583 int timeout = -1;
584 if (wakeLockAcquired) timeout = 5000;
585 int ret = looper->pollOnce(timeout);
586 if (ret == ALOOPER_POLL_TIMEOUT) {
587 mService->resetAllWakeLockRefCounts();
588 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700589 } while(!Thread::exitPending());
590 return false;
591}
592
Aravind Akella9a844cf2014-02-11 18:58:52 -0800593void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -0800594 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -0800595 for (size_t i = 0; i < count; i++) {
Aravind Akella444f2672015-05-07 12:40:52 -0700596 if (buffer[i].type != SENSOR_TYPE_META_DATA) {
597 CircularBuffer* &circular_buf = mLastEventSeen.editValueFor(buffer[i].sensor);
598 if (circular_buf == NULL) {
599 circular_buf = new CircularBuffer(buffer[i].type);
Aravind Akella4b847042014-03-03 19:02:46 -0800600 }
Aravind Akella444f2672015-05-07 12:40:52 -0700601 circular_buf->addEvent(buffer[i]);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800602 }
603 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800604}
605
Mathias Agopianf001c922010-11-11 17:58:51 -0800606void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count)
607{
608 struct compar {
609 static int cmp(void const* lhs, void const* rhs) {
610 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
611 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -0700612 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -0800613 }
614 };
615 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
616}
617
Mathias Agopian5d270722010-07-19 15:20:39 -0700618String8 SensorService::getSensorName(int handle) const {
Mathias Agopian010e4222011-06-08 20:06:50 -0700619 size_t count = mUserSensorList.size();
Mathias Agopian5d270722010-07-19 15:20:39 -0700620 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian010e4222011-06-08 20:06:50 -0700621 const Sensor& sensor(mUserSensorList[i]);
Mathias Agopian5d270722010-07-19 15:20:39 -0700622 if (sensor.getHandle() == handle) {
623 return sensor.getName();
624 }
625 }
626 String8 result("unknown");
627 return result;
628}
629
Aravind Akellab4099e72013-10-15 15:43:10 -0700630bool SensorService::isVirtualSensor(int handle) const {
631 SensorInterface* sensor = mSensorMap.valueFor(handle);
632 return sensor->isVirtual();
633}
634
Aravind Akella9a844cf2014-02-11 18:58:52 -0800635bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -0700636 int handle = event.sensor;
637 if (event.type == SENSOR_TYPE_META_DATA) {
638 handle = event.meta_data.sensor;
639 }
640 SensorInterface* sensor = mSensorMap.valueFor(handle);
641 return sensor != NULL && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -0800642}
643
Aravind Akella6c2664a2014-08-13 12:24:50 -0700644SensorService::SensorRecord * SensorService::getSensorRecord(int handle) {
645 return mActiveSensors.valueFor(handle);
646}
647
Mathias Agopianfc328812010-07-14 23:41:37 -0700648Vector<Sensor> SensorService::getSensorList()
649{
Mathias Agopian33264862012-06-28 19:46:54 -0700650 char value[PROPERTY_VALUE_MAX];
651 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +0000652 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
653 mUserSensorListDebug : mUserSensorList;
654 Vector<Sensor> accessibleSensorList;
655 for (size_t i = 0; i < initialSensorList.size(); i++) {
656 Sensor sensor = initialSensorList[i];
657 if (canAccessSensor(sensor)) {
658 accessibleSensorList.add(sensor);
659 } else {
Bernhard Rosenkränzer5f619932014-11-17 21:06:20 +0100660 ALOGI("Skipped sensor %s because it requires permission %s",
661 sensor.getName().string(),
662 sensor.getRequiredPermission().string());
Aravind Akella70018042014-04-07 22:52:37 +0000663 }
Mathias Agopian33264862012-06-28 19:46:54 -0700664 }
Aravind Akella70018042014-04-07 22:52:37 +0000665 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -0700666}
667
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700668sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
669 int requestedMode) {
670 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
671 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
672 return NULL;
673 }
674 // DATA_INJECTION mode needs to have the required permissions set.
675 if (requestedMode == DATA_INJECTION && !hasDataInjectionPermissions()) {
676 return NULL;
677 }
678
679 Mutex::Autolock _l(mLock);
Mathias Agopian5307d172012-09-18 17:02:43 -0700680 uid_t uid = IPCThreadState::self()->getCallingUid();
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700681 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, packageName,
682 requestedMode == DATA_INJECTION));
683 if (requestedMode == DATA_INJECTION) {
684 if (mActiveConnections.indexOf(result) < 0) {
685 mActiveConnections.add(result);
686 }
687 // Add the associated file descriptor to the Looper for polling whenever there is data to
688 // be injected.
689 result->updateLooperRegistration(mLooper);
690 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700691 return result;
692}
693
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700694status_t SensorService::enableDataInjection(int requestedMode) {
695 if (!hasDataInjectionPermissions()) {
696 return INVALID_OPERATION;
697 }
698 Mutex::Autolock _l(mLock);
699 ALOGD_IF(DEBUG_CONNECTIONS, "SensorService::enableDataInjection %d", requestedMode);
700 SensorDevice& dev(SensorDevice::getInstance());
701 status_t err(NO_ERROR);
702 if (requestedMode == DATA_INJECTION) {
703 if (mCurrentOperatingMode == NORMAL) {
704 dev.disableAllSensors();
705 err = dev.setMode(requestedMode);
706 if (err == NO_ERROR) {
707 mCurrentOperatingMode = DATA_INJECTION;
708 } else {
709 // Re-enable sensors.
710 dev.enableAllSensors();
711 }
712 } else if (mCurrentOperatingMode == DATA_INJECTION) {
713 // Already in DATA_INJECTION mode. Treat this as a no_op.
714 return NO_ERROR;
715 } else {
716 // Transition to data injection mode supported only from NORMAL mode.
717 return INVALID_OPERATION;
718 }
719 } else if (requestedMode == NORMAL && mCurrentOperatingMode != NORMAL) {
720 err = resetToNormalModeLocked();
721 }
722 return err;
723}
724
725status_t SensorService::resetToNormalMode() {
726 Mutex::Autolock _l(mLock);
727 return resetToNormalModeLocked();
728}
729
730status_t SensorService::resetToNormalModeLocked() {
731 SensorDevice& dev(SensorDevice::getInstance());
732 dev.enableAllSensors();
733 status_t err = dev.setMode(NORMAL);
734 mCurrentOperatingMode = NORMAL;
735 return err;
736}
737
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800738void SensorService::cleanupConnection(SensorEventConnection* c)
Mathias Agopianfc328812010-07-14 23:41:37 -0700739{
740 Mutex::Autolock _l(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800741 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700742 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -0700743 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700744 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800745 int handle = mActiveSensors.keyAt(i);
746 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -0700747 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800748 SensorInterface* sensor = mSensorMap.valueFor( handle );
Steve Blockf5a12302012-01-06 19:20:56 +0000749 ALOGE_IF(!sensor, "mSensorMap[handle=0x%08x] is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800750 if (sensor) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800751 sensor->activate(c, false);
Mathias Agopianf001c922010-11-11 17:58:51 -0800752 }
Aravind Akella8a969552014-09-28 17:52:41 -0700753 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800754 }
755 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -0700756 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +0000757 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -0700758 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700759 c, i, handle);
760
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800761 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +0000762 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700763 mActiveSensors.removeItemsAt(i, 1);
Mathias Agopianf001c922010-11-11 17:58:51 -0800764 mActiveVirtualSensors.removeItem(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700765 delete rec;
766 size--;
767 } else {
768 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -0700769 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700770 }
Aravind Akella8a969552014-09-28 17:52:41 -0700771 c->updateLooperRegistration(mLooper);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700772 mActiveConnections.remove(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -0700773 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -0800774 if (c->needsWakeLock()) {
775 checkWakeLockStateLocked();
776 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700777}
778
Aravind Akella70018042014-04-07 22:52:37 +0000779Sensor SensorService::getSensorFromHandle(int handle) const {
780 return mSensorMap.valueFor(handle)->getSensor();
781}
782
Mathias Agopianfc328812010-07-14 23:41:37 -0700783status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Aravind Akella4949c502015-02-11 15:54:35 -0800784 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags)
Mathias Agopianfc328812010-07-14 23:41:37 -0700785{
Mathias Agopian50df2952010-07-19 19:09:10 -0700786 if (mInitCheck != NO_ERROR)
787 return mInitCheck;
788
Mathias Agopianf001c922010-11-11 17:58:51 -0800789 SensorInterface* sensor = mSensorMap.valueFor(handle);
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700790 if (sensor == NULL) {
791 return BAD_VALUE;
792 }
Aravind Akella70018042014-04-07 22:52:37 +0000793
794 if (!verifyCanAccessSensor(sensor->getSensor(), "Tried enabling")) {
795 return BAD_VALUE;
796 }
797
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700798 Mutex::Autolock _l(mLock);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700799 if (mCurrentOperatingMode == RESTRICTED && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -0800800 return INVALID_OPERATION;
801 }
802
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700803 SensorRecord* rec = mActiveSensors.valueFor(handle);
804 if (rec == 0) {
805 rec = new SensorRecord(connection);
806 mActiveSensors.add(handle, rec);
807 if (sensor->isVirtual()) {
808 mActiveVirtualSensors.add(handle, sensor);
809 }
810 } else {
811 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800812 // this sensor is already activated, but we are adding a connection that uses it.
813 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700814 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -0700815 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800816 // NOTE: The wake_up flag of this event may get set to
817 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Aravind Akella444f2672015-05-07 12:40:52 -0700818 CircularBuffer *circular_buf = mLastEventSeen.valueFor(handle);
819 if (circular_buf) {
820 sensors_event_t event;
821 memset(&event, 0, sizeof(event));
822 // It is unlikely that this buffer is empty as the sensor is already active.
823 // One possible corner case may be two applications activating an on-change
824 // sensor at the same time.
825 if(circular_buf->populateLastEvent(&event)) {
826 event.sensor = handle;
827 if (event.version == sizeof(sensors_event_t)) {
828 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
829 setWakeLockAcquiredLocked(true);
830 }
831 connection->sendEvents(&event, 1, NULL);
832 if (!connection->needsWakeLock() && mWakeLockAcquired) {
833 checkWakeLockStateLocked();
834 }
835 }
Aravind Akella9a844cf2014-02-11 18:58:52 -0800836 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700837 }
838 }
839 }
840 }
841
842 if (connection->addSensor(handle)) {
843 BatteryService::enableSensor(connection->getUid(), handle);
844 // the sensor was added (which means it wasn't already there)
845 // so, see if this connection becomes active
846 if (mActiveConnections.indexOf(connection) < 0) {
847 mActiveConnections.add(connection);
848 }
849 } else {
850 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
851 handle, connection.get());
852 }
853
Aravind Akella724d91d2013-06-27 12:04:23 -0700854 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
855 if (samplingPeriodNs < minDelayNs) {
856 samplingPeriodNs = minDelayNs;
857 }
858
Aravind Akella6c2664a2014-08-13 12:24:50 -0700859 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
860 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -0700861 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
862
Aravind Akella4949c502015-02-11 15:54:35 -0800863 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -0700864 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -0700865
Aravind Akella5466c3d2014-08-22 16:11:10 -0700866 // Call flush() before calling activate() on the sensor. Wait for a first flush complete
867 // event before sending events on this connection. Ignore one-shot sensors which don't
868 // support flush(). Also if this sensor isn't already active, don't call flush().
869 if (err == NO_ERROR && sensor->getSensor().getReportingMode() != AREPORTING_MODE_ONE_SHOT &&
870 rec->getNumConnections() > 1) {
871 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700872 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -0700873 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -0700874 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700875 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -0700876 } else {
877 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700878 }
879 }
Aravind Akella724d91d2013-06-27 12:04:23 -0700880
881 if (err == NO_ERROR) {
882 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
883 err = sensor->activate(connection.get(), true);
884 }
885
Aravind Akella8a969552014-09-28 17:52:41 -0700886 if (err == NO_ERROR) {
887 connection->updateLooperRegistration(mLooper);
Aravind Akella56ae4262014-07-10 16:01:10 -0700888 }
889
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700890 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -0700891 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700892 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700893 }
894 return err;
895}
896
897status_t SensorService::disable(const sp<SensorEventConnection>& connection,
898 int handle)
899{
Mathias Agopian50df2952010-07-19 19:09:10 -0700900 if (mInitCheck != NO_ERROR)
901 return mInitCheck;
902
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700903 Mutex::Autolock _l(mLock);
904 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700905 if (err == NO_ERROR) {
906 SensorInterface* sensor = mSensorMap.valueFor(handle);
907 err = sensor ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
908 }
909 return err;
910}
911
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700912status_t SensorService::cleanupWithoutDisable(
913 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700914 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700915 return cleanupWithoutDisableLocked(connection, handle);
916}
917
918status_t SensorService::cleanupWithoutDisableLocked(
919 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700920 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700921 if (rec) {
922 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -0700923 if (connection->removeSensor(handle)) {
924 BatteryService::disableSensor(connection->getUid(), handle);
925 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700926 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -0700927 connection->updateLooperRegistration(mLooper);
Mathias Agopianfc328812010-07-14 23:41:37 -0700928 mActiveConnections.remove(connection);
929 }
930 // see if this sensor becomes inactive
931 if (rec->removeConnection(connection)) {
932 mActiveSensors.removeItem(handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800933 mActiveVirtualSensors.removeItem(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700934 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -0700935 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700936 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700937 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700938 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -0700939}
940
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700941status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Mathias Agopianfc328812010-07-14 23:41:37 -0700942 int handle, nsecs_t ns)
943{
Mathias Agopian50df2952010-07-19 19:09:10 -0700944 if (mInitCheck != NO_ERROR)
945 return mInitCheck;
946
Mathias Agopianae09d652011-11-01 17:37:49 -0700947 SensorInterface* sensor = mSensorMap.valueFor(handle);
948 if (!sensor)
949 return BAD_VALUE;
950
Aravind Akella70018042014-04-07 22:52:37 +0000951 if (!verifyCanAccessSensor(sensor->getSensor(), "Tried configuring")) {
952 return BAD_VALUE;
953 }
954
Mathias Agopian1cd70002010-07-21 15:59:50 -0700955 if (ns < 0)
956 return BAD_VALUE;
957
Mathias Agopian62569ec2011-11-07 21:21:47 -0800958 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
959 if (ns < minDelayNs) {
960 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -0700961 }
962
Mathias Agopianf001c922010-11-11 17:58:51 -0800963 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -0700964}
965
Aravind Akella9e3adfc2014-09-03 15:48:05 -0700966status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection) {
Aravind Akella70018042014-04-07 22:52:37 +0000967 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -0700968 SensorDevice& dev(SensorDevice::getInstance());
969 const int halVersion = dev.getHalDeviceVersion();
970 status_t err(NO_ERROR);
971 Mutex::Autolock _l(mLock);
972 // Loop through all sensors for this connection and call flush on each of them.
973 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
974 const int handle = connection->mSensorInfo.keyAt(i);
975 SensorInterface* sensor = mSensorMap.valueFor(handle);
976 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
977 ALOGE("flush called on a one-shot sensor");
978 err = INVALID_OPERATION;
979 continue;
980 }
Aravind Akella8493b792014-09-08 15:45:47 -0700981 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -0700982 // For older devices just increment pending flush count which will send a trivial
983 // flush complete event.
Aravind Akella8a969552014-09-28 17:52:41 -0700984 connection->incrementPendingFlushCount(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -0700985 } else {
986 status_t err_flush = sensor->flush(connection.get(), handle);
987 if (err_flush == NO_ERROR) {
988 SensorRecord* rec = mActiveSensors.valueFor(handle);
989 if (rec != NULL) rec->addPendingFlushConnection(connection);
990 }
991 err = (err_flush != NO_ERROR) ? err_flush : err;
992 }
Aravind Akella70018042014-04-07 22:52:37 +0000993 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -0700994 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -0700995}
Aravind Akella70018042014-04-07 22:52:37 +0000996
Aravind Akella70018042014-04-07 22:52:37 +0000997bool SensorService::canAccessSensor(const Sensor& sensor) {
Aravind Akella56ae4262014-07-10 16:01:10 -0700998 return (sensor.getRequiredPermission().isEmpty()) ||
999 PermissionCache::checkCallingPermission(String16(sensor.getRequiredPermission()));
Aravind Akella70018042014-04-07 22:52:37 +00001000}
1001
1002bool SensorService::verifyCanAccessSensor(const Sensor& sensor, const char* operation) {
1003 if (canAccessSensor(sensor)) {
1004 return true;
1005 } else {
1006 String8 errorMessage;
1007 errorMessage.appendFormat(
1008 "%s a sensor (%s) without holding its required permission: %s",
1009 operation,
1010 sensor.getName().string(),
1011 sensor.getRequiredPermission().string());
1012 return false;
1013 }
1014}
1015
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001016bool SensorService::hasDataInjectionPermissions() {
1017 if (!PermissionCache::checkCallingPermission(sDataInjectionPermission)) {
1018 ALOGE("Permission Denial trying to activate data injection without"
1019 " the required permission");
1020 return false;
1021 }
1022 return true;
1023}
1024
Aravind Akella9a844cf2014-02-11 18:58:52 -08001025void SensorService::checkWakeLockState() {
1026 Mutex::Autolock _l(mLock);
1027 checkWakeLockStateLocked();
1028}
1029
1030void SensorService::checkWakeLockStateLocked() {
1031 if (!mWakeLockAcquired) {
1032 return;
1033 }
1034 bool releaseLock = true;
1035 for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
1036 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1037 if (connection != 0) {
1038 if (connection->needsWakeLock()) {
1039 releaseLock = false;
1040 break;
1041 }
1042 }
1043 }
1044 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001045 setWakeLockAcquiredLocked(false);
1046 }
1047}
1048
1049void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1050 Mutex::Autolock _l(mLock);
1051 connection->writeToSocketFromCache();
1052 if (connection->needsWakeLock()) {
1053 setWakeLockAcquiredLocked(true);
1054 }
1055}
1056
1057void SensorService::populateActiveConnections(
1058 SortedVector< sp<SensorEventConnection> >* activeConnections) {
1059 Mutex::Autolock _l(mLock);
1060 for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
1061 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1062 if (connection != 0) {
1063 activeConnections->add(connection);
1064 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001065 }
1066}
Aravind Akella6c2664a2014-08-13 12:24:50 -07001067
Aravind Akella4949c502015-02-11 15:54:35 -08001068bool SensorService::isWhiteListedPackage(const String8& packageName) {
1069 // TODO: Come up with a list of packages.
1070 return (packageName.find(".cts.") != -1);
1071}
1072
Aravind Akella444f2672015-05-07 12:40:52 -07001073int SensorService::getNumEventsForSensorType(int sensor_event_type) {
1074 switch (sensor_event_type) {
1075 case SENSOR_TYPE_ROTATION_VECTOR:
1076 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
1077 return 5;
1078
1079 case SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED:
1080 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
1081 return 6;
1082
1083 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
1084 return 4;
1085
1086 case SENSOR_TYPE_SIGNIFICANT_MOTION:
1087 case SENSOR_TYPE_STEP_DETECTOR:
1088 case SENSOR_TYPE_STEP_COUNTER:
1089 return 1;
1090
1091 default:
1092 return 3;
1093 }
1094}
1095
Mathias Agopianfc328812010-07-14 23:41:37 -07001096// ---------------------------------------------------------------------------
Mathias Agopianfc328812010-07-14 23:41:37 -07001097SensorService::SensorRecord::SensorRecord(
1098 const sp<SensorEventConnection>& connection)
1099{
1100 mConnections.add(connection);
1101}
1102
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001103bool SensorService::SensorRecord::addConnection(
Mathias Agopianfc328812010-07-14 23:41:37 -07001104 const sp<SensorEventConnection>& connection)
1105{
1106 if (mConnections.indexOf(connection) < 0) {
1107 mConnections.add(connection);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001108 return true;
Mathias Agopianfc328812010-07-14 23:41:37 -07001109 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001110 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -07001111}
1112
1113bool SensorService::SensorRecord::removeConnection(
1114 const wp<SensorEventConnection>& connection)
1115{
1116 ssize_t index = mConnections.indexOf(connection);
1117 if (index >= 0) {
1118 mConnections.removeItemsAt(index, 1);
1119 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001120 // Remove this connections from the queue of flush() calls made on this sensor.
1121 for (Vector< wp<SensorEventConnection> >::iterator it =
1122 mPendingFlushConnections.begin(); it != mPendingFlushConnections.end();) {
Aravind Akella8a969552014-09-28 17:52:41 -07001123
Aravind Akella6c2664a2014-08-13 12:24:50 -07001124 if (it->unsafe_get() == connection.unsafe_get()) {
1125 it = mPendingFlushConnections.erase(it);
1126 } else {
1127 ++it;
1128 }
1129 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001130 return mConnections.size() ? false : true;
1131}
1132
Aravind Akella6c2664a2014-08-13 12:24:50 -07001133void SensorService::SensorRecord::addPendingFlushConnection(
1134 const sp<SensorEventConnection>& connection) {
1135 mPendingFlushConnections.add(connection);
1136}
1137
1138void SensorService::SensorRecord::removeFirstPendingFlushConnection() {
1139 if (mPendingFlushConnections.size() > 0) {
1140 mPendingFlushConnections.removeAt(0);
1141 }
1142}
1143
1144SensorService::SensorEventConnection *
1145SensorService::SensorRecord::getFirstPendingFlushConnection() {
1146 if (mPendingFlushConnections.size() > 0) {
1147 return mPendingFlushConnections[0].unsafe_get();
1148 }
1149 return NULL;
1150}
1151
Aravind Akella4949c502015-02-11 15:54:35 -08001152void SensorService::SensorRecord::clearAllPendingFlushConnections() {
1153 mPendingFlushConnections.clear();
1154}
1155
Aravind Akella444f2672015-05-07 12:40:52 -07001156// --------------------------------------------------------------------------
1157SensorService::CircularBuffer::CircularBuffer(int sensor_event_type) {
1158 mNextInd = 0;
1159 mTrimmedSensorEventArr = new TrimmedSensorEvent *[CIRCULAR_BUF_SIZE];
1160 mSensorType = sensor_event_type;
1161 const int numData = SensorService::getNumEventsForSensorType(mSensorType);
1162 for (int i = 0; i < CIRCULAR_BUF_SIZE; ++i) {
1163 mTrimmedSensorEventArr[i] = new TrimmedSensorEvent(numData, mSensorType);
1164 }
1165}
1166
1167void SensorService::CircularBuffer::addEvent(const sensors_event_t& sensor_event) {
1168 TrimmedSensorEvent *curr_event = mTrimmedSensorEventArr[mNextInd];
1169 curr_event->mTimestamp = sensor_event.timestamp;
1170 if (mSensorType == SENSOR_TYPE_STEP_COUNTER) {
1171 curr_event->mStepCounter = sensor_event.u64.step_counter;
1172 } else {
1173 memcpy(curr_event->mData, sensor_event.data,
1174 sizeof(float) * SensorService::getNumEventsForSensorType(mSensorType));
1175 }
1176 time_t rawtime = time(NULL);
1177 struct tm * timeinfo = localtime(&rawtime);
1178 curr_event->mHour = timeinfo->tm_hour;
1179 curr_event->mMin = timeinfo->tm_min;
1180 curr_event->mSec = timeinfo->tm_sec;
1181 mNextInd = (mNextInd + 1) % CIRCULAR_BUF_SIZE;
1182}
1183
1184void SensorService::CircularBuffer::printBuffer(String8& result) const {
1185 const int numData = SensorService::getNumEventsForSensorType(mSensorType);
1186 int i = mNextInd, eventNum = 1;
1187 result.appendFormat("last %d events = < ", CIRCULAR_BUF_SIZE);
1188 do {
1189 if (mTrimmedSensorEventArr[i]->mTimestamp == -1) {
1190 // Sentinel, ignore.
1191 i = (i + 1) % CIRCULAR_BUF_SIZE;
1192 continue;
1193 }
1194 result.appendFormat("%d) ", eventNum++);
1195 if (mSensorType == SENSOR_TYPE_STEP_COUNTER) {
1196 result.appendFormat("%llu,", mTrimmedSensorEventArr[i]->mStepCounter);
1197 } else {
1198 for (int j = 0; j < numData; ++j) {
1199 result.appendFormat("%5.1f,", mTrimmedSensorEventArr[i]->mData[j]);
1200 }
1201 }
1202 result.appendFormat("%lld %02d:%02d:%02d ", mTrimmedSensorEventArr[i]->mTimestamp,
1203 mTrimmedSensorEventArr[i]->mHour, mTrimmedSensorEventArr[i]->mMin,
1204 mTrimmedSensorEventArr[i]->mSec);
1205 i = (i + 1) % CIRCULAR_BUF_SIZE;
1206 } while (i != mNextInd);
1207 result.appendFormat(">\n");
1208}
1209
1210bool SensorService::CircularBuffer::populateLastEvent(sensors_event_t *event) {
1211 int lastEventInd = (mNextInd - 1 + CIRCULAR_BUF_SIZE) % CIRCULAR_BUF_SIZE;
1212 // Check if the buffer is empty.
1213 if (mTrimmedSensorEventArr[lastEventInd]->mTimestamp == -1) {
1214 return false;
1215 }
1216 event->version = sizeof(sensors_event_t);
1217 event->type = mSensorType;
1218 event->timestamp = mTrimmedSensorEventArr[lastEventInd]->mTimestamp;
1219 if (mSensorType == SENSOR_TYPE_STEP_COUNTER) {
1220 event->u64.step_counter = mTrimmedSensorEventArr[lastEventInd]->mStepCounter;
1221 } else {
1222 memcpy(event->data, mTrimmedSensorEventArr[lastEventInd]->mData,
1223 sizeof(float) * SensorService::getNumEventsForSensorType(mSensorType));
1224 }
1225 return true;
1226}
1227
1228SensorService::CircularBuffer::~CircularBuffer() {
1229 for (int i = 0; i < CIRCULAR_BUF_SIZE; ++i) {
1230 delete mTrimmedSensorEventArr[i];
1231 }
1232 delete [] mTrimmedSensorEventArr;
1233}
1234
Mathias Agopianfc328812010-07-14 23:41:37 -07001235// ---------------------------------------------------------------------------
1236
1237SensorService::SensorEventConnection::SensorEventConnection(
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001238 const sp<SensorService>& service, uid_t uid, String8 packageName, bool isDataInjectionMode)
Aravind Akella8a969552014-09-28 17:52:41 -07001239 : mService(service), mUid(uid), mWakeLockRefCount(0), mHasLooperCallbacks(false),
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001240 mDead(false), mEventCache(NULL), mCacheSize(0), mMaxCacheSize(0), mPackageName(packageName),
1241 mDataInjectionMode(isDataInjectionMode) {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001242 mChannel = new BitTube(mService->mSocketBufferSize);
Aravind Akella56ae4262014-07-10 16:01:10 -07001243#if DEBUG_CONNECTIONS
1244 mEventsReceived = mEventsSentFromCache = mEventsSent = 0;
Aravind Akellae74baf62014-08-21 12:28:35 -07001245 mTotalAcksNeeded = mTotalAcksReceived = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -07001246#endif
Mathias Agopianfc328812010-07-14 23:41:37 -07001247}
1248
Aravind Akella56ae4262014-07-10 16:01:10 -07001249SensorService::SensorEventConnection::~SensorEventConnection() {
Steve Blocka5512372011-12-20 16:23:08 +00001250 ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this);
Aravind Akellae148bc22014-09-24 22:12:58 -07001251 mService->cleanupConnection(this);
Aravind Akella56ae4262014-07-10 16:01:10 -07001252 if (mEventCache != NULL) {
1253 delete mEventCache;
1254 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001255}
1256
Aravind Akella56ae4262014-07-10 16:01:10 -07001257void SensorService::SensorEventConnection::onFirstRef() {
1258 LooperCallback::onFirstRef();
Mathias Agopianfc328812010-07-14 23:41:37 -07001259}
1260
Aravind Akella9a844cf2014-02-11 18:58:52 -08001261bool SensorService::SensorEventConnection::needsWakeLock() {
1262 Mutex::Autolock _l(mConnectionLock);
Aravind Akella8a969552014-09-28 17:52:41 -07001263 return !mDead && mWakeLockRefCount > 0;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001264}
1265
Aravind Akellab4373ac2014-10-29 17:55:20 -07001266void SensorService::SensorEventConnection::resetWakeLockRefCount() {
1267 Mutex::Autolock _l(mConnectionLock);
1268 mWakeLockRefCount = 0;
1269}
1270
Aravind Akella4c8b9512013-09-05 17:03:38 -07001271void SensorService::SensorEventConnection::dump(String8& result) {
1272 Mutex::Autolock _l(mConnectionLock);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001273 result.appendFormat("Operating Mode: %s\n", mDataInjectionMode ? "DATA_INJECTION" : "NORMAL");
Aravind Akella4949c502015-02-11 15:54:35 -08001274 result.appendFormat("\t%s | WakeLockRefCount %d | uid %d | cache size %d | max cache size %d\n",
1275 mPackageName.string(), mWakeLockRefCount, mUid, mCacheSize, mMaxCacheSize);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001276 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1277 const FlushInfo& flushInfo = mSensorInfo.valueAt(i);
Aravind Akella0ec20662014-09-14 17:29:48 -07001278 result.appendFormat("\t %s 0x%08x | status: %s | pending flush events %d \n",
Aravind Akella4c8b9512013-09-05 17:03:38 -07001279 mService->getSensorName(mSensorInfo.keyAt(i)).string(),
Aravind Akella6c2664a2014-08-13 12:24:50 -07001280 mSensorInfo.keyAt(i),
Aravind Akella4c8b9512013-09-05 17:03:38 -07001281 flushInfo.mFirstFlushPending ? "First flush pending" :
1282 "active",
Aravind Akella0ec20662014-09-14 17:29:48 -07001283 flushInfo.mPendingFlushEventsToSend);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001284 }
Aravind Akella0ec20662014-09-14 17:29:48 -07001285#if DEBUG_CONNECTIONS
1286 result.appendFormat("\t events recvd: %d | sent %d | cache %d | dropped %d |"
1287 " total_acks_needed %d | total_acks_recvd %d\n",
1288 mEventsReceived,
1289 mEventsSent,
1290 mEventsSentFromCache,
1291 mEventsReceived - (mEventsSentFromCache + mEventsSent + mCacheSize),
1292 mTotalAcksNeeded,
1293 mTotalAcksReceived);
1294#endif
Aravind Akella4c8b9512013-09-05 17:03:38 -07001295}
1296
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001297bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001298 Mutex::Autolock _l(mConnectionLock);
Aravind Akella70018042014-04-07 22:52:37 +00001299 if (!verifyCanAccessSensor(mService->getSensorFromHandle(handle), "Tried adding")) {
1300 return false;
1301 }
Aravind Akella4c8b9512013-09-05 17:03:38 -07001302 if (mSensorInfo.indexOfKey(handle) < 0) {
1303 mSensorInfo.add(handle, FlushInfo());
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001304 return true;
Mathias Agopianfc328812010-07-14 23:41:37 -07001305 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001306 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -07001307}
1308
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001309bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001310 Mutex::Autolock _l(mConnectionLock);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001311 if (mSensorInfo.removeItem(handle) >= 0) {
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001312 return true;
1313 }
1314 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -07001315}
1316
1317bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001318 Mutex::Autolock _l(mConnectionLock);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001319 return mSensorInfo.indexOfKey(handle) >= 0;
Mathias Agopianfc328812010-07-14 23:41:37 -07001320}
1321
1322bool SensorService::SensorEventConnection::hasAnySensor() const {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001323 Mutex::Autolock _l(mConnectionLock);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001324 return mSensorInfo.size() ? true : false;
1325}
1326
Aravind Akella8493b792014-09-08 15:45:47 -07001327bool SensorService::SensorEventConnection::hasOneShotSensors() const {
1328 Mutex::Autolock _l(mConnectionLock);
1329 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1330 const int handle = mSensorInfo.keyAt(i);
1331 if (mService->getSensorFromHandle(handle).getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1332 return true;
1333 }
1334 }
1335 return false;
1336}
1337
Aravind Akella4949c502015-02-11 15:54:35 -08001338String8 SensorService::SensorEventConnection::getPackageName() const {
1339 return mPackageName;
1340}
1341
Aravind Akella4c8b9512013-09-05 17:03:38 -07001342void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle,
1343 bool value) {
1344 Mutex::Autolock _l(mConnectionLock);
1345 ssize_t index = mSensorInfo.indexOfKey(handle);
1346 if (index >= 0) {
1347 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
1348 flushInfo.mFirstFlushPending = value;
1349 }
1350}
1351
Aravind Akella8a969552014-09-28 17:52:41 -07001352void SensorService::SensorEventConnection::updateLooperRegistration(const sp<Looper>& looper) {
1353 Mutex::Autolock _l(mConnectionLock);
1354 updateLooperRegistrationLocked(looper);
1355}
1356
1357void SensorService::SensorEventConnection::updateLooperRegistrationLocked(
1358 const sp<Looper>& looper) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001359 bool isConnectionActive = (mSensorInfo.size() > 0 && !mDataInjectionMode) ||
1360 mDataInjectionMode;
Aravind Akella8a969552014-09-28 17:52:41 -07001361 // If all sensors are unregistered OR Looper has encountered an error, we
1362 // can remove the Fd from the Looper if it has been previously added.
1363 if (!isConnectionActive || mDead) {
1364 if (mHasLooperCallbacks) {
1365 ALOGD_IF(DEBUG_CONNECTIONS, "%p removeFd fd=%d", this, mChannel->getSendFd());
1366 looper->removeFd(mChannel->getSendFd());
1367 mHasLooperCallbacks = false;
1368 }
1369 return;
1370 }
1371
1372 int looper_flags = 0;
1373 if (mCacheSize > 0) looper_flags |= ALOOPER_EVENT_OUTPUT;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001374 if (mDataInjectionMode) looper_flags |= ALOOPER_EVENT_INPUT;
Aravind Akella8a969552014-09-28 17:52:41 -07001375 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1376 const int handle = mSensorInfo.keyAt(i);
1377 if (mService->getSensorFromHandle(handle).isWakeUpSensor()) {
1378 looper_flags |= ALOOPER_EVENT_INPUT;
1379 break;
1380 }
1381 }
1382 // If flags is still set to zero, we don't need to add this fd to the Looper, if
1383 // the fd has already been added, remove it. This is likely to happen when ALL the
1384 // events stored in the cache have been sent to the corresponding app.
1385 if (looper_flags == 0) {
1386 if (mHasLooperCallbacks) {
1387 ALOGD_IF(DEBUG_CONNECTIONS, "removeFd fd=%d", mChannel->getSendFd());
1388 looper->removeFd(mChannel->getSendFd());
1389 mHasLooperCallbacks = false;
1390 }
1391 return;
1392 }
1393 // Add the file descriptor to the Looper for receiving acknowledegments if the app has
1394 // registered for wake-up sensors OR for sending events in the cache.
1395 int ret = looper->addFd(mChannel->getSendFd(), 0, looper_flags, this, NULL);
1396 if (ret == 1) {
1397 ALOGD_IF(DEBUG_CONNECTIONS, "%p addFd fd=%d", this, mChannel->getSendFd());
1398 mHasLooperCallbacks = true;
1399 } else {
1400 ALOGE("Looper::addFd failed ret=%d fd=%d", ret, mChannel->getSendFd());
1401 }
1402}
1403
1404void SensorService::SensorEventConnection::incrementPendingFlushCount(int32_t handle) {
1405 Mutex::Autolock _l(mConnectionLock);
1406 ssize_t index = mSensorInfo.indexOfKey(handle);
1407 if (index >= 0) {
1408 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
1409 flushInfo.mPendingFlushEventsToSend++;
1410 }
1411}
1412
Mathias Agopianfc328812010-07-14 23:41:37 -07001413status_t SensorService::SensorEventConnection::sendEvents(
Aravind Akella0ec20662014-09-14 17:29:48 -07001414 sensors_event_t const* buffer, size_t numEvents,
Aravind Akella8493b792014-09-08 15:45:47 -07001415 sensors_event_t* scratch,
1416 SensorEventConnection const * const * mapFlushEventsToConnections) {
Mathias Agopiancf510012010-07-22 16:18:10 -07001417 // filter out events not for this connection
Mathias Agopian3560fb22010-07-22 21:24:39 -07001418 size_t count = 0;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001419 Mutex::Autolock _l(mConnectionLock);
Mathias Agopian3560fb22010-07-22 21:24:39 -07001420 if (scratch) {
1421 size_t i=0;
1422 while (i<numEvents) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001423 int32_t sensor_handle = buffer[i].sensor;
Aravind Akella724d91d2013-06-27 12:04:23 -07001424 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
1425 ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ",
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001426 buffer[i].meta_data.sensor);
Aravind Akella8a969552014-09-28 17:52:41 -07001427 // Setting sensor_handle to the correct sensor to ensure the sensor events per
1428 // connection are filtered correctly. buffer[i].sensor is zero for meta_data
1429 // events.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001430 sensor_handle = buffer[i].meta_data.sensor;
Aravind Akella724d91d2013-06-27 12:04:23 -07001431 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001432 ssize_t index = mSensorInfo.indexOfKey(sensor_handle);
Aravind Akella56ae4262014-07-10 16:01:10 -07001433 // Check if this connection has registered for this sensor. If not continue to the
1434 // next sensor_event.
1435 if (index < 0) {
1436 ++i;
1437 continue;
Aravind Akella4c8b9512013-09-05 17:03:38 -07001438 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001439
Aravind Akella56ae4262014-07-10 16:01:10 -07001440 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001441 // Check if there is a pending flush_complete event for this sensor on this connection.
Aravind Akella8493b792014-09-08 15:45:47 -07001442 if (buffer[i].type == SENSOR_TYPE_META_DATA && flushInfo.mFirstFlushPending == true &&
1443 this == mapFlushEventsToConnections[i]) {
1444 flushInfo.mFirstFlushPending = false;
1445 ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ",
1446 buffer[i].meta_data.sensor);
1447 ++i;
1448 continue;
Aravind Akella56ae4262014-07-10 16:01:10 -07001449 }
1450
1451 // If there is a pending flush complete event for this sensor on this connection,
1452 // ignore the event and proceed to the next.
1453 if (flushInfo.mFirstFlushPending) {
1454 ++i;
1455 continue;
1456 }
1457
1458 do {
Aravind Akella8493b792014-09-08 15:45:47 -07001459 // Keep copying events into the scratch buffer as long as they are regular
1460 // sensor_events are from the same sensor_handle OR they are flush_complete_events
1461 // from the same sensor_handle AND the current connection is mapped to the
1462 // corresponding flush_complete_event.
Aravind Akella56ae4262014-07-10 16:01:10 -07001463 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
Aravind Akella8493b792014-09-08 15:45:47 -07001464 if (this == mapFlushEventsToConnections[i]) {
Aravind Akella56ae4262014-07-10 16:01:10 -07001465 scratch[count++] = buffer[i];
Aravind Akella56ae4262014-07-10 16:01:10 -07001466 }
1467 ++i;
1468 } else {
1469 // Regular sensor event, just copy it to the scratch buffer.
Aravind Akella4c8b9512013-09-05 17:03:38 -07001470 scratch[count++] = buffer[i++];
Aravind Akella56ae4262014-07-10 16:01:10 -07001471 }
Aravind Akella8493b792014-09-08 15:45:47 -07001472 } while ((i<numEvents) && ((buffer[i].sensor == sensor_handle &&
1473 buffer[i].type != SENSOR_TYPE_META_DATA) ||
Aravind Akella56ae4262014-07-10 16:01:10 -07001474 (buffer[i].type == SENSOR_TYPE_META_DATA &&
Aravind Akella6c2664a2014-08-13 12:24:50 -07001475 buffer[i].meta_data.sensor == sensor_handle)));
Mathias Agopiancf510012010-07-22 16:18:10 -07001476 }
Mathias Agopian3560fb22010-07-22 21:24:39 -07001477 } else {
1478 scratch = const_cast<sensors_event_t *>(buffer);
1479 count = numEvents;
Mathias Agopiancf510012010-07-22 16:18:10 -07001480 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001481
Aravind Akella6c2664a2014-08-13 12:24:50 -07001482 sendPendingFlushEventsLocked();
Aravind Akella56ae4262014-07-10 16:01:10 -07001483 // Early return if there are no events for this connection.
1484 if (count == 0) {
1485 return status_t(NO_ERROR);
1486 }
1487
1488#if DEBUG_CONNECTIONS
1489 mEventsReceived += count;
1490#endif
1491 if (mCacheSize != 0) {
1492 // There are some events in the cache which need to be sent first. Copy this buffer to
1493 // the end of cache.
1494 if (mCacheSize + count <= mMaxCacheSize) {
1495 memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
1496 mCacheSize += count;
1497 } else {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001498 // Check if any new sensors have registered on this connection which may have increased
1499 // the max cache size that is desired.
1500 if (mCacheSize + count < computeMaxCacheSizeLocked()) {
1501 reAllocateCacheLocked(scratch, count);
1502 return status_t(NO_ERROR);
1503 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001504 // Some events need to be dropped.
1505 int remaningCacheSize = mMaxCacheSize - mCacheSize;
1506 if (remaningCacheSize != 0) {
1507 memcpy(&mEventCache[mCacheSize], scratch,
1508 remaningCacheSize * sizeof(sensors_event_t));
1509 }
1510 int numEventsDropped = count - remaningCacheSize;
1511 countFlushCompleteEventsLocked(mEventCache, numEventsDropped);
1512 // Drop the first "numEventsDropped" in the cache.
1513 memmove(mEventCache, &mEventCache[numEventsDropped],
1514 (mCacheSize - numEventsDropped) * sizeof(sensors_event_t));
1515
1516 // Copy the remainingEvents in scratch buffer to the end of cache.
1517 memcpy(&mEventCache[mCacheSize - numEventsDropped], scratch + remaningCacheSize,
1518 numEventsDropped * sizeof(sensors_event_t));
1519 }
1520 return status_t(NO_ERROR);
1521 }
1522
Aravind Akella6c2664a2014-08-13 12:24:50 -07001523 int index_wake_up_event = findWakeUpSensorEventLocked(scratch, count);
1524 if (index_wake_up_event >= 0) {
1525 scratch[index_wake_up_event].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1526 ++mWakeLockRefCount;
Aravind Akellae74baf62014-08-21 12:28:35 -07001527#if DEBUG_CONNECTIONS
1528 ++mTotalAcksNeeded;
1529#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001530 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001531
1532 // NOTE: ASensorEvent and sensors_event_t are the same type.
1533 ssize_t size = SensorEventQueue::write(mChannel,
1534 reinterpret_cast<ASensorEvent const*>(scratch), count);
1535 if (size < 0) {
1536 // Write error, copy events to local cache.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001537 if (index_wake_up_event >= 0) {
1538 // If there was a wake_up sensor_event, reset the flag.
1539 scratch[index_wake_up_event].flags &= ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
Aravind Akella0ec20662014-09-14 17:29:48 -07001540 if (mWakeLockRefCount > 0) {
1541 --mWakeLockRefCount;
1542 }
Aravind Akellae74baf62014-08-21 12:28:35 -07001543#if DEBUG_CONNECTIONS
1544 --mTotalAcksNeeded;
1545#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001546 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001547 if (mEventCache == NULL) {
1548 mMaxCacheSize = computeMaxCacheSizeLocked();
1549 mEventCache = new sensors_event_t[mMaxCacheSize];
1550 mCacheSize = 0;
1551 }
1552 memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
1553 mCacheSize += count;
1554
1555 // Add this file descriptor to the looper to get a callback when this fd is available for
1556 // writing.
Aravind Akella8a969552014-09-28 17:52:41 -07001557 updateLooperRegistrationLocked(mService->getLooper());
Aravind Akella56ae4262014-07-10 16:01:10 -07001558 return size;
1559 }
1560
1561#if DEBUG_CONNECTIONS
1562 if (size > 0) {
1563 mEventsSent += count;
1564 }
1565#endif
1566
1567 return size < 0 ? status_t(size) : status_t(NO_ERROR);
1568}
1569
Aravind Akella6c2664a2014-08-13 12:24:50 -07001570void SensorService::SensorEventConnection::reAllocateCacheLocked(sensors_event_t const* scratch,
1571 int count) {
1572 sensors_event_t *eventCache_new;
1573 const int new_cache_size = computeMaxCacheSizeLocked();
1574 // Allocate new cache, copy over events from the old cache & scratch, free up memory.
1575 eventCache_new = new sensors_event_t[new_cache_size];
1576 memcpy(eventCache_new, mEventCache, mCacheSize * sizeof(sensors_event_t));
1577 memcpy(&eventCache_new[mCacheSize], scratch, count * sizeof(sensors_event_t));
1578
1579 ALOGD_IF(DEBUG_CONNECTIONS, "reAllocateCacheLocked maxCacheSize=%d %d", mMaxCacheSize,
1580 new_cache_size);
1581
1582 delete mEventCache;
1583 mEventCache = eventCache_new;
1584 mCacheSize += count;
1585 mMaxCacheSize = new_cache_size;
1586}
1587
1588void SensorService::SensorEventConnection::sendPendingFlushEventsLocked() {
1589 ASensorEvent flushCompleteEvent;
Aravind Akella0ec20662014-09-14 17:29:48 -07001590 memset(&flushCompleteEvent, 0, sizeof(flushCompleteEvent));
Aravind Akella6c2664a2014-08-13 12:24:50 -07001591 flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
Aravind Akella6c2664a2014-08-13 12:24:50 -07001592 // Loop through all the sensors for this connection and check if there are any pending
1593 // flush complete events to be sent.
1594 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1595 FlushInfo& flushInfo = mSensorInfo.editValueAt(i);
1596 while (flushInfo.mPendingFlushEventsToSend > 0) {
Aravind Akella0ec20662014-09-14 17:29:48 -07001597 const int sensor_handle = mSensorInfo.keyAt(i);
1598 flushCompleteEvent.meta_data.sensor = sensor_handle;
Aravind Akellab4373ac2014-10-29 17:55:20 -07001599 bool wakeUpSensor = mService->getSensorFromHandle(sensor_handle).isWakeUpSensor();
1600 if (wakeUpSensor) {
1601 ++mWakeLockRefCount;
Aravind Akella0ec20662014-09-14 17:29:48 -07001602 flushCompleteEvent.flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1603 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001604 ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
1605 if (size < 0) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001606 if (wakeUpSensor) --mWakeLockRefCount;
Aravind Akella6c2664a2014-08-13 12:24:50 -07001607 return;
1608 }
1609 ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
1610 flushCompleteEvent.meta_data.sensor);
1611 flushInfo.mPendingFlushEventsToSend--;
1612 }
1613 }
1614}
1615
Aravind Akellab4373ac2014-10-29 17:55:20 -07001616void SensorService::SensorEventConnection::writeToSocketFromCache() {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001617 // At a time write at most half the size of the receiver buffer in SensorEventQueue OR
1618 // half the size of the socket buffer allocated in BitTube whichever is smaller.
1619 const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
1620 int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
Aravind Akellab4373ac2014-10-29 17:55:20 -07001621 Mutex::Autolock _l(mConnectionLock);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001622 // Send pending flush complete events (if any)
Aravind Akella6c2664a2014-08-13 12:24:50 -07001623 sendPendingFlushEventsLocked();
Aravind Akella56ae4262014-07-10 16:01:10 -07001624 for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001625 const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001626 int index_wake_up_event =
1627 findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite);
1628 if (index_wake_up_event >= 0) {
1629 mEventCache[index_wake_up_event + numEventsSent].flags |=
1630 WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1631 ++mWakeLockRefCount;
Aravind Akellae74baf62014-08-21 12:28:35 -07001632#if DEBUG_CONNECTIONS
1633 ++mTotalAcksNeeded;
1634#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001635 }
Aravind Akella4c8b9512013-09-05 17:03:38 -07001636
Aravind Akella56ae4262014-07-10 16:01:10 -07001637 ssize_t size = SensorEventQueue::write(mChannel,
1638 reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent),
Aravind Akella6c2664a2014-08-13 12:24:50 -07001639 numEventsToWrite);
Aravind Akella56ae4262014-07-10 16:01:10 -07001640 if (size < 0) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001641 if (index_wake_up_event >= 0) {
1642 // If there was a wake_up sensor_event, reset the flag.
1643 mEventCache[index_wake_up_event + numEventsSent].flags &=
1644 ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
Aravind Akella0ec20662014-09-14 17:29:48 -07001645 if (mWakeLockRefCount > 0) {
1646 --mWakeLockRefCount;
1647 }
Aravind Akellae74baf62014-08-21 12:28:35 -07001648#if DEBUG_CONNECTIONS
1649 --mTotalAcksNeeded;
1650#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001651 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001652 memmove(mEventCache, &mEventCache[numEventsSent],
1653 (mCacheSize - numEventsSent) * sizeof(sensors_event_t));
1654 ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ",
Aravind Akella6c2664a2014-08-13 12:24:50 -07001655 numEventsSent, mCacheSize);
Aravind Akella56ae4262014-07-10 16:01:10 -07001656 mCacheSize -= numEventsSent;
Aravind Akella56ae4262014-07-10 16:01:10 -07001657 return;
1658 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001659 numEventsSent += numEventsToWrite;
Aravind Akella56ae4262014-07-10 16:01:10 -07001660#if DEBUG_CONNECTIONS
Aravind Akella6c2664a2014-08-13 12:24:50 -07001661 mEventsSentFromCache += numEventsToWrite;
Aravind Akella56ae4262014-07-10 16:01:10 -07001662#endif
Aravind Akellab4099e72013-10-15 15:43:10 -07001663 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001664 ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize);
1665 // All events from the cache have been sent. Reset cache size to zero.
1666 mCacheSize = 0;
Aravind Akella8a969552014-09-28 17:52:41 -07001667 // There are no more events in the cache. We don't need to poll for write on the fd.
1668 // Update Looper registration.
1669 updateLooperRegistrationLocked(mService->getLooper());
Mathias Agopianfc328812010-07-14 23:41:37 -07001670}
1671
Aravind Akellac551eac2013-10-14 17:04:42 -07001672void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
Aravind Akella0ec20662014-09-14 17:29:48 -07001673 sensors_event_t const* scratch, const int numEventsDropped) {
Aravind Akella4c8b9512013-09-05 17:03:38 -07001674 ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001675 // Count flushComplete events in the events that are about to the dropped. These will be sent
1676 // separately before the next batch of events.
1677 for (int j = 0; j < numEventsDropped; ++j) {
1678 if (scratch[j].type == SENSOR_TYPE_META_DATA) {
1679 FlushInfo& flushInfo = mSensorInfo.editValueFor(scratch[j].meta_data.sensor);
1680 flushInfo.mPendingFlushEventsToSend++;
1681 ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
1682 flushInfo.mPendingFlushEventsToSend);
1683 }
1684 }
1685 return;
1686}
1687
Aravind Akella6c2664a2014-08-13 12:24:50 -07001688int SensorService::SensorEventConnection::findWakeUpSensorEventLocked(
1689 sensors_event_t const* scratch, const int count) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001690 for (int i = 0; i < count; ++i) {
1691 if (mService->isWakeUpSensorEvent(scratch[i])) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001692 return i;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001693 }
1694 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001695 return -1;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001696}
1697
Mathias Agopianb3989272011-10-20 18:42:02 -07001698sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
Mathias Agopianfc328812010-07-14 23:41:37 -07001699{
1700 return mChannel;
1701}
1702
1703status_t SensorService::SensorEventConnection::enableDisable(
Aravind Akella724d91d2013-06-27 12:04:23 -07001704 int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
1705 int reservedFlags)
Mathias Agopianfc328812010-07-14 23:41:37 -07001706{
1707 status_t err;
1708 if (enabled) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001709 err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
1710 reservedFlags);
Aravind Akella56ae4262014-07-10 16:01:10 -07001711
Mathias Agopianfc328812010-07-14 23:41:37 -07001712 } else {
1713 err = mService->disable(this, handle);
1714 }
1715 return err;
1716}
1717
1718status_t SensorService::SensorEventConnection::setEventRate(
Aravind Akella724d91d2013-06-27 12:04:23 -07001719 int handle, nsecs_t samplingPeriodNs)
Mathias Agopianfc328812010-07-14 23:41:37 -07001720{
Aravind Akella724d91d2013-06-27 12:04:23 -07001721 return mService->setEventRate(this, handle, samplingPeriodNs);
Mathias Agopianfc328812010-07-14 23:41:37 -07001722}
1723
Aravind Akella701166d2013-10-08 14:59:26 -07001724status_t SensorService::SensorEventConnection::flush() {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001725 return mService->flushSensor(this);
Aravind Akella724d91d2013-06-27 12:04:23 -07001726}
Aravind Akella4c8b9512013-09-05 17:03:38 -07001727
Aravind Akella8a969552014-09-28 17:52:41 -07001728int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* /*data*/) {
Aravind Akella56ae4262014-07-10 16:01:10 -07001729 if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) {
Aravind Akella8a969552014-09-28 17:52:41 -07001730 {
1731 // If the Looper encounters some error, set the flag mDead, reset mWakeLockRefCount,
1732 // and remove the fd from Looper. Call checkWakeLockState to know if SensorService
1733 // can release the wake-lock.
1734 ALOGD_IF(DEBUG_CONNECTIONS, "%p Looper error %d", this, fd);
1735 Mutex::Autolock _l(mConnectionLock);
1736 mDead = true;
1737 mWakeLockRefCount = 0;
1738 updateLooperRegistrationLocked(mService->getLooper());
1739 }
1740 mService->checkWakeLockState();
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001741 if (mDataInjectionMode) {
1742 // If the Looper has encountered some error in data injection mode, reset SensorService
1743 // back to normal mode.
1744 mService->resetToNormalMode();
1745 mDataInjectionMode = false;
1746 }
Aravind Akella8a969552014-09-28 17:52:41 -07001747 return 1;
Aravind Akella56ae4262014-07-10 16:01:10 -07001748 }
1749
1750 if (events & ALOOPER_EVENT_INPUT) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001751 unsigned char buf[sizeof(sensors_event_t)];
1752 ssize_t numBytesRead = ::recv(fd, buf, sizeof(buf), MSG_DONTWAIT);
Aravind Akella56ae4262014-07-10 16:01:10 -07001753 {
1754 Mutex::Autolock _l(mConnectionLock);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001755 if (numBytesRead == sizeof(sensors_event_t)) {
1756 if (!mDataInjectionMode) {
1757 ALOGE("Data injected in normal mode, dropping event"
1758 "package=%s uid=%d", mPackageName.string(), mUid);
1759 // Unregister call backs.
1760 return 0;
1761 }
1762 SensorDevice& dev(SensorDevice::getInstance());
1763 sensors_event_t sensor_event;
1764 memset(&sensor_event, 0, sizeof(sensor_event));
1765 memcpy(&sensor_event, buf, sizeof(sensors_event_t));
1766 Sensor sensor = mService->getSensorFromHandle(sensor_event.sensor);
1767 sensor_event.type = sensor.getType();
1768 dev.injectSensorData(&sensor_event, 1);
Aravind Akellae74baf62014-08-21 12:28:35 -07001769#if DEBUG_CONNECTIONS
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001770 ++mEventsReceived;
Aravind Akellae74baf62014-08-21 12:28:35 -07001771#endif
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001772 } else if (numBytesRead == sizeof(uint32_t)) {
1773 uint32_t numAcks = 0;
1774 memcpy(&numAcks, buf, sizeof(numBytesRead));
1775 // Sanity check to ensure there are no read errors in recv, numAcks is always
1776 // within the range and not zero. If any of the above don't hold reset
1777 // mWakeLockRefCount to zero.
1778 if (numAcks > 0 && numAcks < mWakeLockRefCount) {
1779 mWakeLockRefCount -= numAcks;
1780 } else {
1781 mWakeLockRefCount = 0;
1782 }
1783#if DEBUG_CONNECTIONS
1784 mTotalAcksReceived += numAcks;
1785#endif
1786 } else {
1787 // Read error, reset wakelock refcount.
1788 mWakeLockRefCount = 0;
1789 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001790 }
1791 // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released
1792 // here as checkWakeLockState() will need it.
1793 if (mWakeLockRefCount == 0) {
1794 mService->checkWakeLockState();
1795 }
1796 // continue getting callbacks.
1797 return 1;
1798 }
1799
1800 if (events & ALOOPER_EVENT_OUTPUT) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001801 // send sensor data that is stored in mEventCache for this connection.
1802 mService->sendEventsFromCache(this);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001803 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001804 return 1;
1805}
1806
1807int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
1808 int fifoWakeUpSensors = 0;
1809 int fifoNonWakeUpSensors = 0;
1810 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1811 const Sensor& sensor = mService->getSensorFromHandle(mSensorInfo.keyAt(i));
1812 if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) {
1813 // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and
1814 // non wake_up sensors.
1815 if (sensor.isWakeUpSensor()) {
1816 fifoWakeUpSensors += sensor.getFifoReservedEventCount();
1817 } else {
1818 fifoNonWakeUpSensors += sensor.getFifoReservedEventCount();
1819 }
1820 } else {
1821 // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors.
1822 if (sensor.isWakeUpSensor()) {
1823 fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ?
1824 fifoWakeUpSensors : sensor.getFifoMaxEventCount();
1825
1826 } else {
1827 fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ?
1828 fifoNonWakeUpSensors : sensor.getFifoMaxEventCount();
1829
1830 }
1831 }
1832 }
1833 if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) {
1834 // It is extremely unlikely that there is a write failure in non batch mode. Return a cache
Aravind Akella6c2664a2014-08-13 12:24:50 -07001835 // size that is equal to that of the batch mode.
Aravind Akellae74baf62014-08-21 12:28:35 -07001836 // ALOGW("Write failure in non-batch mode");
Aravind Akella6c2664a2014-08-13 12:24:50 -07001837 return MAX_SOCKET_BUFFER_SIZE_BATCHED/sizeof(sensors_event_t);
Aravind Akella56ae4262014-07-10 16:01:10 -07001838 }
1839 return fifoWakeUpSensors + fifoNonWakeUpSensors;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001840}
1841
Mathias Agopianfc328812010-07-14 23:41:37 -07001842// ---------------------------------------------------------------------------
1843}; // namespace android
1844