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 
17 #ifndef ANDROID_SENSOR_DEVICE_H
18 #define ANDROID_SENSOR_DEVICE_H
19 
20 #include "SensorDeviceUtils.h"
21 #include "SensorService.h"
22 #include "SensorServiceUtils.h"
23 #include "ISensorsWrapper.h"
24 
25 #include <fmq/MessageQueue.h>
26 #include <sensor/SensorEventQueue.h>
27 #include <sensor/Sensor.h>
28 #include <stdint.h>
29 #include <sys/types.h>
30 #include <utils/KeyedVector.h>
31 #include <utils/Singleton.h>
32 #include <utils/String8.h>
33 #include <utils/Timers.h>
34 
35 #include <string>
36 #include <unordered_map>
37 #include <algorithm> //std::max std::min
38 
39 #include "RingBuffer.h"
40 
41 // ---------------------------------------------------------------------------
42 
43 namespace android {
44 
45 // ---------------------------------------------------------------------------
46 class SensorsHalDeathReceivier : public android::hardware::hidl_death_recipient {
47     virtual void serviceDied(uint64_t cookie,
48                              const wp<::android::hidl::base::V1_0::IBase>& service) override;
49 };
50 
51 class SensorDevice : public Singleton<SensorDevice>,
52                      public SensorServiceUtil::Dumpable {
53 public:
54     class HidlTransportErrorLog {
55      public:
56 
HidlTransportErrorLog()57         HidlTransportErrorLog() {
58             mTs = 0;
59             mCount = 0;
60         }
61 
HidlTransportErrorLog(time_t ts,int count)62         HidlTransportErrorLog(time_t ts, int count) {
63             mTs = ts;
64             mCount = count;
65         }
66 
toString()67         String8 toString() const {
68             String8 result;
69             struct tm *timeInfo = localtime(&mTs);
70             result.appendFormat("%02d:%02d:%02d :: %d", timeInfo->tm_hour, timeInfo->tm_min,
71                                 timeInfo->tm_sec, mCount);
72             return result;
73         }
74 
75     private:
76         time_t mTs; // timestamp of the error
77         int mCount;   // number of transport errors observed
78     };
79 
80     ~SensorDevice();
81     void prepareForReconnect();
82     void reconnect();
83 
84     ssize_t getSensorList(sensor_t const** list);
85 
86     void handleDynamicSensorConnection(int handle, bool connected);
87     status_t initCheck() const;
88     int getHalDeviceVersion() const;
89 
90     ssize_t poll(sensors_event_t* buffer, size_t count);
91     void writeWakeLockHandled(uint32_t count);
92 
93     status_t activate(void* ident, int handle, int enabled);
94     status_t batch(void* ident, int handle, int flags, int64_t samplingPeriodNs,
95                    int64_t maxBatchReportLatencyNs);
96     // Call batch with timeout zero instead of calling setDelay() for newer devices.
97     status_t setDelay(void* ident, int handle, int64_t ns);
98     status_t flush(void* ident, int handle);
99     status_t setMode(uint32_t mode);
100 
101     bool isDirectReportSupported() const;
102     int32_t registerDirectChannel(const sensors_direct_mem_t *memory);
103     void unregisterDirectChannel(int32_t channelHandle);
104     int32_t configureDirectChannel(int32_t sensorHandle,
105             int32_t channelHandle, const struct sensors_direct_cfg_t *config);
106 
107     void disableAllSensors();
108     void enableAllSensors();
109     void autoDisable(void *ident, int handle);
110 
111     status_t injectSensorData(const sensors_event_t *event);
112     void notifyConnectionDestroyed(void *ident);
113 
114     using Result = ::android::hardware::sensors::V1_0::Result;
115     hardware::Return<void> onDynamicSensorsConnected(
116             const hardware::hidl_vec<hardware::sensors::V2_1::SensorInfo> &dynamicSensorsAdded);
117     hardware::Return<void> onDynamicSensorsDisconnected(
118             const hardware::hidl_vec<int32_t> &dynamicSensorHandlesRemoved);
119 
120     void setUidStateForConnection(void* ident, SensorService::UidState state);
121 
isReconnecting()122     bool isReconnecting() const {
123         return mReconnecting;
124     }
125 
126     bool isSensorActive(int handle) const;
127 
128     // To update the BatchParams of a SensorEventConnection when the mic toggle changes its state
129     // while the Sensors Off toggle is on.
130     void onMicSensorAccessChanged(void* ident, int handle, nsecs_t samplingPeriodNs);
131 
132     // Dumpable
133     virtual std::string dump() const override;
134     virtual void dump(util::ProtoOutputStream* proto) const override;
135 private:
136     friend class Singleton<SensorDevice>;
137 
138     sp<::android::hardware::sensors::V2_1::implementation::ISensorsWrapperBase> mSensors;
139     Vector<sensor_t> mSensorList;
140     std::unordered_map<int32_t, sensor_t*> mConnectedDynamicSensors;
141 
142     // A bug in the Sensors HIDL spec which marks onDynamicSensorsConnected as oneway causes dynamic
143     // meta events and onDynamicSensorsConnected to be received out of order. This mutex + CV are
144     // used to block meta event processing until onDynamicSensorsConnected is received to simplify
145     // HAL implementations.
146     std::mutex mDynamicSensorsMutex;
147     std::condition_variable mDynamicSensorsCv;
148     static constexpr std::chrono::seconds MAX_DYN_SENSOR_WAIT{5};
149 
150     static const nsecs_t MINIMUM_EVENTS_PERIOD =   1000000; // 1000 Hz
151     mutable Mutex mLock; // protect mActivationCount[].batchParams
152     // fixed-size array after construction
153 
154     // Struct to store all the parameters(samplingPeriod, maxBatchReportLatency and flags) from
155     // batch call. For continous mode clients, maxBatchReportLatency is set to zero.
156     struct BatchParams {
157       nsecs_t mTSample, mTBatch;
BatchParamsBatchParams158       BatchParams() : mTSample(INT64_MAX), mTBatch(INT64_MAX) {}
BatchParamsBatchParams159       BatchParams(nsecs_t tSample, nsecs_t tBatch): mTSample(tSample), mTBatch(tBatch) {}
160       bool operator != (const BatchParams& other) {
161           return !(mTSample == other.mTSample && mTBatch == other.mTBatch);
162       }
163       // Merge another parameter with this one. The updated mTSample will be the min of the two.
164       // The update mTBatch will be the min of original mTBatch and the apparent batch period
165       // of the other. the apparent batch is the maximum of mTBatch and mTSample,
mergeBatchParams166       void merge(const BatchParams &other) {
167           mTSample = std::min(mTSample, other.mTSample);
168           mTBatch = std::min(mTBatch, std::max(other.mTBatch, other.mTSample));
169       }
170     };
171 
172     // Store batch parameters in the KeyedVector and the optimal batch_rate and timeout in
173     // bestBatchParams. For every batch() call corresponding params are stored in batchParams
174     // vector. A continuous mode request is batch(... timeout=0 ..) followed by activate(). A batch
175     // mode request is batch(... timeout > 0 ...) followed by activate().
176     // Info is a per-sensor data structure which contains the batch parameters for each client that
177     // has registered for this sensor.
178     struct Info {
179         BatchParams bestBatchParams;
180         // Key is the unique identifier(ident) for each client, value is the batch parameters
181         // requested by the client.
182         KeyedVector<void*, BatchParams> batchParams;
183 
184         // Flag to track if the sensor is active
185         bool isActive = false;
186 
187         // Sets batch parameters for this ident. Returns error if this ident is not already present
188         // in the KeyedVector above.
189         status_t setBatchParamsForIdent(void* ident, int flags, int64_t samplingPeriodNs,
190                                         int64_t maxBatchReportLatencyNs);
191         // Finds the optimal parameters for batching and stores them in bestBatchParams variable.
192         void selectBatchParams();
193         // Removes batchParams for an ident and re-computes bestBatchParams. Returns the index of
194         // the removed ident. If index >=0, ident is present and successfully removed.
195         ssize_t removeBatchParamsForIdent(void* ident);
196 
hasBatchParamsForIdentInfo197         bool hasBatchParamsForIdent(void* ident) const {
198             return batchParams.indexOfKey(ident) >= 0;
199         }
200 
201         /**
202          * @return The number of active clients of this sensor.
203          */
204         int numActiveClients() const;
205     };
206     DefaultKeyedVector<int, Info> mActivationCount;
207 
208     // Keep track of any hidl transport failures
209     SensorServiceUtil::RingBuffer<HidlTransportErrorLog> mHidlTransportErrors;
210     int mTotalHidlTransportErrors;
211 
212     /**
213      * Enums describing the reason why a client was disabled.
214      */
215     enum DisabledReason : uint8_t {
216         // UID becomes idle (e.g. app goes to background).
217         DISABLED_REASON_UID_IDLE = 0,
218 
219         // Sensors are restricted for all clients.
220         DISABLED_REASON_SERVICE_RESTRICTED,
221         DISABLED_REASON_MAX,
222     };
223 
224     static_assert(DisabledReason::DISABLED_REASON_MAX < sizeof(uint8_t) * CHAR_BIT);
225 
226     // Use this map to determine which client is activated or deactivated.
227     std::unordered_map<void *, uint8_t> mDisabledClients;
228 
229     void addDisabledReasonForIdentLocked(void* ident, DisabledReason reason);
230     void removeDisabledReasonForIdentLocked(void* ident, DisabledReason reason);
231 
232     SensorDevice();
233     bool connectHidlService();
234     void initializeSensorList();
235     void reactivateSensors(const DefaultKeyedVector<int, Info>& previousActivations);
236     static bool sensorHandlesChanged(const Vector<sensor_t>& oldSensorList,
237                                      const Vector<sensor_t>& newSensorList);
238     static bool sensorIsEquivalent(const sensor_t& prevSensor, const sensor_t& newSensor);
239 
240     enum HalConnectionStatus {
241         CONNECTED, // Successfully connected to the HAL
242         DOES_NOT_EXIST, // Could not find the HAL
243         FAILED_TO_CONNECT, // Found the HAL but failed to connect/initialize
244         UNKNOWN,
245     };
246     HalConnectionStatus connectHidlServiceV1_0();
247     HalConnectionStatus connectHidlServiceV2_0();
248     HalConnectionStatus connectHidlServiceV2_1();
249     HalConnectionStatus initializeHidlServiceV2_X();
250 
251     ssize_t pollHal(sensors_event_t* buffer, size_t count);
252     ssize_t pollFmq(sensors_event_t* buffer, size_t count);
253     status_t activateLocked(void* ident, int handle, int enabled);
254     status_t batchLocked(void* ident, int handle, int flags, int64_t samplingPeriodNs,
255                          int64_t maxBatchReportLatencyNs);
256 
257     status_t updateBatchParamsLocked(int handle, Info& info);
258     status_t doActivateHardwareLocked(int handle, bool enable);
259 
260     void handleHidlDeath(const std::string &detail);
261     template<typename T>
checkReturn(const Return<T> & ret)262     void checkReturn(const Return<T>& ret) {
263         if (!ret.isOk()) {
264             handleHidlDeath(ret.description());
265         }
266     }
267     status_t checkReturnAndGetStatus(const Return<Result>& ret);
268     //TODO(b/67425500): remove waiter after bug is resolved.
269     sp<SensorDeviceUtils::HidlServiceRegistrationWaiter> mRestartWaiter;
270 
271     bool isClientDisabled(void* ident) const;
272     bool isClientDisabledLocked(void* ident) const;
273     std::vector<void *> getDisabledClientsLocked() const;
274 
275     bool clientHasNoAccessLocked(void* ident) const;
276 
277     using Event = hardware::sensors::V2_1::Event;
278     using SensorInfo = hardware::sensors::V2_1::SensorInfo;
279 
280     void convertToSensorEvent(const Event &src, sensors_event_t *dst);
281 
282     void convertToSensorEventsAndQuantize(
283             const hardware::hidl_vec<Event> &src,
284             const hardware::hidl_vec<SensorInfo> &dynamicSensorsAdded,
285             sensors_event_t *dst);
286 
287     float getResolutionForSensor(int sensorHandle);
288 
289     bool mIsDirectReportSupported;
290 
291     typedef hardware::MessageQueue<uint32_t, hardware::kSynchronizedReadWrite> WakeLockQueue;
292     std::unique_ptr<WakeLockQueue> mWakeLockQueue;
293 
294     hardware::EventFlag* mEventQueueFlag;
295     hardware::EventFlag* mWakeLockQueueFlag;
296 
297     std::array<Event, SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT> mEventBuffer;
298 
299     sp<SensorsHalDeathReceivier> mSensorsHalDeathReceiver;
300     std::atomic_bool mReconnecting;
301 };
302 
303 // ---------------------------------------------------------------------------
304 }; // namespace android
305 
306 #endif // ANDROID_SENSOR_DEVICE_H
307