blob: c7bcaeff273f122ab0489b4fcdbc44fa4bf16a57 [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.
69static const String16 sDataInjectionPermission("android.permission.HARDWARE_TEST");
70static 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
217 mLastEventSeen.add(sensor.getHandle(), event);
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 Akella4949c502015-02-11 15:54:35 -0800243 } else if (args.size() > 0) {
244 if (args.size() > 1) {
245 return INVALID_OPERATION;
246 }
247 Mutex::Autolock _l(mLock);
248 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700249 if (args[0] == String16("restrict") && mCurrentOperatingMode == NORMAL) {
250 mCurrentOperatingMode = RESTRICTED;
Aravind Akella4949c502015-02-11 15:54:35 -0800251 dev.disableAllSensors();
252 // Clear all pending flush connections for all active sensors. If one of the active
253 // connections has called flush() and the underlying sensor has been disabled before a
254 // flush complete event is returned, we need to remove the connection from this queue.
255 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
256 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
257 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700258 } else if (args[0] == String16("enable") && mCurrentOperatingMode == RESTRICTED) {
259 mCurrentOperatingMode = NORMAL;
Aravind Akella4949c502015-02-11 15:54:35 -0800260 dev.enableAllSensors();
261 }
262 return status_t(NO_ERROR);
Mathias Agopianfc328812010-07-14 23:41:37 -0700263 } else {
264 Mutex::Autolock _l(mLock);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700265 result.append("Sensor List:\n");
Mathias Agopian3560fb22010-07-22 21:24:39 -0700266 for (size_t i=0 ; i<mSensorList.size() ; i++) {
267 const Sensor& s(mSensorList[i]);
268 const sensors_event_t& e(mLastEventSeen.valueFor(s.getHandle()));
Mathias Agopianba02cd22013-07-03 16:20:57 -0700269 result.appendFormat(
Aravind Akella0b6acb22014-10-18 16:37:13 -0700270 "%-15s| %-10s| version=%d |%-20s| 0x%08x | \"%s\" | type=%d |",
Mathias Agopian3560fb22010-07-22 21:24:39 -0700271 s.getName().string(),
272 s.getVendor().string(),
Aravind Akella0b6acb22014-10-18 16:37:13 -0700273 s.getVersion(),
Aravind Akella70018042014-04-07 22:52:37 +0000274 s.getStringType().string(),
275 s.getHandle(),
Aravind Akella6c2664a2014-08-13 12:24:50 -0700276 s.getRequiredPermission().string(),
277 s.getType());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700278
Aravind Akella0e025c52014-06-03 19:19:57 -0700279 const int reportingMode = s.getReportingMode();
280 if (reportingMode == AREPORTING_MODE_CONTINUOUS) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700281 result.append(" continuous | ");
Aravind Akella0e025c52014-06-03 19:19:57 -0700282 } else if (reportingMode == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700283 result.append(" on-change | ");
Aravind Akella0e025c52014-06-03 19:19:57 -0700284 } else if (reportingMode == AREPORTING_MODE_ONE_SHOT) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700285 result.append(" one-shot | ");
Mathias Agopianba02cd22013-07-03 16:20:57 -0700286 } else {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700287 result.append(" special-trigger | ");
288 }
289
290 if (s.getMaxDelay() > 0) {
291 result.appendFormat("minRate=%.2fHz | ", 1e6f / s.getMaxDelay());
292 } else {
293 result.appendFormat("maxDelay=%dus |", s.getMaxDelay());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700294 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700295
296 if (s.getMinDelay() > 0) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700297 result.appendFormat("maxRate=%.2fHz | ", 1e6f / s.getMinDelay());
Aravind Akella0e025c52014-06-03 19:19:57 -0700298 } else {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700299 result.appendFormat("minDelay=%dus |", s.getMinDelay());
Aravind Akella0e025c52014-06-03 19:19:57 -0700300 }
301
Aravind Akella724d91d2013-06-27 12:04:23 -0700302 if (s.getFifoMaxEventCount() > 0) {
Aravind Akella70018042014-04-07 22:52:37 +0000303 result.appendFormat("FifoMax=%d events | ",
304 s.getFifoMaxEventCount());
Aravind Akella724d91d2013-06-27 12:04:23 -0700305 } else {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700306 result.append("no batching | ");
307 }
308
309 if (s.isWakeUpSensor()) {
310 result.appendFormat("wakeUp | ");
311 } else {
312 result.appendFormat("non-wakeUp | ");
Aravind Akella724d91d2013-06-27 12:04:23 -0700313 }
Mathias Agopianba02cd22013-07-03 16:20:57 -0700314
315 switch (s.getType()) {
316 case SENSOR_TYPE_ROTATION_VECTOR:
317 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
318 result.appendFormat(
Aravind Akella6c2664a2014-08-13 12:24:50 -0700319 "last=<%5.1f,%5.1f,%5.1f,%5.1f,%5.1f, %" PRId64 ">\n",
320 e.data[0], e.data[1], e.data[2], e.data[3], e.data[4], e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700321 break;
322 case SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED:
323 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
324 result.appendFormat(
Aravind Akella6c2664a2014-08-13 12:24:50 -0700325 "last=<%5.1f,%5.1f,%5.1f,%5.1f,%5.1f,%5.1f, %" PRId64 ">\n",
326 e.data[0], e.data[1], e.data[2], e.data[3], e.data[4], e.data[5],
327 e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700328 break;
329 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
330 result.appendFormat(
Aravind Akella6c2664a2014-08-13 12:24:50 -0700331 "last=<%5.1f,%5.1f,%5.1f,%5.1f, %" PRId64 ">\n",
332 e.data[0], e.data[1], e.data[2], e.data[3], e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700333 break;
334 case SENSOR_TYPE_SIGNIFICANT_MOTION:
335 case SENSOR_TYPE_STEP_DETECTOR:
Aravind Akella6c2664a2014-08-13 12:24:50 -0700336 result.appendFormat( "last=<%f %" PRId64 ">\n", e.data[0], e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700337 break;
338 case SENSOR_TYPE_STEP_COUNTER:
Aravind Akella6c2664a2014-08-13 12:24:50 -0700339 result.appendFormat( "last=<%" PRIu64 ", %" PRId64 ">\n", e.u64.step_counter,
340 e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700341 break;
342 default:
343 // default to 3 values
344 result.appendFormat(
Aravind Akella6c2664a2014-08-13 12:24:50 -0700345 "last=<%5.1f,%5.1f,%5.1f, %" PRId64 ">\n",
346 e.data[0], e.data[1], e.data[2], e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700347 break;
348 }
Aravind Akella6c2664a2014-08-13 12:24:50 -0700349 result.append("\n");
Mathias Agopianba02cd22013-07-03 16:20:57 -0700350 }
351 SensorFusion::getInstance().dump(result);
352 SensorDevice::getInstance().dump(result);
353
Mathias Agopianba02cd22013-07-03 16:20:57 -0700354 result.append("Active sensors:\n");
Mathias Agopianfc328812010-07-14 23:41:37 -0700355 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
Mathias Agopian5d270722010-07-19 15:20:39 -0700356 int handle = mActiveSensors.keyAt(i);
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700357 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
Mathias Agopian5d270722010-07-19 15:20:39 -0700358 getSensorName(handle).string(),
359 handle,
Mathias Agopianfc328812010-07-14 23:41:37 -0700360 mActiveSensors.valueAt(i)->getNumConnections());
Mathias Agopianfc328812010-07-14 23:41:37 -0700361 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700362
Aravind Akella5466c3d2014-08-22 16:11:10 -0700363 result.appendFormat("Socket Buffer size = %d events\n",
Aravind Akella6c2664a2014-08-13 12:24:50 -0700364 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella9a844cf2014-02-11 18:58:52 -0800365 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" : "not held");
Aravind Akella4949c502015-02-11 15:54:35 -0800366 result.appendFormat("Mode :");
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700367 switch(mCurrentOperatingMode) {
Aravind Akella4949c502015-02-11 15:54:35 -0800368 case NORMAL:
369 result.appendFormat(" NORMAL\n");
370 break;
371 case RESTRICTED:
372 result.appendFormat(" RESTRICTED\n");
373 break;
374 case DATA_INJECTION:
375 result.appendFormat(" DATA_INJECTION\n");
376 }
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700377 result.appendFormat("%zd active connections\n", mActiveConnections.size());
Aravind Akella4c8b9512013-09-05 17:03:38 -0700378
379 for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
380 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
381 if (connection != 0) {
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700382 result.appendFormat("Connection Number: %zu \n", i);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700383 connection->dump(result);
384 }
385 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700386 }
387 write(fd, result.string(), result.size());
388 return NO_ERROR;
389}
390
Aravind Akella9a844cf2014-02-11 18:58:52 -0800391void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700392 sensors_event_t const* buffer, const int count) {
393 for (int i=0 ; i<count ; i++) {
394 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700395 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
396 handle = buffer[i].meta_data.sensor;
397 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700398 if (connection->hasSensor(handle)) {
399 SensorInterface* sensor = mSensorMap.valueFor(handle);
400 // If this buffer has an event from a one_shot sensor and this connection is registered
401 // for this particular one_shot sensor, try cleaning up the connection.
402 if (sensor != NULL &&
403 sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
404 sensor->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800405 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700406 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700407
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700408 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700409 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700410}
411
Mathias Agopianfc328812010-07-14 23:41:37 -0700412bool SensorService::threadLoop()
413{
Steve Blocka5512372011-12-20 16:23:08 +0000414 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700415
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700416 // each virtual sensor could generate an event per "real" event, that's why we need
417 // to size numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT.
418 // in practice, this is too aggressive, but guaranteed to be enough.
419 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
420 const size_t numEventMax = minBufferSize / (1 + mVirtualSensorList.size());
421
Mathias Agopianf001c922010-11-11 17:58:51 -0800422 SensorDevice& device(SensorDevice::getInstance());
423 const size_t vcount = mVirtualSensorList.size();
Mathias Agopianfc328812010-07-14 23:41:37 -0700424
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700425 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700426 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700427 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
428 if (count < 0) {
Steve Blockf5a12302012-01-06 19:20:56 +0000429 ALOGE("sensor poll failed (%s)", strerror(-count));
Mathias Agopianfc328812010-07-14 23:41:37 -0700430 break;
431 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700432
433 // Reset sensors_event_t.flags to zero for all events in the buffer.
434 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700435 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700436 }
Aravind Akellae148bc22014-09-24 22:12:58 -0700437
438 // Make a copy of the connection vector as some connections may be removed during the
439 // course of this loop (especially when one-shot sensor events are present in the
440 // sensor_event buffer). Promote all connections to StrongPointers before the lock is
441 // acquired. If the destructor of the sp gets called when the lock is acquired, it may
442 // result in a deadlock as ~SensorEventConnection() needs to acquire mLock again for
443 // cleanup. So copy all the strongPointers to a vector before the lock is acquired.
444 SortedVector< sp<SensorEventConnection> > activeConnections;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700445 populateActiveConnections(&activeConnections);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800446 Mutex::Autolock _l(mLock);
447 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
448 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
449 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
450 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
451 // releasing the wakelock.
452 bool bufferHasWakeUpEvent = false;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700453 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700454 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800455 bufferHasWakeUpEvent = true;
456 break;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700457 }
458 }
459
Aravind Akella9a844cf2014-02-11 18:58:52 -0800460 if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700461 setWakeLockAcquiredLocked(true);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800462 }
Aravind Akella8493b792014-09-08 15:45:47 -0700463 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800464
Mathias Agopianf001c922010-11-11 17:58:51 -0800465 // handle virtual sensors
466 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700467 sensors_event_t const * const event = mSensorEventBuffer;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800468 const size_t activeVirtualSensorCount = mActiveVirtualSensors.size();
Mathias Agopianf001c922010-11-11 17:58:51 -0800469 if (activeVirtualSensorCount) {
470 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700471 SensorFusion& fusion(SensorFusion::getInstance());
472 if (fusion.isEnabled()) {
473 for (size_t i=0 ; i<size_t(count) ; i++) {
474 fusion.process(event[i]);
475 }
476 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700477 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800478 for (size_t j=0 ; j<activeVirtualSensorCount ; j++) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700479 if (count + k >= minBufferSize) {
480 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700481 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700482 count, k, minBufferSize);
483 break;
484 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800485 sensors_event_t out;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800486 SensorInterface* si = mActiveVirtualSensors.valueAt(j);
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700487 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700488 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800489 k++;
490 }
491 }
492 }
493 if (k) {
494 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700495 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800496 count += k;
497 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700498 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700499 }
500 }
501 }
502
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700503 // handle backward compatibility for RotationVector sensor
504 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
505 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700506 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700507 // All the 4 components of the quaternion should be available
508 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700509 mSensorEventBuffer[i].data[4] = -1;
510 }
511 }
512 }
513
514 // Map flush_complete_events in the buffer to SensorEventConnections which called
515 // flush on the hardware sensor. mapFlushEventsToConnections[i] will be the
516 // SensorEventConnection mapped to the corresponding flush_complete_event in
517 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
518 for (int i = 0; i < count; ++i) {
519 mMapFlushEventsToConnections[i] = NULL;
520 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
521 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
522 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
523 if (rec != NULL) {
524 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
525 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700526 }
527 }
528 }
529
Aravind Akella9a844cf2014-02-11 18:58:52 -0800530 // Send our events to clients. Check the state of wake lock for each client and release the
531 // lock if none of the clients need it.
532 bool needsWakeLock = false;
Aravind Akella8493b792014-09-08 15:45:47 -0700533 size_t numConnections = activeConnections.size();
534 for (size_t i=0 ; i < numConnections; ++i) {
Aravind Akellae148bc22014-09-24 22:12:58 -0700535 if (activeConnections[i] != 0) {
536 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
Aravind Akella8493b792014-09-08 15:45:47 -0700537 mMapFlushEventsToConnections);
Aravind Akellae148bc22014-09-24 22:12:58 -0700538 needsWakeLock |= activeConnections[i]->needsWakeLock();
Aravind Akella8493b792014-09-08 15:45:47 -0700539 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
540 // Early check for one-shot sensors.
Aravind Akellae148bc22014-09-24 22:12:58 -0700541 if (activeConnections[i]->hasOneShotSensors()) {
542 cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
543 count);
Aravind Akella8493b792014-09-08 15:45:47 -0700544 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800545 }
546 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700547
Aravind Akella9a844cf2014-02-11 18:58:52 -0800548 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700549 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800550 }
Aravind Akella8493b792014-09-08 15:45:47 -0700551 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -0700552
Steve Block3c20fbe2012-01-05 23:22:43 +0000553 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -0800554 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -0700555 return false;
556}
557
Aravind Akella56ae4262014-07-10 16:01:10 -0700558sp<Looper> SensorService::getLooper() const {
559 return mLooper;
560}
561
Aravind Akellab4373ac2014-10-29 17:55:20 -0700562void SensorService::resetAllWakeLockRefCounts() {
563 SortedVector< sp<SensorEventConnection> > activeConnections;
564 populateActiveConnections(&activeConnections);
565 {
566 Mutex::Autolock _l(mLock);
567 for (size_t i=0 ; i < activeConnections.size(); ++i) {
568 if (activeConnections[i] != 0) {
569 activeConnections[i]->resetWakeLockRefCount();
570 }
571 }
572 setWakeLockAcquiredLocked(false);
573 }
574}
575
576void SensorService::setWakeLockAcquiredLocked(bool acquire) {
577 if (acquire) {
578 if (!mWakeLockAcquired) {
579 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
580 mWakeLockAcquired = true;
581 }
582 mLooper->wake();
583 } else {
584 if (mWakeLockAcquired) {
585 release_wake_lock(WAKE_LOCK_NAME);
586 mWakeLockAcquired = false;
587 }
588 }
589}
590
Aravind Akellab4373ac2014-10-29 17:55:20 -0700591bool SensorService::isWakeLockAcquired() {
592 Mutex::Autolock _l(mLock);
593 return mWakeLockAcquired;
594}
595
Aravind Akella56ae4262014-07-10 16:01:10 -0700596bool SensorService::SensorEventAckReceiver::threadLoop() {
597 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -0700598 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -0700599 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700600 bool wakeLockAcquired = mService->isWakeLockAcquired();
601 int timeout = -1;
602 if (wakeLockAcquired) timeout = 5000;
603 int ret = looper->pollOnce(timeout);
604 if (ret == ALOOPER_POLL_TIMEOUT) {
605 mService->resetAllWakeLockRefCounts();
606 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700607 } while(!Thread::exitPending());
608 return false;
609}
610
Aravind Akella9a844cf2014-02-11 18:58:52 -0800611void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -0800612 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -0800613 const sensors_event_t* last = NULL;
614 for (size_t i = 0; i < count; i++) {
615 const sensors_event_t* event = &buffer[i];
616 if (event->type != SENSOR_TYPE_META_DATA) {
617 if (last && event->sensor != last->sensor) {
618 mLastEventSeen.editValueFor(last->sensor) = *last;
619 }
620 last = event;
Mathias Agopian94e8f682010-11-10 17:50:28 -0800621 }
622 }
Aravind Akella4b847042014-03-03 19:02:46 -0800623 if (last) {
624 mLastEventSeen.editValueFor(last->sensor) = *last;
625 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800626}
627
Mathias Agopianf001c922010-11-11 17:58:51 -0800628void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count)
629{
630 struct compar {
631 static int cmp(void const* lhs, void const* rhs) {
632 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
633 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -0700634 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -0800635 }
636 };
637 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
638}
639
Mathias Agopian5d270722010-07-19 15:20:39 -0700640String8 SensorService::getSensorName(int handle) const {
Mathias Agopian010e4222011-06-08 20:06:50 -0700641 size_t count = mUserSensorList.size();
Mathias Agopian5d270722010-07-19 15:20:39 -0700642 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian010e4222011-06-08 20:06:50 -0700643 const Sensor& sensor(mUserSensorList[i]);
Mathias Agopian5d270722010-07-19 15:20:39 -0700644 if (sensor.getHandle() == handle) {
645 return sensor.getName();
646 }
647 }
648 String8 result("unknown");
649 return result;
650}
651
Aravind Akellab4099e72013-10-15 15:43:10 -0700652bool SensorService::isVirtualSensor(int handle) const {
653 SensorInterface* sensor = mSensorMap.valueFor(handle);
654 return sensor->isVirtual();
655}
656
Aravind Akella9a844cf2014-02-11 18:58:52 -0800657bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -0700658 int handle = event.sensor;
659 if (event.type == SENSOR_TYPE_META_DATA) {
660 handle = event.meta_data.sensor;
661 }
662 SensorInterface* sensor = mSensorMap.valueFor(handle);
663 return sensor != NULL && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -0800664}
665
Aravind Akella6c2664a2014-08-13 12:24:50 -0700666SensorService::SensorRecord * SensorService::getSensorRecord(int handle) {
667 return mActiveSensors.valueFor(handle);
668}
669
Svetoslavb412f6e2015-04-29 16:50:41 -0700670Vector<Sensor> SensorService::getSensorList(const String16& opPackageName)
Mathias Agopianfc328812010-07-14 23:41:37 -0700671{
Mathias Agopian33264862012-06-28 19:46:54 -0700672 char value[PROPERTY_VALUE_MAX];
673 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +0000674 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
675 mUserSensorListDebug : mUserSensorList;
676 Vector<Sensor> accessibleSensorList;
677 for (size_t i = 0; i < initialSensorList.size(); i++) {
678 Sensor sensor = initialSensorList[i];
Svetoslavb412f6e2015-04-29 16:50:41 -0700679 if (canAccessSensor(sensor, "getSensorList", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +0000680 accessibleSensorList.add(sensor);
681 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -0700682 ALOGI("Skipped sensor %s because it requires permission %s and app op %d",
Bernhard Rosenkränzer5f619932014-11-17 21:06:20 +0100683 sensor.getName().string(),
Svetoslavb412f6e2015-04-29 16:50:41 -0700684 sensor.getRequiredPermission().string(),
685 sensor.getRequiredAppOp());
Aravind Akella70018042014-04-07 22:52:37 +0000686 }
Mathias Agopian33264862012-06-28 19:46:54 -0700687 }
Aravind Akella70018042014-04-07 22:52:37 +0000688 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -0700689}
690
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700691sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -0700692 int requestedMode, const String16& opPackageName) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700693 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
694 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
695 return NULL;
696 }
697 // DATA_INJECTION mode needs to have the required permissions set.
698 if (requestedMode == DATA_INJECTION && !hasDataInjectionPermissions()) {
699 return NULL;
700 }
701
702 Mutex::Autolock _l(mLock);
Mathias Agopian5307d172012-09-18 17:02:43 -0700703 uid_t uid = IPCThreadState::self()->getCallingUid();
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700704 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -0700705 requestedMode == DATA_INJECTION, opPackageName));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700706 if (requestedMode == DATA_INJECTION) {
707 if (mActiveConnections.indexOf(result) < 0) {
708 mActiveConnections.add(result);
709 }
710 // Add the associated file descriptor to the Looper for polling whenever there is data to
711 // be injected.
712 result->updateLooperRegistration(mLooper);
713 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700714 return result;
715}
716
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700717status_t SensorService::enableDataInjection(int requestedMode) {
718 if (!hasDataInjectionPermissions()) {
719 return INVALID_OPERATION;
720 }
721 Mutex::Autolock _l(mLock);
722 ALOGD_IF(DEBUG_CONNECTIONS, "SensorService::enableDataInjection %d", requestedMode);
723 SensorDevice& dev(SensorDevice::getInstance());
724 status_t err(NO_ERROR);
725 if (requestedMode == DATA_INJECTION) {
726 if (mCurrentOperatingMode == NORMAL) {
727 dev.disableAllSensors();
728 err = dev.setMode(requestedMode);
729 if (err == NO_ERROR) {
730 mCurrentOperatingMode = DATA_INJECTION;
731 } else {
732 // Re-enable sensors.
733 dev.enableAllSensors();
734 }
735 } else if (mCurrentOperatingMode == DATA_INJECTION) {
736 // Already in DATA_INJECTION mode. Treat this as a no_op.
737 return NO_ERROR;
738 } else {
739 // Transition to data injection mode supported only from NORMAL mode.
740 return INVALID_OPERATION;
741 }
742 } else if (requestedMode == NORMAL && mCurrentOperatingMode != NORMAL) {
743 err = resetToNormalModeLocked();
744 }
745 return err;
746}
747
748status_t SensorService::resetToNormalMode() {
749 Mutex::Autolock _l(mLock);
750 return resetToNormalModeLocked();
751}
752
753status_t SensorService::resetToNormalModeLocked() {
754 SensorDevice& dev(SensorDevice::getInstance());
755 dev.enableAllSensors();
756 status_t err = dev.setMode(NORMAL);
757 mCurrentOperatingMode = NORMAL;
758 return err;
759}
760
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800761void SensorService::cleanupConnection(SensorEventConnection* c)
Mathias Agopianfc328812010-07-14 23:41:37 -0700762{
763 Mutex::Autolock _l(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800764 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700765 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -0700766 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700767 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800768 int handle = mActiveSensors.keyAt(i);
769 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -0700770 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800771 SensorInterface* sensor = mSensorMap.valueFor( handle );
Steve Blockf5a12302012-01-06 19:20:56 +0000772 ALOGE_IF(!sensor, "mSensorMap[handle=0x%08x] is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800773 if (sensor) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800774 sensor->activate(c, false);
Mathias Agopianf001c922010-11-11 17:58:51 -0800775 }
Aravind Akella8a969552014-09-28 17:52:41 -0700776 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800777 }
778 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -0700779 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +0000780 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -0700781 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700782 c, i, handle);
783
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800784 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +0000785 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700786 mActiveSensors.removeItemsAt(i, 1);
Mathias Agopianf001c922010-11-11 17:58:51 -0800787 mActiveVirtualSensors.removeItem(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700788 delete rec;
789 size--;
790 } else {
791 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -0700792 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700793 }
Aravind Akella8a969552014-09-28 17:52:41 -0700794 c->updateLooperRegistration(mLooper);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700795 mActiveConnections.remove(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -0700796 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -0800797 if (c->needsWakeLock()) {
798 checkWakeLockStateLocked();
799 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700800}
801
Aravind Akella70018042014-04-07 22:52:37 +0000802Sensor SensorService::getSensorFromHandle(int handle) const {
803 return mSensorMap.valueFor(handle)->getSensor();
804}
805
Mathias Agopianfc328812010-07-14 23:41:37 -0700806status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -0700807 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
808 const String16& opPackageName)
Mathias Agopianfc328812010-07-14 23:41:37 -0700809{
Mathias Agopian50df2952010-07-19 19:09:10 -0700810 if (mInitCheck != NO_ERROR)
811 return mInitCheck;
812
Mathias Agopianf001c922010-11-11 17:58:51 -0800813 SensorInterface* sensor = mSensorMap.valueFor(handle);
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700814 if (sensor == NULL) {
815 return BAD_VALUE;
816 }
Aravind Akella70018042014-04-07 22:52:37 +0000817
Svetoslavb412f6e2015-04-29 16:50:41 -0700818 if (!canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +0000819 return BAD_VALUE;
820 }
821
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700822 Mutex::Autolock _l(mLock);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700823 if (mCurrentOperatingMode == RESTRICTED && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -0800824 return INVALID_OPERATION;
825 }
826
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700827 SensorRecord* rec = mActiveSensors.valueFor(handle);
828 if (rec == 0) {
829 rec = new SensorRecord(connection);
830 mActiveSensors.add(handle, rec);
831 if (sensor->isVirtual()) {
832 mActiveVirtualSensors.add(handle, sensor);
833 }
834 } else {
835 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800836 // this sensor is already activated, but we are adding a connection that uses it.
837 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700838 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -0700839 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800840 // NOTE: The wake_up flag of this event may get set to
841 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700842 sensors_event_t& event(mLastEventSeen.editValueFor(handle));
843 if (event.version == sizeof(sensors_event_t)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800844 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700845 setWakeLockAcquiredLocked(true);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800846 }
847 connection->sendEvents(&event, 1, NULL);
848 if (!connection->needsWakeLock() && mWakeLockAcquired) {
849 checkWakeLockStateLocked();
850 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700851 }
852 }
853 }
854 }
855
856 if (connection->addSensor(handle)) {
857 BatteryService::enableSensor(connection->getUid(), handle);
858 // the sensor was added (which means it wasn't already there)
859 // so, see if this connection becomes active
860 if (mActiveConnections.indexOf(connection) < 0) {
861 mActiveConnections.add(connection);
862 }
863 } else {
864 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
865 handle, connection.get());
866 }
867
Aravind Akella724d91d2013-06-27 12:04:23 -0700868 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
869 if (samplingPeriodNs < minDelayNs) {
870 samplingPeriodNs = minDelayNs;
871 }
872
Aravind Akella6c2664a2014-08-13 12:24:50 -0700873 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
874 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -0700875 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
876
Aravind Akella4949c502015-02-11 15:54:35 -0800877 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -0700878 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -0700879
Aravind Akella5466c3d2014-08-22 16:11:10 -0700880 // Call flush() before calling activate() on the sensor. Wait for a first flush complete
881 // event before sending events on this connection. Ignore one-shot sensors which don't
882 // support flush(). Also if this sensor isn't already active, don't call flush().
883 if (err == NO_ERROR && sensor->getSensor().getReportingMode() != AREPORTING_MODE_ONE_SHOT &&
884 rec->getNumConnections() > 1) {
885 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700886 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -0700887 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -0700888 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700889 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -0700890 } else {
891 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700892 }
893 }
Aravind Akella724d91d2013-06-27 12:04:23 -0700894
895 if (err == NO_ERROR) {
896 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
897 err = sensor->activate(connection.get(), true);
898 }
899
Aravind Akella8a969552014-09-28 17:52:41 -0700900 if (err == NO_ERROR) {
901 connection->updateLooperRegistration(mLooper);
Aravind Akella56ae4262014-07-10 16:01:10 -0700902 }
903
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700904 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -0700905 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700906 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700907 }
908 return err;
909}
910
911status_t SensorService::disable(const sp<SensorEventConnection>& connection,
912 int handle)
913{
Mathias Agopian50df2952010-07-19 19:09:10 -0700914 if (mInitCheck != NO_ERROR)
915 return mInitCheck;
916
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700917 Mutex::Autolock _l(mLock);
918 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700919 if (err == NO_ERROR) {
920 SensorInterface* sensor = mSensorMap.valueFor(handle);
921 err = sensor ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
922 }
923 return err;
924}
925
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700926status_t SensorService::cleanupWithoutDisable(
927 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700928 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700929 return cleanupWithoutDisableLocked(connection, handle);
930}
931
932status_t SensorService::cleanupWithoutDisableLocked(
933 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700934 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700935 if (rec) {
936 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -0700937 if (connection->removeSensor(handle)) {
938 BatteryService::disableSensor(connection->getUid(), handle);
939 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700940 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -0700941 connection->updateLooperRegistration(mLooper);
Mathias Agopianfc328812010-07-14 23:41:37 -0700942 mActiveConnections.remove(connection);
943 }
944 // see if this sensor becomes inactive
945 if (rec->removeConnection(connection)) {
946 mActiveSensors.removeItem(handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800947 mActiveVirtualSensors.removeItem(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700948 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -0700949 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700950 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700951 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700952 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -0700953}
954
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700955status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -0700956 int handle, nsecs_t ns, const String16& opPackageName)
Mathias Agopianfc328812010-07-14 23:41:37 -0700957{
Mathias Agopian50df2952010-07-19 19:09:10 -0700958 if (mInitCheck != NO_ERROR)
959 return mInitCheck;
960
Mathias Agopianae09d652011-11-01 17:37:49 -0700961 SensorInterface* sensor = mSensorMap.valueFor(handle);
962 if (!sensor)
963 return BAD_VALUE;
964
Svetoslavb412f6e2015-04-29 16:50:41 -0700965 if (!canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +0000966 return BAD_VALUE;
967 }
968
Mathias Agopian1cd70002010-07-21 15:59:50 -0700969 if (ns < 0)
970 return BAD_VALUE;
971
Mathias Agopian62569ec2011-11-07 21:21:47 -0800972 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
973 if (ns < minDelayNs) {
974 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -0700975 }
976
Mathias Agopianf001c922010-11-11 17:58:51 -0800977 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -0700978}
979
Svetoslavb412f6e2015-04-29 16:50:41 -0700980status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
981 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +0000982 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -0700983 SensorDevice& dev(SensorDevice::getInstance());
984 const int halVersion = dev.getHalDeviceVersion();
985 status_t err(NO_ERROR);
986 Mutex::Autolock _l(mLock);
987 // Loop through all sensors for this connection and call flush on each of them.
988 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
989 const int handle = connection->mSensorInfo.keyAt(i);
990 SensorInterface* sensor = mSensorMap.valueFor(handle);
991 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
992 ALOGE("flush called on a one-shot sensor");
993 err = INVALID_OPERATION;
994 continue;
995 }
Aravind Akella8493b792014-09-08 15:45:47 -0700996 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -0700997 // For older devices just increment pending flush count which will send a trivial
998 // flush complete event.
Aravind Akella8a969552014-09-28 17:52:41 -0700999 connection->incrementPendingFlushCount(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001000 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001001 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1002 err = INVALID_OPERATION;
1003 continue;
1004 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001005 status_t err_flush = sensor->flush(connection.get(), handle);
1006 if (err_flush == NO_ERROR) {
1007 SensorRecord* rec = mActiveSensors.valueFor(handle);
1008 if (rec != NULL) rec->addPendingFlushConnection(connection);
1009 }
1010 err = (err_flush != NO_ERROR) ? err_flush : err;
1011 }
Aravind Akella70018042014-04-07 22:52:37 +00001012 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001013 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001014}
Aravind Akella70018042014-04-07 22:52:37 +00001015
Svetoslavb412f6e2015-04-29 16:50:41 -07001016bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1017 const String16& opPackageName) {
1018 const String8& requiredPermission = sensor.getRequiredPermission();
Aravind Akella70018042014-04-07 22:52:37 +00001019
Svetoslavb412f6e2015-04-29 16:50:41 -07001020 if (requiredPermission.length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00001021 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07001022 }
1023
1024 bool hasPermission = false;
1025
1026 // Runtime permissions can't use the cache as they may change.
1027 if (sensor.isRequiredPermissionRuntime()) {
1028 hasPermission = checkPermission(String16(requiredPermission),
1029 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Aravind Akella70018042014-04-07 22:52:37 +00001030 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001031 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1032 }
1033
1034 if (!hasPermission) {
1035 ALOGE("%s a sensor (%s) without holding its required permission: %s",
1036 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
Aravind Akella70018042014-04-07 22:52:37 +00001037 return false;
1038 }
Svetoslavb412f6e2015-04-29 16:50:41 -07001039
1040 const int32_t opCode = sensor.getRequiredAppOp();
1041 if (opCode >= 0) {
1042 AppOpsManager appOps;
1043 if (appOps.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName)
1044 != AppOpsManager::MODE_ALLOWED) {
1045 ALOGE("%s a sensor (%s) without enabled required app op: %D",
1046 operation, sensor.getName().string(), opCode);
1047 return false;
1048 }
1049 }
1050
1051 return true;
Aravind Akella70018042014-04-07 22:52:37 +00001052}
1053
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001054bool SensorService::hasDataInjectionPermissions() {
1055 if (!PermissionCache::checkCallingPermission(sDataInjectionPermission)) {
1056 ALOGE("Permission Denial trying to activate data injection without"
1057 " the required permission");
1058 return false;
1059 }
1060 return true;
1061}
1062
Aravind Akella9a844cf2014-02-11 18:58:52 -08001063void SensorService::checkWakeLockState() {
1064 Mutex::Autolock _l(mLock);
1065 checkWakeLockStateLocked();
1066}
1067
1068void SensorService::checkWakeLockStateLocked() {
1069 if (!mWakeLockAcquired) {
1070 return;
1071 }
1072 bool releaseLock = true;
1073 for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
1074 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1075 if (connection != 0) {
1076 if (connection->needsWakeLock()) {
1077 releaseLock = false;
1078 break;
1079 }
1080 }
1081 }
1082 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001083 setWakeLockAcquiredLocked(false);
1084 }
1085}
1086
1087void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1088 Mutex::Autolock _l(mLock);
1089 connection->writeToSocketFromCache();
1090 if (connection->needsWakeLock()) {
1091 setWakeLockAcquiredLocked(true);
1092 }
1093}
1094
1095void SensorService::populateActiveConnections(
1096 SortedVector< sp<SensorEventConnection> >* activeConnections) {
1097 Mutex::Autolock _l(mLock);
1098 for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
1099 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1100 if (connection != 0) {
1101 activeConnections->add(connection);
1102 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001103 }
1104}
Aravind Akella6c2664a2014-08-13 12:24:50 -07001105
Aravind Akella4949c502015-02-11 15:54:35 -08001106bool SensorService::isWhiteListedPackage(const String8& packageName) {
1107 // TODO: Come up with a list of packages.
1108 return (packageName.find(".cts.") != -1);
1109}
1110
Mathias Agopianfc328812010-07-14 23:41:37 -07001111// ---------------------------------------------------------------------------
Mathias Agopianfc328812010-07-14 23:41:37 -07001112SensorService::SensorRecord::SensorRecord(
1113 const sp<SensorEventConnection>& connection)
1114{
1115 mConnections.add(connection);
1116}
1117
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001118bool SensorService::SensorRecord::addConnection(
Mathias Agopianfc328812010-07-14 23:41:37 -07001119 const sp<SensorEventConnection>& connection)
1120{
1121 if (mConnections.indexOf(connection) < 0) {
1122 mConnections.add(connection);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001123 return true;
Mathias Agopianfc328812010-07-14 23:41:37 -07001124 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001125 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -07001126}
1127
1128bool SensorService::SensorRecord::removeConnection(
1129 const wp<SensorEventConnection>& connection)
1130{
1131 ssize_t index = mConnections.indexOf(connection);
1132 if (index >= 0) {
1133 mConnections.removeItemsAt(index, 1);
1134 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001135 // Remove this connections from the queue of flush() calls made on this sensor.
1136 for (Vector< wp<SensorEventConnection> >::iterator it =
1137 mPendingFlushConnections.begin(); it != mPendingFlushConnections.end();) {
Aravind Akella8a969552014-09-28 17:52:41 -07001138
Aravind Akella6c2664a2014-08-13 12:24:50 -07001139 if (it->unsafe_get() == connection.unsafe_get()) {
1140 it = mPendingFlushConnections.erase(it);
1141 } else {
1142 ++it;
1143 }
1144 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001145 return mConnections.size() ? false : true;
1146}
1147
Aravind Akella6c2664a2014-08-13 12:24:50 -07001148void SensorService::SensorRecord::addPendingFlushConnection(
1149 const sp<SensorEventConnection>& connection) {
1150 mPendingFlushConnections.add(connection);
1151}
1152
1153void SensorService::SensorRecord::removeFirstPendingFlushConnection() {
1154 if (mPendingFlushConnections.size() > 0) {
1155 mPendingFlushConnections.removeAt(0);
1156 }
1157}
1158
1159SensorService::SensorEventConnection *
1160SensorService::SensorRecord::getFirstPendingFlushConnection() {
1161 if (mPendingFlushConnections.size() > 0) {
1162 return mPendingFlushConnections[0].unsafe_get();
1163 }
1164 return NULL;
1165}
1166
Aravind Akella4949c502015-02-11 15:54:35 -08001167void SensorService::SensorRecord::clearAllPendingFlushConnections() {
1168 mPendingFlushConnections.clear();
1169}
1170
Mathias Agopianfc328812010-07-14 23:41:37 -07001171// ---------------------------------------------------------------------------
1172
1173SensorService::SensorEventConnection::SensorEventConnection(
Svetoslavb412f6e2015-04-29 16:50:41 -07001174 const sp<SensorService>& service, uid_t uid, String8 packageName, bool isDataInjectionMode,
1175 const String16& opPackageName)
Aravind Akella8a969552014-09-28 17:52:41 -07001176 : mService(service), mUid(uid), mWakeLockRefCount(0), mHasLooperCallbacks(false),
Svetoslavb412f6e2015-04-29 16:50:41 -07001177 mDead(false), mDataInjectionMode(isDataInjectionMode), mEventCache(NULL),
1178 mCacheSize(0), mMaxCacheSize(0), mPackageName(packageName), mOpPackageName(opPackageName) {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001179 mChannel = new BitTube(mService->mSocketBufferSize);
Aravind Akella56ae4262014-07-10 16:01:10 -07001180#if DEBUG_CONNECTIONS
1181 mEventsReceived = mEventsSentFromCache = mEventsSent = 0;
Aravind Akellae74baf62014-08-21 12:28:35 -07001182 mTotalAcksNeeded = mTotalAcksReceived = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -07001183#endif
Mathias Agopianfc328812010-07-14 23:41:37 -07001184}
1185
Aravind Akella56ae4262014-07-10 16:01:10 -07001186SensorService::SensorEventConnection::~SensorEventConnection() {
Steve Blocka5512372011-12-20 16:23:08 +00001187 ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this);
Aravind Akellae148bc22014-09-24 22:12:58 -07001188 mService->cleanupConnection(this);
Aravind Akella56ae4262014-07-10 16:01:10 -07001189 if (mEventCache != NULL) {
1190 delete mEventCache;
1191 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001192}
1193
Aravind Akella56ae4262014-07-10 16:01:10 -07001194void SensorService::SensorEventConnection::onFirstRef() {
1195 LooperCallback::onFirstRef();
Mathias Agopianfc328812010-07-14 23:41:37 -07001196}
1197
Aravind Akella9a844cf2014-02-11 18:58:52 -08001198bool SensorService::SensorEventConnection::needsWakeLock() {
1199 Mutex::Autolock _l(mConnectionLock);
Aravind Akella8a969552014-09-28 17:52:41 -07001200 return !mDead && mWakeLockRefCount > 0;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001201}
1202
Aravind Akellab4373ac2014-10-29 17:55:20 -07001203void SensorService::SensorEventConnection::resetWakeLockRefCount() {
1204 Mutex::Autolock _l(mConnectionLock);
1205 mWakeLockRefCount = 0;
1206}
1207
Aravind Akella4c8b9512013-09-05 17:03:38 -07001208void SensorService::SensorEventConnection::dump(String8& result) {
1209 Mutex::Autolock _l(mConnectionLock);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001210 result.appendFormat("Operating Mode: %s\n", mDataInjectionMode ? "DATA_INJECTION" : "NORMAL");
Aravind Akella4949c502015-02-11 15:54:35 -08001211 result.appendFormat("\t%s | WakeLockRefCount %d | uid %d | cache size %d | max cache size %d\n",
1212 mPackageName.string(), mWakeLockRefCount, mUid, mCacheSize, mMaxCacheSize);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001213 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1214 const FlushInfo& flushInfo = mSensorInfo.valueAt(i);
Aravind Akella0ec20662014-09-14 17:29:48 -07001215 result.appendFormat("\t %s 0x%08x | status: %s | pending flush events %d \n",
Aravind Akella4c8b9512013-09-05 17:03:38 -07001216 mService->getSensorName(mSensorInfo.keyAt(i)).string(),
Aravind Akella6c2664a2014-08-13 12:24:50 -07001217 mSensorInfo.keyAt(i),
Aravind Akella4c8b9512013-09-05 17:03:38 -07001218 flushInfo.mFirstFlushPending ? "First flush pending" :
1219 "active",
Aravind Akella0ec20662014-09-14 17:29:48 -07001220 flushInfo.mPendingFlushEventsToSend);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001221 }
Aravind Akella0ec20662014-09-14 17:29:48 -07001222#if DEBUG_CONNECTIONS
1223 result.appendFormat("\t events recvd: %d | sent %d | cache %d | dropped %d |"
1224 " total_acks_needed %d | total_acks_recvd %d\n",
1225 mEventsReceived,
1226 mEventsSent,
1227 mEventsSentFromCache,
1228 mEventsReceived - (mEventsSentFromCache + mEventsSent + mCacheSize),
1229 mTotalAcksNeeded,
1230 mTotalAcksReceived);
1231#endif
Aravind Akella4c8b9512013-09-05 17:03:38 -07001232}
1233
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001234bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001235 Mutex::Autolock _l(mConnectionLock);
Svetoslavb412f6e2015-04-29 16:50:41 -07001236 if (!canAccessSensor(mService->getSensorFromHandle(handle),
1237 "Tried adding", mOpPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001238 return false;
1239 }
Aravind Akella4c8b9512013-09-05 17:03:38 -07001240 if (mSensorInfo.indexOfKey(handle) < 0) {
1241 mSensorInfo.add(handle, FlushInfo());
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001242 return true;
Mathias Agopianfc328812010-07-14 23:41:37 -07001243 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001244 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -07001245}
1246
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001247bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001248 Mutex::Autolock _l(mConnectionLock);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001249 if (mSensorInfo.removeItem(handle) >= 0) {
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001250 return true;
1251 }
1252 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -07001253}
1254
1255bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001256 Mutex::Autolock _l(mConnectionLock);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001257 return mSensorInfo.indexOfKey(handle) >= 0;
Mathias Agopianfc328812010-07-14 23:41:37 -07001258}
1259
1260bool SensorService::SensorEventConnection::hasAnySensor() const {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001261 Mutex::Autolock _l(mConnectionLock);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001262 return mSensorInfo.size() ? true : false;
1263}
1264
Aravind Akella8493b792014-09-08 15:45:47 -07001265bool SensorService::SensorEventConnection::hasOneShotSensors() const {
1266 Mutex::Autolock _l(mConnectionLock);
1267 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1268 const int handle = mSensorInfo.keyAt(i);
1269 if (mService->getSensorFromHandle(handle).getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1270 return true;
1271 }
1272 }
1273 return false;
1274}
1275
Aravind Akella4949c502015-02-11 15:54:35 -08001276String8 SensorService::SensorEventConnection::getPackageName() const {
1277 return mPackageName;
1278}
1279
Aravind Akella4c8b9512013-09-05 17:03:38 -07001280void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle,
1281 bool value) {
1282 Mutex::Autolock _l(mConnectionLock);
1283 ssize_t index = mSensorInfo.indexOfKey(handle);
1284 if (index >= 0) {
1285 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
1286 flushInfo.mFirstFlushPending = value;
1287 }
1288}
1289
Aravind Akella8a969552014-09-28 17:52:41 -07001290void SensorService::SensorEventConnection::updateLooperRegistration(const sp<Looper>& looper) {
1291 Mutex::Autolock _l(mConnectionLock);
1292 updateLooperRegistrationLocked(looper);
1293}
1294
1295void SensorService::SensorEventConnection::updateLooperRegistrationLocked(
1296 const sp<Looper>& looper) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001297 bool isConnectionActive = (mSensorInfo.size() > 0 && !mDataInjectionMode) ||
1298 mDataInjectionMode;
Aravind Akella8a969552014-09-28 17:52:41 -07001299 // If all sensors are unregistered OR Looper has encountered an error, we
1300 // can remove the Fd from the Looper if it has been previously added.
1301 if (!isConnectionActive || mDead) {
1302 if (mHasLooperCallbacks) {
1303 ALOGD_IF(DEBUG_CONNECTIONS, "%p removeFd fd=%d", this, mChannel->getSendFd());
1304 looper->removeFd(mChannel->getSendFd());
1305 mHasLooperCallbacks = false;
1306 }
1307 return;
1308 }
1309
1310 int looper_flags = 0;
1311 if (mCacheSize > 0) looper_flags |= ALOOPER_EVENT_OUTPUT;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001312 if (mDataInjectionMode) looper_flags |= ALOOPER_EVENT_INPUT;
Aravind Akella8a969552014-09-28 17:52:41 -07001313 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1314 const int handle = mSensorInfo.keyAt(i);
1315 if (mService->getSensorFromHandle(handle).isWakeUpSensor()) {
1316 looper_flags |= ALOOPER_EVENT_INPUT;
1317 break;
1318 }
1319 }
1320 // If flags is still set to zero, we don't need to add this fd to the Looper, if
1321 // the fd has already been added, remove it. This is likely to happen when ALL the
1322 // events stored in the cache have been sent to the corresponding app.
1323 if (looper_flags == 0) {
1324 if (mHasLooperCallbacks) {
1325 ALOGD_IF(DEBUG_CONNECTIONS, "removeFd fd=%d", mChannel->getSendFd());
1326 looper->removeFd(mChannel->getSendFd());
1327 mHasLooperCallbacks = false;
1328 }
1329 return;
1330 }
1331 // Add the file descriptor to the Looper for receiving acknowledegments if the app has
1332 // registered for wake-up sensors OR for sending events in the cache.
1333 int ret = looper->addFd(mChannel->getSendFd(), 0, looper_flags, this, NULL);
1334 if (ret == 1) {
1335 ALOGD_IF(DEBUG_CONNECTIONS, "%p addFd fd=%d", this, mChannel->getSendFd());
1336 mHasLooperCallbacks = true;
1337 } else {
1338 ALOGE("Looper::addFd failed ret=%d fd=%d", ret, mChannel->getSendFd());
1339 }
1340}
1341
1342void SensorService::SensorEventConnection::incrementPendingFlushCount(int32_t handle) {
1343 Mutex::Autolock _l(mConnectionLock);
1344 ssize_t index = mSensorInfo.indexOfKey(handle);
1345 if (index >= 0) {
1346 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
1347 flushInfo.mPendingFlushEventsToSend++;
1348 }
1349}
1350
Mathias Agopianfc328812010-07-14 23:41:37 -07001351status_t SensorService::SensorEventConnection::sendEvents(
Aravind Akella0ec20662014-09-14 17:29:48 -07001352 sensors_event_t const* buffer, size_t numEvents,
Aravind Akella8493b792014-09-08 15:45:47 -07001353 sensors_event_t* scratch,
1354 SensorEventConnection const * const * mapFlushEventsToConnections) {
Mathias Agopiancf510012010-07-22 16:18:10 -07001355 // filter out events not for this connection
Svetoslavb412f6e2015-04-29 16:50:41 -07001356 int count = 0;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001357 Mutex::Autolock _l(mConnectionLock);
Mathias Agopian3560fb22010-07-22 21:24:39 -07001358 if (scratch) {
1359 size_t i=0;
1360 while (i<numEvents) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001361 int32_t sensor_handle = buffer[i].sensor;
Aravind Akella724d91d2013-06-27 12:04:23 -07001362 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
1363 ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ",
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001364 buffer[i].meta_data.sensor);
Aravind Akella8a969552014-09-28 17:52:41 -07001365 // Setting sensor_handle to the correct sensor to ensure the sensor events per
1366 // connection are filtered correctly. buffer[i].sensor is zero for meta_data
1367 // events.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001368 sensor_handle = buffer[i].meta_data.sensor;
Aravind Akella724d91d2013-06-27 12:04:23 -07001369 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001370 ssize_t index = mSensorInfo.indexOfKey(sensor_handle);
Aravind Akella56ae4262014-07-10 16:01:10 -07001371 // Check if this connection has registered for this sensor. If not continue to the
1372 // next sensor_event.
1373 if (index < 0) {
1374 ++i;
1375 continue;
Aravind Akella4c8b9512013-09-05 17:03:38 -07001376 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001377
Aravind Akella56ae4262014-07-10 16:01:10 -07001378 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001379 // Check if there is a pending flush_complete event for this sensor on this connection.
Aravind Akella8493b792014-09-08 15:45:47 -07001380 if (buffer[i].type == SENSOR_TYPE_META_DATA && flushInfo.mFirstFlushPending == true &&
1381 this == mapFlushEventsToConnections[i]) {
1382 flushInfo.mFirstFlushPending = false;
1383 ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ",
1384 buffer[i].meta_data.sensor);
1385 ++i;
1386 continue;
Aravind Akella56ae4262014-07-10 16:01:10 -07001387 }
1388
1389 // If there is a pending flush complete event for this sensor on this connection,
1390 // ignore the event and proceed to the next.
1391 if (flushInfo.mFirstFlushPending) {
1392 ++i;
1393 continue;
1394 }
1395
1396 do {
Aravind Akella8493b792014-09-08 15:45:47 -07001397 // Keep copying events into the scratch buffer as long as they are regular
1398 // sensor_events are from the same sensor_handle OR they are flush_complete_events
1399 // from the same sensor_handle AND the current connection is mapped to the
1400 // corresponding flush_complete_event.
Aravind Akella56ae4262014-07-10 16:01:10 -07001401 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
Aravind Akella8493b792014-09-08 15:45:47 -07001402 if (this == mapFlushEventsToConnections[i]) {
Aravind Akella56ae4262014-07-10 16:01:10 -07001403 scratch[count++] = buffer[i];
Aravind Akella56ae4262014-07-10 16:01:10 -07001404 }
1405 ++i;
1406 } else {
1407 // Regular sensor event, just copy it to the scratch buffer.
Aravind Akella4c8b9512013-09-05 17:03:38 -07001408 scratch[count++] = buffer[i++];
Aravind Akella56ae4262014-07-10 16:01:10 -07001409 }
Aravind Akella8493b792014-09-08 15:45:47 -07001410 } while ((i<numEvents) && ((buffer[i].sensor == sensor_handle &&
1411 buffer[i].type != SENSOR_TYPE_META_DATA) ||
Aravind Akella56ae4262014-07-10 16:01:10 -07001412 (buffer[i].type == SENSOR_TYPE_META_DATA &&
Aravind Akella6c2664a2014-08-13 12:24:50 -07001413 buffer[i].meta_data.sensor == sensor_handle)));
Mathias Agopiancf510012010-07-22 16:18:10 -07001414 }
Mathias Agopian3560fb22010-07-22 21:24:39 -07001415 } else {
1416 scratch = const_cast<sensors_event_t *>(buffer);
1417 count = numEvents;
Mathias Agopiancf510012010-07-22 16:18:10 -07001418 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001419
Aravind Akella6c2664a2014-08-13 12:24:50 -07001420 sendPendingFlushEventsLocked();
Aravind Akella56ae4262014-07-10 16:01:10 -07001421 // Early return if there are no events for this connection.
1422 if (count == 0) {
1423 return status_t(NO_ERROR);
1424 }
1425
1426#if DEBUG_CONNECTIONS
1427 mEventsReceived += count;
1428#endif
1429 if (mCacheSize != 0) {
1430 // There are some events in the cache which need to be sent first. Copy this buffer to
1431 // the end of cache.
1432 if (mCacheSize + count <= mMaxCacheSize) {
1433 memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
1434 mCacheSize += count;
1435 } else {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001436 // Check if any new sensors have registered on this connection which may have increased
1437 // the max cache size that is desired.
1438 if (mCacheSize + count < computeMaxCacheSizeLocked()) {
1439 reAllocateCacheLocked(scratch, count);
1440 return status_t(NO_ERROR);
1441 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001442 // Some events need to be dropped.
1443 int remaningCacheSize = mMaxCacheSize - mCacheSize;
1444 if (remaningCacheSize != 0) {
1445 memcpy(&mEventCache[mCacheSize], scratch,
1446 remaningCacheSize * sizeof(sensors_event_t));
1447 }
1448 int numEventsDropped = count - remaningCacheSize;
1449 countFlushCompleteEventsLocked(mEventCache, numEventsDropped);
1450 // Drop the first "numEventsDropped" in the cache.
1451 memmove(mEventCache, &mEventCache[numEventsDropped],
1452 (mCacheSize - numEventsDropped) * sizeof(sensors_event_t));
1453
1454 // Copy the remainingEvents in scratch buffer to the end of cache.
1455 memcpy(&mEventCache[mCacheSize - numEventsDropped], scratch + remaningCacheSize,
1456 numEventsDropped * sizeof(sensors_event_t));
1457 }
1458 return status_t(NO_ERROR);
1459 }
1460
Aravind Akella6c2664a2014-08-13 12:24:50 -07001461 int index_wake_up_event = findWakeUpSensorEventLocked(scratch, count);
1462 if (index_wake_up_event >= 0) {
1463 scratch[index_wake_up_event].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1464 ++mWakeLockRefCount;
Aravind Akellae74baf62014-08-21 12:28:35 -07001465#if DEBUG_CONNECTIONS
1466 ++mTotalAcksNeeded;
1467#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001468 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001469
1470 // NOTE: ASensorEvent and sensors_event_t are the same type.
1471 ssize_t size = SensorEventQueue::write(mChannel,
1472 reinterpret_cast<ASensorEvent const*>(scratch), count);
1473 if (size < 0) {
1474 // Write error, copy events to local cache.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001475 if (index_wake_up_event >= 0) {
1476 // If there was a wake_up sensor_event, reset the flag.
1477 scratch[index_wake_up_event].flags &= ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
Aravind Akella0ec20662014-09-14 17:29:48 -07001478 if (mWakeLockRefCount > 0) {
1479 --mWakeLockRefCount;
1480 }
Aravind Akellae74baf62014-08-21 12:28:35 -07001481#if DEBUG_CONNECTIONS
1482 --mTotalAcksNeeded;
1483#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001484 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001485 if (mEventCache == NULL) {
1486 mMaxCacheSize = computeMaxCacheSizeLocked();
1487 mEventCache = new sensors_event_t[mMaxCacheSize];
1488 mCacheSize = 0;
1489 }
1490 memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
1491 mCacheSize += count;
1492
1493 // Add this file descriptor to the looper to get a callback when this fd is available for
1494 // writing.
Aravind Akella8a969552014-09-28 17:52:41 -07001495 updateLooperRegistrationLocked(mService->getLooper());
Aravind Akella56ae4262014-07-10 16:01:10 -07001496 return size;
1497 }
1498
1499#if DEBUG_CONNECTIONS
1500 if (size > 0) {
1501 mEventsSent += count;
1502 }
1503#endif
1504
1505 return size < 0 ? status_t(size) : status_t(NO_ERROR);
1506}
1507
Aravind Akella6c2664a2014-08-13 12:24:50 -07001508void SensorService::SensorEventConnection::reAllocateCacheLocked(sensors_event_t const* scratch,
1509 int count) {
1510 sensors_event_t *eventCache_new;
1511 const int new_cache_size = computeMaxCacheSizeLocked();
1512 // Allocate new cache, copy over events from the old cache & scratch, free up memory.
1513 eventCache_new = new sensors_event_t[new_cache_size];
1514 memcpy(eventCache_new, mEventCache, mCacheSize * sizeof(sensors_event_t));
1515 memcpy(&eventCache_new[mCacheSize], scratch, count * sizeof(sensors_event_t));
1516
1517 ALOGD_IF(DEBUG_CONNECTIONS, "reAllocateCacheLocked maxCacheSize=%d %d", mMaxCacheSize,
1518 new_cache_size);
1519
1520 delete mEventCache;
1521 mEventCache = eventCache_new;
1522 mCacheSize += count;
1523 mMaxCacheSize = new_cache_size;
1524}
1525
1526void SensorService::SensorEventConnection::sendPendingFlushEventsLocked() {
1527 ASensorEvent flushCompleteEvent;
Aravind Akella0ec20662014-09-14 17:29:48 -07001528 memset(&flushCompleteEvent, 0, sizeof(flushCompleteEvent));
Aravind Akella6c2664a2014-08-13 12:24:50 -07001529 flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
Aravind Akella6c2664a2014-08-13 12:24:50 -07001530 // Loop through all the sensors for this connection and check if there are any pending
1531 // flush complete events to be sent.
1532 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1533 FlushInfo& flushInfo = mSensorInfo.editValueAt(i);
1534 while (flushInfo.mPendingFlushEventsToSend > 0) {
Aravind Akella0ec20662014-09-14 17:29:48 -07001535 const int sensor_handle = mSensorInfo.keyAt(i);
1536 flushCompleteEvent.meta_data.sensor = sensor_handle;
Aravind Akellab4373ac2014-10-29 17:55:20 -07001537 bool wakeUpSensor = mService->getSensorFromHandle(sensor_handle).isWakeUpSensor();
1538 if (wakeUpSensor) {
1539 ++mWakeLockRefCount;
Aravind Akella0ec20662014-09-14 17:29:48 -07001540 flushCompleteEvent.flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1541 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001542 ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
1543 if (size < 0) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001544 if (wakeUpSensor) --mWakeLockRefCount;
Aravind Akella6c2664a2014-08-13 12:24:50 -07001545 return;
1546 }
1547 ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
1548 flushCompleteEvent.meta_data.sensor);
1549 flushInfo.mPendingFlushEventsToSend--;
1550 }
1551 }
1552}
1553
Aravind Akellab4373ac2014-10-29 17:55:20 -07001554void SensorService::SensorEventConnection::writeToSocketFromCache() {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001555 // At a time write at most half the size of the receiver buffer in SensorEventQueue OR
1556 // half the size of the socket buffer allocated in BitTube whichever is smaller.
1557 const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
1558 int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
Aravind Akellab4373ac2014-10-29 17:55:20 -07001559 Mutex::Autolock _l(mConnectionLock);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001560 // Send pending flush complete events (if any)
Aravind Akella6c2664a2014-08-13 12:24:50 -07001561 sendPendingFlushEventsLocked();
Aravind Akella56ae4262014-07-10 16:01:10 -07001562 for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001563 const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001564 int index_wake_up_event =
1565 findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite);
1566 if (index_wake_up_event >= 0) {
1567 mEventCache[index_wake_up_event + numEventsSent].flags |=
1568 WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1569 ++mWakeLockRefCount;
Aravind Akellae74baf62014-08-21 12:28:35 -07001570#if DEBUG_CONNECTIONS
1571 ++mTotalAcksNeeded;
1572#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001573 }
Aravind Akella4c8b9512013-09-05 17:03:38 -07001574
Aravind Akella56ae4262014-07-10 16:01:10 -07001575 ssize_t size = SensorEventQueue::write(mChannel,
1576 reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent),
Aravind Akella6c2664a2014-08-13 12:24:50 -07001577 numEventsToWrite);
Aravind Akella56ae4262014-07-10 16:01:10 -07001578 if (size < 0) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001579 if (index_wake_up_event >= 0) {
1580 // If there was a wake_up sensor_event, reset the flag.
1581 mEventCache[index_wake_up_event + numEventsSent].flags &=
1582 ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
Aravind Akella0ec20662014-09-14 17:29:48 -07001583 if (mWakeLockRefCount > 0) {
1584 --mWakeLockRefCount;
1585 }
Aravind Akellae74baf62014-08-21 12:28:35 -07001586#if DEBUG_CONNECTIONS
1587 --mTotalAcksNeeded;
1588#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001589 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001590 memmove(mEventCache, &mEventCache[numEventsSent],
1591 (mCacheSize - numEventsSent) * sizeof(sensors_event_t));
1592 ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ",
Aravind Akella6c2664a2014-08-13 12:24:50 -07001593 numEventsSent, mCacheSize);
Aravind Akella56ae4262014-07-10 16:01:10 -07001594 mCacheSize -= numEventsSent;
Aravind Akella56ae4262014-07-10 16:01:10 -07001595 return;
1596 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001597 numEventsSent += numEventsToWrite;
Aravind Akella56ae4262014-07-10 16:01:10 -07001598#if DEBUG_CONNECTIONS
Aravind Akella6c2664a2014-08-13 12:24:50 -07001599 mEventsSentFromCache += numEventsToWrite;
Aravind Akella56ae4262014-07-10 16:01:10 -07001600#endif
Aravind Akellab4099e72013-10-15 15:43:10 -07001601 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001602 ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize);
1603 // All events from the cache have been sent. Reset cache size to zero.
1604 mCacheSize = 0;
Aravind Akella8a969552014-09-28 17:52:41 -07001605 // There are no more events in the cache. We don't need to poll for write on the fd.
1606 // Update Looper registration.
1607 updateLooperRegistrationLocked(mService->getLooper());
Mathias Agopianfc328812010-07-14 23:41:37 -07001608}
1609
Aravind Akellac551eac2013-10-14 17:04:42 -07001610void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
Aravind Akella0ec20662014-09-14 17:29:48 -07001611 sensors_event_t const* scratch, const int numEventsDropped) {
Aravind Akella4c8b9512013-09-05 17:03:38 -07001612 ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001613 // Count flushComplete events in the events that are about to the dropped. These will be sent
1614 // separately before the next batch of events.
1615 for (int j = 0; j < numEventsDropped; ++j) {
1616 if (scratch[j].type == SENSOR_TYPE_META_DATA) {
1617 FlushInfo& flushInfo = mSensorInfo.editValueFor(scratch[j].meta_data.sensor);
1618 flushInfo.mPendingFlushEventsToSend++;
1619 ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
1620 flushInfo.mPendingFlushEventsToSend);
1621 }
1622 }
1623 return;
1624}
1625
Aravind Akella6c2664a2014-08-13 12:24:50 -07001626int SensorService::SensorEventConnection::findWakeUpSensorEventLocked(
1627 sensors_event_t const* scratch, const int count) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001628 for (int i = 0; i < count; ++i) {
1629 if (mService->isWakeUpSensorEvent(scratch[i])) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001630 return i;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001631 }
1632 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001633 return -1;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001634}
1635
Mathias Agopianb3989272011-10-20 18:42:02 -07001636sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
Mathias Agopianfc328812010-07-14 23:41:37 -07001637{
1638 return mChannel;
1639}
1640
1641status_t SensorService::SensorEventConnection::enableDisable(
Aravind Akella724d91d2013-06-27 12:04:23 -07001642 int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
1643 int reservedFlags)
Mathias Agopianfc328812010-07-14 23:41:37 -07001644{
1645 status_t err;
1646 if (enabled) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001647 err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
Svetoslavb412f6e2015-04-29 16:50:41 -07001648 reservedFlags, mOpPackageName);
Aravind Akella56ae4262014-07-10 16:01:10 -07001649
Mathias Agopianfc328812010-07-14 23:41:37 -07001650 } else {
1651 err = mService->disable(this, handle);
1652 }
1653 return err;
1654}
1655
1656status_t SensorService::SensorEventConnection::setEventRate(
Aravind Akella724d91d2013-06-27 12:04:23 -07001657 int handle, nsecs_t samplingPeriodNs)
Mathias Agopianfc328812010-07-14 23:41:37 -07001658{
Svetoslavb412f6e2015-04-29 16:50:41 -07001659 return mService->setEventRate(this, handle, samplingPeriodNs, mOpPackageName);
Mathias Agopianfc328812010-07-14 23:41:37 -07001660}
1661
Aravind Akella701166d2013-10-08 14:59:26 -07001662status_t SensorService::SensorEventConnection::flush() {
Svetoslavb412f6e2015-04-29 16:50:41 -07001663 return mService->flushSensor(this, mOpPackageName);
Aravind Akella724d91d2013-06-27 12:04:23 -07001664}
Aravind Akella4c8b9512013-09-05 17:03:38 -07001665
Aravind Akella8a969552014-09-28 17:52:41 -07001666int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* /*data*/) {
Aravind Akella56ae4262014-07-10 16:01:10 -07001667 if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) {
Aravind Akella8a969552014-09-28 17:52:41 -07001668 {
1669 // If the Looper encounters some error, set the flag mDead, reset mWakeLockRefCount,
1670 // and remove the fd from Looper. Call checkWakeLockState to know if SensorService
1671 // can release the wake-lock.
1672 ALOGD_IF(DEBUG_CONNECTIONS, "%p Looper error %d", this, fd);
1673 Mutex::Autolock _l(mConnectionLock);
1674 mDead = true;
1675 mWakeLockRefCount = 0;
1676 updateLooperRegistrationLocked(mService->getLooper());
1677 }
1678 mService->checkWakeLockState();
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001679 if (mDataInjectionMode) {
1680 // If the Looper has encountered some error in data injection mode, reset SensorService
1681 // back to normal mode.
1682 mService->resetToNormalMode();
1683 mDataInjectionMode = false;
1684 }
Aravind Akella8a969552014-09-28 17:52:41 -07001685 return 1;
Aravind Akella56ae4262014-07-10 16:01:10 -07001686 }
1687
1688 if (events & ALOOPER_EVENT_INPUT) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001689 unsigned char buf[sizeof(sensors_event_t)];
1690 ssize_t numBytesRead = ::recv(fd, buf, sizeof(buf), MSG_DONTWAIT);
Aravind Akella56ae4262014-07-10 16:01:10 -07001691 {
1692 Mutex::Autolock _l(mConnectionLock);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001693 if (numBytesRead == sizeof(sensors_event_t)) {
1694 if (!mDataInjectionMode) {
1695 ALOGE("Data injected in normal mode, dropping event"
1696 "package=%s uid=%d", mPackageName.string(), mUid);
1697 // Unregister call backs.
1698 return 0;
1699 }
1700 SensorDevice& dev(SensorDevice::getInstance());
1701 sensors_event_t sensor_event;
1702 memset(&sensor_event, 0, sizeof(sensor_event));
1703 memcpy(&sensor_event, buf, sizeof(sensors_event_t));
1704 Sensor sensor = mService->getSensorFromHandle(sensor_event.sensor);
1705 sensor_event.type = sensor.getType();
Svetoslavb412f6e2015-04-29 16:50:41 -07001706 dev.injectSensorData(&sensor_event);
Aravind Akellae74baf62014-08-21 12:28:35 -07001707#if DEBUG_CONNECTIONS
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001708 ++mEventsReceived;
Aravind Akellae74baf62014-08-21 12:28:35 -07001709#endif
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001710 } else if (numBytesRead == sizeof(uint32_t)) {
1711 uint32_t numAcks = 0;
1712 memcpy(&numAcks, buf, sizeof(numBytesRead));
1713 // Sanity check to ensure there are no read errors in recv, numAcks is always
1714 // within the range and not zero. If any of the above don't hold reset
1715 // mWakeLockRefCount to zero.
1716 if (numAcks > 0 && numAcks < mWakeLockRefCount) {
1717 mWakeLockRefCount -= numAcks;
1718 } else {
1719 mWakeLockRefCount = 0;
1720 }
1721#if DEBUG_CONNECTIONS
1722 mTotalAcksReceived += numAcks;
1723#endif
1724 } else {
1725 // Read error, reset wakelock refcount.
1726 mWakeLockRefCount = 0;
1727 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001728 }
1729 // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released
1730 // here as checkWakeLockState() will need it.
1731 if (mWakeLockRefCount == 0) {
1732 mService->checkWakeLockState();
1733 }
1734 // continue getting callbacks.
1735 return 1;
1736 }
1737
1738 if (events & ALOOPER_EVENT_OUTPUT) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001739 // send sensor data that is stored in mEventCache for this connection.
1740 mService->sendEventsFromCache(this);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001741 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001742 return 1;
1743}
1744
1745int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
Svetoslavb412f6e2015-04-29 16:50:41 -07001746 size_t fifoWakeUpSensors = 0;
1747 size_t fifoNonWakeUpSensors = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -07001748 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1749 const Sensor& sensor = mService->getSensorFromHandle(mSensorInfo.keyAt(i));
1750 if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) {
1751 // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and
1752 // non wake_up sensors.
1753 if (sensor.isWakeUpSensor()) {
1754 fifoWakeUpSensors += sensor.getFifoReservedEventCount();
1755 } else {
1756 fifoNonWakeUpSensors += sensor.getFifoReservedEventCount();
1757 }
1758 } else {
1759 // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors.
1760 if (sensor.isWakeUpSensor()) {
1761 fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ?
1762 fifoWakeUpSensors : sensor.getFifoMaxEventCount();
1763
1764 } else {
1765 fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ?
1766 fifoNonWakeUpSensors : sensor.getFifoMaxEventCount();
1767
1768 }
1769 }
1770 }
1771 if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) {
1772 // It is extremely unlikely that there is a write failure in non batch mode. Return a cache
Aravind Akella6c2664a2014-08-13 12:24:50 -07001773 // size that is equal to that of the batch mode.
Aravind Akellae74baf62014-08-21 12:28:35 -07001774 // ALOGW("Write failure in non-batch mode");
Aravind Akella6c2664a2014-08-13 12:24:50 -07001775 return MAX_SOCKET_BUFFER_SIZE_BATCHED/sizeof(sensors_event_t);
Aravind Akella56ae4262014-07-10 16:01:10 -07001776 }
1777 return fifoWakeUpSensors + fifoNonWakeUpSensors;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001778}
1779
Mathias Agopianfc328812010-07-14 23:41:37 -07001780// ---------------------------------------------------------------------------
1781}; // namespace android
1782