SensorService.cpp 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978
  1. /*
  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. #include <inttypes.h>
  17. #include <math.h>
  18. #include <stdint.h>
  19. #include <sys/types.h>
  20. #include <sys/socket.h>
  21. #include <cutils/properties.h>
  22. #include <utils/SortedVector.h>
  23. #include <utils/KeyedVector.h>
  24. #include <utils/threads.h>
  25. #include <utils/Atomic.h>
  26. #include <utils/Errors.h>
  27. #include <utils/RefBase.h>
  28. #include <utils/Singleton.h>
  29. #include <utils/String16.h>
  30. #include <binder/AppOpsManager.h>
  31. #include <binder/BinderService.h>
  32. #include <binder/IServiceManager.h>
  33. #include <binder/PermissionCache.h>
  34. #include <gui/ISensorServer.h>
  35. #include <gui/ISensorEventConnection.h>
  36. #include <gui/SensorEventQueue.h>
  37. #include <hardware/sensors.h>
  38. #include <hardware_legacy/power.h>
  39. #include "BatteryService.h"
  40. #include "CorrectedGyroSensor.h"
  41. #include "GravitySensor.h"
  42. #include "LinearAccelerationSensor.h"
  43. #include "OrientationSensor.h"
  44. #include "RotationVectorSensor.h"
  45. #include "SensorFusion.h"
  46. #include "SensorService.h"
  47. namespace android {
  48. // ---------------------------------------------------------------------------
  49. /*
  50. * Notes:
  51. *
  52. * - what about a gyro-corrected magnetic-field sensor?
  53. * - run mag sensor from time to time to force calibration
  54. * - gravity sensor length is wrong (=> drift in linear-acc sensor)
  55. *
  56. */
  57. const char* SensorService::WAKE_LOCK_NAME = "SensorService_wakelock";
  58. // Permissions.
  59. static const String16 sDump("android.permission.DUMP");
  60. SensorService::SensorService()
  61. : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
  62. mWakeLockAcquired(false)
  63. {
  64. }
  65. void SensorService::onFirstRef()
  66. {
  67. ALOGD("nuSensorService starting...");
  68. SensorDevice& dev(SensorDevice::getInstance());
  69. if (dev.initCheck() == NO_ERROR) {
  70. sensor_t const* list;
  71. ssize_t count = dev.getSensorList(&list);
  72. if (count > 0) {
  73. ssize_t orientationIndex = -1;
  74. bool hasGyro = false, hasAccel = false, hasMag = false;
  75. uint32_t virtualSensorsNeeds =
  76. (1<<SENSOR_TYPE_GRAVITY) |
  77. (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
  78. (1<<SENSOR_TYPE_ROTATION_VECTOR);
  79. mLastEventSeen.setCapacity(count);
  80. for (ssize_t i=0 ; i<count ; i++) {
  81. registerSensor( new HardwareSensor(list[i]) );
  82. switch (list[i].type) {
  83. case SENSOR_TYPE_ACCELEROMETER:
  84. hasAccel = true;
  85. break;
  86. case SENSOR_TYPE_MAGNETIC_FIELD:
  87. hasMag = true;
  88. break;
  89. case SENSOR_TYPE_ORIENTATION:
  90. orientationIndex = i;
  91. break;
  92. case SENSOR_TYPE_GYROSCOPE:
  93. case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
  94. hasGyro = true;
  95. break;
  96. case SENSOR_TYPE_GRAVITY:
  97. case SENSOR_TYPE_LINEAR_ACCELERATION:
  98. case SENSOR_TYPE_ROTATION_VECTOR:
  99. virtualSensorsNeeds &= ~(1<<list[i].type);
  100. break;
  101. }
  102. }
  103. // it's safe to instantiate the SensorFusion object here
  104. // (it wants to be instantiated after h/w sensors have been
  105. // registered)
  106. const SensorFusion& fusion(SensorFusion::getInstance());
  107. // build the sensor list returned to users
  108. mUserSensorList = mSensorList;
  109. if (hasGyro && hasAccel && hasMag) {
  110. Sensor aSensor;
  111. // Add Android virtual sensors if they're not already
  112. // available in the HAL
  113. aSensor = registerVirtualSensor( new RotationVectorSensor() );
  114. if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
  115. mUserSensorList.add(aSensor);
  116. }
  117. aSensor = registerVirtualSensor( new GravitySensor(list, count) );
  118. if (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) {
  119. mUserSensorList.add(aSensor);
  120. }
  121. aSensor = registerVirtualSensor( new LinearAccelerationSensor(list, count) );
  122. if (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) {
  123. mUserSensorList.add(aSensor);
  124. }
  125. aSensor = registerVirtualSensor( new OrientationSensor() );
  126. if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
  127. if (orientationIndex == -1) {
  128. // some sensor HALs don't provide an orientation sensor.
  129. mUserSensorList.add(aSensor);
  130. }
  131. }
  132. // virtual debugging sensors are not added to mUserSensorList
  133. registerVirtualSensor( new CorrectedGyroSensor(list, count) );
  134. registerVirtualSensor( new GyroDriftSensor() );
  135. }
  136. // debugging sensor list
  137. mUserSensorListDebug = mSensorList;
  138. // Check if the device really supports batching by looking at the FIFO event
  139. // counts for each sensor.
  140. bool batchingSupported = false;
  141. for (size_t i = 0; i < mSensorList.size(); ++i) {
  142. if (mSensorList[i].getFifoMaxEventCount() > 0) {
  143. batchingSupported = true;
  144. break;
  145. }
  146. }
  147. if (batchingSupported) {
  148. // Increase socket buffer size to a max of 100 KB for batching capabilities.
  149. mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
  150. } else {
  151. mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
  152. }
  153. // Compare the socketBufferSize value against the system limits and limit
  154. // it to maxSystemSocketBufferSize if necessary.
  155. FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
  156. char line[128];
  157. if (fp != NULL && fgets(line, sizeof(line), fp) != NULL) {
  158. line[sizeof(line) - 1] = '\0';
  159. size_t maxSystemSocketBufferSize;
  160. sscanf(line, "%zu", &maxSystemSocketBufferSize);
  161. if (mSocketBufferSize > maxSystemSocketBufferSize) {
  162. mSocketBufferSize = maxSystemSocketBufferSize;
  163. }
  164. }
  165. if (fp) {
  166. fclose(fp);
  167. }
  168. mWakeLockAcquired = false;
  169. mLooper = new Looper(false);
  170. const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
  171. mSensorEventBuffer = new sensors_event_t[minBufferSize];
  172. mSensorEventScratch = new sensors_event_t[minBufferSize];
  173. mMapFlushEventsToConnections = new SensorEventConnection const * [minBufferSize];
  174. mCurrentOperatingMode = NORMAL;
  175. mNextSensorRegIndex = 0;
  176. for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
  177. mLastNSensorRegistrations.push();
  178. }
  179. mInitCheck = NO_ERROR;
  180. mAckReceiver = new SensorEventAckReceiver(this);
  181. mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
  182. run("SensorService", PRIORITY_URGENT_DISPLAY);
  183. }
  184. }
  185. }
  186. Sensor SensorService::registerSensor(SensorInterface* s)
  187. {
  188. sensors_event_t event;
  189. memset(&event, 0, sizeof(event));
  190. const Sensor sensor(s->getSensor());
  191. // add to the sensor list (returned to clients)
  192. mSensorList.add(sensor);
  193. // add to our handle->SensorInterface mapping
  194. mSensorMap.add(sensor.getHandle(), s);
  195. // create an entry in the mLastEventSeen array
  196. mLastEventSeen.add(sensor.getHandle(), NULL);
  197. return sensor;
  198. }
  199. Sensor SensorService::registerVirtualSensor(SensorInterface* s)
  200. {
  201. Sensor sensor = registerSensor(s);
  202. mVirtualSensorList.add( s );
  203. return sensor;
  204. }
  205. SensorService::~SensorService()
  206. {
  207. for (size_t i=0 ; i<mSensorMap.size() ; i++)
  208. delete mSensorMap.valueAt(i);
  209. }
  210. status_t SensorService::dump(int fd, const Vector<String16>& args)
  211. {
  212. String8 result;
  213. if (!PermissionCache::checkCallingPermission(sDump)) {
  214. result.appendFormat("Permission Denial: "
  215. "can't dump SensorService from pid=%d, uid=%d\n",
  216. IPCThreadState::self()->getCallingPid(),
  217. IPCThreadState::self()->getCallingUid());
  218. } else {
  219. if (args.size() > 2) {
  220. return INVALID_OPERATION;
  221. }
  222. Mutex::Autolock _l(mLock);
  223. SensorDevice& dev(SensorDevice::getInstance());
  224. if (args.size() == 2 && args[0] == String16("restrict")) {
  225. // If already in restricted mode. Ignore.
  226. if (mCurrentOperatingMode == RESTRICTED) {
  227. return status_t(NO_ERROR);
  228. }
  229. // If in any mode other than normal, ignore.
  230. if (mCurrentOperatingMode != NORMAL) {
  231. return INVALID_OPERATION;
  232. }
  233. mCurrentOperatingMode = RESTRICTED;
  234. dev.disableAllSensors();
  235. // Clear all pending flush connections for all active sensors. If one of the active
  236. // connections has called flush() and the underlying sensor has been disabled before a
  237. // flush complete event is returned, we need to remove the connection from this queue.
  238. for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
  239. mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
  240. }
  241. mWhiteListedPackage.setTo(String8(args[1]));
  242. return status_t(NO_ERROR);
  243. } else if (args.size() == 1 && args[0] == String16("enable")) {
  244. // If currently in restricted mode, reset back to NORMAL mode else ignore.
  245. if (mCurrentOperatingMode == RESTRICTED) {
  246. mCurrentOperatingMode = NORMAL;
  247. dev.enableAllSensors();
  248. }
  249. if (mCurrentOperatingMode == DATA_INJECTION) {
  250. resetToNormalModeLocked();
  251. }
  252. mWhiteListedPackage.clear();
  253. return status_t(NO_ERROR);
  254. } else if (args.size() == 2 && args[0] == String16("data_injection")) {
  255. if (mCurrentOperatingMode == NORMAL) {
  256. dev.disableAllSensors();
  257. status_t err = dev.setMode(DATA_INJECTION);
  258. if (err == NO_ERROR) {
  259. mCurrentOperatingMode = DATA_INJECTION;
  260. } else {
  261. // Re-enable sensors.
  262. dev.enableAllSensors();
  263. }
  264. mWhiteListedPackage.setTo(String8(args[1]));
  265. return NO_ERROR;
  266. } else if (mCurrentOperatingMode == DATA_INJECTION) {
  267. // Already in DATA_INJECTION mode. Treat this as a no_op.
  268. return NO_ERROR;
  269. } else {
  270. // Transition to data injection mode supported only from NORMAL mode.
  271. return INVALID_OPERATION;
  272. }
  273. } else if (mSensorList.size() == 0) {
  274. result.append("No Sensors on the device\n");
  275. } else {
  276. // Default dump the sensor list and debugging information.
  277. result.append("Sensor List:\n");
  278. for (size_t i=0 ; i<mSensorList.size() ; i++) {
  279. const Sensor& s(mSensorList[i]);
  280. result.appendFormat(
  281. "%-15s| %-10s| version=%d |%-20s| 0x%08x | \"%s\" | type=%d |",
  282. s.getName().string(),
  283. s.getVendor().string(),
  284. s.getVersion(),
  285. s.getStringType().string(),
  286. s.getHandle(),
  287. s.getRequiredPermission().string(),
  288. s.getType());
  289. const int reportingMode = s.getReportingMode();
  290. if (reportingMode == AREPORTING_MODE_CONTINUOUS) {
  291. result.append(" continuous | ");
  292. } else if (reportingMode == AREPORTING_MODE_ON_CHANGE) {
  293. result.append(" on-change | ");
  294. } else if (reportingMode == AREPORTING_MODE_ONE_SHOT) {
  295. result.append(" one-shot | ");
  296. } else {
  297. result.append(" special-trigger | ");
  298. }
  299. if (s.getMaxDelay() > 0) {
  300. result.appendFormat("minRate=%.2fHz | ", 1e6f / s.getMaxDelay());
  301. } else {
  302. result.appendFormat("maxDelay=%dus |", s.getMaxDelay());
  303. }
  304. if (s.getMinDelay() > 0) {
  305. result.appendFormat("maxRate=%.2fHz | ", 1e6f / s.getMinDelay());
  306. } else {
  307. result.appendFormat("minDelay=%dus |", s.getMinDelay());
  308. }
  309. if (s.getFifoMaxEventCount() > 0) {
  310. result.appendFormat("FifoMax=%d events | ",
  311. s.getFifoMaxEventCount());
  312. } else {
  313. result.append("no batching | ");
  314. }
  315. if (s.isWakeUpSensor()) {
  316. result.appendFormat("wakeUp | ");
  317. } else {
  318. result.appendFormat("non-wakeUp | ");
  319. }
  320. result.appendFormat("%.4f mA | ", s.getPowerUsage());
  321. int bufIndex = mLastEventSeen.indexOfKey(s.getHandle());
  322. if (bufIndex >= 0) {
  323. const CircularBuffer* buf = mLastEventSeen.valueAt(bufIndex);
  324. if (buf != NULL && s.getRequiredPermission().isEmpty()) {
  325. buf->printBuffer(result);
  326. } else {
  327. result.append("last=<> \n");
  328. }
  329. }
  330. result.append("\n");
  331. }
  332. SensorFusion::getInstance().dump(result);
  333. SensorDevice::getInstance().dump(result);
  334. result.append("Active sensors:\n");
  335. for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
  336. int handle = mActiveSensors.keyAt(i);
  337. result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
  338. getSensorName(handle).string(),
  339. handle,
  340. mActiveSensors.valueAt(i)->getNumConnections());
  341. }
  342. result.appendFormat("Socket Buffer size = %d events\n",
  343. mSocketBufferSize/sizeof(sensors_event_t));
  344. result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
  345. "not held");
  346. result.appendFormat("Mode :");
  347. switch(mCurrentOperatingMode) {
  348. case NORMAL:
  349. result.appendFormat(" NORMAL\n");
  350. break;
  351. case RESTRICTED:
  352. result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
  353. break;
  354. case DATA_INJECTION:
  355. result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
  356. }
  357. result.appendFormat("%zd active connections\n", mActiveConnections.size());
  358. for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
  359. sp<SensorEventConnection> connection(mActiveConnections[i].promote());
  360. if (connection != 0) {
  361. result.appendFormat("Connection Number: %zu \n", i);
  362. connection->dump(result);
  363. }
  364. }
  365. result.appendFormat("Previous Registrations:\n");
  366. // Log in the reverse chronological order.
  367. int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
  368. SENSOR_REGISTRATIONS_BUF_SIZE;
  369. const int startIndex = currentIndex;
  370. do {
  371. const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
  372. if (SensorRegistrationInfo::isSentinel(reg_info)) {
  373. // Ignore sentinel, proceed to next item.
  374. currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
  375. SENSOR_REGISTRATIONS_BUF_SIZE;
  376. continue;
  377. }
  378. if (reg_info.mActivated) {
  379. result.appendFormat("%02d:%02d:%02d activated package=%s handle=0x%08x "
  380. "samplingRate=%dus maxReportLatency=%dus\n",
  381. reg_info.mHour, reg_info.mMin, reg_info.mSec,
  382. reg_info.mPackageName.string(), reg_info.mSensorHandle,
  383. reg_info.mSamplingRateUs, reg_info.mMaxReportLatencyUs);
  384. } else {
  385. result.appendFormat("%02d:%02d:%02d de-activated package=%s handle=0x%08x\n",
  386. reg_info.mHour, reg_info.mMin, reg_info.mSec,
  387. reg_info.mPackageName.string(), reg_info.mSensorHandle);
  388. }
  389. currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
  390. SENSOR_REGISTRATIONS_BUF_SIZE;
  391. } while(startIndex != currentIndex);
  392. }
  393. }
  394. write(fd, result.string(), result.size());
  395. return NO_ERROR;
  396. }
  397. void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
  398. sensors_event_t const* buffer, const int count) {
  399. for (int i=0 ; i<count ; i++) {
  400. int handle = buffer[i].sensor;
  401. if (buffer[i].type == SENSOR_TYPE_META_DATA) {
  402. handle = buffer[i].meta_data.sensor;
  403. }
  404. if (connection->hasSensor(handle)) {
  405. SensorInterface* sensor = mSensorMap.valueFor(handle);
  406. // If this buffer has an event from a one_shot sensor and this connection is registered
  407. // for this particular one_shot sensor, try cleaning up the connection.
  408. if (sensor != NULL &&
  409. sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
  410. sensor->autoDisable(connection.get(), handle);
  411. cleanupWithoutDisableLocked(connection, handle);
  412. }
  413. }
  414. }
  415. }
  416. bool SensorService::threadLoop()
  417. {
  418. ALOGD("nuSensorService thread starting...");
  419. // each virtual sensor could generate an event per "real" event, that's why we need
  420. // to size numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT.
  421. // in practice, this is too aggressive, but guaranteed to be enough.
  422. const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
  423. const size_t numEventMax = minBufferSize / (1 + mVirtualSensorList.size());
  424. SensorDevice& device(SensorDevice::getInstance());
  425. const size_t vcount = mVirtualSensorList.size();
  426. const int halVersion = device.getHalDeviceVersion();
  427. do {
  428. ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
  429. if (count < 0) {
  430. ALOGE("sensor poll failed (%s)", strerror(-count));
  431. break;
  432. }
  433. // Reset sensors_event_t.flags to zero for all events in the buffer.
  434. for (int i = 0; i < count; i++) {
  435. mSensorEventBuffer[i].flags = 0;
  436. }
  437. // Make a copy of the connection vector as some connections may be removed during the
  438. // course of this loop (especially when one-shot sensor events are present in the
  439. // sensor_event buffer). Promote all connections to StrongPointers before the lock is
  440. // acquired. If the destructor of the sp gets called when the lock is acquired, it may
  441. // result in a deadlock as ~SensorEventConnection() needs to acquire mLock again for
  442. // cleanup. So copy all the strongPointers to a vector before the lock is acquired.
  443. SortedVector< sp<SensorEventConnection> > activeConnections;
  444. populateActiveConnections(&activeConnections);
  445. Mutex::Autolock _l(mLock);
  446. // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
  447. // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
  448. // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
  449. // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
  450. // releasing the wakelock.
  451. bool bufferHasWakeUpEvent = false;
  452. for (int i = 0; i < count; i++) {
  453. if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
  454. bufferHasWakeUpEvent = true;
  455. break;
  456. }
  457. }
  458. if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
  459. setWakeLockAcquiredLocked(true);
  460. }
  461. recordLastValueLocked(mSensorEventBuffer, count);
  462. // handle virtual sensors
  463. if (count && vcount) {
  464. sensors_event_t const * const event = mSensorEventBuffer;
  465. const size_t activeVirtualSensorCount = mActiveVirtualSensors.size();
  466. if (activeVirtualSensorCount) {
  467. size_t k = 0;
  468. SensorFusion& fusion(SensorFusion::getInstance());
  469. if (fusion.isEnabled()) {
  470. for (size_t i=0 ; i<size_t(count) ; i++) {
  471. fusion.process(event[i]);
  472. }
  473. }
  474. for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
  475. for (size_t j=0 ; j<activeVirtualSensorCount ; j++) {
  476. if (count + k >= minBufferSize) {
  477. ALOGE("buffer too small to hold all events: "
  478. "count=%zd, k=%zu, size=%zu",
  479. count, k, minBufferSize);
  480. break;
  481. }
  482. sensors_event_t out;
  483. SensorInterface* si = mActiveVirtualSensors.valueAt(j);
  484. if (si->process(&out, event[i])) {
  485. mSensorEventBuffer[count + k] = out;
  486. k++;
  487. }
  488. }
  489. }
  490. if (k) {
  491. // record the last synthesized values
  492. recordLastValueLocked(&mSensorEventBuffer[count], k);
  493. count += k;
  494. // sort the buffer by time-stamps
  495. sortEventBuffer(mSensorEventBuffer, count);
  496. }
  497. }
  498. }
  499. // handle backward compatibility for RotationVector sensor
  500. if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
  501. for (int i = 0; i < count; i++) {
  502. if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
  503. // All the 4 components of the quaternion should be available
  504. // No heading accuracy. Set it to -1
  505. mSensorEventBuffer[i].data[4] = -1;
  506. }
  507. }
  508. }
  509. // Map flush_complete_events in the buffer to SensorEventConnections which called
  510. // flush on the hardware sensor. mapFlushEventsToConnections[i] will be the
  511. // SensorEventConnection mapped to the corresponding flush_complete_event in
  512. // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
  513. for (int i = 0; i < count; ++i) {
  514. mMapFlushEventsToConnections[i] = NULL;
  515. if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
  516. const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
  517. SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
  518. if (rec != NULL) {
  519. mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
  520. rec->removeFirstPendingFlushConnection();
  521. }
  522. }
  523. }
  524. // Send our events to clients. Check the state of wake lock for each client and release the
  525. // lock if none of the clients need it.
  526. bool needsWakeLock = false;
  527. size_t numConnections = activeConnections.size();
  528. for (size_t i=0 ; i < numConnections; ++i) {
  529. if (activeConnections[i] != 0) {
  530. activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
  531. mMapFlushEventsToConnections);
  532. needsWakeLock |= activeConnections[i]->needsWakeLock();
  533. // If the connection has one-shot sensors, it may be cleaned up after first trigger.
  534. // Early check for one-shot sensors.
  535. if (activeConnections[i]->hasOneShotSensors()) {
  536. cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
  537. count);
  538. }
  539. }
  540. }
  541. if (mWakeLockAcquired && !needsWakeLock) {
  542. setWakeLockAcquiredLocked(false);
  543. }
  544. } while (!Thread::exitPending());
  545. ALOGW("Exiting SensorService::threadLoop => aborting...");
  546. abort();
  547. return false;
  548. }
  549. sp<Looper> SensorService::getLooper() const {
  550. return mLooper;
  551. }
  552. void SensorService::resetAllWakeLockRefCounts() {
  553. SortedVector< sp<SensorEventConnection> > activeConnections;
  554. populateActiveConnections(&activeConnections);
  555. {
  556. Mutex::Autolock _l(mLock);
  557. for (size_t i=0 ; i < activeConnections.size(); ++i) {
  558. if (activeConnections[i] != 0) {
  559. activeConnections[i]->resetWakeLockRefCount();
  560. }
  561. }
  562. setWakeLockAcquiredLocked(false);
  563. }
  564. }
  565. void SensorService::setWakeLockAcquiredLocked(bool acquire) {
  566. if (acquire) {
  567. if (!mWakeLockAcquired) {
  568. acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
  569. mWakeLockAcquired = true;
  570. }
  571. mLooper->wake();
  572. } else {
  573. if (mWakeLockAcquired) {
  574. release_wake_lock(WAKE_LOCK_NAME);
  575. mWakeLockAcquired = false;
  576. }
  577. }
  578. }
  579. bool SensorService::isWakeLockAcquired() {
  580. Mutex::Autolock _l(mLock);
  581. return mWakeLockAcquired;
  582. }
  583. bool SensorService::SensorEventAckReceiver::threadLoop() {
  584. ALOGD("new thread SensorEventAckReceiver");
  585. sp<Looper> looper = mService->getLooper();
  586. do {
  587. bool wakeLockAcquired = mService->isWakeLockAcquired();
  588. int timeout = -1;
  589. if (wakeLockAcquired) timeout = 5000;
  590. int ret = looper->pollOnce(timeout);
  591. if (ret == ALOOPER_POLL_TIMEOUT) {
  592. mService->resetAllWakeLockRefCounts();
  593. }
  594. } while(!Thread::exitPending());
  595. return false;
  596. }
  597. void SensorService::recordLastValueLocked(
  598. const sensors_event_t* buffer, size_t count) {
  599. for (size_t i = 0; i < count; i++) {
  600. if (buffer[i].type != SENSOR_TYPE_META_DATA) {
  601. CircularBuffer* &circular_buf = mLastEventSeen.editValueFor(buffer[i].sensor);
  602. if (circular_buf == NULL) {
  603. circular_buf = new CircularBuffer(buffer[i].type);
  604. }
  605. circular_buf->addEvent(buffer[i]);
  606. }
  607. }
  608. }
  609. void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count)
  610. {
  611. struct compar {
  612. static int cmp(void const* lhs, void const* rhs) {
  613. sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
  614. sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
  615. return l->timestamp - r->timestamp;
  616. }
  617. };
  618. qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
  619. }
  620. String8 SensorService::getSensorName(int handle) const {
  621. size_t count = mUserSensorList.size();
  622. for (size_t i=0 ; i<count ; i++) {
  623. const Sensor& sensor(mUserSensorList[i]);
  624. if (sensor.getHandle() == handle) {
  625. return sensor.getName();
  626. }
  627. }
  628. String8 result("unknown");
  629. return result;
  630. }
  631. bool SensorService::isVirtualSensor(int handle) const {
  632. SensorInterface* sensor = mSensorMap.valueFor(handle);
  633. return sensor->isVirtual();
  634. }
  635. bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
  636. int handle = event.sensor;
  637. if (event.type == SENSOR_TYPE_META_DATA) {
  638. handle = event.meta_data.sensor;
  639. }
  640. SensorInterface* sensor = mSensorMap.valueFor(handle);
  641. return sensor != NULL && sensor->getSensor().isWakeUpSensor();
  642. }
  643. SensorService::SensorRecord * SensorService::getSensorRecord(int handle) {
  644. return mActiveSensors.valueFor(handle);
  645. }
  646. Vector<Sensor> SensorService::getSensorList(const String16& opPackageName)
  647. {
  648. char value[PROPERTY_VALUE_MAX];
  649. property_get("debug.sensors", value, "0");
  650. const Vector<Sensor>& initialSensorList = (atoi(value)) ?
  651. mUserSensorListDebug : mUserSensorList;
  652. Vector<Sensor> accessibleSensorList;
  653. for (size_t i = 0; i < initialSensorList.size(); i++) {
  654. Sensor sensor = initialSensorList[i];
  655. if (canAccessSensor(sensor, "getSensorList", opPackageName)) {
  656. accessibleSensorList.add(sensor);
  657. } else {
  658. ALOGI("Skipped sensor %s because it requires permission %s and app op %d",
  659. sensor.getName().string(),
  660. sensor.getRequiredPermission().string(),
  661. sensor.getRequiredAppOp());
  662. }
  663. }
  664. return accessibleSensorList;
  665. }
  666. sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
  667. int requestedMode, const String16& opPackageName) {
  668. // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
  669. if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
  670. return NULL;
  671. }
  672. Mutex::Autolock _l(mLock);
  673. // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
  674. // operating in DI mode.
  675. if (requestedMode == DATA_INJECTION) {
  676. if (mCurrentOperatingMode != DATA_INJECTION) return NULL;
  677. if (!isWhiteListedPackage(packageName)) return NULL;
  678. }
  679. uid_t uid = IPCThreadState::self()->getCallingUid();
  680. sp<SensorEventConnection> result(new SensorEventConnection(this, uid, packageName,
  681. requestedMode == DATA_INJECTION, opPackageName));
  682. if (requestedMode == DATA_INJECTION) {
  683. if (mActiveConnections.indexOf(result) < 0) {
  684. mActiveConnections.add(result);
  685. }
  686. // Add the associated file descriptor to the Looper for polling whenever there is data to
  687. // be injected.
  688. result->updateLooperRegistration(mLooper);
  689. }
  690. return result;
  691. }
  692. int SensorService::isDataInjectionEnabled() {
  693. Mutex::Autolock _l(mLock);
  694. return (mCurrentOperatingMode == DATA_INJECTION);
  695. }
  696. status_t SensorService::resetToNormalMode() {
  697. Mutex::Autolock _l(mLock);
  698. return resetToNormalModeLocked();
  699. }
  700. status_t SensorService::resetToNormalModeLocked() {
  701. SensorDevice& dev(SensorDevice::getInstance());
  702. dev.enableAllSensors();
  703. status_t err = dev.setMode(NORMAL);
  704. mCurrentOperatingMode = NORMAL;
  705. return err;
  706. }
  707. void SensorService::cleanupConnection(SensorEventConnection* c)
  708. {
  709. Mutex::Autolock _l(mLock);
  710. const wp<SensorEventConnection> connection(c);
  711. size_t size = mActiveSensors.size();
  712. ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
  713. for (size_t i=0 ; i<size ; ) {
  714. int handle = mActiveSensors.keyAt(i);
  715. if (c->hasSensor(handle)) {
  716. ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
  717. SensorInterface* sensor = mSensorMap.valueFor( handle );
  718. ALOGE_IF(!sensor, "mSensorMap[handle=0x%08x] is null!", handle);
  719. if (sensor) {
  720. sensor->activate(c, false);
  721. }
  722. c->removeSensor(handle);
  723. }
  724. SensorRecord* rec = mActiveSensors.valueAt(i);
  725. ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
  726. ALOGD_IF(DEBUG_CONNECTIONS,
  727. "removing connection %p for sensor[%zu].handle=0x%08x",
  728. c, i, handle);
  729. if (rec && rec->removeConnection(connection)) {
  730. ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
  731. mActiveSensors.removeItemsAt(i, 1);
  732. mActiveVirtualSensors.removeItem(handle);
  733. delete rec;
  734. size--;
  735. } else {
  736. i++;
  737. }
  738. }
  739. c->updateLooperRegistration(mLooper);
  740. mActiveConnections.remove(connection);
  741. BatteryService::cleanup(c->getUid());
  742. if (c->needsWakeLock()) {
  743. checkWakeLockStateLocked();
  744. }
  745. }
  746. Sensor SensorService::getSensorFromHandle(int handle) const {
  747. return mSensorMap.valueFor(handle)->getSensor();
  748. }
  749. status_t SensorService::enable(const sp<SensorEventConnection>& connection,
  750. int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
  751. const String16& opPackageName)
  752. {
  753. if (mInitCheck != NO_ERROR)
  754. return mInitCheck;
  755. SensorInterface* sensor = mSensorMap.valueFor(handle);
  756. if (sensor == NULL) {
  757. return BAD_VALUE;
  758. }
  759. if (!canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
  760. return BAD_VALUE;
  761. }
  762. Mutex::Autolock _l(mLock);
  763. if ((mCurrentOperatingMode == RESTRICTED || mCurrentOperatingMode == DATA_INJECTION)
  764. && !isWhiteListedPackage(connection->getPackageName())) {
  765. return INVALID_OPERATION;
  766. }
  767. SensorRecord* rec = mActiveSensors.valueFor(handle);
  768. if (rec == 0) {
  769. rec = new SensorRecord(connection);
  770. mActiveSensors.add(handle, rec);
  771. if (sensor->isVirtual()) {
  772. mActiveVirtualSensors.add(handle, sensor);
  773. }
  774. } else {
  775. if (rec->addConnection(connection)) {
  776. // this sensor is already activated, but we are adding a connection that uses it.
  777. // Immediately send down the last known value of the requested sensor if it's not a
  778. // "continuous" sensor.
  779. if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
  780. // NOTE: The wake_up flag of this event may get set to
  781. // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
  782. CircularBuffer *circular_buf = mLastEventSeen.valueFor(handle);
  783. if (circular_buf) {
  784. sensors_event_t event;
  785. memset(&event, 0, sizeof(event));
  786. // It is unlikely that this buffer is empty as the sensor is already active.
  787. // One possible corner case may be two applications activating an on-change
  788. // sensor at the same time.
  789. if(circular_buf->populateLastEvent(&event)) {
  790. event.sensor = handle;
  791. if (event.version == sizeof(sensors_event_t)) {
  792. if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
  793. setWakeLockAcquiredLocked(true);
  794. }
  795. connection->sendEvents(&event, 1, NULL);
  796. if (!connection->needsWakeLock() && mWakeLockAcquired) {
  797. checkWakeLockStateLocked();
  798. }
  799. }
  800. }
  801. }
  802. }
  803. }
  804. }
  805. if (connection->addSensor(handle)) {
  806. BatteryService::enableSensor(connection->getUid(), handle);
  807. // the sensor was added (which means it wasn't already there)
  808. // so, see if this connection becomes active
  809. if (mActiveConnections.indexOf(connection) < 0) {
  810. mActiveConnections.add(connection);
  811. }
  812. } else {
  813. ALOGW("sensor %08x already enabled in connection %p (ignoring)",
  814. handle, connection.get());
  815. }
  816. nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
  817. if (samplingPeriodNs < minDelayNs) {
  818. samplingPeriodNs = minDelayNs;
  819. }
  820. ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
  821. "rate=%" PRId64 " timeout== %" PRId64"",
  822. handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
  823. status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
  824. maxBatchReportLatencyNs);
  825. // Call flush() before calling activate() on the sensor. Wait for a first
  826. // flush complete event before sending events on this connection. Ignore
  827. // one-shot sensors which don't support flush(). Ignore on-change sensors
  828. // to maintain the on-change logic (any on-change events except the initial
  829. // one should be trigger by a change in value). Also if this sensor isn't
  830. // already active, don't call flush().
  831. const SensorDevice& device(SensorDevice::getInstance());
  832. if (err == NO_ERROR &&
  833. sensor->getSensor().getReportingMode() != AREPORTING_MODE_ONE_SHOT &&
  834. sensor->getSensor().getReportingMode() != AREPORTING_MODE_ON_CHANGE &&
  835. rec->getNumConnections() > 1) {
  836. if (device.getHalDeviceVersion() >= SENSORS_DEVICE_API_VERSION_1_1) {
  837. connection->setFirstFlushPending(handle, true);
  838. status_t err_flush = sensor->flush(connection.get(), handle);
  839. // Flush may return error if the underlying h/w sensor uses an older HAL.
  840. if (err_flush == NO_ERROR) {
  841. rec->addPendingFlushConnection(connection.get());
  842. } else {
  843. connection->setFirstFlushPending(handle, false);
  844. }
  845. }
  846. }
  847. if (err == NO_ERROR) {
  848. ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
  849. err = sensor->activate(connection.get(), true);
  850. }
  851. if (err == NO_ERROR) {
  852. connection->updateLooperRegistration(mLooper);
  853. SensorRegistrationInfo &reg_info =
  854. mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex);
  855. reg_info.mSensorHandle = handle;
  856. reg_info.mSamplingRateUs = samplingPeriodNs/1000;
  857. reg_info.mMaxReportLatencyUs = maxBatchReportLatencyNs/1000;
  858. reg_info.mActivated = true;
  859. reg_info.mPackageName = connection->getPackageName();
  860. time_t rawtime = time(NULL);
  861. struct tm * timeinfo = localtime(&rawtime);
  862. reg_info.mHour = timeinfo->tm_hour;
  863. reg_info.mMin = timeinfo->tm_min;
  864. reg_info.mSec = timeinfo->tm_sec;
  865. mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
  866. }
  867. if (device.getHalDeviceVersion() < SENSORS_DEVICE_API_VERSION_1_1) {
  868. // Pre-1.1 sensor HALs had no flush method, and relied on setDelay at init
  869. sensor->setDelay(connection.get(), handle, samplingPeriodNs);
  870. }
  871. if (err != NO_ERROR) {
  872. // batch/activate has failed, reset our state.
  873. cleanupWithoutDisableLocked(connection, handle);
  874. }
  875. return err;
  876. }
  877. status_t SensorService::disable(const sp<SensorEventConnection>& connection,
  878. int handle)
  879. {
  880. if (mInitCheck != NO_ERROR)
  881. return mInitCheck;
  882. Mutex::Autolock _l(mLock);
  883. status_t err = cleanupWithoutDisableLocked(connection, handle);
  884. if (err == NO_ERROR) {
  885. SensorInterface* sensor = mSensorMap.valueFor(handle);
  886. err = sensor ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
  887. }
  888. if (err == NO_ERROR) {
  889. SensorRegistrationInfo &reg_info =
  890. mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex);
  891. reg_info.mActivated = false;
  892. reg_info.mPackageName= connection->getPackageName();
  893. reg_info.mSensorHandle = handle;
  894. time_t rawtime = time(NULL);
  895. struct tm * timeinfo = localtime(&rawtime);
  896. reg_info.mHour = timeinfo->tm_hour;
  897. reg_info.mMin = timeinfo->tm_min;
  898. reg_info.mSec = timeinfo->tm_sec;
  899. mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
  900. }
  901. return err;
  902. }
  903. status_t SensorService::cleanupWithoutDisable(
  904. const sp<SensorEventConnection>& connection, int handle) {
  905. Mutex::Autolock _l(mLock);
  906. return cleanupWithoutDisableLocked(connection, handle);
  907. }
  908. status_t SensorService::cleanupWithoutDisableLocked(
  909. const sp<SensorEventConnection>& connection, int handle) {
  910. SensorRecord* rec = mActiveSensors.valueFor(handle);
  911. if (rec) {
  912. // see if this connection becomes inactive
  913. if (connection->removeSensor(handle)) {
  914. BatteryService::disableSensor(connection->getUid(), handle);
  915. }
  916. if (connection->hasAnySensor() == false) {
  917. connection->updateLooperRegistration(mLooper);
  918. mActiveConnections.remove(connection);
  919. }
  920. // see if this sensor becomes inactive
  921. if (rec->removeConnection(connection)) {
  922. mActiveSensors.removeItem(handle);
  923. mActiveVirtualSensors.removeItem(handle);
  924. delete rec;
  925. }
  926. return NO_ERROR;
  927. }
  928. return BAD_VALUE;
  929. }
  930. status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
  931. int handle, nsecs_t ns, const String16& opPackageName)
  932. {
  933. if (mInitCheck != NO_ERROR)
  934. return mInitCheck;
  935. SensorInterface* sensor = mSensorMap.valueFor(handle);
  936. if (!sensor)
  937. return BAD_VALUE;
  938. if (!canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
  939. return BAD_VALUE;
  940. }
  941. if (ns < 0)
  942. return BAD_VALUE;
  943. nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
  944. if (ns < minDelayNs) {
  945. ns = minDelayNs;
  946. }
  947. return sensor->setDelay(connection.get(), handle, ns);
  948. }
  949. status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
  950. const String16& opPackageName) {
  951. if (mInitCheck != NO_ERROR) return mInitCheck;
  952. SensorDevice& dev(SensorDevice::getInstance());
  953. const int halVersion = dev.getHalDeviceVersion();
  954. status_t err(NO_ERROR);
  955. Mutex::Autolock _l(mLock);
  956. // Loop through all sensors for this connection and call flush on each of them.
  957. for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
  958. const int handle = connection->mSensorInfo.keyAt(i);
  959. SensorInterface* sensor = mSensorMap.valueFor(handle);
  960. if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
  961. ALOGE("flush called on a one-shot sensor");
  962. err = INVALID_OPERATION;
  963. continue;
  964. }
  965. if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
  966. // For older devices just increment pending flush count which will send a trivial
  967. // flush complete event.
  968. connection->incrementPendingFlushCount(handle);
  969. } else {
  970. if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
  971. err = INVALID_OPERATION;
  972. continue;
  973. }
  974. status_t err_flush = sensor->flush(connection.get(), handle);
  975. if (err_flush == NO_ERROR) {
  976. SensorRecord* rec = mActiveSensors.valueFor(handle);
  977. if (rec != NULL) rec->addPendingFlushConnection(connection);
  978. }
  979. err = (err_flush != NO_ERROR) ? err_flush : err;
  980. }
  981. }
  982. return err;
  983. }
  984. bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
  985. const String16& opPackageName) {
  986. const String8& requiredPermission = sensor.getRequiredPermission();
  987. if (requiredPermission.length() <= 0) {
  988. return true;
  989. }
  990. bool hasPermission = false;
  991. // Runtime permissions can't use the cache as they may change.
  992. if (sensor.isRequiredPermissionRuntime()) {
  993. hasPermission = checkPermission(String16(requiredPermission),
  994. IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
  995. } else {
  996. hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
  997. }
  998. if (!hasPermission) {
  999. ALOGE("%s a sensor (%s) without holding its required permission: %s",
  1000. operation, sensor.getName().string(), sensor.getRequiredPermission().string());
  1001. return false;
  1002. }
  1003. const int32_t opCode = sensor.getRequiredAppOp();
  1004. if (opCode >= 0) {
  1005. AppOpsManager appOps;
  1006. if (appOps.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName)
  1007. != AppOpsManager::MODE_ALLOWED) {
  1008. ALOGE("%s a sensor (%s) without enabled required app op: %d",
  1009. operation, sensor.getName().string(), opCode);
  1010. return false;
  1011. }
  1012. }
  1013. return true;
  1014. }
  1015. void SensorService::checkWakeLockState() {
  1016. Mutex::Autolock _l(mLock);
  1017. checkWakeLockStateLocked();
  1018. }
  1019. void SensorService::checkWakeLockStateLocked() {
  1020. if (!mWakeLockAcquired) {
  1021. return;
  1022. }
  1023. bool releaseLock = true;
  1024. for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
  1025. sp<SensorEventConnection> connection(mActiveConnections[i].promote());
  1026. if (connection != 0) {
  1027. if (connection->needsWakeLock()) {
  1028. releaseLock = false;
  1029. break;
  1030. }
  1031. }
  1032. }
  1033. if (releaseLock) {
  1034. setWakeLockAcquiredLocked(false);
  1035. }
  1036. }
  1037. void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
  1038. Mutex::Autolock _l(mLock);
  1039. connection->writeToSocketFromCache();
  1040. if (connection->needsWakeLock()) {
  1041. setWakeLockAcquiredLocked(true);
  1042. }
  1043. }
  1044. void SensorService::populateActiveConnections(
  1045. SortedVector< sp<SensorEventConnection> >* activeConnections) {
  1046. Mutex::Autolock _l(mLock);
  1047. for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
  1048. sp<SensorEventConnection> connection(mActiveConnections[i].promote());
  1049. if (connection != 0) {
  1050. activeConnections->add(connection);
  1051. }
  1052. }
  1053. }
  1054. bool SensorService::isWhiteListedPackage(const String8& packageName) {
  1055. return (packageName.contains(mWhiteListedPackage.string()));
  1056. }
  1057. int SensorService::getNumEventsForSensorType(int sensor_event_type) {
  1058. switch (sensor_event_type) {
  1059. case SENSOR_TYPE_ROTATION_VECTOR:
  1060. case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
  1061. return 5;
  1062. case SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED:
  1063. case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
  1064. return 6;
  1065. case SENSOR_TYPE_GAME_ROTATION_VECTOR:
  1066. return 4;
  1067. case SENSOR_TYPE_SIGNIFICANT_MOTION:
  1068. case SENSOR_TYPE_STEP_DETECTOR:
  1069. case SENSOR_TYPE_STEP_COUNTER:
  1070. return 1;
  1071. default:
  1072. return 3;
  1073. }
  1074. }
  1075. // ---------------------------------------------------------------------------
  1076. SensorService::SensorRecord::SensorRecord(
  1077. const sp<SensorEventConnection>& connection)
  1078. {
  1079. mConnections.add(connection);
  1080. }
  1081. bool SensorService::SensorRecord::addConnection(
  1082. const sp<SensorEventConnection>& connection)
  1083. {
  1084. if (mConnections.indexOf(connection) < 0) {
  1085. mConnections.add(connection);
  1086. return true;
  1087. }
  1088. return false;
  1089. }
  1090. bool SensorService::SensorRecord::removeConnection(
  1091. const wp<SensorEventConnection>& connection)
  1092. {
  1093. ssize_t index = mConnections.indexOf(connection);
  1094. if (index >= 0) {
  1095. mConnections.removeItemsAt(index, 1);
  1096. }
  1097. // Remove this connections from the queue of flush() calls made on this sensor.
  1098. for (Vector< wp<SensorEventConnection> >::iterator it =
  1099. mPendingFlushConnections.begin(); it != mPendingFlushConnections.end();) {
  1100. if (it->unsafe_get() == connection.unsafe_get()) {
  1101. it = mPendingFlushConnections.erase(it);
  1102. } else {
  1103. ++it;
  1104. }
  1105. }
  1106. return mConnections.size() ? false : true;
  1107. }
  1108. void SensorService::SensorRecord::addPendingFlushConnection(
  1109. const sp<SensorEventConnection>& connection) {
  1110. mPendingFlushConnections.add(connection);
  1111. }
  1112. void SensorService::SensorRecord::removeFirstPendingFlushConnection() {
  1113. if (mPendingFlushConnections.size() > 0) {
  1114. mPendingFlushConnections.removeAt(0);
  1115. }
  1116. }
  1117. SensorService::SensorEventConnection *
  1118. SensorService::SensorRecord::getFirstPendingFlushConnection() {
  1119. if (mPendingFlushConnections.size() > 0) {
  1120. return mPendingFlushConnections[0].unsafe_get();
  1121. }
  1122. return NULL;
  1123. }
  1124. void SensorService::SensorRecord::clearAllPendingFlushConnections() {
  1125. mPendingFlushConnections.clear();
  1126. }
  1127. // ---------------------------------------------------------------------------
  1128. SensorService::TrimmedSensorEvent::TrimmedSensorEvent(int sensorType) {
  1129. mTimestamp = -1;
  1130. const int numData = SensorService::getNumEventsForSensorType(sensorType);
  1131. if (sensorType == SENSOR_TYPE_STEP_COUNTER) {
  1132. mStepCounter = 0;
  1133. } else {
  1134. mData = new float[numData];
  1135. for (int i = 0; i < numData; ++i) {
  1136. mData[i] = -1.0;
  1137. }
  1138. }
  1139. mHour = mMin = mSec = INT32_MIN;
  1140. }
  1141. bool SensorService::TrimmedSensorEvent::isSentinel(const TrimmedSensorEvent& event) {
  1142. return (event.mHour == INT32_MIN && event.mMin == INT32_MIN && event.mSec == INT32_MIN);
  1143. }
  1144. // --------------------------------------------------------------------------
  1145. SensorService::CircularBuffer::CircularBuffer(int sensor_event_type) {
  1146. mNextInd = 0;
  1147. mBufSize = CIRCULAR_BUF_SIZE;
  1148. if (sensor_event_type == SENSOR_TYPE_STEP_COUNTER ||
  1149. sensor_event_type == SENSOR_TYPE_SIGNIFICANT_MOTION ||
  1150. sensor_event_type == SENSOR_TYPE_ACCELEROMETER) {
  1151. mBufSize = CIRCULAR_BUF_SIZE * 5;
  1152. }
  1153. mTrimmedSensorEventArr = new TrimmedSensorEvent *[mBufSize];
  1154. mSensorType = sensor_event_type;
  1155. for (int i = 0; i < mBufSize; ++i) {
  1156. mTrimmedSensorEventArr[i] = new TrimmedSensorEvent(mSensorType);
  1157. }
  1158. }
  1159. void SensorService::CircularBuffer::addEvent(const sensors_event_t& sensor_event) {
  1160. TrimmedSensorEvent *curr_event = mTrimmedSensorEventArr[mNextInd];
  1161. curr_event->mTimestamp = sensor_event.timestamp;
  1162. if (mSensorType == SENSOR_TYPE_STEP_COUNTER) {
  1163. curr_event->mStepCounter = sensor_event.u64.step_counter;
  1164. } else {
  1165. memcpy(curr_event->mData, sensor_event.data,
  1166. sizeof(float) * SensorService::getNumEventsForSensorType(mSensorType));
  1167. }
  1168. time_t rawtime = time(NULL);
  1169. struct tm * timeinfo = localtime(&rawtime);
  1170. curr_event->mHour = timeinfo->tm_hour;
  1171. curr_event->mMin = timeinfo->tm_min;
  1172. curr_event->mSec = timeinfo->tm_sec;
  1173. mNextInd = (mNextInd + 1) % mBufSize;
  1174. }
  1175. void SensorService::CircularBuffer::printBuffer(String8& result) const {
  1176. const int numData = SensorService::getNumEventsForSensorType(mSensorType);
  1177. int i = mNextInd, eventNum = 1;
  1178. result.appendFormat("last %d events = < ", mBufSize);
  1179. do {
  1180. if (TrimmedSensorEvent::isSentinel(*mTrimmedSensorEventArr[i])) {
  1181. // Sentinel, ignore.
  1182. i = (i + 1) % mBufSize;
  1183. continue;
  1184. }
  1185. result.appendFormat("%d) ", eventNum++);
  1186. if (mSensorType == SENSOR_TYPE_STEP_COUNTER) {
  1187. result.appendFormat("%llu,", mTrimmedSensorEventArr[i]->mStepCounter);
  1188. } else {
  1189. for (int j = 0; j < numData; ++j) {
  1190. result.appendFormat("%5.1f,", mTrimmedSensorEventArr[i]->mData[j]);
  1191. }
  1192. }
  1193. result.appendFormat("%lld %02d:%02d:%02d ", mTrimmedSensorEventArr[i]->mTimestamp,
  1194. mTrimmedSensorEventArr[i]->mHour, mTrimmedSensorEventArr[i]->mMin,
  1195. mTrimmedSensorEventArr[i]->mSec);
  1196. i = (i + 1) % mBufSize;
  1197. } while (i != mNextInd);
  1198. result.appendFormat(">\n");
  1199. }
  1200. bool SensorService::CircularBuffer::populateLastEvent(sensors_event_t *event) {
  1201. int lastEventInd = (mNextInd - 1 + mBufSize) % mBufSize;
  1202. // Check if the buffer is empty.
  1203. if (TrimmedSensorEvent::isSentinel(*mTrimmedSensorEventArr[lastEventInd])) {
  1204. return false;
  1205. }
  1206. event->version = sizeof(sensors_event_t);
  1207. event->type = mSensorType;
  1208. event->timestamp = mTrimmedSensorEventArr[lastEventInd]->mTimestamp;
  1209. if (mSensorType == SENSOR_TYPE_STEP_COUNTER) {
  1210. event->u64.step_counter = mTrimmedSensorEventArr[lastEventInd]->mStepCounter;
  1211. } else {
  1212. memcpy(event->data, mTrimmedSensorEventArr[lastEventInd]->mData,
  1213. sizeof(float) * SensorService::getNumEventsForSensorType(mSensorType));
  1214. }
  1215. return true;
  1216. }
  1217. SensorService::CircularBuffer::~CircularBuffer() {
  1218. for (int i = 0; i < mBufSize; ++i) {
  1219. delete mTrimmedSensorEventArr[i];
  1220. }
  1221. delete [] mTrimmedSensorEventArr;
  1222. }
  1223. // ---------------------------------------------------------------------------
  1224. SensorService::SensorEventConnection::SensorEventConnection(
  1225. const sp<SensorService>& service, uid_t uid, String8 packageName, bool isDataInjectionMode,
  1226. const String16& opPackageName)
  1227. : mService(service), mUid(uid), mWakeLockRefCount(0), mHasLooperCallbacks(false),
  1228. mDead(false), mDataInjectionMode(isDataInjectionMode), mEventCache(NULL),
  1229. mCacheSize(0), mMaxCacheSize(0), mPackageName(packageName), mOpPackageName(opPackageName) {
  1230. mChannel = new BitTube(mService->mSocketBufferSize);
  1231. #if DEBUG_CONNECTIONS
  1232. mEventsReceived = mEventsSentFromCache = mEventsSent = 0;
  1233. mTotalAcksNeeded = mTotalAcksReceived = 0;
  1234. #endif
  1235. }
  1236. SensorService::SensorEventConnection::~SensorEventConnection() {
  1237. ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this);
  1238. mService->cleanupConnection(this);
  1239. if (mEventCache != NULL) {
  1240. delete mEventCache;
  1241. }
  1242. }
  1243. void SensorService::SensorEventConnection::onFirstRef() {
  1244. LooperCallback::onFirstRef();
  1245. }
  1246. bool SensorService::SensorEventConnection::needsWakeLock() {
  1247. Mutex::Autolock _l(mConnectionLock);
  1248. return !mDead && mWakeLockRefCount > 0;
  1249. }
  1250. void SensorService::SensorEventConnection::resetWakeLockRefCount() {
  1251. Mutex::Autolock _l(mConnectionLock);
  1252. mWakeLockRefCount = 0;
  1253. }
  1254. void SensorService::SensorEventConnection::dump(String8& result) {
  1255. Mutex::Autolock _l(mConnectionLock);
  1256. result.appendFormat("\tOperating Mode: %s\n",mDataInjectionMode ? "DATA_INJECTION" : "NORMAL");
  1257. result.appendFormat("\t %s | WakeLockRefCount %d | uid %d | cache size %d | "
  1258. "max cache size %d\n", mPackageName.string(), mWakeLockRefCount, mUid, mCacheSize,
  1259. mMaxCacheSize);
  1260. for (size_t i = 0; i < mSensorInfo.size(); ++i) {
  1261. const FlushInfo& flushInfo = mSensorInfo.valueAt(i);
  1262. result.appendFormat("\t %s 0x%08x | status: %s | pending flush events %d \n",
  1263. mService->getSensorName(mSensorInfo.keyAt(i)).string(),
  1264. mSensorInfo.keyAt(i),
  1265. flushInfo.mFirstFlushPending ? "First flush pending" :
  1266. "active",
  1267. flushInfo.mPendingFlushEventsToSend);
  1268. }
  1269. #if DEBUG_CONNECTIONS
  1270. result.appendFormat("\t events recvd: %d | sent %d | cache %d | dropped %d |"
  1271. " total_acks_needed %d | total_acks_recvd %d\n",
  1272. mEventsReceived,
  1273. mEventsSent,
  1274. mEventsSentFromCache,
  1275. mEventsReceived - (mEventsSentFromCache + mEventsSent + mCacheSize),
  1276. mTotalAcksNeeded,
  1277. mTotalAcksReceived);
  1278. #endif
  1279. }
  1280. bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
  1281. Mutex::Autolock _l(mConnectionLock);
  1282. if (!canAccessSensor(mService->getSensorFromHandle(handle),
  1283. "Tried adding", mOpPackageName)) {
  1284. return false;
  1285. }
  1286. if (mSensorInfo.indexOfKey(handle) < 0) {
  1287. mSensorInfo.add(handle, FlushInfo());
  1288. return true;
  1289. }
  1290. return false;
  1291. }
  1292. bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
  1293. Mutex::Autolock _l(mConnectionLock);
  1294. if (mSensorInfo.removeItem(handle) >= 0) {
  1295. return true;
  1296. }
  1297. return false;
  1298. }
  1299. bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
  1300. Mutex::Autolock _l(mConnectionLock);
  1301. return mSensorInfo.indexOfKey(handle) >= 0;
  1302. }
  1303. bool SensorService::SensorEventConnection::hasAnySensor() const {
  1304. Mutex::Autolock _l(mConnectionLock);
  1305. return mSensorInfo.size() ? true : false;
  1306. }
  1307. bool SensorService::SensorEventConnection::hasOneShotSensors() const {
  1308. Mutex::Autolock _l(mConnectionLock);
  1309. for (size_t i = 0; i < mSensorInfo.size(); ++i) {
  1310. const int handle = mSensorInfo.keyAt(i);
  1311. if (mService->getSensorFromHandle(handle).getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
  1312. return true;
  1313. }
  1314. }
  1315. return false;
  1316. }
  1317. String8 SensorService::SensorEventConnection::getPackageName() const {
  1318. return mPackageName;
  1319. }
  1320. void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle,
  1321. bool value) {
  1322. Mutex::Autolock _l(mConnectionLock);
  1323. ssize_t index = mSensorInfo.indexOfKey(handle);
  1324. if (index >= 0) {
  1325. FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
  1326. flushInfo.mFirstFlushPending = value;
  1327. }
  1328. }
  1329. void SensorService::SensorEventConnection::updateLooperRegistration(const sp<Looper>& looper) {
  1330. Mutex::Autolock _l(mConnectionLock);
  1331. updateLooperRegistrationLocked(looper);
  1332. }
  1333. void SensorService::SensorEventConnection::updateLooperRegistrationLocked(
  1334. const sp<Looper>& looper) {
  1335. bool isConnectionActive = (mSensorInfo.size() > 0 && !mDataInjectionMode) ||
  1336. mDataInjectionMode;
  1337. // If all sensors are unregistered OR Looper has encountered an error, we
  1338. // can remove the Fd from the Looper if it has been previously added.
  1339. if (!isConnectionActive || mDead) {
  1340. if (mHasLooperCallbacks) {
  1341. ALOGD_IF(DEBUG_CONNECTIONS, "%p removeFd fd=%d", this, mChannel->getSendFd());
  1342. looper->removeFd(mChannel->getSendFd());
  1343. mHasLooperCallbacks = false;
  1344. }
  1345. return;
  1346. }
  1347. int looper_flags = 0;
  1348. if (mCacheSize > 0) looper_flags |= ALOOPER_EVENT_OUTPUT;
  1349. if (mDataInjectionMode) looper_flags |= ALOOPER_EVENT_INPUT;
  1350. for (size_t i = 0; i < mSensorInfo.size(); ++i) {
  1351. const int handle = mSensorInfo.keyAt(i);
  1352. if (mService->getSensorFromHandle(handle).isWakeUpSensor()) {
  1353. looper_flags |= ALOOPER_EVENT_INPUT;
  1354. break;
  1355. }
  1356. }
  1357. // If flags is still set to zero, we don't need to add this fd to the Looper, if
  1358. // the fd has already been added, remove it. This is likely to happen when ALL the
  1359. // events stored in the cache have been sent to the corresponding app.
  1360. if (looper_flags == 0) {
  1361. if (mHasLooperCallbacks) {
  1362. ALOGD_IF(DEBUG_CONNECTIONS, "removeFd fd=%d", mChannel->getSendFd());
  1363. looper->removeFd(mChannel->getSendFd());
  1364. mHasLooperCallbacks = false;
  1365. }
  1366. return;
  1367. }
  1368. // Add the file descriptor to the Looper for receiving acknowledegments if the app has
  1369. // registered for wake-up sensors OR for sending events in the cache.
  1370. int ret = looper->addFd(mChannel->getSendFd(), 0, looper_flags, this, NULL);
  1371. if (ret == 1) {
  1372. ALOGD_IF(DEBUG_CONNECTIONS, "%p addFd fd=%d", this, mChannel->getSendFd());
  1373. mHasLooperCallbacks = true;
  1374. } else {
  1375. ALOGE("Looper::addFd failed ret=%d fd=%d", ret, mChannel->getSendFd());
  1376. }
  1377. }
  1378. void SensorService::SensorEventConnection::incrementPendingFlushCount(int32_t handle) {
  1379. Mutex::Autolock _l(mConnectionLock);
  1380. ssize_t index = mSensorInfo.indexOfKey(handle);
  1381. if (index >= 0) {
  1382. FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
  1383. flushInfo.mPendingFlushEventsToSend++;
  1384. }
  1385. }
  1386. status_t SensorService::SensorEventConnection::sendEvents(
  1387. sensors_event_t const* buffer, size_t numEvents,
  1388. sensors_event_t* scratch,
  1389. SensorEventConnection const * const * mapFlushEventsToConnections) {
  1390. // filter out events not for this connection
  1391. int count = 0;
  1392. Mutex::Autolock _l(mConnectionLock);
  1393. if (scratch) {
  1394. size_t i=0;
  1395. while (i<numEvents) {
  1396. int32_t sensor_handle = buffer[i].sensor;
  1397. if (buffer[i].type == SENSOR_TYPE_META_DATA) {
  1398. ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ",
  1399. buffer[i].meta_data.sensor);
  1400. // Setting sensor_handle to the correct sensor to ensure the sensor events per
  1401. // connection are filtered correctly. buffer[i].sensor is zero for meta_data
  1402. // events.
  1403. sensor_handle = buffer[i].meta_data.sensor;
  1404. }
  1405. ssize_t index = mSensorInfo.indexOfKey(sensor_handle);
  1406. // Check if this connection has registered for this sensor. If not continue to the
  1407. // next sensor_event.
  1408. if (index < 0) {
  1409. ++i;
  1410. continue;
  1411. }
  1412. FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
  1413. // Check if there is a pending flush_complete event for this sensor on this connection.
  1414. if (buffer[i].type == SENSOR_TYPE_META_DATA && flushInfo.mFirstFlushPending == true &&
  1415. this == mapFlushEventsToConnections[i]) {
  1416. flushInfo.mFirstFlushPending = false;
  1417. ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ",
  1418. buffer[i].meta_data.sensor);
  1419. ++i;
  1420. continue;
  1421. }
  1422. // If there is a pending flush complete event for this sensor on this connection,
  1423. // ignore the event and proceed to the next.
  1424. if (flushInfo.mFirstFlushPending) {
  1425. ++i;
  1426. continue;
  1427. }
  1428. do {
  1429. // Keep copying events into the scratch buffer as long as they are regular
  1430. // sensor_events are from the same sensor_handle OR they are flush_complete_events
  1431. // from the same sensor_handle AND the current connection is mapped to the
  1432. // corresponding flush_complete_event.
  1433. if (buffer[i].type == SENSOR_TYPE_META_DATA) {
  1434. if (this == mapFlushEventsToConnections[i]) {
  1435. scratch[count++] = buffer[i];
  1436. }
  1437. ++i;
  1438. } else {
  1439. // Regular sensor event, just copy it to the scratch buffer.
  1440. scratch[count++] = buffer[i++];
  1441. }
  1442. } while ((i<numEvents) && ((buffer[i].sensor == sensor_handle &&
  1443. buffer[i].type != SENSOR_TYPE_META_DATA) ||
  1444. (buffer[i].type == SENSOR_TYPE_META_DATA &&
  1445. buffer[i].meta_data.sensor == sensor_handle)));
  1446. }
  1447. } else {
  1448. scratch = const_cast<sensors_event_t *>(buffer);
  1449. count = numEvents;
  1450. }
  1451. sendPendingFlushEventsLocked();
  1452. // Early return if there are no events for this connection.
  1453. if (count == 0) {
  1454. return status_t(NO_ERROR);
  1455. }
  1456. #if DEBUG_CONNECTIONS
  1457. mEventsReceived += count;
  1458. #endif
  1459. if (mCacheSize != 0) {
  1460. // There are some events in the cache which need to be sent first. Copy this buffer to
  1461. // the end of cache.
  1462. if (mCacheSize + count <= mMaxCacheSize) {
  1463. memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
  1464. mCacheSize += count;
  1465. } else {
  1466. // Check if any new sensors have registered on this connection which may have increased
  1467. // the max cache size that is desired.
  1468. if (mCacheSize + count < computeMaxCacheSizeLocked()) {
  1469. reAllocateCacheLocked(scratch, count);
  1470. return status_t(NO_ERROR);
  1471. }
  1472. // Some events need to be dropped.
  1473. int remaningCacheSize = mMaxCacheSize - mCacheSize;
  1474. if (remaningCacheSize != 0) {
  1475. memcpy(&mEventCache[mCacheSize], scratch,
  1476. remaningCacheSize * sizeof(sensors_event_t));
  1477. }
  1478. int numEventsDropped = count - remaningCacheSize;
  1479. countFlushCompleteEventsLocked(mEventCache, numEventsDropped);
  1480. // Drop the first "numEventsDropped" in the cache.
  1481. memmove(mEventCache, &mEventCache[numEventsDropped],
  1482. (mCacheSize - numEventsDropped) * sizeof(sensors_event_t));
  1483. // Copy the remainingEvents in scratch buffer to the end of cache.
  1484. memcpy(&mEventCache[mCacheSize - numEventsDropped], scratch + remaningCacheSize,
  1485. numEventsDropped * sizeof(sensors_event_t));
  1486. }
  1487. return status_t(NO_ERROR);
  1488. }
  1489. int index_wake_up_event = findWakeUpSensorEventLocked(scratch, count);
  1490. if (index_wake_up_event >= 0) {
  1491. scratch[index_wake_up_event].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
  1492. ++mWakeLockRefCount;
  1493. #if DEBUG_CONNECTIONS
  1494. ++mTotalAcksNeeded;
  1495. #endif
  1496. }
  1497. // NOTE: ASensorEvent and sensors_event_t are the same type.
  1498. ssize_t size = SensorEventQueue::write(mChannel,
  1499. reinterpret_cast<ASensorEvent const*>(scratch), count);
  1500. if (size < 0) {
  1501. // Write error, copy events to local cache.
  1502. if (index_wake_up_event >= 0) {
  1503. // If there was a wake_up sensor_event, reset the flag.
  1504. scratch[index_wake_up_event].flags &= ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
  1505. if (mWakeLockRefCount > 0) {
  1506. --mWakeLockRefCount;
  1507. }
  1508. #if DEBUG_CONNECTIONS
  1509. --mTotalAcksNeeded;
  1510. #endif
  1511. }
  1512. if (mEventCache == NULL) {
  1513. mMaxCacheSize = computeMaxCacheSizeLocked();
  1514. mEventCache = new sensors_event_t[mMaxCacheSize];
  1515. mCacheSize = 0;
  1516. }
  1517. memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
  1518. mCacheSize += count;
  1519. // Add this file descriptor to the looper to get a callback when this fd is available for
  1520. // writing.
  1521. updateLooperRegistrationLocked(mService->getLooper());
  1522. return size;
  1523. }
  1524. #if DEBUG_CONNECTIONS
  1525. if (size > 0) {
  1526. mEventsSent += count;
  1527. }
  1528. #endif
  1529. return size < 0 ? status_t(size) : status_t(NO_ERROR);
  1530. }
  1531. void SensorService::SensorEventConnection::reAllocateCacheLocked(sensors_event_t const* scratch,
  1532. int count) {
  1533. sensors_event_t *eventCache_new;
  1534. const int new_cache_size = computeMaxCacheSizeLocked();
  1535. // Allocate new cache, copy over events from the old cache & scratch, free up memory.
  1536. eventCache_new = new sensors_event_t[new_cache_size];
  1537. memcpy(eventCache_new, mEventCache, mCacheSize * sizeof(sensors_event_t));
  1538. memcpy(&eventCache_new[mCacheSize], scratch, count * sizeof(sensors_event_t));
  1539. ALOGD_IF(DEBUG_CONNECTIONS, "reAllocateCacheLocked maxCacheSize=%d %d", mMaxCacheSize,
  1540. new_cache_size);
  1541. delete mEventCache;
  1542. mEventCache = eventCache_new;
  1543. mCacheSize += count;
  1544. mMaxCacheSize = new_cache_size;
  1545. }
  1546. void SensorService::SensorEventConnection::sendPendingFlushEventsLocked() {
  1547. ASensorEvent flushCompleteEvent;
  1548. memset(&flushCompleteEvent, 0, sizeof(flushCompleteEvent));
  1549. flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
  1550. // Loop through all the sensors for this connection and check if there are any pending
  1551. // flush complete events to be sent.
  1552. for (size_t i = 0; i < mSensorInfo.size(); ++i) {
  1553. FlushInfo& flushInfo = mSensorInfo.editValueAt(i);
  1554. while (flushInfo.mPendingFlushEventsToSend > 0) {
  1555. const int sensor_handle = mSensorInfo.keyAt(i);
  1556. flushCompleteEvent.meta_data.sensor = sensor_handle;
  1557. bool wakeUpSensor = mService->getSensorFromHandle(sensor_handle).isWakeUpSensor();
  1558. if (wakeUpSensor) {
  1559. ++mWakeLockRefCount;
  1560. flushCompleteEvent.flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
  1561. }
  1562. ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
  1563. if (size < 0) {
  1564. if (wakeUpSensor) --mWakeLockRefCount;
  1565. return;
  1566. }
  1567. ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
  1568. flushCompleteEvent.meta_data.sensor);
  1569. flushInfo.mPendingFlushEventsToSend--;
  1570. }
  1571. }
  1572. }
  1573. void SensorService::SensorEventConnection::writeToSocketFromCache() {
  1574. // At a time write at most half the size of the receiver buffer in SensorEventQueue OR
  1575. // half the size of the socket buffer allocated in BitTube whichever is smaller.
  1576. const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
  1577. int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
  1578. Mutex::Autolock _l(mConnectionLock);
  1579. // Send pending flush complete events (if any)
  1580. sendPendingFlushEventsLocked();
  1581. for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
  1582. const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize);
  1583. int index_wake_up_event =
  1584. findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite);
  1585. if (index_wake_up_event >= 0) {
  1586. mEventCache[index_wake_up_event + numEventsSent].flags |=
  1587. WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
  1588. ++mWakeLockRefCount;
  1589. #if DEBUG_CONNECTIONS
  1590. ++mTotalAcksNeeded;
  1591. #endif
  1592. }
  1593. ssize_t size = SensorEventQueue::write(mChannel,
  1594. reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent),
  1595. numEventsToWrite);
  1596. if (size < 0) {
  1597. if (index_wake_up_event >= 0) {
  1598. // If there was a wake_up sensor_event, reset the flag.
  1599. mEventCache[index_wake_up_event + numEventsSent].flags &=
  1600. ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
  1601. if (mWakeLockRefCount > 0) {
  1602. --mWakeLockRefCount;
  1603. }
  1604. #if DEBUG_CONNECTIONS
  1605. --mTotalAcksNeeded;
  1606. #endif
  1607. }
  1608. memmove(mEventCache, &mEventCache[numEventsSent],
  1609. (mCacheSize - numEventsSent) * sizeof(sensors_event_t));
  1610. ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ",
  1611. numEventsSent, mCacheSize);
  1612. mCacheSize -= numEventsSent;
  1613. return;
  1614. }
  1615. numEventsSent += numEventsToWrite;
  1616. #if DEBUG_CONNECTIONS
  1617. mEventsSentFromCache += numEventsToWrite;
  1618. #endif
  1619. }
  1620. ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize);
  1621. // All events from the cache have been sent. Reset cache size to zero.
  1622. mCacheSize = 0;
  1623. // There are no more events in the cache. We don't need to poll for write on the fd.
  1624. // Update Looper registration.
  1625. updateLooperRegistrationLocked(mService->getLooper());
  1626. }
  1627. void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
  1628. sensors_event_t const* scratch, const int numEventsDropped) {
  1629. ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
  1630. // Count flushComplete events in the events that are about to the dropped. These will be sent
  1631. // separately before the next batch of events.
  1632. for (int j = 0; j < numEventsDropped; ++j) {
  1633. if (scratch[j].type == SENSOR_TYPE_META_DATA) {
  1634. FlushInfo& flushInfo = mSensorInfo.editValueFor(scratch[j].meta_data.sensor);
  1635. flushInfo.mPendingFlushEventsToSend++;
  1636. ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
  1637. flushInfo.mPendingFlushEventsToSend);
  1638. }
  1639. }
  1640. return;
  1641. }
  1642. int SensorService::SensorEventConnection::findWakeUpSensorEventLocked(
  1643. sensors_event_t const* scratch, const int count) {
  1644. for (int i = 0; i < count; ++i) {
  1645. if (mService->isWakeUpSensorEvent(scratch[i])) {
  1646. return i;
  1647. }
  1648. }
  1649. return -1;
  1650. }
  1651. sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
  1652. {
  1653. return mChannel;
  1654. }
  1655. status_t SensorService::SensorEventConnection::enableDisable(
  1656. int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
  1657. int reservedFlags)
  1658. {
  1659. status_t err;
  1660. if (enabled) {
  1661. err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
  1662. reservedFlags, mOpPackageName);
  1663. } else {
  1664. err = mService->disable(this, handle);
  1665. }
  1666. return err;
  1667. }
  1668. status_t SensorService::SensorEventConnection::setEventRate(
  1669. int handle, nsecs_t samplingPeriodNs)
  1670. {
  1671. return mService->setEventRate(this, handle, samplingPeriodNs, mOpPackageName);
  1672. }
  1673. status_t SensorService::SensorEventConnection::flush() {
  1674. return mService->flushSensor(this, mOpPackageName);
  1675. }
  1676. int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* /*data*/) {
  1677. if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) {
  1678. {
  1679. // If the Looper encounters some error, set the flag mDead, reset mWakeLockRefCount,
  1680. // and remove the fd from Looper. Call checkWakeLockState to know if SensorService
  1681. // can release the wake-lock.
  1682. ALOGD_IF(DEBUG_CONNECTIONS, "%p Looper error %d", this, fd);
  1683. Mutex::Autolock _l(mConnectionLock);
  1684. mDead = true;
  1685. mWakeLockRefCount = 0;
  1686. updateLooperRegistrationLocked(mService->getLooper());
  1687. }
  1688. mService->checkWakeLockState();
  1689. if (mDataInjectionMode) {
  1690. // If the Looper has encountered some error in data injection mode, reset SensorService
  1691. // back to normal mode.
  1692. mService->resetToNormalMode();
  1693. mDataInjectionMode = false;
  1694. }
  1695. return 1;
  1696. }
  1697. if (events & ALOOPER_EVENT_INPUT) {
  1698. unsigned char buf[sizeof(sensors_event_t)];
  1699. ssize_t numBytesRead = ::recv(fd, buf, sizeof(buf), MSG_DONTWAIT);
  1700. {
  1701. Mutex::Autolock _l(mConnectionLock);
  1702. if (numBytesRead == sizeof(sensors_event_t)) {
  1703. if (!mDataInjectionMode) {
  1704. ALOGE("Data injected in normal mode, dropping event"
  1705. "package=%s uid=%d", mPackageName.string(), mUid);
  1706. // Unregister call backs.
  1707. return 0;
  1708. }
  1709. SensorDevice& dev(SensorDevice::getInstance());
  1710. sensors_event_t sensor_event;
  1711. memset(&sensor_event, 0, sizeof(sensor_event));
  1712. memcpy(&sensor_event, buf, sizeof(sensors_event_t));
  1713. Sensor sensor = mService->getSensorFromHandle(sensor_event.sensor);
  1714. sensor_event.type = sensor.getType();
  1715. dev.injectSensorData(&sensor_event);
  1716. #if DEBUG_CONNECTIONS
  1717. ++mEventsReceived;
  1718. #endif
  1719. } else if (numBytesRead == sizeof(uint32_t)) {
  1720. uint32_t numAcks = 0;
  1721. memcpy(&numAcks, buf, numBytesRead);
  1722. // Sanity check to ensure there are no read errors in recv, numAcks is always
  1723. // within the range and not zero. If any of the above don't hold reset
  1724. // mWakeLockRefCount to zero.
  1725. if (numAcks > 0 && numAcks < mWakeLockRefCount) {
  1726. mWakeLockRefCount -= numAcks;
  1727. } else {
  1728. mWakeLockRefCount = 0;
  1729. }
  1730. #if DEBUG_CONNECTIONS
  1731. mTotalAcksReceived += numAcks;
  1732. #endif
  1733. } else {
  1734. // Read error, reset wakelock refcount.
  1735. mWakeLockRefCount = 0;
  1736. }
  1737. }
  1738. // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released
  1739. // here as checkWakeLockState() will need it.
  1740. if (mWakeLockRefCount == 0) {
  1741. mService->checkWakeLockState();
  1742. }
  1743. // continue getting callbacks.
  1744. return 1;
  1745. }
  1746. if (events & ALOOPER_EVENT_OUTPUT) {
  1747. // send sensor data that is stored in mEventCache for this connection.
  1748. mService->sendEventsFromCache(this);
  1749. }
  1750. return 1;
  1751. }
  1752. int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
  1753. size_t fifoWakeUpSensors = 0;
  1754. size_t fifoNonWakeUpSensors = 0;
  1755. for (size_t i = 0; i < mSensorInfo.size(); ++i) {
  1756. const Sensor& sensor = mService->getSensorFromHandle(mSensorInfo.keyAt(i));
  1757. if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) {
  1758. // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and
  1759. // non wake_up sensors.
  1760. if (sensor.isWakeUpSensor()) {
  1761. fifoWakeUpSensors += sensor.getFifoReservedEventCount();
  1762. } else {
  1763. fifoNonWakeUpSensors += sensor.getFifoReservedEventCount();
  1764. }
  1765. } else {
  1766. // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors.
  1767. if (sensor.isWakeUpSensor()) {
  1768. fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ?
  1769. fifoWakeUpSensors : sensor.getFifoMaxEventCount();
  1770. } else {
  1771. fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ?
  1772. fifoNonWakeUpSensors : sensor.getFifoMaxEventCount();
  1773. }
  1774. }
  1775. }
  1776. if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) {
  1777. // It is extremely unlikely that there is a write failure in non batch mode. Return a cache
  1778. // size that is equal to that of the batch mode.
  1779. // ALOGW("Write failure in non-batch mode");
  1780. return MAX_SOCKET_BUFFER_SIZE_BATCHED/sizeof(sensors_event_t);
  1781. }
  1782. return fifoWakeUpSensors + fifoNonWakeUpSensors;
  1783. }
  1784. // ---------------------------------------------------------------------------
  1785. }; // namespace android