blob: f6ff0927738113b5f79d3d14e836cd9a8ed79911 [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 Akellaa8814ce2015-06-10 15:15:57 -070069static const String16 sDataInjectionPermission("android.permission.LOCATION_HARDWARE");
Aravind Akellaa9e6cc32015-04-16 18:57:31 -070070static const String16 sDump("android.permission.DUMP");
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070071
Mathias Agopianfc328812010-07-14 23:41:37 -070072SensorService::SensorService()
Aravind Akella8a969552014-09-28 17:52:41 -070073 : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
74 mWakeLockAcquired(false)
Mathias Agopianfc328812010-07-14 23:41:37 -070075{
76}
77
78void SensorService::onFirstRef()
79{
Steve Blocka5512372011-12-20 16:23:08 +000080 ALOGD("nuSensorService starting...");
Mathias Agopianf001c922010-11-11 17:58:51 -080081 SensorDevice& dev(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -070082
Mathias Agopianf001c922010-11-11 17:58:51 -080083 if (dev.initCheck() == NO_ERROR) {
Mathias Agopianf001c922010-11-11 17:58:51 -080084 sensor_t const* list;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070085 ssize_t count = dev.getSensorList(&list);
86 if (count > 0) {
87 ssize_t orientationIndex = -1;
88 bool hasGyro = false;
89 uint32_t virtualSensorsNeeds =
90 (1<<SENSOR_TYPE_GRAVITY) |
91 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
92 (1<<SENSOR_TYPE_ROTATION_VECTOR);
93
94 mLastEventSeen.setCapacity(count);
95 for (ssize_t i=0 ; i<count ; i++) {
96 registerSensor( new HardwareSensor(list[i]) );
97 switch (list[i].type) {
98 case SENSOR_TYPE_ORIENTATION:
99 orientationIndex = i;
100 break;
101 case SENSOR_TYPE_GYROSCOPE:
Mathias Agopian03193062013-05-10 19:32:39 -0700102 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700103 hasGyro = true;
104 break;
105 case SENSOR_TYPE_GRAVITY:
106 case SENSOR_TYPE_LINEAR_ACCELERATION:
107 case SENSOR_TYPE_ROTATION_VECTOR:
108 virtualSensorsNeeds &= ~(1<<list[i].type);
109 break;
110 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700111 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700112
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700113 // it's safe to instantiate the SensorFusion object here
114 // (it wants to be instantiated after h/w sensors have been
115 // registered)
116 const SensorFusion& fusion(SensorFusion::getInstance());
Mathias Agopian984826c2011-05-17 22:54:42 -0700117
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700118 // build the sensor list returned to users
119 mUserSensorList = mSensorList;
Mathias Agopian33264862012-06-28 19:46:54 -0700120
121 if (hasGyro) {
Mathias Agopian03193062013-05-10 19:32:39 -0700122 Sensor aSensor;
123
124 // Add Android virtual sensors if they're not already
125 // available in the HAL
126
127 aSensor = registerVirtualSensor( new RotationVectorSensor() );
128 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
129 mUserSensorList.add(aSensor);
130 }
131
132 aSensor = registerVirtualSensor( new GravitySensor(list, count) );
133 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) {
134 mUserSensorList.add(aSensor);
135 }
136
137 aSensor = registerVirtualSensor( new LinearAccelerationSensor(list, count) );
138 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) {
139 mUserSensorList.add(aSensor);
140 }
141
142 aSensor = registerVirtualSensor( new OrientationSensor() );
143 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
144 // if we are doing our own rotation-vector, also add
145 // the orientation sensor and remove the HAL provided one.
146 mUserSensorList.replaceAt(aSensor, orientationIndex);
147 }
148
Mathias Agopian33264862012-06-28 19:46:54 -0700149 // virtual debugging sensors are not added to mUserSensorList
Mathias Agopian03193062013-05-10 19:32:39 -0700150 registerVirtualSensor( new CorrectedGyroSensor(list, count) );
Mathias Agopian33264862012-06-28 19:46:54 -0700151 registerVirtualSensor( new GyroDriftSensor() );
152 }
153
Mathias Agopian33264862012-06-28 19:46:54 -0700154 // debugging sensor list
Mathias Agopian03193062013-05-10 19:32:39 -0700155 mUserSensorListDebug = mSensorList;
Mathias Agopian33264862012-06-28 19:46:54 -0700156
Aravind Akella5466c3d2014-08-22 16:11:10 -0700157 // Check if the device really supports batching by looking at the FIFO event
158 // counts for each sensor.
159 bool batchingSupported = false;
Svetoslavb412f6e2015-04-29 16:50:41 -0700160 for (size_t i = 0; i < mSensorList.size(); ++i) {
Aravind Akella5466c3d2014-08-22 16:11:10 -0700161 if (mSensorList[i].getFifoMaxEventCount() > 0) {
162 batchingSupported = true;
163 break;
164 }
165 }
166
167 if (batchingSupported) {
168 // Increase socket buffer size to a max of 100 KB for batching capabilities.
169 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
170 } else {
171 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
172 }
173
174 // Compare the socketBufferSize value against the system limits and limit
175 // it to maxSystemSocketBufferSize if necessary.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700176 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
177 char line[128];
178 if (fp != NULL && fgets(line, sizeof(line), fp) != NULL) {
179 line[sizeof(line) - 1] = '\0';
Aravind Akella5466c3d2014-08-22 16:11:10 -0700180 size_t maxSystemSocketBufferSize;
181 sscanf(line, "%zu", &maxSystemSocketBufferSize);
182 if (mSocketBufferSize > maxSystemSocketBufferSize) {
183 mSocketBufferSize = maxSystemSocketBufferSize;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700184 }
185 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700186 if (fp) {
187 fclose(fp);
188 }
189
Aravind Akella9a844cf2014-02-11 18:58:52 -0800190 mWakeLockAcquired = false;
Aravind Akella56ae4262014-07-10 16:01:10 -0700191 mLooper = new Looper(false);
Aravind Akella8493b792014-09-08 15:45:47 -0700192 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
193 mSensorEventBuffer = new sensors_event_t[minBufferSize];
194 mSensorEventScratch = new sensors_event_t[minBufferSize];
195 mMapFlushEventsToConnections = new SensorEventConnection const * [minBufferSize];
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700196 mCurrentOperatingMode = NORMAL;
Aravind Akella7830ef32014-10-07 14:13:12 -0700197
Aravind Akellab4373ac2014-10-29 17:55:20 -0700198 mAckReceiver = new SensorEventAckReceiver(this);
199 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700200 mInitCheck = NO_ERROR;
Aravind Akella7830ef32014-10-07 14:13:12 -0700201 run("SensorService", PRIORITY_URGENT_DISPLAY);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700202 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700203 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700204}
205
Mathias Agopian03193062013-05-10 19:32:39 -0700206Sensor SensorService::registerSensor(SensorInterface* s)
Mathias Agopianf001c922010-11-11 17:58:51 -0800207{
208 sensors_event_t event;
209 memset(&event, 0, sizeof(event));
210
211 const Sensor sensor(s->getSensor());
212 // add to the sensor list (returned to clients)
213 mSensorList.add(sensor);
214 // add to our handle->SensorInterface mapping
215 mSensorMap.add(sensor.getHandle(), s);
216 // create an entry in the mLastEventSeen array
Aravind Akella444f2672015-05-07 12:40:52 -0700217 mLastEventSeen.add(sensor.getHandle(), NULL);
Mathias Agopian03193062013-05-10 19:32:39 -0700218
219 return sensor;
Mathias Agopianf001c922010-11-11 17:58:51 -0800220}
221
Mathias Agopian03193062013-05-10 19:32:39 -0700222Sensor SensorService::registerVirtualSensor(SensorInterface* s)
Mathias Agopianf001c922010-11-11 17:58:51 -0800223{
Mathias Agopian03193062013-05-10 19:32:39 -0700224 Sensor sensor = registerSensor(s);
Mathias Agopianf001c922010-11-11 17:58:51 -0800225 mVirtualSensorList.add( s );
Mathias Agopian03193062013-05-10 19:32:39 -0700226 return sensor;
Mathias Agopianf001c922010-11-11 17:58:51 -0800227}
228
Mathias Agopianfc328812010-07-14 23:41:37 -0700229SensorService::~SensorService()
230{
Mathias Agopianf001c922010-11-11 17:58:51 -0800231 for (size_t i=0 ; i<mSensorMap.size() ; i++)
232 delete mSensorMap.valueAt(i);
Mathias Agopianfc328812010-07-14 23:41:37 -0700233}
234
Aravind Akella4949c502015-02-11 15:54:35 -0800235status_t SensorService::dump(int fd, const Vector<String16>& args)
Mathias Agopianfc328812010-07-14 23:41:37 -0700236{
Mathias Agopianfc328812010-07-14 23:41:37 -0700237 String8 result;
Mathias Agopian1cb13462011-06-27 16:05:52 -0700238 if (!PermissionCache::checkCallingPermission(sDump)) {
Mathias Agopianba02cd22013-07-03 16:20:57 -0700239 result.appendFormat("Permission Denial: "
Aravind Akella70018042014-04-07 22:52:37 +0000240 "can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700241 IPCThreadState::self()->getCallingPid(),
242 IPCThreadState::self()->getCallingUid());
Aravind Akella444f2672015-05-07 12:40:52 -0700243 } else {
Aravind Akella4949c502015-02-11 15:54:35 -0800244 if (args.size() > 1) {
245 return INVALID_OPERATION;
246 }
247 Mutex::Autolock _l(mLock);
248 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akella444f2672015-05-07 12:40:52 -0700249 if (args.size() == 1 && args[0] == String16("restrict")) {
250 // If already in restricted mode. Ignore.
251 if (mCurrentOperatingMode == RESTRICTED) {
252 return status_t(NO_ERROR);
253 }
254 // If in any mode other than normal, ignore.
255 if (mCurrentOperatingMode != NORMAL) {
256 return INVALID_OPERATION;
257 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700258 mCurrentOperatingMode = RESTRICTED;
Aravind Akella4949c502015-02-11 15:54:35 -0800259 dev.disableAllSensors();
260 // Clear all pending flush connections for all active sensors. If one of the active
261 // connections has called flush() and the underlying sensor has been disabled before a
262 // flush complete event is returned, we need to remove the connection from this queue.
263 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
264 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
265 }
Aravind Akella444f2672015-05-07 12:40:52 -0700266 return status_t(NO_ERROR);
267 } else if (args.size() == 1 && args[0] == String16("enable")) {
268 // If currently in restricted mode, reset back to NORMAL mode else ignore.
269 if (mCurrentOperatingMode == RESTRICTED) {
270 mCurrentOperatingMode = NORMAL;
271 dev.enableAllSensors();
272 }
273 return status_t(NO_ERROR);
Aravind Akellaee155ca2015-06-24 08:31:32 -0700274 } else if (mSensorList.size() == 0) {
275 result.append("No Sensors on the device\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700276 } else {
277 // Default dump the sensor list and debugging information.
278 result.append("Sensor List:\n");
279 for (size_t i=0 ; i<mSensorList.size() ; i++) {
280 const Sensor& s(mSensorList[i]);
281 result.appendFormat(
282 "%-15s| %-10s| version=%d |%-20s| 0x%08x | \"%s\" | type=%d |",
283 s.getName().string(),
284 s.getVendor().string(),
285 s.getVersion(),
286 s.getStringType().string(),
287 s.getHandle(),
288 s.getRequiredPermission().string(),
289 s.getType());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700290
Aravind Akella444f2672015-05-07 12:40:52 -0700291 const int reportingMode = s.getReportingMode();
292 if (reportingMode == AREPORTING_MODE_CONTINUOUS) {
293 result.append(" continuous | ");
294 } else if (reportingMode == AREPORTING_MODE_ON_CHANGE) {
295 result.append(" on-change | ");
296 } else if (reportingMode == AREPORTING_MODE_ONE_SHOT) {
297 result.append(" one-shot | ");
298 } else {
299 result.append(" special-trigger | ");
300 }
301
302 if (s.getMaxDelay() > 0) {
303 result.appendFormat("minRate=%.2fHz | ", 1e6f / s.getMaxDelay());
304 } else {
305 result.appendFormat("maxDelay=%dus |", s.getMaxDelay());
306 }
307
308 if (s.getMinDelay() > 0) {
309 result.appendFormat("maxRate=%.2fHz | ", 1e6f / s.getMinDelay());
310 } else {
311 result.appendFormat("minDelay=%dus |", s.getMinDelay());
312 }
313
314 if (s.getFifoMaxEventCount() > 0) {
315 result.appendFormat("FifoMax=%d events | ",
316 s.getFifoMaxEventCount());
317 } else {
318 result.append("no batching | ");
319 }
320
321 if (s.isWakeUpSensor()) {
322 result.appendFormat("wakeUp | ");
323 } else {
324 result.appendFormat("non-wakeUp | ");
325 }
326
327 const CircularBuffer* buf = mLastEventSeen.valueFor(s.getHandle());
328 if (buf != NULL && s.getRequiredPermission().isEmpty()) {
329 buf->printBuffer(result);
330 } else {
331 result.append("last=<> \n");
332 }
333 result.append("\n");
334 }
335 SensorFusion::getInstance().dump(result);
336 SensorDevice::getInstance().dump(result);
337
338 result.append("Active sensors:\n");
339 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
340 int handle = mActiveSensors.keyAt(i);
341 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
342 getSensorName(handle).string(),
343 handle,
344 mActiveSensors.valueAt(i)->getNumConnections());
Aravind Akella6c2664a2014-08-13 12:24:50 -0700345 }
346
Aravind Akella444f2672015-05-07 12:40:52 -0700347 result.appendFormat("Socket Buffer size = %d events\n",
348 mSocketBufferSize/sizeof(sensors_event_t));
349 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" : "not held");
350 result.appendFormat("Mode :");
351 switch(mCurrentOperatingMode) {
352 case NORMAL:
353 result.appendFormat(" NORMAL\n");
354 break;
355 case RESTRICTED:
356 result.appendFormat(" RESTRICTED\n");
357 break;
358 case DATA_INJECTION:
359 result.appendFormat(" DATA_INJECTION\n");
Mathias Agopianba02cd22013-07-03 16:20:57 -0700360 }
Aravind Akella444f2672015-05-07 12:40:52 -0700361 result.appendFormat("%zd active connections\n", mActiveConnections.size());
Aravind Akella0e025c52014-06-03 19:19:57 -0700362
Aravind Akella444f2672015-05-07 12:40:52 -0700363 for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
364 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
365 if (connection != 0) {
366 result.appendFormat("Connection Number: %zu \n", i);
367 connection->dump(result);
368 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700369 }
370 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700371 }
372 write(fd, result.string(), result.size());
373 return NO_ERROR;
374}
375
Aravind Akella9a844cf2014-02-11 18:58:52 -0800376void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700377 sensors_event_t const* buffer, const int count) {
378 for (int i=0 ; i<count ; i++) {
379 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700380 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
381 handle = buffer[i].meta_data.sensor;
382 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700383 if (connection->hasSensor(handle)) {
384 SensorInterface* sensor = mSensorMap.valueFor(handle);
385 // If this buffer has an event from a one_shot sensor and this connection is registered
386 // for this particular one_shot sensor, try cleaning up the connection.
387 if (sensor != NULL &&
388 sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
389 sensor->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800390 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700391 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700392
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700393 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700394 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700395}
396
Mathias Agopianfc328812010-07-14 23:41:37 -0700397bool SensorService::threadLoop()
398{
Steve Blocka5512372011-12-20 16:23:08 +0000399 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700400
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700401 // each virtual sensor could generate an event per "real" event, that's why we need
402 // to size numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT.
403 // in practice, this is too aggressive, but guaranteed to be enough.
404 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
405 const size_t numEventMax = minBufferSize / (1 + mVirtualSensorList.size());
406
Mathias Agopianf001c922010-11-11 17:58:51 -0800407 SensorDevice& device(SensorDevice::getInstance());
408 const size_t vcount = mVirtualSensorList.size();
Mathias Agopianfc328812010-07-14 23:41:37 -0700409
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700410 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700411 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700412 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
413 if (count < 0) {
Steve Blockf5a12302012-01-06 19:20:56 +0000414 ALOGE("sensor poll failed (%s)", strerror(-count));
Mathias Agopianfc328812010-07-14 23:41:37 -0700415 break;
416 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700417
418 // Reset sensors_event_t.flags to zero for all events in the buffer.
419 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700420 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700421 }
Aravind Akellae148bc22014-09-24 22:12:58 -0700422
423 // Make a copy of the connection vector as some connections may be removed during the
424 // course of this loop (especially when one-shot sensor events are present in the
425 // sensor_event buffer). Promote all connections to StrongPointers before the lock is
426 // acquired. If the destructor of the sp gets called when the lock is acquired, it may
427 // result in a deadlock as ~SensorEventConnection() needs to acquire mLock again for
428 // cleanup. So copy all the strongPointers to a vector before the lock is acquired.
429 SortedVector< sp<SensorEventConnection> > activeConnections;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700430 populateActiveConnections(&activeConnections);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800431 Mutex::Autolock _l(mLock);
432 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
433 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
434 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
435 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
436 // releasing the wakelock.
437 bool bufferHasWakeUpEvent = false;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700438 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700439 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800440 bufferHasWakeUpEvent = true;
441 break;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700442 }
443 }
444
Aravind Akella9a844cf2014-02-11 18:58:52 -0800445 if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700446 setWakeLockAcquiredLocked(true);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800447 }
Aravind Akella8493b792014-09-08 15:45:47 -0700448 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800449
Mathias Agopianf001c922010-11-11 17:58:51 -0800450 // handle virtual sensors
451 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700452 sensors_event_t const * const event = mSensorEventBuffer;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800453 const size_t activeVirtualSensorCount = mActiveVirtualSensors.size();
Mathias Agopianf001c922010-11-11 17:58:51 -0800454 if (activeVirtualSensorCount) {
455 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700456 SensorFusion& fusion(SensorFusion::getInstance());
457 if (fusion.isEnabled()) {
458 for (size_t i=0 ; i<size_t(count) ; i++) {
459 fusion.process(event[i]);
460 }
461 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700462 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800463 for (size_t j=0 ; j<activeVirtualSensorCount ; j++) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700464 if (count + k >= minBufferSize) {
465 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700466 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700467 count, k, minBufferSize);
468 break;
469 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800470 sensors_event_t out;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800471 SensorInterface* si = mActiveVirtualSensors.valueAt(j);
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700472 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700473 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800474 k++;
475 }
476 }
477 }
478 if (k) {
479 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700480 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800481 count += k;
482 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700483 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700484 }
485 }
486 }
487
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700488 // handle backward compatibility for RotationVector sensor
489 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
490 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700491 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700492 // All the 4 components of the quaternion should be available
493 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700494 mSensorEventBuffer[i].data[4] = -1;
495 }
496 }
497 }
498
499 // Map flush_complete_events in the buffer to SensorEventConnections which called
500 // flush on the hardware sensor. mapFlushEventsToConnections[i] will be the
501 // SensorEventConnection mapped to the corresponding flush_complete_event in
502 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
503 for (int i = 0; i < count; ++i) {
504 mMapFlushEventsToConnections[i] = NULL;
505 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
506 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
507 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
508 if (rec != NULL) {
509 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
510 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700511 }
512 }
513 }
514
Aravind Akella9a844cf2014-02-11 18:58:52 -0800515 // Send our events to clients. Check the state of wake lock for each client and release the
516 // lock if none of the clients need it.
517 bool needsWakeLock = false;
Aravind Akella8493b792014-09-08 15:45:47 -0700518 size_t numConnections = activeConnections.size();
519 for (size_t i=0 ; i < numConnections; ++i) {
Aravind Akellae148bc22014-09-24 22:12:58 -0700520 if (activeConnections[i] != 0) {
521 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
Aravind Akella8493b792014-09-08 15:45:47 -0700522 mMapFlushEventsToConnections);
Aravind Akellae148bc22014-09-24 22:12:58 -0700523 needsWakeLock |= activeConnections[i]->needsWakeLock();
Aravind Akella8493b792014-09-08 15:45:47 -0700524 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
525 // Early check for one-shot sensors.
Aravind Akellae148bc22014-09-24 22:12:58 -0700526 if (activeConnections[i]->hasOneShotSensors()) {
527 cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
528 count);
Aravind Akella8493b792014-09-08 15:45:47 -0700529 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800530 }
531 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700532
Aravind Akella9a844cf2014-02-11 18:58:52 -0800533 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700534 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800535 }
Aravind Akella8493b792014-09-08 15:45:47 -0700536 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -0700537
Steve Block3c20fbe2012-01-05 23:22:43 +0000538 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -0800539 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -0700540 return false;
541}
542
Aravind Akella56ae4262014-07-10 16:01:10 -0700543sp<Looper> SensorService::getLooper() const {
544 return mLooper;
545}
546
Aravind Akellab4373ac2014-10-29 17:55:20 -0700547void SensorService::resetAllWakeLockRefCounts() {
548 SortedVector< sp<SensorEventConnection> > activeConnections;
549 populateActiveConnections(&activeConnections);
550 {
551 Mutex::Autolock _l(mLock);
552 for (size_t i=0 ; i < activeConnections.size(); ++i) {
553 if (activeConnections[i] != 0) {
554 activeConnections[i]->resetWakeLockRefCount();
555 }
556 }
557 setWakeLockAcquiredLocked(false);
558 }
559}
560
561void SensorService::setWakeLockAcquiredLocked(bool acquire) {
562 if (acquire) {
563 if (!mWakeLockAcquired) {
564 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
565 mWakeLockAcquired = true;
566 }
567 mLooper->wake();
568 } else {
569 if (mWakeLockAcquired) {
570 release_wake_lock(WAKE_LOCK_NAME);
571 mWakeLockAcquired = false;
572 }
573 }
574}
575
Aravind Akellab4373ac2014-10-29 17:55:20 -0700576bool SensorService::isWakeLockAcquired() {
577 Mutex::Autolock _l(mLock);
578 return mWakeLockAcquired;
579}
580
Aravind Akella56ae4262014-07-10 16:01:10 -0700581bool SensorService::SensorEventAckReceiver::threadLoop() {
582 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -0700583 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -0700584 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700585 bool wakeLockAcquired = mService->isWakeLockAcquired();
586 int timeout = -1;
587 if (wakeLockAcquired) timeout = 5000;
588 int ret = looper->pollOnce(timeout);
589 if (ret == ALOOPER_POLL_TIMEOUT) {
590 mService->resetAllWakeLockRefCounts();
591 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700592 } while(!Thread::exitPending());
593 return false;
594}
595
Aravind Akella9a844cf2014-02-11 18:58:52 -0800596void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -0800597 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -0800598 for (size_t i = 0; i < count; i++) {
Aravind Akella444f2672015-05-07 12:40:52 -0700599 if (buffer[i].type != SENSOR_TYPE_META_DATA) {
600 CircularBuffer* &circular_buf = mLastEventSeen.editValueFor(buffer[i].sensor);
601 if (circular_buf == NULL) {
602 circular_buf = new CircularBuffer(buffer[i].type);
Aravind Akella4b847042014-03-03 19:02:46 -0800603 }
Aravind Akella444f2672015-05-07 12:40:52 -0700604 circular_buf->addEvent(buffer[i]);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800605 }
606 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800607}
608
Mathias Agopianf001c922010-11-11 17:58:51 -0800609void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count)
610{
611 struct compar {
612 static int cmp(void const* lhs, void const* rhs) {
613 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
614 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -0700615 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -0800616 }
617 };
618 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
619}
620
Mathias Agopian5d270722010-07-19 15:20:39 -0700621String8 SensorService::getSensorName(int handle) const {
Mathias Agopian010e4222011-06-08 20:06:50 -0700622 size_t count = mUserSensorList.size();
Mathias Agopian5d270722010-07-19 15:20:39 -0700623 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian010e4222011-06-08 20:06:50 -0700624 const Sensor& sensor(mUserSensorList[i]);
Mathias Agopian5d270722010-07-19 15:20:39 -0700625 if (sensor.getHandle() == handle) {
626 return sensor.getName();
627 }
628 }
629 String8 result("unknown");
630 return result;
631}
632
Aravind Akellab4099e72013-10-15 15:43:10 -0700633bool SensorService::isVirtualSensor(int handle) const {
634 SensorInterface* sensor = mSensorMap.valueFor(handle);
635 return sensor->isVirtual();
636}
637
Aravind Akella9a844cf2014-02-11 18:58:52 -0800638bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -0700639 int handle = event.sensor;
640 if (event.type == SENSOR_TYPE_META_DATA) {
641 handle = event.meta_data.sensor;
642 }
643 SensorInterface* sensor = mSensorMap.valueFor(handle);
644 return sensor != NULL && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -0800645}
646
Aravind Akella6c2664a2014-08-13 12:24:50 -0700647SensorService::SensorRecord * SensorService::getSensorRecord(int handle) {
648 return mActiveSensors.valueFor(handle);
649}
650
Svetoslavb412f6e2015-04-29 16:50:41 -0700651Vector<Sensor> SensorService::getSensorList(const String16& opPackageName)
Mathias Agopianfc328812010-07-14 23:41:37 -0700652{
Mathias Agopian33264862012-06-28 19:46:54 -0700653 char value[PROPERTY_VALUE_MAX];
654 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +0000655 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
656 mUserSensorListDebug : mUserSensorList;
657 Vector<Sensor> accessibleSensorList;
658 for (size_t i = 0; i < initialSensorList.size(); i++) {
659 Sensor sensor = initialSensorList[i];
Svetoslavb412f6e2015-04-29 16:50:41 -0700660 if (canAccessSensor(sensor, "getSensorList", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +0000661 accessibleSensorList.add(sensor);
662 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -0700663 ALOGI("Skipped sensor %s because it requires permission %s and app op %d",
Bernhard Rosenkränzer5f619932014-11-17 21:06:20 +0100664 sensor.getName().string(),
Svetoslavb412f6e2015-04-29 16:50:41 -0700665 sensor.getRequiredPermission().string(),
666 sensor.getRequiredAppOp());
Aravind Akella70018042014-04-07 22:52:37 +0000667 }
Mathias Agopian33264862012-06-28 19:46:54 -0700668 }
Aravind Akella70018042014-04-07 22:52:37 +0000669 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -0700670}
671
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700672sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -0700673 int requestedMode, const String16& opPackageName) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700674 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
675 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
676 return NULL;
677 }
678 // DATA_INJECTION mode needs to have the required permissions set.
679 if (requestedMode == DATA_INJECTION && !hasDataInjectionPermissions()) {
680 return NULL;
681 }
682
683 Mutex::Autolock _l(mLock);
Mathias Agopian5307d172012-09-18 17:02:43 -0700684 uid_t uid = IPCThreadState::self()->getCallingUid();
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700685 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -0700686 requestedMode == DATA_INJECTION, opPackageName));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700687 if (requestedMode == DATA_INJECTION) {
688 if (mActiveConnections.indexOf(result) < 0) {
689 mActiveConnections.add(result);
690 }
691 // Add the associated file descriptor to the Looper for polling whenever there is data to
692 // be injected.
693 result->updateLooperRegistration(mLooper);
694 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700695 return result;
696}
697
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700698status_t SensorService::enableDataInjection(int requestedMode) {
699 if (!hasDataInjectionPermissions()) {
700 return INVALID_OPERATION;
701 }
702 Mutex::Autolock _l(mLock);
703 ALOGD_IF(DEBUG_CONNECTIONS, "SensorService::enableDataInjection %d", requestedMode);
704 SensorDevice& dev(SensorDevice::getInstance());
705 status_t err(NO_ERROR);
706 if (requestedMode == DATA_INJECTION) {
707 if (mCurrentOperatingMode == NORMAL) {
708 dev.disableAllSensors();
709 err = dev.setMode(requestedMode);
710 if (err == NO_ERROR) {
711 mCurrentOperatingMode = DATA_INJECTION;
712 } else {
713 // Re-enable sensors.
714 dev.enableAllSensors();
715 }
716 } else if (mCurrentOperatingMode == DATA_INJECTION) {
717 // Already in DATA_INJECTION mode. Treat this as a no_op.
718 return NO_ERROR;
719 } else {
720 // Transition to data injection mode supported only from NORMAL mode.
721 return INVALID_OPERATION;
722 }
723 } else if (requestedMode == NORMAL && mCurrentOperatingMode != NORMAL) {
724 err = resetToNormalModeLocked();
725 }
726 return err;
727}
728
729status_t SensorService::resetToNormalMode() {
730 Mutex::Autolock _l(mLock);
731 return resetToNormalModeLocked();
732}
733
734status_t SensorService::resetToNormalModeLocked() {
735 SensorDevice& dev(SensorDevice::getInstance());
736 dev.enableAllSensors();
737 status_t err = dev.setMode(NORMAL);
738 mCurrentOperatingMode = NORMAL;
739 return err;
740}
741
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800742void SensorService::cleanupConnection(SensorEventConnection* c)
Mathias Agopianfc328812010-07-14 23:41:37 -0700743{
744 Mutex::Autolock _l(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800745 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700746 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -0700747 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700748 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800749 int handle = mActiveSensors.keyAt(i);
750 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -0700751 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800752 SensorInterface* sensor = mSensorMap.valueFor( handle );
Steve Blockf5a12302012-01-06 19:20:56 +0000753 ALOGE_IF(!sensor, "mSensorMap[handle=0x%08x] is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800754 if (sensor) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800755 sensor->activate(c, false);
Mathias Agopianf001c922010-11-11 17:58:51 -0800756 }
Aravind Akella8a969552014-09-28 17:52:41 -0700757 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800758 }
759 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -0700760 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +0000761 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -0700762 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700763 c, i, handle);
764
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800765 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +0000766 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700767 mActiveSensors.removeItemsAt(i, 1);
Mathias Agopianf001c922010-11-11 17:58:51 -0800768 mActiveVirtualSensors.removeItem(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700769 delete rec;
770 size--;
771 } else {
772 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -0700773 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700774 }
Aravind Akella8a969552014-09-28 17:52:41 -0700775 c->updateLooperRegistration(mLooper);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700776 mActiveConnections.remove(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -0700777 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -0800778 if (c->needsWakeLock()) {
779 checkWakeLockStateLocked();
780 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700781}
782
Aravind Akella70018042014-04-07 22:52:37 +0000783Sensor SensorService::getSensorFromHandle(int handle) const {
784 return mSensorMap.valueFor(handle)->getSensor();
785}
786
Mathias Agopianfc328812010-07-14 23:41:37 -0700787status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -0700788 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
789 const String16& opPackageName)
Mathias Agopianfc328812010-07-14 23:41:37 -0700790{
Mathias Agopian50df2952010-07-19 19:09:10 -0700791 if (mInitCheck != NO_ERROR)
792 return mInitCheck;
793
Mathias Agopianf001c922010-11-11 17:58:51 -0800794 SensorInterface* sensor = mSensorMap.valueFor(handle);
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700795 if (sensor == NULL) {
796 return BAD_VALUE;
797 }
Aravind Akella70018042014-04-07 22:52:37 +0000798
Svetoslavb412f6e2015-04-29 16:50:41 -0700799 if (!canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +0000800 return BAD_VALUE;
801 }
802
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700803 Mutex::Autolock _l(mLock);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700804 if (mCurrentOperatingMode == RESTRICTED && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -0800805 return INVALID_OPERATION;
806 }
807
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700808 SensorRecord* rec = mActiveSensors.valueFor(handle);
809 if (rec == 0) {
810 rec = new SensorRecord(connection);
811 mActiveSensors.add(handle, rec);
812 if (sensor->isVirtual()) {
813 mActiveVirtualSensors.add(handle, sensor);
814 }
815 } else {
816 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800817 // this sensor is already activated, but we are adding a connection that uses it.
818 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700819 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -0700820 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800821 // NOTE: The wake_up flag of this event may get set to
822 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Aravind Akella444f2672015-05-07 12:40:52 -0700823 CircularBuffer *circular_buf = mLastEventSeen.valueFor(handle);
824 if (circular_buf) {
825 sensors_event_t event;
826 memset(&event, 0, sizeof(event));
827 // It is unlikely that this buffer is empty as the sensor is already active.
828 // One possible corner case may be two applications activating an on-change
829 // sensor at the same time.
830 if(circular_buf->populateLastEvent(&event)) {
831 event.sensor = handle;
832 if (event.version == sizeof(sensors_event_t)) {
833 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
834 setWakeLockAcquiredLocked(true);
835 }
836 connection->sendEvents(&event, 1, NULL);
837 if (!connection->needsWakeLock() && mWakeLockAcquired) {
838 checkWakeLockStateLocked();
839 }
840 }
Aravind Akella9a844cf2014-02-11 18:58:52 -0800841 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700842 }
843 }
844 }
845 }
846
847 if (connection->addSensor(handle)) {
848 BatteryService::enableSensor(connection->getUid(), handle);
849 // the sensor was added (which means it wasn't already there)
850 // so, see if this connection becomes active
851 if (mActiveConnections.indexOf(connection) < 0) {
852 mActiveConnections.add(connection);
853 }
854 } else {
855 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
856 handle, connection.get());
857 }
858
Aravind Akella724d91d2013-06-27 12:04:23 -0700859 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
860 if (samplingPeriodNs < minDelayNs) {
861 samplingPeriodNs = minDelayNs;
862 }
863
Aravind Akella6c2664a2014-08-13 12:24:50 -0700864 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
865 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -0700866 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
867
Aravind Akella4949c502015-02-11 15:54:35 -0800868 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -0700869 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -0700870
Aravind Akella5466c3d2014-08-22 16:11:10 -0700871 // Call flush() before calling activate() on the sensor. Wait for a first flush complete
872 // event before sending events on this connection. Ignore one-shot sensors which don't
873 // support flush(). Also if this sensor isn't already active, don't call flush().
874 if (err == NO_ERROR && sensor->getSensor().getReportingMode() != AREPORTING_MODE_ONE_SHOT &&
875 rec->getNumConnections() > 1) {
876 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700877 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -0700878 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -0700879 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700880 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -0700881 } else {
882 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700883 }
884 }
Aravind Akella724d91d2013-06-27 12:04:23 -0700885
886 if (err == NO_ERROR) {
887 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
888 err = sensor->activate(connection.get(), true);
889 }
890
Aravind Akella8a969552014-09-28 17:52:41 -0700891 if (err == NO_ERROR) {
892 connection->updateLooperRegistration(mLooper);
Aravind Akella56ae4262014-07-10 16:01:10 -0700893 }
894
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700895 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -0700896 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700897 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700898 }
899 return err;
900}
901
902status_t SensorService::disable(const sp<SensorEventConnection>& connection,
903 int handle)
904{
Mathias Agopian50df2952010-07-19 19:09:10 -0700905 if (mInitCheck != NO_ERROR)
906 return mInitCheck;
907
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700908 Mutex::Autolock _l(mLock);
909 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700910 if (err == NO_ERROR) {
911 SensorInterface* sensor = mSensorMap.valueFor(handle);
912 err = sensor ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
913 }
914 return err;
915}
916
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700917status_t SensorService::cleanupWithoutDisable(
918 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700919 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700920 return cleanupWithoutDisableLocked(connection, handle);
921}
922
923status_t SensorService::cleanupWithoutDisableLocked(
924 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700925 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700926 if (rec) {
927 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -0700928 if (connection->removeSensor(handle)) {
929 BatteryService::disableSensor(connection->getUid(), handle);
930 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700931 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -0700932 connection->updateLooperRegistration(mLooper);
Mathias Agopianfc328812010-07-14 23:41:37 -0700933 mActiveConnections.remove(connection);
934 }
935 // see if this sensor becomes inactive
936 if (rec->removeConnection(connection)) {
937 mActiveSensors.removeItem(handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800938 mActiveVirtualSensors.removeItem(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700939 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -0700940 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700941 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700942 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700943 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -0700944}
945
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700946status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -0700947 int handle, nsecs_t ns, const String16& opPackageName)
Mathias Agopianfc328812010-07-14 23:41:37 -0700948{
Mathias Agopian50df2952010-07-19 19:09:10 -0700949 if (mInitCheck != NO_ERROR)
950 return mInitCheck;
951
Mathias Agopianae09d652011-11-01 17:37:49 -0700952 SensorInterface* sensor = mSensorMap.valueFor(handle);
953 if (!sensor)
954 return BAD_VALUE;
955
Svetoslavb412f6e2015-04-29 16:50:41 -0700956 if (!canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +0000957 return BAD_VALUE;
958 }
959
Mathias Agopian1cd70002010-07-21 15:59:50 -0700960 if (ns < 0)
961 return BAD_VALUE;
962
Mathias Agopian62569ec2011-11-07 21:21:47 -0800963 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
964 if (ns < minDelayNs) {
965 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -0700966 }
967
Mathias Agopianf001c922010-11-11 17:58:51 -0800968 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -0700969}
970
Svetoslavb412f6e2015-04-29 16:50:41 -0700971status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
972 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +0000973 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -0700974 SensorDevice& dev(SensorDevice::getInstance());
975 const int halVersion = dev.getHalDeviceVersion();
976 status_t err(NO_ERROR);
977 Mutex::Autolock _l(mLock);
978 // Loop through all sensors for this connection and call flush on each of them.
979 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
980 const int handle = connection->mSensorInfo.keyAt(i);
981 SensorInterface* sensor = mSensorMap.valueFor(handle);
982 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
983 ALOGE("flush called on a one-shot sensor");
984 err = INVALID_OPERATION;
985 continue;
986 }
Aravind Akella8493b792014-09-08 15:45:47 -0700987 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -0700988 // For older devices just increment pending flush count which will send a trivial
989 // flush complete event.
Aravind Akella8a969552014-09-28 17:52:41 -0700990 connection->incrementPendingFlushCount(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -0700991 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -0700992 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
993 err = INVALID_OPERATION;
994 continue;
995 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -0700996 status_t err_flush = sensor->flush(connection.get(), handle);
997 if (err_flush == NO_ERROR) {
998 SensorRecord* rec = mActiveSensors.valueFor(handle);
999 if (rec != NULL) rec->addPendingFlushConnection(connection);
1000 }
1001 err = (err_flush != NO_ERROR) ? err_flush : err;
1002 }
Aravind Akella70018042014-04-07 22:52:37 +00001003 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001004 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001005}
Aravind Akella70018042014-04-07 22:52:37 +00001006
Svetoslavb412f6e2015-04-29 16:50:41 -07001007bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1008 const String16& opPackageName) {
1009 const String8& requiredPermission = sensor.getRequiredPermission();
Aravind Akella70018042014-04-07 22:52:37 +00001010
Svetoslavb412f6e2015-04-29 16:50:41 -07001011 if (requiredPermission.length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00001012 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07001013 }
1014
1015 bool hasPermission = false;
1016
1017 // Runtime permissions can't use the cache as they may change.
1018 if (sensor.isRequiredPermissionRuntime()) {
1019 hasPermission = checkPermission(String16(requiredPermission),
1020 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Aravind Akella70018042014-04-07 22:52:37 +00001021 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001022 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1023 }
1024
1025 if (!hasPermission) {
1026 ALOGE("%s a sensor (%s) without holding its required permission: %s",
1027 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
Aravind Akella70018042014-04-07 22:52:37 +00001028 return false;
1029 }
Svetoslavb412f6e2015-04-29 16:50:41 -07001030
1031 const int32_t opCode = sensor.getRequiredAppOp();
1032 if (opCode >= 0) {
1033 AppOpsManager appOps;
1034 if (appOps.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName)
1035 != AppOpsManager::MODE_ALLOWED) {
1036 ALOGE("%s a sensor (%s) without enabled required app op: %D",
1037 operation, sensor.getName().string(), opCode);
1038 return false;
1039 }
1040 }
1041
1042 return true;
Aravind Akella70018042014-04-07 22:52:37 +00001043}
1044
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001045bool SensorService::hasDataInjectionPermissions() {
1046 if (!PermissionCache::checkCallingPermission(sDataInjectionPermission)) {
1047 ALOGE("Permission Denial trying to activate data injection without"
1048 " the required permission");
1049 return false;
1050 }
1051 return true;
1052}
1053
Aravind Akella9a844cf2014-02-11 18:58:52 -08001054void SensorService::checkWakeLockState() {
1055 Mutex::Autolock _l(mLock);
1056 checkWakeLockStateLocked();
1057}
1058
1059void SensorService::checkWakeLockStateLocked() {
1060 if (!mWakeLockAcquired) {
1061 return;
1062 }
1063 bool releaseLock = true;
1064 for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
1065 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1066 if (connection != 0) {
1067 if (connection->needsWakeLock()) {
1068 releaseLock = false;
1069 break;
1070 }
1071 }
1072 }
1073 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001074 setWakeLockAcquiredLocked(false);
1075 }
1076}
1077
1078void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1079 Mutex::Autolock _l(mLock);
1080 connection->writeToSocketFromCache();
1081 if (connection->needsWakeLock()) {
1082 setWakeLockAcquiredLocked(true);
1083 }
1084}
1085
1086void SensorService::populateActiveConnections(
1087 SortedVector< sp<SensorEventConnection> >* activeConnections) {
1088 Mutex::Autolock _l(mLock);
1089 for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
1090 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1091 if (connection != 0) {
1092 activeConnections->add(connection);
1093 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001094 }
1095}
Aravind Akella6c2664a2014-08-13 12:24:50 -07001096
Aravind Akella4949c502015-02-11 15:54:35 -08001097bool SensorService::isWhiteListedPackage(const String8& packageName) {
1098 // TODO: Come up with a list of packages.
1099 return (packageName.find(".cts.") != -1);
1100}
1101
Aravind Akella444f2672015-05-07 12:40:52 -07001102int SensorService::getNumEventsForSensorType(int sensor_event_type) {
1103 switch (sensor_event_type) {
1104 case SENSOR_TYPE_ROTATION_VECTOR:
1105 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
1106 return 5;
1107
1108 case SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED:
1109 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
1110 return 6;
1111
1112 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
1113 return 4;
1114
1115 case SENSOR_TYPE_SIGNIFICANT_MOTION:
1116 case SENSOR_TYPE_STEP_DETECTOR:
1117 case SENSOR_TYPE_STEP_COUNTER:
1118 return 1;
1119
1120 default:
1121 return 3;
1122 }
1123}
1124
Mathias Agopianfc328812010-07-14 23:41:37 -07001125// ---------------------------------------------------------------------------
Mathias Agopianfc328812010-07-14 23:41:37 -07001126SensorService::SensorRecord::SensorRecord(
1127 const sp<SensorEventConnection>& connection)
1128{
1129 mConnections.add(connection);
1130}
1131
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001132bool SensorService::SensorRecord::addConnection(
Mathias Agopianfc328812010-07-14 23:41:37 -07001133 const sp<SensorEventConnection>& connection)
1134{
1135 if (mConnections.indexOf(connection) < 0) {
1136 mConnections.add(connection);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001137 return true;
Mathias Agopianfc328812010-07-14 23:41:37 -07001138 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001139 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -07001140}
1141
1142bool SensorService::SensorRecord::removeConnection(
1143 const wp<SensorEventConnection>& connection)
1144{
1145 ssize_t index = mConnections.indexOf(connection);
1146 if (index >= 0) {
1147 mConnections.removeItemsAt(index, 1);
1148 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001149 // Remove this connections from the queue of flush() calls made on this sensor.
1150 for (Vector< wp<SensorEventConnection> >::iterator it =
1151 mPendingFlushConnections.begin(); it != mPendingFlushConnections.end();) {
Aravind Akella8a969552014-09-28 17:52:41 -07001152
Aravind Akella6c2664a2014-08-13 12:24:50 -07001153 if (it->unsafe_get() == connection.unsafe_get()) {
1154 it = mPendingFlushConnections.erase(it);
1155 } else {
1156 ++it;
1157 }
1158 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001159 return mConnections.size() ? false : true;
1160}
1161
Aravind Akella6c2664a2014-08-13 12:24:50 -07001162void SensorService::SensorRecord::addPendingFlushConnection(
1163 const sp<SensorEventConnection>& connection) {
1164 mPendingFlushConnections.add(connection);
1165}
1166
1167void SensorService::SensorRecord::removeFirstPendingFlushConnection() {
1168 if (mPendingFlushConnections.size() > 0) {
1169 mPendingFlushConnections.removeAt(0);
1170 }
1171}
1172
1173SensorService::SensorEventConnection *
1174SensorService::SensorRecord::getFirstPendingFlushConnection() {
1175 if (mPendingFlushConnections.size() > 0) {
1176 return mPendingFlushConnections[0].unsafe_get();
1177 }
1178 return NULL;
1179}
1180
Aravind Akella4949c502015-02-11 15:54:35 -08001181void SensorService::SensorRecord::clearAllPendingFlushConnections() {
1182 mPendingFlushConnections.clear();
1183}
1184
Aravind Akella444f2672015-05-07 12:40:52 -07001185// --------------------------------------------------------------------------
1186SensorService::CircularBuffer::CircularBuffer(int sensor_event_type) {
1187 mNextInd = 0;
1188 mTrimmedSensorEventArr = new TrimmedSensorEvent *[CIRCULAR_BUF_SIZE];
1189 mSensorType = sensor_event_type;
1190 const int numData = SensorService::getNumEventsForSensorType(mSensorType);
1191 for (int i = 0; i < CIRCULAR_BUF_SIZE; ++i) {
1192 mTrimmedSensorEventArr[i] = new TrimmedSensorEvent(numData, mSensorType);
1193 }
1194}
1195
1196void SensorService::CircularBuffer::addEvent(const sensors_event_t& sensor_event) {
1197 TrimmedSensorEvent *curr_event = mTrimmedSensorEventArr[mNextInd];
1198 curr_event->mTimestamp = sensor_event.timestamp;
1199 if (mSensorType == SENSOR_TYPE_STEP_COUNTER) {
1200 curr_event->mStepCounter = sensor_event.u64.step_counter;
1201 } else {
1202 memcpy(curr_event->mData, sensor_event.data,
1203 sizeof(float) * SensorService::getNumEventsForSensorType(mSensorType));
1204 }
1205 time_t rawtime = time(NULL);
1206 struct tm * timeinfo = localtime(&rawtime);
1207 curr_event->mHour = timeinfo->tm_hour;
1208 curr_event->mMin = timeinfo->tm_min;
1209 curr_event->mSec = timeinfo->tm_sec;
1210 mNextInd = (mNextInd + 1) % CIRCULAR_BUF_SIZE;
1211}
1212
1213void SensorService::CircularBuffer::printBuffer(String8& result) const {
1214 const int numData = SensorService::getNumEventsForSensorType(mSensorType);
1215 int i = mNextInd, eventNum = 1;
1216 result.appendFormat("last %d events = < ", CIRCULAR_BUF_SIZE);
1217 do {
1218 if (mTrimmedSensorEventArr[i]->mTimestamp == -1) {
1219 // Sentinel, ignore.
1220 i = (i + 1) % CIRCULAR_BUF_SIZE;
1221 continue;
1222 }
1223 result.appendFormat("%d) ", eventNum++);
1224 if (mSensorType == SENSOR_TYPE_STEP_COUNTER) {
1225 result.appendFormat("%llu,", mTrimmedSensorEventArr[i]->mStepCounter);
1226 } else {
1227 for (int j = 0; j < numData; ++j) {
1228 result.appendFormat("%5.1f,", mTrimmedSensorEventArr[i]->mData[j]);
1229 }
1230 }
1231 result.appendFormat("%lld %02d:%02d:%02d ", mTrimmedSensorEventArr[i]->mTimestamp,
1232 mTrimmedSensorEventArr[i]->mHour, mTrimmedSensorEventArr[i]->mMin,
1233 mTrimmedSensorEventArr[i]->mSec);
1234 i = (i + 1) % CIRCULAR_BUF_SIZE;
1235 } while (i != mNextInd);
1236 result.appendFormat(">\n");
1237}
1238
1239bool SensorService::CircularBuffer::populateLastEvent(sensors_event_t *event) {
1240 int lastEventInd = (mNextInd - 1 + CIRCULAR_BUF_SIZE) % CIRCULAR_BUF_SIZE;
1241 // Check if the buffer is empty.
1242 if (mTrimmedSensorEventArr[lastEventInd]->mTimestamp == -1) {
1243 return false;
1244 }
1245 event->version = sizeof(sensors_event_t);
1246 event->type = mSensorType;
1247 event->timestamp = mTrimmedSensorEventArr[lastEventInd]->mTimestamp;
1248 if (mSensorType == SENSOR_TYPE_STEP_COUNTER) {
1249 event->u64.step_counter = mTrimmedSensorEventArr[lastEventInd]->mStepCounter;
1250 } else {
1251 memcpy(event->data, mTrimmedSensorEventArr[lastEventInd]->mData,
1252 sizeof(float) * SensorService::getNumEventsForSensorType(mSensorType));
1253 }
1254 return true;
1255}
1256
1257SensorService::CircularBuffer::~CircularBuffer() {
1258 for (int i = 0; i < CIRCULAR_BUF_SIZE; ++i) {
1259 delete mTrimmedSensorEventArr[i];
1260 }
1261 delete [] mTrimmedSensorEventArr;
1262}
1263
Mathias Agopianfc328812010-07-14 23:41:37 -07001264// ---------------------------------------------------------------------------
1265
1266SensorService::SensorEventConnection::SensorEventConnection(
Svetoslavb412f6e2015-04-29 16:50:41 -07001267 const sp<SensorService>& service, uid_t uid, String8 packageName, bool isDataInjectionMode,
1268 const String16& opPackageName)
Aravind Akella8a969552014-09-28 17:52:41 -07001269 : mService(service), mUid(uid), mWakeLockRefCount(0), mHasLooperCallbacks(false),
Svetoslavb412f6e2015-04-29 16:50:41 -07001270 mDead(false), mDataInjectionMode(isDataInjectionMode), mEventCache(NULL),
1271 mCacheSize(0), mMaxCacheSize(0), mPackageName(packageName), mOpPackageName(opPackageName) {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001272 mChannel = new BitTube(mService->mSocketBufferSize);
Aravind Akella56ae4262014-07-10 16:01:10 -07001273#if DEBUG_CONNECTIONS
1274 mEventsReceived = mEventsSentFromCache = mEventsSent = 0;
Aravind Akellae74baf62014-08-21 12:28:35 -07001275 mTotalAcksNeeded = mTotalAcksReceived = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -07001276#endif
Mathias Agopianfc328812010-07-14 23:41:37 -07001277}
1278
Aravind Akella56ae4262014-07-10 16:01:10 -07001279SensorService::SensorEventConnection::~SensorEventConnection() {
Steve Blocka5512372011-12-20 16:23:08 +00001280 ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this);
Aravind Akellae148bc22014-09-24 22:12:58 -07001281 mService->cleanupConnection(this);
Aravind Akella56ae4262014-07-10 16:01:10 -07001282 if (mEventCache != NULL) {
1283 delete mEventCache;
1284 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001285}
1286
Aravind Akella56ae4262014-07-10 16:01:10 -07001287void SensorService::SensorEventConnection::onFirstRef() {
1288 LooperCallback::onFirstRef();
Mathias Agopianfc328812010-07-14 23:41:37 -07001289}
1290
Aravind Akella9a844cf2014-02-11 18:58:52 -08001291bool SensorService::SensorEventConnection::needsWakeLock() {
1292 Mutex::Autolock _l(mConnectionLock);
Aravind Akella8a969552014-09-28 17:52:41 -07001293 return !mDead && mWakeLockRefCount > 0;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001294}
1295
Aravind Akellab4373ac2014-10-29 17:55:20 -07001296void SensorService::SensorEventConnection::resetWakeLockRefCount() {
1297 Mutex::Autolock _l(mConnectionLock);
1298 mWakeLockRefCount = 0;
1299}
1300
Aravind Akella4c8b9512013-09-05 17:03:38 -07001301void SensorService::SensorEventConnection::dump(String8& result) {
1302 Mutex::Autolock _l(mConnectionLock);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001303 result.appendFormat("Operating Mode: %s\n", mDataInjectionMode ? "DATA_INJECTION" : "NORMAL");
Aravind Akella4949c502015-02-11 15:54:35 -08001304 result.appendFormat("\t%s | WakeLockRefCount %d | uid %d | cache size %d | max cache size %d\n",
1305 mPackageName.string(), mWakeLockRefCount, mUid, mCacheSize, mMaxCacheSize);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001306 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1307 const FlushInfo& flushInfo = mSensorInfo.valueAt(i);
Aravind Akella0ec20662014-09-14 17:29:48 -07001308 result.appendFormat("\t %s 0x%08x | status: %s | pending flush events %d \n",
Aravind Akella4c8b9512013-09-05 17:03:38 -07001309 mService->getSensorName(mSensorInfo.keyAt(i)).string(),
Aravind Akella6c2664a2014-08-13 12:24:50 -07001310 mSensorInfo.keyAt(i),
Aravind Akella4c8b9512013-09-05 17:03:38 -07001311 flushInfo.mFirstFlushPending ? "First flush pending" :
1312 "active",
Aravind Akella0ec20662014-09-14 17:29:48 -07001313 flushInfo.mPendingFlushEventsToSend);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001314 }
Aravind Akella0ec20662014-09-14 17:29:48 -07001315#if DEBUG_CONNECTIONS
1316 result.appendFormat("\t events recvd: %d | sent %d | cache %d | dropped %d |"
1317 " total_acks_needed %d | total_acks_recvd %d\n",
1318 mEventsReceived,
1319 mEventsSent,
1320 mEventsSentFromCache,
1321 mEventsReceived - (mEventsSentFromCache + mEventsSent + mCacheSize),
1322 mTotalAcksNeeded,
1323 mTotalAcksReceived);
1324#endif
Aravind Akella4c8b9512013-09-05 17:03:38 -07001325}
1326
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001327bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001328 Mutex::Autolock _l(mConnectionLock);
Svetoslavb412f6e2015-04-29 16:50:41 -07001329 if (!canAccessSensor(mService->getSensorFromHandle(handle),
1330 "Tried adding", mOpPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001331 return false;
1332 }
Aravind Akella4c8b9512013-09-05 17:03:38 -07001333 if (mSensorInfo.indexOfKey(handle) < 0) {
1334 mSensorInfo.add(handle, FlushInfo());
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001335 return true;
Mathias Agopianfc328812010-07-14 23:41:37 -07001336 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001337 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -07001338}
1339
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001340bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001341 Mutex::Autolock _l(mConnectionLock);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001342 if (mSensorInfo.removeItem(handle) >= 0) {
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001343 return true;
1344 }
1345 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -07001346}
1347
1348bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001349 Mutex::Autolock _l(mConnectionLock);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001350 return mSensorInfo.indexOfKey(handle) >= 0;
Mathias Agopianfc328812010-07-14 23:41:37 -07001351}
1352
1353bool SensorService::SensorEventConnection::hasAnySensor() const {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001354 Mutex::Autolock _l(mConnectionLock);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001355 return mSensorInfo.size() ? true : false;
1356}
1357
Aravind Akella8493b792014-09-08 15:45:47 -07001358bool SensorService::SensorEventConnection::hasOneShotSensors() const {
1359 Mutex::Autolock _l(mConnectionLock);
1360 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1361 const int handle = mSensorInfo.keyAt(i);
1362 if (mService->getSensorFromHandle(handle).getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1363 return true;
1364 }
1365 }
1366 return false;
1367}
1368
Aravind Akella4949c502015-02-11 15:54:35 -08001369String8 SensorService::SensorEventConnection::getPackageName() const {
1370 return mPackageName;
1371}
1372
Aravind Akella4c8b9512013-09-05 17:03:38 -07001373void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle,
1374 bool value) {
1375 Mutex::Autolock _l(mConnectionLock);
1376 ssize_t index = mSensorInfo.indexOfKey(handle);
1377 if (index >= 0) {
1378 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
1379 flushInfo.mFirstFlushPending = value;
1380 }
1381}
1382
Aravind Akella8a969552014-09-28 17:52:41 -07001383void SensorService::SensorEventConnection::updateLooperRegistration(const sp<Looper>& looper) {
1384 Mutex::Autolock _l(mConnectionLock);
1385 updateLooperRegistrationLocked(looper);
1386}
1387
1388void SensorService::SensorEventConnection::updateLooperRegistrationLocked(
1389 const sp<Looper>& looper) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001390 bool isConnectionActive = (mSensorInfo.size() > 0 && !mDataInjectionMode) ||
1391 mDataInjectionMode;
Aravind Akella8a969552014-09-28 17:52:41 -07001392 // If all sensors are unregistered OR Looper has encountered an error, we
1393 // can remove the Fd from the Looper if it has been previously added.
1394 if (!isConnectionActive || mDead) {
1395 if (mHasLooperCallbacks) {
1396 ALOGD_IF(DEBUG_CONNECTIONS, "%p removeFd fd=%d", this, mChannel->getSendFd());
1397 looper->removeFd(mChannel->getSendFd());
1398 mHasLooperCallbacks = false;
1399 }
1400 return;
1401 }
1402
1403 int looper_flags = 0;
1404 if (mCacheSize > 0) looper_flags |= ALOOPER_EVENT_OUTPUT;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001405 if (mDataInjectionMode) looper_flags |= ALOOPER_EVENT_INPUT;
Aravind Akella8a969552014-09-28 17:52:41 -07001406 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1407 const int handle = mSensorInfo.keyAt(i);
1408 if (mService->getSensorFromHandle(handle).isWakeUpSensor()) {
1409 looper_flags |= ALOOPER_EVENT_INPUT;
1410 break;
1411 }
1412 }
1413 // If flags is still set to zero, we don't need to add this fd to the Looper, if
1414 // the fd has already been added, remove it. This is likely to happen when ALL the
1415 // events stored in the cache have been sent to the corresponding app.
1416 if (looper_flags == 0) {
1417 if (mHasLooperCallbacks) {
1418 ALOGD_IF(DEBUG_CONNECTIONS, "removeFd fd=%d", mChannel->getSendFd());
1419 looper->removeFd(mChannel->getSendFd());
1420 mHasLooperCallbacks = false;
1421 }
1422 return;
1423 }
1424 // Add the file descriptor to the Looper for receiving acknowledegments if the app has
1425 // registered for wake-up sensors OR for sending events in the cache.
1426 int ret = looper->addFd(mChannel->getSendFd(), 0, looper_flags, this, NULL);
1427 if (ret == 1) {
1428 ALOGD_IF(DEBUG_CONNECTIONS, "%p addFd fd=%d", this, mChannel->getSendFd());
1429 mHasLooperCallbacks = true;
1430 } else {
1431 ALOGE("Looper::addFd failed ret=%d fd=%d", ret, mChannel->getSendFd());
1432 }
1433}
1434
1435void SensorService::SensorEventConnection::incrementPendingFlushCount(int32_t handle) {
1436 Mutex::Autolock _l(mConnectionLock);
1437 ssize_t index = mSensorInfo.indexOfKey(handle);
1438 if (index >= 0) {
1439 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
1440 flushInfo.mPendingFlushEventsToSend++;
1441 }
1442}
1443
Mathias Agopianfc328812010-07-14 23:41:37 -07001444status_t SensorService::SensorEventConnection::sendEvents(
Aravind Akella0ec20662014-09-14 17:29:48 -07001445 sensors_event_t const* buffer, size_t numEvents,
Aravind Akella8493b792014-09-08 15:45:47 -07001446 sensors_event_t* scratch,
1447 SensorEventConnection const * const * mapFlushEventsToConnections) {
Mathias Agopiancf510012010-07-22 16:18:10 -07001448 // filter out events not for this connection
Svetoslavb412f6e2015-04-29 16:50:41 -07001449 int count = 0;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001450 Mutex::Autolock _l(mConnectionLock);
Mathias Agopian3560fb22010-07-22 21:24:39 -07001451 if (scratch) {
1452 size_t i=0;
1453 while (i<numEvents) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001454 int32_t sensor_handle = buffer[i].sensor;
Aravind Akella724d91d2013-06-27 12:04:23 -07001455 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
1456 ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ",
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001457 buffer[i].meta_data.sensor);
Aravind Akella8a969552014-09-28 17:52:41 -07001458 // Setting sensor_handle to the correct sensor to ensure the sensor events per
1459 // connection are filtered correctly. buffer[i].sensor is zero for meta_data
1460 // events.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001461 sensor_handle = buffer[i].meta_data.sensor;
Aravind Akella724d91d2013-06-27 12:04:23 -07001462 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001463 ssize_t index = mSensorInfo.indexOfKey(sensor_handle);
Aravind Akella56ae4262014-07-10 16:01:10 -07001464 // Check if this connection has registered for this sensor. If not continue to the
1465 // next sensor_event.
1466 if (index < 0) {
1467 ++i;
1468 continue;
Aravind Akella4c8b9512013-09-05 17:03:38 -07001469 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001470
Aravind Akella56ae4262014-07-10 16:01:10 -07001471 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001472 // Check if there is a pending flush_complete event for this sensor on this connection.
Aravind Akella8493b792014-09-08 15:45:47 -07001473 if (buffer[i].type == SENSOR_TYPE_META_DATA && flushInfo.mFirstFlushPending == true &&
1474 this == mapFlushEventsToConnections[i]) {
1475 flushInfo.mFirstFlushPending = false;
1476 ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ",
1477 buffer[i].meta_data.sensor);
1478 ++i;
1479 continue;
Aravind Akella56ae4262014-07-10 16:01:10 -07001480 }
1481
1482 // If there is a pending flush complete event for this sensor on this connection,
1483 // ignore the event and proceed to the next.
1484 if (flushInfo.mFirstFlushPending) {
1485 ++i;
1486 continue;
1487 }
1488
1489 do {
Aravind Akella8493b792014-09-08 15:45:47 -07001490 // Keep copying events into the scratch buffer as long as they are regular
1491 // sensor_events are from the same sensor_handle OR they are flush_complete_events
1492 // from the same sensor_handle AND the current connection is mapped to the
1493 // corresponding flush_complete_event.
Aravind Akella56ae4262014-07-10 16:01:10 -07001494 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
Aravind Akella8493b792014-09-08 15:45:47 -07001495 if (this == mapFlushEventsToConnections[i]) {
Aravind Akella56ae4262014-07-10 16:01:10 -07001496 scratch[count++] = buffer[i];
Aravind Akella56ae4262014-07-10 16:01:10 -07001497 }
1498 ++i;
1499 } else {
1500 // Regular sensor event, just copy it to the scratch buffer.
Aravind Akella4c8b9512013-09-05 17:03:38 -07001501 scratch[count++] = buffer[i++];
Aravind Akella56ae4262014-07-10 16:01:10 -07001502 }
Aravind Akella8493b792014-09-08 15:45:47 -07001503 } while ((i<numEvents) && ((buffer[i].sensor == sensor_handle &&
1504 buffer[i].type != SENSOR_TYPE_META_DATA) ||
Aravind Akella56ae4262014-07-10 16:01:10 -07001505 (buffer[i].type == SENSOR_TYPE_META_DATA &&
Aravind Akella6c2664a2014-08-13 12:24:50 -07001506 buffer[i].meta_data.sensor == sensor_handle)));
Mathias Agopiancf510012010-07-22 16:18:10 -07001507 }
Mathias Agopian3560fb22010-07-22 21:24:39 -07001508 } else {
1509 scratch = const_cast<sensors_event_t *>(buffer);
1510 count = numEvents;
Mathias Agopiancf510012010-07-22 16:18:10 -07001511 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001512
Aravind Akella6c2664a2014-08-13 12:24:50 -07001513 sendPendingFlushEventsLocked();
Aravind Akella56ae4262014-07-10 16:01:10 -07001514 // Early return if there are no events for this connection.
1515 if (count == 0) {
1516 return status_t(NO_ERROR);
1517 }
1518
1519#if DEBUG_CONNECTIONS
1520 mEventsReceived += count;
1521#endif
1522 if (mCacheSize != 0) {
1523 // There are some events in the cache which need to be sent first. Copy this buffer to
1524 // the end of cache.
1525 if (mCacheSize + count <= mMaxCacheSize) {
1526 memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
1527 mCacheSize += count;
1528 } else {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001529 // Check if any new sensors have registered on this connection which may have increased
1530 // the max cache size that is desired.
1531 if (mCacheSize + count < computeMaxCacheSizeLocked()) {
1532 reAllocateCacheLocked(scratch, count);
1533 return status_t(NO_ERROR);
1534 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001535 // Some events need to be dropped.
1536 int remaningCacheSize = mMaxCacheSize - mCacheSize;
1537 if (remaningCacheSize != 0) {
1538 memcpy(&mEventCache[mCacheSize], scratch,
1539 remaningCacheSize * sizeof(sensors_event_t));
1540 }
1541 int numEventsDropped = count - remaningCacheSize;
1542 countFlushCompleteEventsLocked(mEventCache, numEventsDropped);
1543 // Drop the first "numEventsDropped" in the cache.
1544 memmove(mEventCache, &mEventCache[numEventsDropped],
1545 (mCacheSize - numEventsDropped) * sizeof(sensors_event_t));
1546
1547 // Copy the remainingEvents in scratch buffer to the end of cache.
1548 memcpy(&mEventCache[mCacheSize - numEventsDropped], scratch + remaningCacheSize,
1549 numEventsDropped * sizeof(sensors_event_t));
1550 }
1551 return status_t(NO_ERROR);
1552 }
1553
Aravind Akella6c2664a2014-08-13 12:24:50 -07001554 int index_wake_up_event = findWakeUpSensorEventLocked(scratch, count);
1555 if (index_wake_up_event >= 0) {
1556 scratch[index_wake_up_event].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1557 ++mWakeLockRefCount;
Aravind Akellae74baf62014-08-21 12:28:35 -07001558#if DEBUG_CONNECTIONS
1559 ++mTotalAcksNeeded;
1560#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001561 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001562
1563 // NOTE: ASensorEvent and sensors_event_t are the same type.
1564 ssize_t size = SensorEventQueue::write(mChannel,
1565 reinterpret_cast<ASensorEvent const*>(scratch), count);
1566 if (size < 0) {
1567 // Write error, copy events to local cache.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001568 if (index_wake_up_event >= 0) {
1569 // If there was a wake_up sensor_event, reset the flag.
1570 scratch[index_wake_up_event].flags &= ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
Aravind Akella0ec20662014-09-14 17:29:48 -07001571 if (mWakeLockRefCount > 0) {
1572 --mWakeLockRefCount;
1573 }
Aravind Akellae74baf62014-08-21 12:28:35 -07001574#if DEBUG_CONNECTIONS
1575 --mTotalAcksNeeded;
1576#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001577 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001578 if (mEventCache == NULL) {
1579 mMaxCacheSize = computeMaxCacheSizeLocked();
1580 mEventCache = new sensors_event_t[mMaxCacheSize];
1581 mCacheSize = 0;
1582 }
1583 memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
1584 mCacheSize += count;
1585
1586 // Add this file descriptor to the looper to get a callback when this fd is available for
1587 // writing.
Aravind Akella8a969552014-09-28 17:52:41 -07001588 updateLooperRegistrationLocked(mService->getLooper());
Aravind Akella56ae4262014-07-10 16:01:10 -07001589 return size;
1590 }
1591
1592#if DEBUG_CONNECTIONS
1593 if (size > 0) {
1594 mEventsSent += count;
1595 }
1596#endif
1597
1598 return size < 0 ? status_t(size) : status_t(NO_ERROR);
1599}
1600
Aravind Akella6c2664a2014-08-13 12:24:50 -07001601void SensorService::SensorEventConnection::reAllocateCacheLocked(sensors_event_t const* scratch,
1602 int count) {
1603 sensors_event_t *eventCache_new;
1604 const int new_cache_size = computeMaxCacheSizeLocked();
1605 // Allocate new cache, copy over events from the old cache & scratch, free up memory.
1606 eventCache_new = new sensors_event_t[new_cache_size];
1607 memcpy(eventCache_new, mEventCache, mCacheSize * sizeof(sensors_event_t));
1608 memcpy(&eventCache_new[mCacheSize], scratch, count * sizeof(sensors_event_t));
1609
1610 ALOGD_IF(DEBUG_CONNECTIONS, "reAllocateCacheLocked maxCacheSize=%d %d", mMaxCacheSize,
1611 new_cache_size);
1612
1613 delete mEventCache;
1614 mEventCache = eventCache_new;
1615 mCacheSize += count;
1616 mMaxCacheSize = new_cache_size;
1617}
1618
1619void SensorService::SensorEventConnection::sendPendingFlushEventsLocked() {
1620 ASensorEvent flushCompleteEvent;
Aravind Akella0ec20662014-09-14 17:29:48 -07001621 memset(&flushCompleteEvent, 0, sizeof(flushCompleteEvent));
Aravind Akella6c2664a2014-08-13 12:24:50 -07001622 flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
Aravind Akella6c2664a2014-08-13 12:24:50 -07001623 // Loop through all the sensors for this connection and check if there are any pending
1624 // flush complete events to be sent.
1625 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1626 FlushInfo& flushInfo = mSensorInfo.editValueAt(i);
1627 while (flushInfo.mPendingFlushEventsToSend > 0) {
Aravind Akella0ec20662014-09-14 17:29:48 -07001628 const int sensor_handle = mSensorInfo.keyAt(i);
1629 flushCompleteEvent.meta_data.sensor = sensor_handle;
Aravind Akellab4373ac2014-10-29 17:55:20 -07001630 bool wakeUpSensor = mService->getSensorFromHandle(sensor_handle).isWakeUpSensor();
1631 if (wakeUpSensor) {
1632 ++mWakeLockRefCount;
Aravind Akella0ec20662014-09-14 17:29:48 -07001633 flushCompleteEvent.flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1634 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001635 ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
1636 if (size < 0) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001637 if (wakeUpSensor) --mWakeLockRefCount;
Aravind Akella6c2664a2014-08-13 12:24:50 -07001638 return;
1639 }
1640 ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
1641 flushCompleteEvent.meta_data.sensor);
1642 flushInfo.mPendingFlushEventsToSend--;
1643 }
1644 }
1645}
1646
Aravind Akellab4373ac2014-10-29 17:55:20 -07001647void SensorService::SensorEventConnection::writeToSocketFromCache() {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001648 // At a time write at most half the size of the receiver buffer in SensorEventQueue OR
1649 // half the size of the socket buffer allocated in BitTube whichever is smaller.
1650 const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
1651 int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
Aravind Akellab4373ac2014-10-29 17:55:20 -07001652 Mutex::Autolock _l(mConnectionLock);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001653 // Send pending flush complete events (if any)
Aravind Akella6c2664a2014-08-13 12:24:50 -07001654 sendPendingFlushEventsLocked();
Aravind Akella56ae4262014-07-10 16:01:10 -07001655 for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001656 const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001657 int index_wake_up_event =
1658 findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite);
1659 if (index_wake_up_event >= 0) {
1660 mEventCache[index_wake_up_event + numEventsSent].flags |=
1661 WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1662 ++mWakeLockRefCount;
Aravind Akellae74baf62014-08-21 12:28:35 -07001663#if DEBUG_CONNECTIONS
1664 ++mTotalAcksNeeded;
1665#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001666 }
Aravind Akella4c8b9512013-09-05 17:03:38 -07001667
Aravind Akella56ae4262014-07-10 16:01:10 -07001668 ssize_t size = SensorEventQueue::write(mChannel,
1669 reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent),
Aravind Akella6c2664a2014-08-13 12:24:50 -07001670 numEventsToWrite);
Aravind Akella56ae4262014-07-10 16:01:10 -07001671 if (size < 0) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001672 if (index_wake_up_event >= 0) {
1673 // If there was a wake_up sensor_event, reset the flag.
1674 mEventCache[index_wake_up_event + numEventsSent].flags &=
1675 ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
Aravind Akella0ec20662014-09-14 17:29:48 -07001676 if (mWakeLockRefCount > 0) {
1677 --mWakeLockRefCount;
1678 }
Aravind Akellae74baf62014-08-21 12:28:35 -07001679#if DEBUG_CONNECTIONS
1680 --mTotalAcksNeeded;
1681#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001682 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001683 memmove(mEventCache, &mEventCache[numEventsSent],
1684 (mCacheSize - numEventsSent) * sizeof(sensors_event_t));
1685 ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ",
Aravind Akella6c2664a2014-08-13 12:24:50 -07001686 numEventsSent, mCacheSize);
Aravind Akella56ae4262014-07-10 16:01:10 -07001687 mCacheSize -= numEventsSent;
Aravind Akella56ae4262014-07-10 16:01:10 -07001688 return;
1689 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001690 numEventsSent += numEventsToWrite;
Aravind Akella56ae4262014-07-10 16:01:10 -07001691#if DEBUG_CONNECTIONS
Aravind Akella6c2664a2014-08-13 12:24:50 -07001692 mEventsSentFromCache += numEventsToWrite;
Aravind Akella56ae4262014-07-10 16:01:10 -07001693#endif
Aravind Akellab4099e72013-10-15 15:43:10 -07001694 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001695 ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize);
1696 // All events from the cache have been sent. Reset cache size to zero.
1697 mCacheSize = 0;
Aravind Akella8a969552014-09-28 17:52:41 -07001698 // There are no more events in the cache. We don't need to poll for write on the fd.
1699 // Update Looper registration.
1700 updateLooperRegistrationLocked(mService->getLooper());
Mathias Agopianfc328812010-07-14 23:41:37 -07001701}
1702
Aravind Akellac551eac2013-10-14 17:04:42 -07001703void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
Aravind Akella0ec20662014-09-14 17:29:48 -07001704 sensors_event_t const* scratch, const int numEventsDropped) {
Aravind Akella4c8b9512013-09-05 17:03:38 -07001705 ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001706 // Count flushComplete events in the events that are about to the dropped. These will be sent
1707 // separately before the next batch of events.
1708 for (int j = 0; j < numEventsDropped; ++j) {
1709 if (scratch[j].type == SENSOR_TYPE_META_DATA) {
1710 FlushInfo& flushInfo = mSensorInfo.editValueFor(scratch[j].meta_data.sensor);
1711 flushInfo.mPendingFlushEventsToSend++;
1712 ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
1713 flushInfo.mPendingFlushEventsToSend);
1714 }
1715 }
1716 return;
1717}
1718
Aravind Akella6c2664a2014-08-13 12:24:50 -07001719int SensorService::SensorEventConnection::findWakeUpSensorEventLocked(
1720 sensors_event_t const* scratch, const int count) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001721 for (int i = 0; i < count; ++i) {
1722 if (mService->isWakeUpSensorEvent(scratch[i])) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001723 return i;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001724 }
1725 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001726 return -1;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001727}
1728
Mathias Agopianb3989272011-10-20 18:42:02 -07001729sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
Mathias Agopianfc328812010-07-14 23:41:37 -07001730{
1731 return mChannel;
1732}
1733
1734status_t SensorService::SensorEventConnection::enableDisable(
Aravind Akella724d91d2013-06-27 12:04:23 -07001735 int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
1736 int reservedFlags)
Mathias Agopianfc328812010-07-14 23:41:37 -07001737{
1738 status_t err;
1739 if (enabled) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001740 err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
Svetoslavb412f6e2015-04-29 16:50:41 -07001741 reservedFlags, mOpPackageName);
Aravind Akella56ae4262014-07-10 16:01:10 -07001742
Mathias Agopianfc328812010-07-14 23:41:37 -07001743 } else {
1744 err = mService->disable(this, handle);
1745 }
1746 return err;
1747}
1748
1749status_t SensorService::SensorEventConnection::setEventRate(
Aravind Akella724d91d2013-06-27 12:04:23 -07001750 int handle, nsecs_t samplingPeriodNs)
Mathias Agopianfc328812010-07-14 23:41:37 -07001751{
Svetoslavb412f6e2015-04-29 16:50:41 -07001752 return mService->setEventRate(this, handle, samplingPeriodNs, mOpPackageName);
Mathias Agopianfc328812010-07-14 23:41:37 -07001753}
1754
Aravind Akella701166d2013-10-08 14:59:26 -07001755status_t SensorService::SensorEventConnection::flush() {
Svetoslavb412f6e2015-04-29 16:50:41 -07001756 return mService->flushSensor(this, mOpPackageName);
Aravind Akella724d91d2013-06-27 12:04:23 -07001757}
Aravind Akella4c8b9512013-09-05 17:03:38 -07001758
Aravind Akella8a969552014-09-28 17:52:41 -07001759int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* /*data*/) {
Aravind Akella56ae4262014-07-10 16:01:10 -07001760 if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) {
Aravind Akella8a969552014-09-28 17:52:41 -07001761 {
1762 // If the Looper encounters some error, set the flag mDead, reset mWakeLockRefCount,
1763 // and remove the fd from Looper. Call checkWakeLockState to know if SensorService
1764 // can release the wake-lock.
1765 ALOGD_IF(DEBUG_CONNECTIONS, "%p Looper error %d", this, fd);
1766 Mutex::Autolock _l(mConnectionLock);
1767 mDead = true;
1768 mWakeLockRefCount = 0;
1769 updateLooperRegistrationLocked(mService->getLooper());
1770 }
1771 mService->checkWakeLockState();
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001772 if (mDataInjectionMode) {
1773 // If the Looper has encountered some error in data injection mode, reset SensorService
1774 // back to normal mode.
1775 mService->resetToNormalMode();
1776 mDataInjectionMode = false;
1777 }
Aravind Akella8a969552014-09-28 17:52:41 -07001778 return 1;
Aravind Akella56ae4262014-07-10 16:01:10 -07001779 }
1780
1781 if (events & ALOOPER_EVENT_INPUT) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001782 unsigned char buf[sizeof(sensors_event_t)];
1783 ssize_t numBytesRead = ::recv(fd, buf, sizeof(buf), MSG_DONTWAIT);
Aravind Akella56ae4262014-07-10 16:01:10 -07001784 {
1785 Mutex::Autolock _l(mConnectionLock);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001786 if (numBytesRead == sizeof(sensors_event_t)) {
1787 if (!mDataInjectionMode) {
1788 ALOGE("Data injected in normal mode, dropping event"
1789 "package=%s uid=%d", mPackageName.string(), mUid);
1790 // Unregister call backs.
1791 return 0;
1792 }
1793 SensorDevice& dev(SensorDevice::getInstance());
1794 sensors_event_t sensor_event;
1795 memset(&sensor_event, 0, sizeof(sensor_event));
1796 memcpy(&sensor_event, buf, sizeof(sensors_event_t));
1797 Sensor sensor = mService->getSensorFromHandle(sensor_event.sensor);
1798 sensor_event.type = sensor.getType();
Svetoslavb412f6e2015-04-29 16:50:41 -07001799 dev.injectSensorData(&sensor_event);
Aravind Akellae74baf62014-08-21 12:28:35 -07001800#if DEBUG_CONNECTIONS
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001801 ++mEventsReceived;
Aravind Akellae74baf62014-08-21 12:28:35 -07001802#endif
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001803 } else if (numBytesRead == sizeof(uint32_t)) {
1804 uint32_t numAcks = 0;
Aravind Akella08f04bf2015-05-08 15:59:23 -07001805 memcpy(&numAcks, buf, numBytesRead);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001806 // Sanity check to ensure there are no read errors in recv, numAcks is always
1807 // within the range and not zero. If any of the above don't hold reset
1808 // mWakeLockRefCount to zero.
1809 if (numAcks > 0 && numAcks < mWakeLockRefCount) {
1810 mWakeLockRefCount -= numAcks;
1811 } else {
1812 mWakeLockRefCount = 0;
1813 }
1814#if DEBUG_CONNECTIONS
1815 mTotalAcksReceived += numAcks;
1816#endif
1817 } else {
1818 // Read error, reset wakelock refcount.
1819 mWakeLockRefCount = 0;
1820 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001821 }
1822 // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released
1823 // here as checkWakeLockState() will need it.
1824 if (mWakeLockRefCount == 0) {
1825 mService->checkWakeLockState();
1826 }
1827 // continue getting callbacks.
1828 return 1;
1829 }
1830
1831 if (events & ALOOPER_EVENT_OUTPUT) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001832 // send sensor data that is stored in mEventCache for this connection.
1833 mService->sendEventsFromCache(this);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001834 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001835 return 1;
1836}
1837
1838int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
Svetoslavb412f6e2015-04-29 16:50:41 -07001839 size_t fifoWakeUpSensors = 0;
1840 size_t fifoNonWakeUpSensors = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -07001841 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1842 const Sensor& sensor = mService->getSensorFromHandle(mSensorInfo.keyAt(i));
1843 if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) {
1844 // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and
1845 // non wake_up sensors.
1846 if (sensor.isWakeUpSensor()) {
1847 fifoWakeUpSensors += sensor.getFifoReservedEventCount();
1848 } else {
1849 fifoNonWakeUpSensors += sensor.getFifoReservedEventCount();
1850 }
1851 } else {
1852 // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors.
1853 if (sensor.isWakeUpSensor()) {
1854 fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ?
1855 fifoWakeUpSensors : sensor.getFifoMaxEventCount();
1856
1857 } else {
1858 fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ?
1859 fifoNonWakeUpSensors : sensor.getFifoMaxEventCount();
1860
1861 }
1862 }
1863 }
1864 if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) {
1865 // It is extremely unlikely that there is a write failure in non batch mode. Return a cache
Aravind Akella6c2664a2014-08-13 12:24:50 -07001866 // size that is equal to that of the batch mode.
Aravind Akellae74baf62014-08-21 12:28:35 -07001867 // ALOGW("Write failure in non-batch mode");
Aravind Akella6c2664a2014-08-13 12:24:50 -07001868 return MAX_SOCKET_BUFFER_SIZE_BATCHED/sizeof(sensors_event_t);
Aravind Akella56ae4262014-07-10 16:01:10 -07001869 }
1870 return fifoWakeUpSensors + fifoNonWakeUpSensors;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001871}
1872
Mathias Agopianfc328812010-07-14 23:41:37 -07001873// ---------------------------------------------------------------------------
1874}; // namespace android
1875