blob: 7bc499031e44528803fe0b8be47b8381a2c9dbb9 [file] [log] [blame]
Mathias Agopianfc328812010-07-14 23:41:37 -07001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -070017#include <inttypes.h>
Mathias Agopianf001c922010-11-11 17:58:51 -080018#include <math.h>
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -070019#include <stdint.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070020#include <sys/types.h>
Aravind Akella56ae4262014-07-10 16:01:10 -070021#include <sys/socket.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070022
Mathias Agopian33015422011-05-27 18:18:13 -070023#include <cutils/properties.h>
24
Mathias Agopianfc328812010-07-14 23:41:37 -070025#include <utils/SortedVector.h>
26#include <utils/KeyedVector.h>
27#include <utils/threads.h>
28#include <utils/Atomic.h>
29#include <utils/Errors.h>
30#include <utils/RefBase.h>
Mathias Agopian451beee2010-07-19 15:03:55 -070031#include <utils/Singleton.h>
Mathias Agopianc4a930d2010-07-22 22:19:43 -070032#include <utils/String16.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070033
34#include <binder/BinderService.h>
Mathias Agopian451beee2010-07-19 15:03:55 -070035#include <binder/IServiceManager.h>
Mathias Agopian1cb13462011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070037
38#include <gui/ISensorServer.h>
39#include <gui/ISensorEventConnection.h>
Mathias Agopian907103b2012-04-02 18:38:02 -070040#include <gui/SensorEventQueue.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070041
42#include <hardware/sensors.h>
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070043#include <hardware_legacy/power.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070044
Mathias Agopian787ac1b2012-09-18 18:49:18 -070045#include "BatteryService.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070046#include "CorrectedGyroSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080047#include "GravitySensor.h"
48#include "LinearAccelerationSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070049#include "OrientationSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080050#include "RotationVectorSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070051#include "SensorFusion.h"
52#include "SensorService.h"
Mathias Agopianfc328812010-07-14 23:41:37 -070053
54namespace android {
55// ---------------------------------------------------------------------------
56
Mathias Agopian33015422011-05-27 18:18:13 -070057/*
58 * Notes:
59 *
60 * - what about a gyro-corrected magnetic-field sensor?
Mathias Agopian33015422011-05-27 18:18:13 -070061 * - run mag sensor from time to time to force calibration
62 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
63 *
64 */
65
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070066const char* SensorService::WAKE_LOCK_NAME = "SensorService";
Aravind Akellaa9e6cc32015-04-16 18:57:31 -070067// Permissions.
68static const String16 sDataInjectionPermission("android.permission.HARDWARE_TEST");
69static const String16 sDump("android.permission.DUMP");
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070070
Mathias Agopianfc328812010-07-14 23:41:37 -070071SensorService::SensorService()
Aravind Akella8a969552014-09-28 17:52:41 -070072 : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
73 mWakeLockAcquired(false)
Mathias Agopianfc328812010-07-14 23:41:37 -070074{
75}
76
77void SensorService::onFirstRef()
78{
Steve Blocka5512372011-12-20 16:23:08 +000079 ALOGD("nuSensorService starting...");
Mathias Agopianf001c922010-11-11 17:58:51 -080080 SensorDevice& dev(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -070081
Mathias Agopianf001c922010-11-11 17:58:51 -080082 if (dev.initCheck() == NO_ERROR) {
Mathias Agopianf001c922010-11-11 17:58:51 -080083 sensor_t const* list;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070084 ssize_t count = dev.getSensorList(&list);
85 if (count > 0) {
86 ssize_t orientationIndex = -1;
87 bool hasGyro = false;
88 uint32_t virtualSensorsNeeds =
89 (1<<SENSOR_TYPE_GRAVITY) |
90 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
91 (1<<SENSOR_TYPE_ROTATION_VECTOR);
92
93 mLastEventSeen.setCapacity(count);
94 for (ssize_t i=0 ; i<count ; i++) {
95 registerSensor( new HardwareSensor(list[i]) );
96 switch (list[i].type) {
97 case SENSOR_TYPE_ORIENTATION:
98 orientationIndex = i;
99 break;
100 case SENSOR_TYPE_GYROSCOPE:
Mathias Agopian03193062013-05-10 19:32:39 -0700101 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700102 hasGyro = true;
103 break;
104 case SENSOR_TYPE_GRAVITY:
105 case SENSOR_TYPE_LINEAR_ACCELERATION:
106 case SENSOR_TYPE_ROTATION_VECTOR:
107 virtualSensorsNeeds &= ~(1<<list[i].type);
108 break;
109 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700110 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700111
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700112 // it's safe to instantiate the SensorFusion object here
113 // (it wants to be instantiated after h/w sensors have been
114 // registered)
115 const SensorFusion& fusion(SensorFusion::getInstance());
Mathias Agopian984826c2011-05-17 22:54:42 -0700116
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700117 // build the sensor list returned to users
118 mUserSensorList = mSensorList;
Mathias Agopian33264862012-06-28 19:46:54 -0700119
120 if (hasGyro) {
Mathias Agopian03193062013-05-10 19:32:39 -0700121 Sensor aSensor;
122
123 // Add Android virtual sensors if they're not already
124 // available in the HAL
125
126 aSensor = registerVirtualSensor( new RotationVectorSensor() );
127 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
128 mUserSensorList.add(aSensor);
129 }
130
131 aSensor = registerVirtualSensor( new GravitySensor(list, count) );
132 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) {
133 mUserSensorList.add(aSensor);
134 }
135
136 aSensor = registerVirtualSensor( new LinearAccelerationSensor(list, count) );
137 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) {
138 mUserSensorList.add(aSensor);
139 }
140
141 aSensor = registerVirtualSensor( new OrientationSensor() );
142 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
143 // if we are doing our own rotation-vector, also add
144 // the orientation sensor and remove the HAL provided one.
145 mUserSensorList.replaceAt(aSensor, orientationIndex);
146 }
147
Mathias Agopian33264862012-06-28 19:46:54 -0700148 // virtual debugging sensors are not added to mUserSensorList
Mathias Agopian03193062013-05-10 19:32:39 -0700149 registerVirtualSensor( new CorrectedGyroSensor(list, count) );
Mathias Agopian33264862012-06-28 19:46:54 -0700150 registerVirtualSensor( new GyroDriftSensor() );
151 }
152
Mathias Agopian33264862012-06-28 19:46:54 -0700153 // debugging sensor list
Mathias Agopian03193062013-05-10 19:32:39 -0700154 mUserSensorListDebug = mSensorList;
Mathias Agopian33264862012-06-28 19:46:54 -0700155
Aravind Akella5466c3d2014-08-22 16:11:10 -0700156 // Check if the device really supports batching by looking at the FIFO event
157 // counts for each sensor.
158 bool batchingSupported = false;
159 for (int i = 0; i < mSensorList.size(); ++i) {
160 if (mSensorList[i].getFifoMaxEventCount() > 0) {
161 batchingSupported = true;
162 break;
163 }
164 }
165
166 if (batchingSupported) {
167 // Increase socket buffer size to a max of 100 KB for batching capabilities.
168 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
169 } else {
170 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
171 }
172
173 // Compare the socketBufferSize value against the system limits and limit
174 // it to maxSystemSocketBufferSize if necessary.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700175 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
176 char line[128];
177 if (fp != NULL && fgets(line, sizeof(line), fp) != NULL) {
178 line[sizeof(line) - 1] = '\0';
Aravind Akella5466c3d2014-08-22 16:11:10 -0700179 size_t maxSystemSocketBufferSize;
180 sscanf(line, "%zu", &maxSystemSocketBufferSize);
181 if (mSocketBufferSize > maxSystemSocketBufferSize) {
182 mSocketBufferSize = maxSystemSocketBufferSize;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700183 }
184 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700185 if (fp) {
186 fclose(fp);
187 }
188
Aravind Akella9a844cf2014-02-11 18:58:52 -0800189 mWakeLockAcquired = false;
Aravind Akella56ae4262014-07-10 16:01:10 -0700190 mLooper = new Looper(false);
Aravind Akella8493b792014-09-08 15:45:47 -0700191 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
192 mSensorEventBuffer = new sensors_event_t[minBufferSize];
193 mSensorEventScratch = new sensors_event_t[minBufferSize];
194 mMapFlushEventsToConnections = new SensorEventConnection const * [minBufferSize];
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700195 mCurrentOperatingMode = NORMAL;
Aravind Akella7830ef32014-10-07 14:13:12 -0700196
Aravind Akellab4373ac2014-10-29 17:55:20 -0700197 mAckReceiver = new SensorEventAckReceiver(this);
198 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700199 mInitCheck = NO_ERROR;
Aravind Akella7830ef32014-10-07 14:13:12 -0700200 run("SensorService", PRIORITY_URGENT_DISPLAY);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700201 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700202 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700203}
204
Mathias Agopian03193062013-05-10 19:32:39 -0700205Sensor SensorService::registerSensor(SensorInterface* s)
Mathias Agopianf001c922010-11-11 17:58:51 -0800206{
207 sensors_event_t event;
208 memset(&event, 0, sizeof(event));
209
210 const Sensor sensor(s->getSensor());
211 // add to the sensor list (returned to clients)
212 mSensorList.add(sensor);
213 // add to our handle->SensorInterface mapping
214 mSensorMap.add(sensor.getHandle(), s);
215 // create an entry in the mLastEventSeen array
216 mLastEventSeen.add(sensor.getHandle(), event);
Mathias Agopian03193062013-05-10 19:32:39 -0700217
218 return sensor;
Mathias Agopianf001c922010-11-11 17:58:51 -0800219}
220
Mathias Agopian03193062013-05-10 19:32:39 -0700221Sensor SensorService::registerVirtualSensor(SensorInterface* s)
Mathias Agopianf001c922010-11-11 17:58:51 -0800222{
Mathias Agopian03193062013-05-10 19:32:39 -0700223 Sensor sensor = registerSensor(s);
Mathias Agopianf001c922010-11-11 17:58:51 -0800224 mVirtualSensorList.add( s );
Mathias Agopian03193062013-05-10 19:32:39 -0700225 return sensor;
Mathias Agopianf001c922010-11-11 17:58:51 -0800226}
227
Mathias Agopianfc328812010-07-14 23:41:37 -0700228SensorService::~SensorService()
229{
Mathias Agopianf001c922010-11-11 17:58:51 -0800230 for (size_t i=0 ; i<mSensorMap.size() ; i++)
231 delete mSensorMap.valueAt(i);
Mathias Agopianfc328812010-07-14 23:41:37 -0700232}
233
Aravind Akella4949c502015-02-11 15:54:35 -0800234status_t SensorService::dump(int fd, const Vector<String16>& args)
Mathias Agopianfc328812010-07-14 23:41:37 -0700235{
Mathias Agopianfc328812010-07-14 23:41:37 -0700236 String8 result;
Mathias Agopian1cb13462011-06-27 16:05:52 -0700237 if (!PermissionCache::checkCallingPermission(sDump)) {
Mathias Agopianba02cd22013-07-03 16:20:57 -0700238 result.appendFormat("Permission Denial: "
Aravind Akella70018042014-04-07 22:52:37 +0000239 "can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700240 IPCThreadState::self()->getCallingPid(),
241 IPCThreadState::self()->getCallingUid());
Aravind Akella4949c502015-02-11 15:54:35 -0800242 } else if (args.size() > 0) {
243 if (args.size() > 1) {
244 return INVALID_OPERATION;
245 }
246 Mutex::Autolock _l(mLock);
247 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700248 if (args[0] == String16("restrict") && mCurrentOperatingMode == NORMAL) {
249 mCurrentOperatingMode = RESTRICTED;
Aravind Akella4949c502015-02-11 15:54:35 -0800250 dev.disableAllSensors();
251 // Clear all pending flush connections for all active sensors. If one of the active
252 // connections has called flush() and the underlying sensor has been disabled before a
253 // flush complete event is returned, we need to remove the connection from this queue.
254 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
255 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
256 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700257 } else if (args[0] == String16("enable") && mCurrentOperatingMode == RESTRICTED) {
258 mCurrentOperatingMode = NORMAL;
Aravind Akella4949c502015-02-11 15:54:35 -0800259 dev.enableAllSensors();
260 }
261 return status_t(NO_ERROR);
Mathias Agopianfc328812010-07-14 23:41:37 -0700262 } else {
263 Mutex::Autolock _l(mLock);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700264 result.append("Sensor List:\n");
Mathias Agopian3560fb22010-07-22 21:24:39 -0700265 for (size_t i=0 ; i<mSensorList.size() ; i++) {
266 const Sensor& s(mSensorList[i]);
267 const sensors_event_t& e(mLastEventSeen.valueFor(s.getHandle()));
Mathias Agopianba02cd22013-07-03 16:20:57 -0700268 result.appendFormat(
Aravind Akella0b6acb22014-10-18 16:37:13 -0700269 "%-15s| %-10s| version=%d |%-20s| 0x%08x | \"%s\" | type=%d |",
Mathias Agopian3560fb22010-07-22 21:24:39 -0700270 s.getName().string(),
271 s.getVendor().string(),
Aravind Akella0b6acb22014-10-18 16:37:13 -0700272 s.getVersion(),
Aravind Akella70018042014-04-07 22:52:37 +0000273 s.getStringType().string(),
274 s.getHandle(),
Aravind Akella6c2664a2014-08-13 12:24:50 -0700275 s.getRequiredPermission().string(),
276 s.getType());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700277
Aravind Akella0e025c52014-06-03 19:19:57 -0700278 const int reportingMode = s.getReportingMode();
279 if (reportingMode == AREPORTING_MODE_CONTINUOUS) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700280 result.append(" continuous | ");
Aravind Akella0e025c52014-06-03 19:19:57 -0700281 } else if (reportingMode == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700282 result.append(" on-change | ");
Aravind Akella0e025c52014-06-03 19:19:57 -0700283 } else if (reportingMode == AREPORTING_MODE_ONE_SHOT) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700284 result.append(" one-shot | ");
Mathias Agopianba02cd22013-07-03 16:20:57 -0700285 } else {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700286 result.append(" special-trigger | ");
287 }
288
289 if (s.getMaxDelay() > 0) {
290 result.appendFormat("minRate=%.2fHz | ", 1e6f / s.getMaxDelay());
291 } else {
292 result.appendFormat("maxDelay=%dus |", s.getMaxDelay());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700293 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700294
295 if (s.getMinDelay() > 0) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700296 result.appendFormat("maxRate=%.2fHz | ", 1e6f / s.getMinDelay());
Aravind Akella0e025c52014-06-03 19:19:57 -0700297 } else {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700298 result.appendFormat("minDelay=%dus |", s.getMinDelay());
Aravind Akella0e025c52014-06-03 19:19:57 -0700299 }
300
Aravind Akella724d91d2013-06-27 12:04:23 -0700301 if (s.getFifoMaxEventCount() > 0) {
Aravind Akella70018042014-04-07 22:52:37 +0000302 result.appendFormat("FifoMax=%d events | ",
303 s.getFifoMaxEventCount());
Aravind Akella724d91d2013-06-27 12:04:23 -0700304 } else {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700305 result.append("no batching | ");
306 }
307
308 if (s.isWakeUpSensor()) {
309 result.appendFormat("wakeUp | ");
310 } else {
311 result.appendFormat("non-wakeUp | ");
Aravind Akella724d91d2013-06-27 12:04:23 -0700312 }
Mathias Agopianba02cd22013-07-03 16:20:57 -0700313
314 switch (s.getType()) {
315 case SENSOR_TYPE_ROTATION_VECTOR:
316 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
317 result.appendFormat(
Aravind Akella6c2664a2014-08-13 12:24:50 -0700318 "last=<%5.1f,%5.1f,%5.1f,%5.1f,%5.1f, %" PRId64 ">\n",
319 e.data[0], e.data[1], e.data[2], e.data[3], e.data[4], e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700320 break;
321 case SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED:
322 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
323 result.appendFormat(
Aravind Akella6c2664a2014-08-13 12:24:50 -0700324 "last=<%5.1f,%5.1f,%5.1f,%5.1f,%5.1f,%5.1f, %" PRId64 ">\n",
325 e.data[0], e.data[1], e.data[2], e.data[3], e.data[4], e.data[5],
326 e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700327 break;
328 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
329 result.appendFormat(
Aravind Akella6c2664a2014-08-13 12:24:50 -0700330 "last=<%5.1f,%5.1f,%5.1f,%5.1f, %" PRId64 ">\n",
331 e.data[0], e.data[1], e.data[2], e.data[3], e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700332 break;
333 case SENSOR_TYPE_SIGNIFICANT_MOTION:
334 case SENSOR_TYPE_STEP_DETECTOR:
Aravind Akella6c2664a2014-08-13 12:24:50 -0700335 result.appendFormat( "last=<%f %" PRId64 ">\n", e.data[0], e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700336 break;
337 case SENSOR_TYPE_STEP_COUNTER:
Aravind Akella6c2664a2014-08-13 12:24:50 -0700338 result.appendFormat( "last=<%" PRIu64 ", %" PRId64 ">\n", e.u64.step_counter,
339 e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700340 break;
341 default:
342 // default to 3 values
343 result.appendFormat(
Aravind Akella6c2664a2014-08-13 12:24:50 -0700344 "last=<%5.1f,%5.1f,%5.1f, %" PRId64 ">\n",
345 e.data[0], e.data[1], e.data[2], e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700346 break;
347 }
Aravind Akella6c2664a2014-08-13 12:24:50 -0700348 result.append("\n");
Mathias Agopianba02cd22013-07-03 16:20:57 -0700349 }
350 SensorFusion::getInstance().dump(result);
351 SensorDevice::getInstance().dump(result);
352
Mathias Agopianba02cd22013-07-03 16:20:57 -0700353 result.append("Active sensors:\n");
Mathias Agopianfc328812010-07-14 23:41:37 -0700354 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
Mathias Agopian5d270722010-07-19 15:20:39 -0700355 int handle = mActiveSensors.keyAt(i);
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700356 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
Mathias Agopian5d270722010-07-19 15:20:39 -0700357 getSensorName(handle).string(),
358 handle,
Mathias Agopianfc328812010-07-14 23:41:37 -0700359 mActiveSensors.valueAt(i)->getNumConnections());
Mathias Agopianfc328812010-07-14 23:41:37 -0700360 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700361
Aravind Akella5466c3d2014-08-22 16:11:10 -0700362 result.appendFormat("Socket Buffer size = %d events\n",
Aravind Akella6c2664a2014-08-13 12:24:50 -0700363 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella9a844cf2014-02-11 18:58:52 -0800364 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" : "not held");
Aravind Akella4949c502015-02-11 15:54:35 -0800365 result.appendFormat("Mode :");
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700366 switch(mCurrentOperatingMode) {
Aravind Akella4949c502015-02-11 15:54:35 -0800367 case NORMAL:
368 result.appendFormat(" NORMAL\n");
369 break;
370 case RESTRICTED:
371 result.appendFormat(" RESTRICTED\n");
372 break;
373 case DATA_INJECTION:
374 result.appendFormat(" DATA_INJECTION\n");
375 }
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700376 result.appendFormat("%zd active connections\n", mActiveConnections.size());
Aravind Akella4c8b9512013-09-05 17:03:38 -0700377
378 for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
379 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
380 if (connection != 0) {
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700381 result.appendFormat("Connection Number: %zu \n", i);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700382 connection->dump(result);
383 }
384 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700385 }
386 write(fd, result.string(), result.size());
387 return NO_ERROR;
388}
389
Aravind Akella9a844cf2014-02-11 18:58:52 -0800390void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700391 sensors_event_t const* buffer, const int count) {
392 for (int i=0 ; i<count ; i++) {
393 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700394 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
395 handle = buffer[i].meta_data.sensor;
396 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700397 if (connection->hasSensor(handle)) {
398 SensorInterface* sensor = mSensorMap.valueFor(handle);
399 // If this buffer has an event from a one_shot sensor and this connection is registered
400 // for this particular one_shot sensor, try cleaning up the connection.
401 if (sensor != NULL &&
402 sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
403 sensor->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800404 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700405 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700406
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700407 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700408 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700409}
410
Mathias Agopianfc328812010-07-14 23:41:37 -0700411bool SensorService::threadLoop()
412{
Steve Blocka5512372011-12-20 16:23:08 +0000413 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700414
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700415 // each virtual sensor could generate an event per "real" event, that's why we need
416 // to size numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT.
417 // in practice, this is too aggressive, but guaranteed to be enough.
418 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
419 const size_t numEventMax = minBufferSize / (1 + mVirtualSensorList.size());
420
Mathias Agopianf001c922010-11-11 17:58:51 -0800421 SensorDevice& device(SensorDevice::getInstance());
422 const size_t vcount = mVirtualSensorList.size();
Mathias Agopianfc328812010-07-14 23:41:37 -0700423
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700424 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700425 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700426 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
427 if (count < 0) {
Steve Blockf5a12302012-01-06 19:20:56 +0000428 ALOGE("sensor poll failed (%s)", strerror(-count));
Mathias Agopianfc328812010-07-14 23:41:37 -0700429 break;
430 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700431
432 // Reset sensors_event_t.flags to zero for all events in the buffer.
433 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700434 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700435 }
Aravind Akellae148bc22014-09-24 22:12:58 -0700436
437 // Make a copy of the connection vector as some connections may be removed during the
438 // course of this loop (especially when one-shot sensor events are present in the
439 // sensor_event buffer). Promote all connections to StrongPointers before the lock is
440 // acquired. If the destructor of the sp gets called when the lock is acquired, it may
441 // result in a deadlock as ~SensorEventConnection() needs to acquire mLock again for
442 // cleanup. So copy all the strongPointers to a vector before the lock is acquired.
443 SortedVector< sp<SensorEventConnection> > activeConnections;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700444 populateActiveConnections(&activeConnections);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800445 Mutex::Autolock _l(mLock);
446 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
447 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
448 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
449 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
450 // releasing the wakelock.
451 bool bufferHasWakeUpEvent = false;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700452 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700453 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800454 bufferHasWakeUpEvent = true;
455 break;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700456 }
457 }
458
Aravind Akella9a844cf2014-02-11 18:58:52 -0800459 if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700460 setWakeLockAcquiredLocked(true);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800461 }
Aravind Akella8493b792014-09-08 15:45:47 -0700462 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800463
Mathias Agopianf001c922010-11-11 17:58:51 -0800464 // handle virtual sensors
465 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700466 sensors_event_t const * const event = mSensorEventBuffer;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800467 const size_t activeVirtualSensorCount = mActiveVirtualSensors.size();
Mathias Agopianf001c922010-11-11 17:58:51 -0800468 if (activeVirtualSensorCount) {
469 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700470 SensorFusion& fusion(SensorFusion::getInstance());
471 if (fusion.isEnabled()) {
472 for (size_t i=0 ; i<size_t(count) ; i++) {
473 fusion.process(event[i]);
474 }
475 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700476 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800477 for (size_t j=0 ; j<activeVirtualSensorCount ; j++) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700478 if (count + k >= minBufferSize) {
479 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700480 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700481 count, k, minBufferSize);
482 break;
483 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800484 sensors_event_t out;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800485 SensorInterface* si = mActiveVirtualSensors.valueAt(j);
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700486 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700487 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800488 k++;
489 }
490 }
491 }
492 if (k) {
493 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700494 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800495 count += k;
496 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700497 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700498 }
499 }
500 }
501
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700502 // handle backward compatibility for RotationVector sensor
503 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
504 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700505 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700506 // All the 4 components of the quaternion should be available
507 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700508 mSensorEventBuffer[i].data[4] = -1;
509 }
510 }
511 }
512
513 // Map flush_complete_events in the buffer to SensorEventConnections which called
514 // flush on the hardware sensor. mapFlushEventsToConnections[i] will be the
515 // SensorEventConnection mapped to the corresponding flush_complete_event in
516 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
517 for (int i = 0; i < count; ++i) {
518 mMapFlushEventsToConnections[i] = NULL;
519 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
520 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
521 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
522 if (rec != NULL) {
523 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
524 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700525 }
526 }
527 }
528
Aravind Akella9a844cf2014-02-11 18:58:52 -0800529 // Send our events to clients. Check the state of wake lock for each client and release the
530 // lock if none of the clients need it.
531 bool needsWakeLock = false;
Aravind Akella8493b792014-09-08 15:45:47 -0700532 size_t numConnections = activeConnections.size();
533 for (size_t i=0 ; i < numConnections; ++i) {
Aravind Akellae148bc22014-09-24 22:12:58 -0700534 if (activeConnections[i] != 0) {
535 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
Aravind Akella8493b792014-09-08 15:45:47 -0700536 mMapFlushEventsToConnections);
Aravind Akellae148bc22014-09-24 22:12:58 -0700537 needsWakeLock |= activeConnections[i]->needsWakeLock();
Aravind Akella8493b792014-09-08 15:45:47 -0700538 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
539 // Early check for one-shot sensors.
Aravind Akellae148bc22014-09-24 22:12:58 -0700540 if (activeConnections[i]->hasOneShotSensors()) {
541 cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
542 count);
Aravind Akella8493b792014-09-08 15:45:47 -0700543 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800544 }
545 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700546
Aravind Akella9a844cf2014-02-11 18:58:52 -0800547 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700548 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800549 }
Aravind Akella8493b792014-09-08 15:45:47 -0700550 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -0700551
Steve Block3c20fbe2012-01-05 23:22:43 +0000552 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -0800553 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -0700554 return false;
555}
556
Aravind Akella56ae4262014-07-10 16:01:10 -0700557sp<Looper> SensorService::getLooper() const {
558 return mLooper;
559}
560
Aravind Akellab4373ac2014-10-29 17:55:20 -0700561void SensorService::resetAllWakeLockRefCounts() {
562 SortedVector< sp<SensorEventConnection> > activeConnections;
563 populateActiveConnections(&activeConnections);
564 {
565 Mutex::Autolock _l(mLock);
566 for (size_t i=0 ; i < activeConnections.size(); ++i) {
567 if (activeConnections[i] != 0) {
568 activeConnections[i]->resetWakeLockRefCount();
569 }
570 }
571 setWakeLockAcquiredLocked(false);
572 }
573}
574
575void SensorService::setWakeLockAcquiredLocked(bool acquire) {
576 if (acquire) {
577 if (!mWakeLockAcquired) {
578 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
579 mWakeLockAcquired = true;
580 }
581 mLooper->wake();
582 } else {
583 if (mWakeLockAcquired) {
584 release_wake_lock(WAKE_LOCK_NAME);
585 mWakeLockAcquired = false;
586 }
587 }
588}
589
Aravind Akellab4373ac2014-10-29 17:55:20 -0700590bool SensorService::isWakeLockAcquired() {
591 Mutex::Autolock _l(mLock);
592 return mWakeLockAcquired;
593}
594
Aravind Akella56ae4262014-07-10 16:01:10 -0700595bool SensorService::SensorEventAckReceiver::threadLoop() {
596 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -0700597 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -0700598 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700599 bool wakeLockAcquired = mService->isWakeLockAcquired();
600 int timeout = -1;
601 if (wakeLockAcquired) timeout = 5000;
602 int ret = looper->pollOnce(timeout);
603 if (ret == ALOOPER_POLL_TIMEOUT) {
604 mService->resetAllWakeLockRefCounts();
605 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700606 } while(!Thread::exitPending());
607 return false;
608}
609
Aravind Akella9a844cf2014-02-11 18:58:52 -0800610void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -0800611 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -0800612 const sensors_event_t* last = NULL;
613 for (size_t i = 0; i < count; i++) {
614 const sensors_event_t* event = &buffer[i];
615 if (event->type != SENSOR_TYPE_META_DATA) {
616 if (last && event->sensor != last->sensor) {
617 mLastEventSeen.editValueFor(last->sensor) = *last;
618 }
619 last = event;
Mathias Agopian94e8f682010-11-10 17:50:28 -0800620 }
621 }
Aravind Akella4b847042014-03-03 19:02:46 -0800622 if (last) {
623 mLastEventSeen.editValueFor(last->sensor) = *last;
624 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800625}
626
Mathias Agopianf001c922010-11-11 17:58:51 -0800627void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count)
628{
629 struct compar {
630 static int cmp(void const* lhs, void const* rhs) {
631 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
632 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -0700633 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -0800634 }
635 };
636 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
637}
638
Mathias Agopian5d270722010-07-19 15:20:39 -0700639String8 SensorService::getSensorName(int handle) const {
Mathias Agopian010e4222011-06-08 20:06:50 -0700640 size_t count = mUserSensorList.size();
Mathias Agopian5d270722010-07-19 15:20:39 -0700641 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian010e4222011-06-08 20:06:50 -0700642 const Sensor& sensor(mUserSensorList[i]);
Mathias Agopian5d270722010-07-19 15:20:39 -0700643 if (sensor.getHandle() == handle) {
644 return sensor.getName();
645 }
646 }
647 String8 result("unknown");
648 return result;
649}
650
Aravind Akellab4099e72013-10-15 15:43:10 -0700651bool SensorService::isVirtualSensor(int handle) const {
652 SensorInterface* sensor = mSensorMap.valueFor(handle);
653 return sensor->isVirtual();
654}
655
Aravind Akella9a844cf2014-02-11 18:58:52 -0800656bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -0700657 int handle = event.sensor;
658 if (event.type == SENSOR_TYPE_META_DATA) {
659 handle = event.meta_data.sensor;
660 }
661 SensorInterface* sensor = mSensorMap.valueFor(handle);
662 return sensor != NULL && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -0800663}
664
Aravind Akella6c2664a2014-08-13 12:24:50 -0700665SensorService::SensorRecord * SensorService::getSensorRecord(int handle) {
666 return mActiveSensors.valueFor(handle);
667}
668
Mathias Agopianfc328812010-07-14 23:41:37 -0700669Vector<Sensor> SensorService::getSensorList()
670{
Mathias Agopian33264862012-06-28 19:46:54 -0700671 char value[PROPERTY_VALUE_MAX];
672 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +0000673 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
674 mUserSensorListDebug : mUserSensorList;
675 Vector<Sensor> accessibleSensorList;
676 for (size_t i = 0; i < initialSensorList.size(); i++) {
677 Sensor sensor = initialSensorList[i];
678 if (canAccessSensor(sensor)) {
679 accessibleSensorList.add(sensor);
680 } else {
Bernhard Rosenkränzer5f619932014-11-17 21:06:20 +0100681 ALOGI("Skipped sensor %s because it requires permission %s",
682 sensor.getName().string(),
683 sensor.getRequiredPermission().string());
Aravind Akella70018042014-04-07 22:52:37 +0000684 }
Mathias Agopian33264862012-06-28 19:46:54 -0700685 }
Aravind Akella70018042014-04-07 22:52:37 +0000686 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -0700687}
688
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700689sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
690 int requestedMode) {
691 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
692 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
693 return NULL;
694 }
695 // DATA_INJECTION mode needs to have the required permissions set.
696 if (requestedMode == DATA_INJECTION && !hasDataInjectionPermissions()) {
697 return NULL;
698 }
699
700 Mutex::Autolock _l(mLock);
Mathias Agopian5307d172012-09-18 17:02:43 -0700701 uid_t uid = IPCThreadState::self()->getCallingUid();
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700702 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, packageName,
703 requestedMode == DATA_INJECTION));
704 if (requestedMode == DATA_INJECTION) {
705 if (mActiveConnections.indexOf(result) < 0) {
706 mActiveConnections.add(result);
707 }
708 // Add the associated file descriptor to the Looper for polling whenever there is data to
709 // be injected.
710 result->updateLooperRegistration(mLooper);
711 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700712 return result;
713}
714
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700715status_t SensorService::enableDataInjection(int requestedMode) {
716 if (!hasDataInjectionPermissions()) {
717 return INVALID_OPERATION;
718 }
719 Mutex::Autolock _l(mLock);
720 ALOGD_IF(DEBUG_CONNECTIONS, "SensorService::enableDataInjection %d", requestedMode);
721 SensorDevice& dev(SensorDevice::getInstance());
722 status_t err(NO_ERROR);
723 if (requestedMode == DATA_INJECTION) {
724 if (mCurrentOperatingMode == NORMAL) {
725 dev.disableAllSensors();
726 err = dev.setMode(requestedMode);
727 if (err == NO_ERROR) {
728 mCurrentOperatingMode = DATA_INJECTION;
729 } else {
730 // Re-enable sensors.
731 dev.enableAllSensors();
732 }
733 } else if (mCurrentOperatingMode == DATA_INJECTION) {
734 // Already in DATA_INJECTION mode. Treat this as a no_op.
735 return NO_ERROR;
736 } else {
737 // Transition to data injection mode supported only from NORMAL mode.
738 return INVALID_OPERATION;
739 }
740 } else if (requestedMode == NORMAL && mCurrentOperatingMode != NORMAL) {
741 err = resetToNormalModeLocked();
742 }
743 return err;
744}
745
746status_t SensorService::resetToNormalMode() {
747 Mutex::Autolock _l(mLock);
748 return resetToNormalModeLocked();
749}
750
751status_t SensorService::resetToNormalModeLocked() {
752 SensorDevice& dev(SensorDevice::getInstance());
753 dev.enableAllSensors();
754 status_t err = dev.setMode(NORMAL);
755 mCurrentOperatingMode = NORMAL;
756 return err;
757}
758
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800759void SensorService::cleanupConnection(SensorEventConnection* c)
Mathias Agopianfc328812010-07-14 23:41:37 -0700760{
761 Mutex::Autolock _l(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800762 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700763 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -0700764 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700765 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800766 int handle = mActiveSensors.keyAt(i);
767 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -0700768 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800769 SensorInterface* sensor = mSensorMap.valueFor( handle );
Steve Blockf5a12302012-01-06 19:20:56 +0000770 ALOGE_IF(!sensor, "mSensorMap[handle=0x%08x] is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800771 if (sensor) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800772 sensor->activate(c, false);
Mathias Agopianf001c922010-11-11 17:58:51 -0800773 }
Aravind Akella8a969552014-09-28 17:52:41 -0700774 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800775 }
776 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -0700777 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +0000778 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -0700779 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700780 c, i, handle);
781
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800782 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +0000783 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700784 mActiveSensors.removeItemsAt(i, 1);
Mathias Agopianf001c922010-11-11 17:58:51 -0800785 mActiveVirtualSensors.removeItem(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700786 delete rec;
787 size--;
788 } else {
789 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -0700790 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700791 }
Aravind Akella8a969552014-09-28 17:52:41 -0700792 c->updateLooperRegistration(mLooper);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700793 mActiveConnections.remove(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -0700794 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -0800795 if (c->needsWakeLock()) {
796 checkWakeLockStateLocked();
797 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700798}
799
Aravind Akella70018042014-04-07 22:52:37 +0000800Sensor SensorService::getSensorFromHandle(int handle) const {
801 return mSensorMap.valueFor(handle)->getSensor();
802}
803
Mathias Agopianfc328812010-07-14 23:41:37 -0700804status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Aravind Akella4949c502015-02-11 15:54:35 -0800805 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags)
Mathias Agopianfc328812010-07-14 23:41:37 -0700806{
Mathias Agopian50df2952010-07-19 19:09:10 -0700807 if (mInitCheck != NO_ERROR)
808 return mInitCheck;
809
Mathias Agopianf001c922010-11-11 17:58:51 -0800810 SensorInterface* sensor = mSensorMap.valueFor(handle);
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700811 if (sensor == NULL) {
812 return BAD_VALUE;
813 }
Aravind Akella70018042014-04-07 22:52:37 +0000814
815 if (!verifyCanAccessSensor(sensor->getSensor(), "Tried enabling")) {
816 return BAD_VALUE;
817 }
818
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700819 Mutex::Autolock _l(mLock);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700820 if (mCurrentOperatingMode == RESTRICTED && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -0800821 return INVALID_OPERATION;
822 }
823
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700824 SensorRecord* rec = mActiveSensors.valueFor(handle);
825 if (rec == 0) {
826 rec = new SensorRecord(connection);
827 mActiveSensors.add(handle, rec);
828 if (sensor->isVirtual()) {
829 mActiveVirtualSensors.add(handle, sensor);
830 }
831 } else {
832 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800833 // this sensor is already activated, but we are adding a connection that uses it.
834 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700835 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -0700836 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800837 // NOTE: The wake_up flag of this event may get set to
838 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700839 sensors_event_t& event(mLastEventSeen.editValueFor(handle));
840 if (event.version == sizeof(sensors_event_t)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800841 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700842 setWakeLockAcquiredLocked(true);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800843 }
844 connection->sendEvents(&event, 1, NULL);
845 if (!connection->needsWakeLock() && mWakeLockAcquired) {
846 checkWakeLockStateLocked();
847 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700848 }
849 }
850 }
851 }
852
853 if (connection->addSensor(handle)) {
854 BatteryService::enableSensor(connection->getUid(), handle);
855 // the sensor was added (which means it wasn't already there)
856 // so, see if this connection becomes active
857 if (mActiveConnections.indexOf(connection) < 0) {
858 mActiveConnections.add(connection);
859 }
860 } else {
861 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
862 handle, connection.get());
863 }
864
Aravind Akella724d91d2013-06-27 12:04:23 -0700865 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
866 if (samplingPeriodNs < minDelayNs) {
867 samplingPeriodNs = minDelayNs;
868 }
869
Aravind Akella6c2664a2014-08-13 12:24:50 -0700870 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
871 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -0700872 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
873
Aravind Akella4949c502015-02-11 15:54:35 -0800874 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -0700875 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -0700876
Aravind Akella5466c3d2014-08-22 16:11:10 -0700877 // Call flush() before calling activate() on the sensor. Wait for a first flush complete
878 // event before sending events on this connection. Ignore one-shot sensors which don't
879 // support flush(). Also if this sensor isn't already active, don't call flush().
880 if (err == NO_ERROR && sensor->getSensor().getReportingMode() != AREPORTING_MODE_ONE_SHOT &&
881 rec->getNumConnections() > 1) {
882 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700883 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -0700884 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -0700885 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700886 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -0700887 } else {
888 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700889 }
890 }
Aravind Akella724d91d2013-06-27 12:04:23 -0700891
892 if (err == NO_ERROR) {
893 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
894 err = sensor->activate(connection.get(), true);
895 }
896
Aravind Akella8a969552014-09-28 17:52:41 -0700897 if (err == NO_ERROR) {
898 connection->updateLooperRegistration(mLooper);
Aravind Akella56ae4262014-07-10 16:01:10 -0700899 }
900
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700901 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -0700902 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700903 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700904 }
905 return err;
906}
907
908status_t SensorService::disable(const sp<SensorEventConnection>& connection,
909 int handle)
910{
Mathias Agopian50df2952010-07-19 19:09:10 -0700911 if (mInitCheck != NO_ERROR)
912 return mInitCheck;
913
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700914 Mutex::Autolock _l(mLock);
915 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700916 if (err == NO_ERROR) {
917 SensorInterface* sensor = mSensorMap.valueFor(handle);
918 err = sensor ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
919 }
920 return err;
921}
922
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700923status_t SensorService::cleanupWithoutDisable(
924 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700925 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700926 return cleanupWithoutDisableLocked(connection, handle);
927}
928
929status_t SensorService::cleanupWithoutDisableLocked(
930 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700931 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700932 if (rec) {
933 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -0700934 if (connection->removeSensor(handle)) {
935 BatteryService::disableSensor(connection->getUid(), handle);
936 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700937 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -0700938 connection->updateLooperRegistration(mLooper);
Mathias Agopianfc328812010-07-14 23:41:37 -0700939 mActiveConnections.remove(connection);
940 }
941 // see if this sensor becomes inactive
942 if (rec->removeConnection(connection)) {
943 mActiveSensors.removeItem(handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800944 mActiveVirtualSensors.removeItem(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700945 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -0700946 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700947 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700948 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700949 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -0700950}
951
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700952status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Mathias Agopianfc328812010-07-14 23:41:37 -0700953 int handle, nsecs_t ns)
954{
Mathias Agopian50df2952010-07-19 19:09:10 -0700955 if (mInitCheck != NO_ERROR)
956 return mInitCheck;
957
Mathias Agopianae09d652011-11-01 17:37:49 -0700958 SensorInterface* sensor = mSensorMap.valueFor(handle);
959 if (!sensor)
960 return BAD_VALUE;
961
Aravind Akella70018042014-04-07 22:52:37 +0000962 if (!verifyCanAccessSensor(sensor->getSensor(), "Tried configuring")) {
963 return BAD_VALUE;
964 }
965
Mathias Agopian1cd70002010-07-21 15:59:50 -0700966 if (ns < 0)
967 return BAD_VALUE;
968
Mathias Agopian62569ec2011-11-07 21:21:47 -0800969 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
970 if (ns < minDelayNs) {
971 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -0700972 }
973
Mathias Agopianf001c922010-11-11 17:58:51 -0800974 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -0700975}
976
Aravind Akella9e3adfc2014-09-03 15:48:05 -0700977status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection) {
Aravind Akella70018042014-04-07 22:52:37 +0000978 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -0700979 SensorDevice& dev(SensorDevice::getInstance());
980 const int halVersion = dev.getHalDeviceVersion();
981 status_t err(NO_ERROR);
982 Mutex::Autolock _l(mLock);
983 // Loop through all sensors for this connection and call flush on each of them.
984 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
985 const int handle = connection->mSensorInfo.keyAt(i);
986 SensorInterface* sensor = mSensorMap.valueFor(handle);
987 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
988 ALOGE("flush called on a one-shot sensor");
989 err = INVALID_OPERATION;
990 continue;
991 }
Aravind Akella8493b792014-09-08 15:45:47 -0700992 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -0700993 // For older devices just increment pending flush count which will send a trivial
994 // flush complete event.
Aravind Akella8a969552014-09-28 17:52:41 -0700995 connection->incrementPendingFlushCount(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -0700996 } else {
997 status_t err_flush = sensor->flush(connection.get(), handle);
998 if (err_flush == NO_ERROR) {
999 SensorRecord* rec = mActiveSensors.valueFor(handle);
1000 if (rec != NULL) rec->addPendingFlushConnection(connection);
1001 }
1002 err = (err_flush != NO_ERROR) ? err_flush : err;
1003 }
Aravind Akella70018042014-04-07 22:52:37 +00001004 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001005 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001006}
Aravind Akella70018042014-04-07 22:52:37 +00001007
Aravind Akella70018042014-04-07 22:52:37 +00001008bool SensorService::canAccessSensor(const Sensor& sensor) {
Aravind Akella56ae4262014-07-10 16:01:10 -07001009 return (sensor.getRequiredPermission().isEmpty()) ||
1010 PermissionCache::checkCallingPermission(String16(sensor.getRequiredPermission()));
Aravind Akella70018042014-04-07 22:52:37 +00001011}
1012
1013bool SensorService::verifyCanAccessSensor(const Sensor& sensor, const char* operation) {
1014 if (canAccessSensor(sensor)) {
1015 return true;
1016 } else {
1017 String8 errorMessage;
1018 errorMessage.appendFormat(
1019 "%s a sensor (%s) without holding its required permission: %s",
1020 operation,
1021 sensor.getName().string(),
1022 sensor.getRequiredPermission().string());
1023 return false;
1024 }
1025}
1026
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001027bool SensorService::hasDataInjectionPermissions() {
1028 if (!PermissionCache::checkCallingPermission(sDataInjectionPermission)) {
1029 ALOGE("Permission Denial trying to activate data injection without"
1030 " the required permission");
1031 return false;
1032 }
1033 return true;
1034}
1035
Aravind Akella9a844cf2014-02-11 18:58:52 -08001036void SensorService::checkWakeLockState() {
1037 Mutex::Autolock _l(mLock);
1038 checkWakeLockStateLocked();
1039}
1040
1041void SensorService::checkWakeLockStateLocked() {
1042 if (!mWakeLockAcquired) {
1043 return;
1044 }
1045 bool releaseLock = true;
1046 for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
1047 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1048 if (connection != 0) {
1049 if (connection->needsWakeLock()) {
1050 releaseLock = false;
1051 break;
1052 }
1053 }
1054 }
1055 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001056 setWakeLockAcquiredLocked(false);
1057 }
1058}
1059
1060void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1061 Mutex::Autolock _l(mLock);
1062 connection->writeToSocketFromCache();
1063 if (connection->needsWakeLock()) {
1064 setWakeLockAcquiredLocked(true);
1065 }
1066}
1067
1068void SensorService::populateActiveConnections(
1069 SortedVector< sp<SensorEventConnection> >* activeConnections) {
1070 Mutex::Autolock _l(mLock);
1071 for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
1072 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1073 if (connection != 0) {
1074 activeConnections->add(connection);
1075 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001076 }
1077}
Aravind Akella6c2664a2014-08-13 12:24:50 -07001078
Aravind Akella4949c502015-02-11 15:54:35 -08001079bool SensorService::isWhiteListedPackage(const String8& packageName) {
1080 // TODO: Come up with a list of packages.
1081 return (packageName.find(".cts.") != -1);
1082}
1083
Mathias Agopianfc328812010-07-14 23:41:37 -07001084// ---------------------------------------------------------------------------
Mathias Agopianfc328812010-07-14 23:41:37 -07001085SensorService::SensorRecord::SensorRecord(
1086 const sp<SensorEventConnection>& connection)
1087{
1088 mConnections.add(connection);
1089}
1090
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001091bool SensorService::SensorRecord::addConnection(
Mathias Agopianfc328812010-07-14 23:41:37 -07001092 const sp<SensorEventConnection>& connection)
1093{
1094 if (mConnections.indexOf(connection) < 0) {
1095 mConnections.add(connection);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001096 return true;
Mathias Agopianfc328812010-07-14 23:41:37 -07001097 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001098 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -07001099}
1100
1101bool SensorService::SensorRecord::removeConnection(
1102 const wp<SensorEventConnection>& connection)
1103{
1104 ssize_t index = mConnections.indexOf(connection);
1105 if (index >= 0) {
1106 mConnections.removeItemsAt(index, 1);
1107 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001108 // Remove this connections from the queue of flush() calls made on this sensor.
1109 for (Vector< wp<SensorEventConnection> >::iterator it =
1110 mPendingFlushConnections.begin(); it != mPendingFlushConnections.end();) {
Aravind Akella8a969552014-09-28 17:52:41 -07001111
Aravind Akella6c2664a2014-08-13 12:24:50 -07001112 if (it->unsafe_get() == connection.unsafe_get()) {
1113 it = mPendingFlushConnections.erase(it);
1114 } else {
1115 ++it;
1116 }
1117 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001118 return mConnections.size() ? false : true;
1119}
1120
Aravind Akella6c2664a2014-08-13 12:24:50 -07001121void SensorService::SensorRecord::addPendingFlushConnection(
1122 const sp<SensorEventConnection>& connection) {
1123 mPendingFlushConnections.add(connection);
1124}
1125
1126void SensorService::SensorRecord::removeFirstPendingFlushConnection() {
1127 if (mPendingFlushConnections.size() > 0) {
1128 mPendingFlushConnections.removeAt(0);
1129 }
1130}
1131
1132SensorService::SensorEventConnection *
1133SensorService::SensorRecord::getFirstPendingFlushConnection() {
1134 if (mPendingFlushConnections.size() > 0) {
1135 return mPendingFlushConnections[0].unsafe_get();
1136 }
1137 return NULL;
1138}
1139
Aravind Akella4949c502015-02-11 15:54:35 -08001140void SensorService::SensorRecord::clearAllPendingFlushConnections() {
1141 mPendingFlushConnections.clear();
1142}
1143
Mathias Agopianfc328812010-07-14 23:41:37 -07001144// ---------------------------------------------------------------------------
1145
1146SensorService::SensorEventConnection::SensorEventConnection(
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001147 const sp<SensorService>& service, uid_t uid, String8 packageName, bool isDataInjectionMode)
Aravind Akella8a969552014-09-28 17:52:41 -07001148 : mService(service), mUid(uid), mWakeLockRefCount(0), mHasLooperCallbacks(false),
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001149 mDead(false), mEventCache(NULL), mCacheSize(0), mMaxCacheSize(0), mPackageName(packageName),
1150 mDataInjectionMode(isDataInjectionMode) {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001151 mChannel = new BitTube(mService->mSocketBufferSize);
Aravind Akella56ae4262014-07-10 16:01:10 -07001152#if DEBUG_CONNECTIONS
1153 mEventsReceived = mEventsSentFromCache = mEventsSent = 0;
Aravind Akellae74baf62014-08-21 12:28:35 -07001154 mTotalAcksNeeded = mTotalAcksReceived = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -07001155#endif
Mathias Agopianfc328812010-07-14 23:41:37 -07001156}
1157
Aravind Akella56ae4262014-07-10 16:01:10 -07001158SensorService::SensorEventConnection::~SensorEventConnection() {
Steve Blocka5512372011-12-20 16:23:08 +00001159 ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this);
Aravind Akellae148bc22014-09-24 22:12:58 -07001160 mService->cleanupConnection(this);
Aravind Akella56ae4262014-07-10 16:01:10 -07001161 if (mEventCache != NULL) {
1162 delete mEventCache;
1163 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001164}
1165
Aravind Akella56ae4262014-07-10 16:01:10 -07001166void SensorService::SensorEventConnection::onFirstRef() {
1167 LooperCallback::onFirstRef();
Mathias Agopianfc328812010-07-14 23:41:37 -07001168}
1169
Aravind Akella9a844cf2014-02-11 18:58:52 -08001170bool SensorService::SensorEventConnection::needsWakeLock() {
1171 Mutex::Autolock _l(mConnectionLock);
Aravind Akella8a969552014-09-28 17:52:41 -07001172 return !mDead && mWakeLockRefCount > 0;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001173}
1174
Aravind Akellab4373ac2014-10-29 17:55:20 -07001175void SensorService::SensorEventConnection::resetWakeLockRefCount() {
1176 Mutex::Autolock _l(mConnectionLock);
1177 mWakeLockRefCount = 0;
1178}
1179
Aravind Akella4c8b9512013-09-05 17:03:38 -07001180void SensorService::SensorEventConnection::dump(String8& result) {
1181 Mutex::Autolock _l(mConnectionLock);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001182 result.appendFormat("Operating Mode: %s\n", mDataInjectionMode ? "DATA_INJECTION" : "NORMAL");
Aravind Akella4949c502015-02-11 15:54:35 -08001183 result.appendFormat("\t%s | WakeLockRefCount %d | uid %d | cache size %d | max cache size %d\n",
1184 mPackageName.string(), mWakeLockRefCount, mUid, mCacheSize, mMaxCacheSize);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001185 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1186 const FlushInfo& flushInfo = mSensorInfo.valueAt(i);
Aravind Akella0ec20662014-09-14 17:29:48 -07001187 result.appendFormat("\t %s 0x%08x | status: %s | pending flush events %d \n",
Aravind Akella4c8b9512013-09-05 17:03:38 -07001188 mService->getSensorName(mSensorInfo.keyAt(i)).string(),
Aravind Akella6c2664a2014-08-13 12:24:50 -07001189 mSensorInfo.keyAt(i),
Aravind Akella4c8b9512013-09-05 17:03:38 -07001190 flushInfo.mFirstFlushPending ? "First flush pending" :
1191 "active",
Aravind Akella0ec20662014-09-14 17:29:48 -07001192 flushInfo.mPendingFlushEventsToSend);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001193 }
Aravind Akella0ec20662014-09-14 17:29:48 -07001194#if DEBUG_CONNECTIONS
1195 result.appendFormat("\t events recvd: %d | sent %d | cache %d | dropped %d |"
1196 " total_acks_needed %d | total_acks_recvd %d\n",
1197 mEventsReceived,
1198 mEventsSent,
1199 mEventsSentFromCache,
1200 mEventsReceived - (mEventsSentFromCache + mEventsSent + mCacheSize),
1201 mTotalAcksNeeded,
1202 mTotalAcksReceived);
1203#endif
Aravind Akella4c8b9512013-09-05 17:03:38 -07001204}
1205
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001206bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001207 Mutex::Autolock _l(mConnectionLock);
Aravind Akella70018042014-04-07 22:52:37 +00001208 if (!verifyCanAccessSensor(mService->getSensorFromHandle(handle), "Tried adding")) {
1209 return false;
1210 }
Aravind Akella4c8b9512013-09-05 17:03:38 -07001211 if (mSensorInfo.indexOfKey(handle) < 0) {
1212 mSensorInfo.add(handle, FlushInfo());
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001213 return true;
Mathias Agopianfc328812010-07-14 23:41:37 -07001214 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001215 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -07001216}
1217
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001218bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001219 Mutex::Autolock _l(mConnectionLock);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001220 if (mSensorInfo.removeItem(handle) >= 0) {
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001221 return true;
1222 }
1223 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -07001224}
1225
1226bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001227 Mutex::Autolock _l(mConnectionLock);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001228 return mSensorInfo.indexOfKey(handle) >= 0;
Mathias Agopianfc328812010-07-14 23:41:37 -07001229}
1230
1231bool SensorService::SensorEventConnection::hasAnySensor() const {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001232 Mutex::Autolock _l(mConnectionLock);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001233 return mSensorInfo.size() ? true : false;
1234}
1235
Aravind Akella8493b792014-09-08 15:45:47 -07001236bool SensorService::SensorEventConnection::hasOneShotSensors() const {
1237 Mutex::Autolock _l(mConnectionLock);
1238 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1239 const int handle = mSensorInfo.keyAt(i);
1240 if (mService->getSensorFromHandle(handle).getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1241 return true;
1242 }
1243 }
1244 return false;
1245}
1246
Aravind Akella4949c502015-02-11 15:54:35 -08001247String8 SensorService::SensorEventConnection::getPackageName() const {
1248 return mPackageName;
1249}
1250
Aravind Akella4c8b9512013-09-05 17:03:38 -07001251void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle,
1252 bool value) {
1253 Mutex::Autolock _l(mConnectionLock);
1254 ssize_t index = mSensorInfo.indexOfKey(handle);
1255 if (index >= 0) {
1256 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
1257 flushInfo.mFirstFlushPending = value;
1258 }
1259}
1260
Aravind Akella8a969552014-09-28 17:52:41 -07001261void SensorService::SensorEventConnection::updateLooperRegistration(const sp<Looper>& looper) {
1262 Mutex::Autolock _l(mConnectionLock);
1263 updateLooperRegistrationLocked(looper);
1264}
1265
1266void SensorService::SensorEventConnection::updateLooperRegistrationLocked(
1267 const sp<Looper>& looper) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001268 bool isConnectionActive = (mSensorInfo.size() > 0 && !mDataInjectionMode) ||
1269 mDataInjectionMode;
Aravind Akella8a969552014-09-28 17:52:41 -07001270 // If all sensors are unregistered OR Looper has encountered an error, we
1271 // can remove the Fd from the Looper if it has been previously added.
1272 if (!isConnectionActive || mDead) {
1273 if (mHasLooperCallbacks) {
1274 ALOGD_IF(DEBUG_CONNECTIONS, "%p removeFd fd=%d", this, mChannel->getSendFd());
1275 looper->removeFd(mChannel->getSendFd());
1276 mHasLooperCallbacks = false;
1277 }
1278 return;
1279 }
1280
1281 int looper_flags = 0;
1282 if (mCacheSize > 0) looper_flags |= ALOOPER_EVENT_OUTPUT;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001283 if (mDataInjectionMode) looper_flags |= ALOOPER_EVENT_INPUT;
Aravind Akella8a969552014-09-28 17:52:41 -07001284 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1285 const int handle = mSensorInfo.keyAt(i);
1286 if (mService->getSensorFromHandle(handle).isWakeUpSensor()) {
1287 looper_flags |= ALOOPER_EVENT_INPUT;
1288 break;
1289 }
1290 }
1291 // If flags is still set to zero, we don't need to add this fd to the Looper, if
1292 // the fd has already been added, remove it. This is likely to happen when ALL the
1293 // events stored in the cache have been sent to the corresponding app.
1294 if (looper_flags == 0) {
1295 if (mHasLooperCallbacks) {
1296 ALOGD_IF(DEBUG_CONNECTIONS, "removeFd fd=%d", mChannel->getSendFd());
1297 looper->removeFd(mChannel->getSendFd());
1298 mHasLooperCallbacks = false;
1299 }
1300 return;
1301 }
1302 // Add the file descriptor to the Looper for receiving acknowledegments if the app has
1303 // registered for wake-up sensors OR for sending events in the cache.
1304 int ret = looper->addFd(mChannel->getSendFd(), 0, looper_flags, this, NULL);
1305 if (ret == 1) {
1306 ALOGD_IF(DEBUG_CONNECTIONS, "%p addFd fd=%d", this, mChannel->getSendFd());
1307 mHasLooperCallbacks = true;
1308 } else {
1309 ALOGE("Looper::addFd failed ret=%d fd=%d", ret, mChannel->getSendFd());
1310 }
1311}
1312
1313void SensorService::SensorEventConnection::incrementPendingFlushCount(int32_t handle) {
1314 Mutex::Autolock _l(mConnectionLock);
1315 ssize_t index = mSensorInfo.indexOfKey(handle);
1316 if (index >= 0) {
1317 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
1318 flushInfo.mPendingFlushEventsToSend++;
1319 }
1320}
1321
Mathias Agopianfc328812010-07-14 23:41:37 -07001322status_t SensorService::SensorEventConnection::sendEvents(
Aravind Akella0ec20662014-09-14 17:29:48 -07001323 sensors_event_t const* buffer, size_t numEvents,
Aravind Akella8493b792014-09-08 15:45:47 -07001324 sensors_event_t* scratch,
1325 SensorEventConnection const * const * mapFlushEventsToConnections) {
Mathias Agopiancf510012010-07-22 16:18:10 -07001326 // filter out events not for this connection
Mathias Agopian3560fb22010-07-22 21:24:39 -07001327 size_t count = 0;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001328 Mutex::Autolock _l(mConnectionLock);
Mathias Agopian3560fb22010-07-22 21:24:39 -07001329 if (scratch) {
1330 size_t i=0;
1331 while (i<numEvents) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001332 int32_t sensor_handle = buffer[i].sensor;
Aravind Akella724d91d2013-06-27 12:04:23 -07001333 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
1334 ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ",
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001335 buffer[i].meta_data.sensor);
Aravind Akella8a969552014-09-28 17:52:41 -07001336 // Setting sensor_handle to the correct sensor to ensure the sensor events per
1337 // connection are filtered correctly. buffer[i].sensor is zero for meta_data
1338 // events.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001339 sensor_handle = buffer[i].meta_data.sensor;
Aravind Akella724d91d2013-06-27 12:04:23 -07001340 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001341 ssize_t index = mSensorInfo.indexOfKey(sensor_handle);
Aravind Akella56ae4262014-07-10 16:01:10 -07001342 // Check if this connection has registered for this sensor. If not continue to the
1343 // next sensor_event.
1344 if (index < 0) {
1345 ++i;
1346 continue;
Aravind Akella4c8b9512013-09-05 17:03:38 -07001347 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001348
Aravind Akella56ae4262014-07-10 16:01:10 -07001349 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001350 // Check if there is a pending flush_complete event for this sensor on this connection.
Aravind Akella8493b792014-09-08 15:45:47 -07001351 if (buffer[i].type == SENSOR_TYPE_META_DATA && flushInfo.mFirstFlushPending == true &&
1352 this == mapFlushEventsToConnections[i]) {
1353 flushInfo.mFirstFlushPending = false;
1354 ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ",
1355 buffer[i].meta_data.sensor);
1356 ++i;
1357 continue;
Aravind Akella56ae4262014-07-10 16:01:10 -07001358 }
1359
1360 // If there is a pending flush complete event for this sensor on this connection,
1361 // ignore the event and proceed to the next.
1362 if (flushInfo.mFirstFlushPending) {
1363 ++i;
1364 continue;
1365 }
1366
1367 do {
Aravind Akella8493b792014-09-08 15:45:47 -07001368 // Keep copying events into the scratch buffer as long as they are regular
1369 // sensor_events are from the same sensor_handle OR they are flush_complete_events
1370 // from the same sensor_handle AND the current connection is mapped to the
1371 // corresponding flush_complete_event.
Aravind Akella56ae4262014-07-10 16:01:10 -07001372 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
Aravind Akella8493b792014-09-08 15:45:47 -07001373 if (this == mapFlushEventsToConnections[i]) {
Aravind Akella56ae4262014-07-10 16:01:10 -07001374 scratch[count++] = buffer[i];
Aravind Akella56ae4262014-07-10 16:01:10 -07001375 }
1376 ++i;
1377 } else {
1378 // Regular sensor event, just copy it to the scratch buffer.
Aravind Akella4c8b9512013-09-05 17:03:38 -07001379 scratch[count++] = buffer[i++];
Aravind Akella56ae4262014-07-10 16:01:10 -07001380 }
Aravind Akella8493b792014-09-08 15:45:47 -07001381 } while ((i<numEvents) && ((buffer[i].sensor == sensor_handle &&
1382 buffer[i].type != SENSOR_TYPE_META_DATA) ||
Aravind Akella56ae4262014-07-10 16:01:10 -07001383 (buffer[i].type == SENSOR_TYPE_META_DATA &&
Aravind Akella6c2664a2014-08-13 12:24:50 -07001384 buffer[i].meta_data.sensor == sensor_handle)));
Mathias Agopiancf510012010-07-22 16:18:10 -07001385 }
Mathias Agopian3560fb22010-07-22 21:24:39 -07001386 } else {
1387 scratch = const_cast<sensors_event_t *>(buffer);
1388 count = numEvents;
Mathias Agopiancf510012010-07-22 16:18:10 -07001389 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001390
Aravind Akella6c2664a2014-08-13 12:24:50 -07001391 sendPendingFlushEventsLocked();
Aravind Akella56ae4262014-07-10 16:01:10 -07001392 // Early return if there are no events for this connection.
1393 if (count == 0) {
1394 return status_t(NO_ERROR);
1395 }
1396
1397#if DEBUG_CONNECTIONS
1398 mEventsReceived += count;
1399#endif
1400 if (mCacheSize != 0) {
1401 // There are some events in the cache which need to be sent first. Copy this buffer to
1402 // the end of cache.
1403 if (mCacheSize + count <= mMaxCacheSize) {
1404 memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
1405 mCacheSize += count;
1406 } else {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001407 // Check if any new sensors have registered on this connection which may have increased
1408 // the max cache size that is desired.
1409 if (mCacheSize + count < computeMaxCacheSizeLocked()) {
1410 reAllocateCacheLocked(scratch, count);
1411 return status_t(NO_ERROR);
1412 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001413 // Some events need to be dropped.
1414 int remaningCacheSize = mMaxCacheSize - mCacheSize;
1415 if (remaningCacheSize != 0) {
1416 memcpy(&mEventCache[mCacheSize], scratch,
1417 remaningCacheSize * sizeof(sensors_event_t));
1418 }
1419 int numEventsDropped = count - remaningCacheSize;
1420 countFlushCompleteEventsLocked(mEventCache, numEventsDropped);
1421 // Drop the first "numEventsDropped" in the cache.
1422 memmove(mEventCache, &mEventCache[numEventsDropped],
1423 (mCacheSize - numEventsDropped) * sizeof(sensors_event_t));
1424
1425 // Copy the remainingEvents in scratch buffer to the end of cache.
1426 memcpy(&mEventCache[mCacheSize - numEventsDropped], scratch + remaningCacheSize,
1427 numEventsDropped * sizeof(sensors_event_t));
1428 }
1429 return status_t(NO_ERROR);
1430 }
1431
Aravind Akella6c2664a2014-08-13 12:24:50 -07001432 int index_wake_up_event = findWakeUpSensorEventLocked(scratch, count);
1433 if (index_wake_up_event >= 0) {
1434 scratch[index_wake_up_event].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1435 ++mWakeLockRefCount;
Aravind Akellae74baf62014-08-21 12:28:35 -07001436#if DEBUG_CONNECTIONS
1437 ++mTotalAcksNeeded;
1438#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001439 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001440
1441 // NOTE: ASensorEvent and sensors_event_t are the same type.
1442 ssize_t size = SensorEventQueue::write(mChannel,
1443 reinterpret_cast<ASensorEvent const*>(scratch), count);
1444 if (size < 0) {
1445 // Write error, copy events to local cache.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001446 if (index_wake_up_event >= 0) {
1447 // If there was a wake_up sensor_event, reset the flag.
1448 scratch[index_wake_up_event].flags &= ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
Aravind Akella0ec20662014-09-14 17:29:48 -07001449 if (mWakeLockRefCount > 0) {
1450 --mWakeLockRefCount;
1451 }
Aravind Akellae74baf62014-08-21 12:28:35 -07001452#if DEBUG_CONNECTIONS
1453 --mTotalAcksNeeded;
1454#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001455 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001456 if (mEventCache == NULL) {
1457 mMaxCacheSize = computeMaxCacheSizeLocked();
1458 mEventCache = new sensors_event_t[mMaxCacheSize];
1459 mCacheSize = 0;
1460 }
1461 memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
1462 mCacheSize += count;
1463
1464 // Add this file descriptor to the looper to get a callback when this fd is available for
1465 // writing.
Aravind Akella8a969552014-09-28 17:52:41 -07001466 updateLooperRegistrationLocked(mService->getLooper());
Aravind Akella56ae4262014-07-10 16:01:10 -07001467 return size;
1468 }
1469
1470#if DEBUG_CONNECTIONS
1471 if (size > 0) {
1472 mEventsSent += count;
1473 }
1474#endif
1475
1476 return size < 0 ? status_t(size) : status_t(NO_ERROR);
1477}
1478
Aravind Akella6c2664a2014-08-13 12:24:50 -07001479void SensorService::SensorEventConnection::reAllocateCacheLocked(sensors_event_t const* scratch,
1480 int count) {
1481 sensors_event_t *eventCache_new;
1482 const int new_cache_size = computeMaxCacheSizeLocked();
1483 // Allocate new cache, copy over events from the old cache & scratch, free up memory.
1484 eventCache_new = new sensors_event_t[new_cache_size];
1485 memcpy(eventCache_new, mEventCache, mCacheSize * sizeof(sensors_event_t));
1486 memcpy(&eventCache_new[mCacheSize], scratch, count * sizeof(sensors_event_t));
1487
1488 ALOGD_IF(DEBUG_CONNECTIONS, "reAllocateCacheLocked maxCacheSize=%d %d", mMaxCacheSize,
1489 new_cache_size);
1490
1491 delete mEventCache;
1492 mEventCache = eventCache_new;
1493 mCacheSize += count;
1494 mMaxCacheSize = new_cache_size;
1495}
1496
1497void SensorService::SensorEventConnection::sendPendingFlushEventsLocked() {
1498 ASensorEvent flushCompleteEvent;
Aravind Akella0ec20662014-09-14 17:29:48 -07001499 memset(&flushCompleteEvent, 0, sizeof(flushCompleteEvent));
Aravind Akella6c2664a2014-08-13 12:24:50 -07001500 flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
Aravind Akella6c2664a2014-08-13 12:24:50 -07001501 // Loop through all the sensors for this connection and check if there are any pending
1502 // flush complete events to be sent.
1503 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1504 FlushInfo& flushInfo = mSensorInfo.editValueAt(i);
1505 while (flushInfo.mPendingFlushEventsToSend > 0) {
Aravind Akella0ec20662014-09-14 17:29:48 -07001506 const int sensor_handle = mSensorInfo.keyAt(i);
1507 flushCompleteEvent.meta_data.sensor = sensor_handle;
Aravind Akellab4373ac2014-10-29 17:55:20 -07001508 bool wakeUpSensor = mService->getSensorFromHandle(sensor_handle).isWakeUpSensor();
1509 if (wakeUpSensor) {
1510 ++mWakeLockRefCount;
Aravind Akella0ec20662014-09-14 17:29:48 -07001511 flushCompleteEvent.flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1512 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001513 ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
1514 if (size < 0) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001515 if (wakeUpSensor) --mWakeLockRefCount;
Aravind Akella6c2664a2014-08-13 12:24:50 -07001516 return;
1517 }
1518 ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
1519 flushCompleteEvent.meta_data.sensor);
1520 flushInfo.mPendingFlushEventsToSend--;
1521 }
1522 }
1523}
1524
Aravind Akellab4373ac2014-10-29 17:55:20 -07001525void SensorService::SensorEventConnection::writeToSocketFromCache() {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001526 // At a time write at most half the size of the receiver buffer in SensorEventQueue OR
1527 // half the size of the socket buffer allocated in BitTube whichever is smaller.
1528 const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
1529 int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
Aravind Akellab4373ac2014-10-29 17:55:20 -07001530 Mutex::Autolock _l(mConnectionLock);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001531 // Send pending flush complete events (if any)
Aravind Akella6c2664a2014-08-13 12:24:50 -07001532 sendPendingFlushEventsLocked();
Aravind Akella56ae4262014-07-10 16:01:10 -07001533 for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001534 const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001535 int index_wake_up_event =
1536 findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite);
1537 if (index_wake_up_event >= 0) {
1538 mEventCache[index_wake_up_event + numEventsSent].flags |=
1539 WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1540 ++mWakeLockRefCount;
Aravind Akellae74baf62014-08-21 12:28:35 -07001541#if DEBUG_CONNECTIONS
1542 ++mTotalAcksNeeded;
1543#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001544 }
Aravind Akella4c8b9512013-09-05 17:03:38 -07001545
Aravind Akella56ae4262014-07-10 16:01:10 -07001546 ssize_t size = SensorEventQueue::write(mChannel,
1547 reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent),
Aravind Akella6c2664a2014-08-13 12:24:50 -07001548 numEventsToWrite);
Aravind Akella56ae4262014-07-10 16:01:10 -07001549 if (size < 0) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001550 if (index_wake_up_event >= 0) {
1551 // If there was a wake_up sensor_event, reset the flag.
1552 mEventCache[index_wake_up_event + numEventsSent].flags &=
1553 ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
Aravind Akella0ec20662014-09-14 17:29:48 -07001554 if (mWakeLockRefCount > 0) {
1555 --mWakeLockRefCount;
1556 }
Aravind Akellae74baf62014-08-21 12:28:35 -07001557#if DEBUG_CONNECTIONS
1558 --mTotalAcksNeeded;
1559#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001560 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001561 memmove(mEventCache, &mEventCache[numEventsSent],
1562 (mCacheSize - numEventsSent) * sizeof(sensors_event_t));
1563 ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ",
Aravind Akella6c2664a2014-08-13 12:24:50 -07001564 numEventsSent, mCacheSize);
Aravind Akella56ae4262014-07-10 16:01:10 -07001565 mCacheSize -= numEventsSent;
Aravind Akella56ae4262014-07-10 16:01:10 -07001566 return;
1567 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001568 numEventsSent += numEventsToWrite;
Aravind Akella56ae4262014-07-10 16:01:10 -07001569#if DEBUG_CONNECTIONS
Aravind Akella6c2664a2014-08-13 12:24:50 -07001570 mEventsSentFromCache += numEventsToWrite;
Aravind Akella56ae4262014-07-10 16:01:10 -07001571#endif
Aravind Akellab4099e72013-10-15 15:43:10 -07001572 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001573 ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize);
1574 // All events from the cache have been sent. Reset cache size to zero.
1575 mCacheSize = 0;
Aravind Akella8a969552014-09-28 17:52:41 -07001576 // There are no more events in the cache. We don't need to poll for write on the fd.
1577 // Update Looper registration.
1578 updateLooperRegistrationLocked(mService->getLooper());
Mathias Agopianfc328812010-07-14 23:41:37 -07001579}
1580
Aravind Akellac551eac2013-10-14 17:04:42 -07001581void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
Aravind Akella0ec20662014-09-14 17:29:48 -07001582 sensors_event_t const* scratch, const int numEventsDropped) {
Aravind Akella4c8b9512013-09-05 17:03:38 -07001583 ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001584 // Count flushComplete events in the events that are about to the dropped. These will be sent
1585 // separately before the next batch of events.
1586 for (int j = 0; j < numEventsDropped; ++j) {
1587 if (scratch[j].type == SENSOR_TYPE_META_DATA) {
1588 FlushInfo& flushInfo = mSensorInfo.editValueFor(scratch[j].meta_data.sensor);
1589 flushInfo.mPendingFlushEventsToSend++;
1590 ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
1591 flushInfo.mPendingFlushEventsToSend);
1592 }
1593 }
1594 return;
1595}
1596
Aravind Akella6c2664a2014-08-13 12:24:50 -07001597int SensorService::SensorEventConnection::findWakeUpSensorEventLocked(
1598 sensors_event_t const* scratch, const int count) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001599 for (int i = 0; i < count; ++i) {
1600 if (mService->isWakeUpSensorEvent(scratch[i])) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001601 return i;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001602 }
1603 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001604 return -1;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001605}
1606
Mathias Agopianb3989272011-10-20 18:42:02 -07001607sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
Mathias Agopianfc328812010-07-14 23:41:37 -07001608{
1609 return mChannel;
1610}
1611
1612status_t SensorService::SensorEventConnection::enableDisable(
Aravind Akella724d91d2013-06-27 12:04:23 -07001613 int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
1614 int reservedFlags)
Mathias Agopianfc328812010-07-14 23:41:37 -07001615{
1616 status_t err;
1617 if (enabled) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001618 err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
1619 reservedFlags);
Aravind Akella56ae4262014-07-10 16:01:10 -07001620
Mathias Agopianfc328812010-07-14 23:41:37 -07001621 } else {
1622 err = mService->disable(this, handle);
1623 }
1624 return err;
1625}
1626
1627status_t SensorService::SensorEventConnection::setEventRate(
Aravind Akella724d91d2013-06-27 12:04:23 -07001628 int handle, nsecs_t samplingPeriodNs)
Mathias Agopianfc328812010-07-14 23:41:37 -07001629{
Aravind Akella724d91d2013-06-27 12:04:23 -07001630 return mService->setEventRate(this, handle, samplingPeriodNs);
Mathias Agopianfc328812010-07-14 23:41:37 -07001631}
1632
Aravind Akella701166d2013-10-08 14:59:26 -07001633status_t SensorService::SensorEventConnection::flush() {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001634 return mService->flushSensor(this);
Aravind Akella724d91d2013-06-27 12:04:23 -07001635}
Aravind Akella4c8b9512013-09-05 17:03:38 -07001636
Aravind Akella8a969552014-09-28 17:52:41 -07001637int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* /*data*/) {
Aravind Akella56ae4262014-07-10 16:01:10 -07001638 if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) {
Aravind Akella8a969552014-09-28 17:52:41 -07001639 {
1640 // If the Looper encounters some error, set the flag mDead, reset mWakeLockRefCount,
1641 // and remove the fd from Looper. Call checkWakeLockState to know if SensorService
1642 // can release the wake-lock.
1643 ALOGD_IF(DEBUG_CONNECTIONS, "%p Looper error %d", this, fd);
1644 Mutex::Autolock _l(mConnectionLock);
1645 mDead = true;
1646 mWakeLockRefCount = 0;
1647 updateLooperRegistrationLocked(mService->getLooper());
1648 }
1649 mService->checkWakeLockState();
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001650 if (mDataInjectionMode) {
1651 // If the Looper has encountered some error in data injection mode, reset SensorService
1652 // back to normal mode.
1653 mService->resetToNormalMode();
1654 mDataInjectionMode = false;
1655 }
Aravind Akella8a969552014-09-28 17:52:41 -07001656 return 1;
Aravind Akella56ae4262014-07-10 16:01:10 -07001657 }
1658
1659 if (events & ALOOPER_EVENT_INPUT) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001660 unsigned char buf[sizeof(sensors_event_t)];
1661 ssize_t numBytesRead = ::recv(fd, buf, sizeof(buf), MSG_DONTWAIT);
Aravind Akella56ae4262014-07-10 16:01:10 -07001662 {
1663 Mutex::Autolock _l(mConnectionLock);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001664 if (numBytesRead == sizeof(sensors_event_t)) {
1665 if (!mDataInjectionMode) {
1666 ALOGE("Data injected in normal mode, dropping event"
1667 "package=%s uid=%d", mPackageName.string(), mUid);
1668 // Unregister call backs.
1669 return 0;
1670 }
1671 SensorDevice& dev(SensorDevice::getInstance());
1672 sensors_event_t sensor_event;
1673 memset(&sensor_event, 0, sizeof(sensor_event));
1674 memcpy(&sensor_event, buf, sizeof(sensors_event_t));
1675 Sensor sensor = mService->getSensorFromHandle(sensor_event.sensor);
1676 sensor_event.type = sensor.getType();
1677 dev.injectSensorData(&sensor_event, 1);
Aravind Akellae74baf62014-08-21 12:28:35 -07001678#if DEBUG_CONNECTIONS
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001679 ++mEventsReceived;
Aravind Akellae74baf62014-08-21 12:28:35 -07001680#endif
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001681 } else if (numBytesRead == sizeof(uint32_t)) {
1682 uint32_t numAcks = 0;
Aravind Akella08f04bf2015-05-08 15:59:23 -07001683 memcpy(&numAcks, buf, numBytesRead);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001684 // Sanity check to ensure there are no read errors in recv, numAcks is always
1685 // within the range and not zero. If any of the above don't hold reset
1686 // mWakeLockRefCount to zero.
1687 if (numAcks > 0 && numAcks < mWakeLockRefCount) {
1688 mWakeLockRefCount -= numAcks;
1689 } else {
1690 mWakeLockRefCount = 0;
1691 }
1692#if DEBUG_CONNECTIONS
1693 mTotalAcksReceived += numAcks;
1694#endif
1695 } else {
1696 // Read error, reset wakelock refcount.
1697 mWakeLockRefCount = 0;
1698 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001699 }
1700 // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released
1701 // here as checkWakeLockState() will need it.
1702 if (mWakeLockRefCount == 0) {
1703 mService->checkWakeLockState();
1704 }
1705 // continue getting callbacks.
1706 return 1;
1707 }
1708
1709 if (events & ALOOPER_EVENT_OUTPUT) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001710 // send sensor data that is stored in mEventCache for this connection.
1711 mService->sendEventsFromCache(this);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001712 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001713 return 1;
1714}
1715
1716int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
1717 int fifoWakeUpSensors = 0;
1718 int fifoNonWakeUpSensors = 0;
1719 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1720 const Sensor& sensor = mService->getSensorFromHandle(mSensorInfo.keyAt(i));
1721 if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) {
1722 // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and
1723 // non wake_up sensors.
1724 if (sensor.isWakeUpSensor()) {
1725 fifoWakeUpSensors += sensor.getFifoReservedEventCount();
1726 } else {
1727 fifoNonWakeUpSensors += sensor.getFifoReservedEventCount();
1728 }
1729 } else {
1730 // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors.
1731 if (sensor.isWakeUpSensor()) {
1732 fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ?
1733 fifoWakeUpSensors : sensor.getFifoMaxEventCount();
1734
1735 } else {
1736 fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ?
1737 fifoNonWakeUpSensors : sensor.getFifoMaxEventCount();
1738
1739 }
1740 }
1741 }
1742 if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) {
1743 // It is extremely unlikely that there is a write failure in non batch mode. Return a cache
Aravind Akella6c2664a2014-08-13 12:24:50 -07001744 // size that is equal to that of the batch mode.
Aravind Akellae74baf62014-08-21 12:28:35 -07001745 // ALOGW("Write failure in non-batch mode");
Aravind Akella6c2664a2014-08-13 12:24:50 -07001746 return MAX_SOCKET_BUFFER_SIZE_BATCHED/sizeof(sensors_event_t);
Aravind Akella56ae4262014-07-10 16:01:10 -07001747 }
1748 return fifoWakeUpSensors + fifoNonWakeUpSensors;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001749}
1750
Mathias Agopianfc328812010-07-14 23:41:37 -07001751// ---------------------------------------------------------------------------
1752}; // namespace android
1753