1 /*
2 * Copyright (C) 2021 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 #define LOG_TAG "LatencyTracker"
18 #include "LatencyTracker.h"
19 #include "../InputDeviceMetricsSource.h"
20
21 #include <inttypes.h>
22
23 #include <android-base/logging.h>
24 #include <android-base/properties.h>
25 #include <android-base/stringprintf.h>
26 #include <android/os/IInputConstants.h>
27 #include <input/Input.h>
28 #include <input/InputDevice.h>
29 #include <log/log.h>
30
31 using android::base::HwTimeoutMultiplier;
32 using android::base::StringPrintf;
33
34 namespace android::inputdispatcher {
35
36 namespace {
37
38 /**
39 * Events that are older than this time will be considered mature, at which point we will stop
40 * waiting for the apps to provide further information about them.
41 * It's likely that the apps will ANR if the events are not received by this deadline, and we
42 * already track ANR metrics separately.
43 */
44 const std::chrono::duration ANR_TIMEOUT = std::chrono::milliseconds(
45 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
46 HwTimeoutMultiplier());
47
isMatureEvent(nsecs_t eventTime,nsecs_t now)48 static bool isMatureEvent(nsecs_t eventTime, nsecs_t now) {
49 std::chrono::duration age = std::chrono::nanoseconds(now) - std::chrono::nanoseconds(eventTime);
50 return age > ANR_TIMEOUT;
51 }
52
53 /**
54 * A multimap allows to have several entries with the same key. This function just erases a specific
55 * key-value pair. Equivalent to the imaginary std api std::multimap::erase(key, value).
56 */
57 template <typename K, typename V>
eraseByValue(std::multimap<K,V> & map,const V & value)58 static void eraseByValue(std::multimap<K, V>& map, const V& value) {
59 for (auto it = map.begin(); it != map.end();) {
60 if (it->second == value) {
61 it = map.erase(it);
62 } else {
63 it++;
64 }
65 }
66 }
67
68 } // namespace
69
LatencyTracker(InputEventTimelineProcessor & processor)70 LatencyTracker::LatencyTracker(InputEventTimelineProcessor& processor)
71 : mTimelineProcessor(&processor) {}
72
trackListener(const NotifyArgs & args)73 void LatencyTracker::trackListener(const NotifyArgs& args) {
74 if (const NotifyKeyArgs* keyArgs = std::get_if<NotifyKeyArgs>(&args)) {
75 std::set<InputDeviceUsageSource> sources =
76 getUsageSourcesForKeyArgs(*keyArgs, mInputDevices);
77 trackListener(keyArgs->id, keyArgs->eventTime, keyArgs->readTime, keyArgs->deviceId,
78 sources, keyArgs->action, InputEventType::KEY);
79
80 } else if (const NotifyMotionArgs* motionArgs = std::get_if<NotifyMotionArgs>(&args)) {
81 std::set<InputDeviceUsageSource> sources = getUsageSourcesForMotionArgs(*motionArgs);
82 trackListener(motionArgs->id, motionArgs->eventTime, motionArgs->readTime,
83 motionArgs->deviceId, sources, motionArgs->action, InputEventType::MOTION);
84 } else {
85 LOG(FATAL) << "Unexpected NotifyArgs type: " << args.index();
86 }
87 }
88
trackListener(int32_t inputEventId,nsecs_t eventTime,nsecs_t readTime,DeviceId deviceId,const std::set<InputDeviceUsageSource> & sources,int32_t inputEventAction,InputEventType inputEventType)89 void LatencyTracker::trackListener(int32_t inputEventId, nsecs_t eventTime, nsecs_t readTime,
90 DeviceId deviceId,
91 const std::set<InputDeviceUsageSource>& sources,
92 int32_t inputEventAction, InputEventType inputEventType) {
93 reportAndPruneMatureRecords(eventTime);
94 const auto it = mTimelines.find(inputEventId);
95 if (it != mTimelines.end()) {
96 // Input event ids are randomly generated, so it's possible that two events have the same
97 // event id. Drop this event, and also drop the existing event because the apps would
98 // confuse us by reporting the rest of the timeline for one of them. This should happen
99 // rarely, so we won't lose much data
100 mTimelines.erase(it);
101 eraseByValue(mEventTimes, inputEventId);
102 return;
103 }
104
105 // Create an InputEventTimeline for the device ID. The vendorId and productId
106 // can be obtained from the InputDeviceIdentifier of the particular device.
107 const InputDeviceIdentifier* identifier = nullptr;
108 for (auto& inputDevice : mInputDevices) {
109 if (deviceId == inputDevice.getId()) {
110 identifier = &inputDevice.getIdentifier();
111 break;
112 }
113 }
114
115 // If no matching ids can be found for the device from among the input devices connected,
116 // the call to trackListener will be dropped.
117 // Note: there generally isn't expected to be a situation where we can't find an InputDeviceInfo
118 // but a possibility of it is handled in case of race conditions
119 if (identifier == nullptr) {
120 ALOGE("Could not find input device identifier. Dropping call to LatencyTracker.");
121 return;
122 }
123
124 const InputEventActionType inputEventActionType = [&]() {
125 switch (inputEventType) {
126 case InputEventType::MOTION: {
127 switch (MotionEvent::getActionMasked(inputEventAction)) {
128 case AMOTION_EVENT_ACTION_DOWN:
129 return InputEventActionType::MOTION_ACTION_DOWN;
130 case AMOTION_EVENT_ACTION_MOVE:
131 return InputEventActionType::MOTION_ACTION_MOVE;
132 case AMOTION_EVENT_ACTION_UP:
133 return InputEventActionType::MOTION_ACTION_UP;
134 case AMOTION_EVENT_ACTION_HOVER_MOVE:
135 return InputEventActionType::MOTION_ACTION_HOVER_MOVE;
136 case AMOTION_EVENT_ACTION_SCROLL:
137 return InputEventActionType::MOTION_ACTION_SCROLL;
138 default:
139 return InputEventActionType::UNKNOWN_INPUT_EVENT;
140 }
141 }
142 case InputEventType::KEY: {
143 switch (inputEventAction) {
144 case AKEY_EVENT_ACTION_DOWN:
145 case AKEY_EVENT_ACTION_UP:
146 return InputEventActionType::KEY;
147 default:
148 return InputEventActionType::UNKNOWN_INPUT_EVENT;
149 }
150 }
151 default:
152 return InputEventActionType::UNKNOWN_INPUT_EVENT;
153 }
154 }();
155
156 mTimelines.emplace(inputEventId,
157 InputEventTimeline(eventTime, readTime, identifier->vendor,
158 identifier->product, sources, inputEventActionType));
159 mEventTimes.emplace(eventTime, inputEventId);
160 }
161
trackFinishedEvent(int32_t inputEventId,const sp<IBinder> & connectionToken,nsecs_t deliveryTime,nsecs_t consumeTime,nsecs_t finishTime)162 void LatencyTracker::trackFinishedEvent(int32_t inputEventId, const sp<IBinder>& connectionToken,
163 nsecs_t deliveryTime, nsecs_t consumeTime,
164 nsecs_t finishTime) {
165 const auto it = mTimelines.find(inputEventId);
166 if (it == mTimelines.end()) {
167 // This could happen if we erased this event when duplicate events were detected. It's
168 // also possible that an app sent a bad (or late) 'Finish' signal, since it's free to do
169 // anything in its process. Just drop the report and move on.
170 return;
171 }
172
173 InputEventTimeline& timeline = it->second;
174 const auto connectionIt = timeline.connectionTimelines.find(connectionToken);
175 if (connectionIt == timeline.connectionTimelines.end()) {
176 // Most likely case: app calls 'finishInputEvent' before it reports the graphics timeline
177 timeline.connectionTimelines.emplace(connectionToken,
178 ConnectionTimeline{deliveryTime, consumeTime,
179 finishTime});
180 } else {
181 // Already have a record for this connectionToken
182 ConnectionTimeline& connectionTimeline = connectionIt->second;
183 const bool success =
184 connectionTimeline.setDispatchTimeline(deliveryTime, consumeTime, finishTime);
185 if (!success) {
186 // We are receiving unreliable data from the app. Just delete the entire connection
187 // timeline for this event
188 timeline.connectionTimelines.erase(connectionIt);
189 }
190 }
191 }
192
trackGraphicsLatency(int32_t inputEventId,const sp<IBinder> & connectionToken,std::array<nsecs_t,GraphicsTimeline::SIZE> graphicsTimeline)193 void LatencyTracker::trackGraphicsLatency(
194 int32_t inputEventId, const sp<IBinder>& connectionToken,
195 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline) {
196 const auto it = mTimelines.find(inputEventId);
197 if (it == mTimelines.end()) {
198 // This could happen if we erased this event when duplicate events were detected. It's
199 // also possible that an app sent a bad (or late) 'Timeline' signal, since it's free to do
200 // anything in its process. Just drop the report and move on.
201 return;
202 }
203
204 InputEventTimeline& timeline = it->second;
205 const auto connectionIt = timeline.connectionTimelines.find(connectionToken);
206 if (connectionIt == timeline.connectionTimelines.end()) {
207 timeline.connectionTimelines.emplace(connectionToken, std::move(graphicsTimeline));
208 } else {
209 // Most likely case
210 ConnectionTimeline& connectionTimeline = connectionIt->second;
211 const bool success = connectionTimeline.setGraphicsTimeline(std::move(graphicsTimeline));
212 if (!success) {
213 // We are receiving unreliable data from the app. Just delete the entire connection
214 // timeline for this event
215 timeline.connectionTimelines.erase(connectionIt);
216 }
217 }
218 }
219
220 /**
221 * We should use the current time 'now()' here to determine the age of the event, but instead we
222 * are using the latest 'eventTime' for efficiency since this time is already acquired, and
223 * 'trackListener' should happen soon after the event occurs.
224 */
reportAndPruneMatureRecords(nsecs_t newEventTime)225 void LatencyTracker::reportAndPruneMatureRecords(nsecs_t newEventTime) {
226 while (!mEventTimes.empty()) {
227 const auto& [oldestEventTime, oldestInputEventId] = *mEventTimes.begin();
228 if (isMatureEvent(oldestEventTime, /*now=*/newEventTime)) {
229 // Report and drop this event
230 const auto it = mTimelines.find(oldestInputEventId);
231 LOG_ALWAYS_FATAL_IF(it == mTimelines.end(),
232 "Event %" PRId32 " is in mEventTimes, but not in mTimelines",
233 oldestInputEventId);
234 const InputEventTimeline& timeline = it->second;
235 mTimelineProcessor->processTimeline(timeline);
236 mTimelines.erase(it);
237 mEventTimes.erase(mEventTimes.begin());
238 } else {
239 // If the oldest event does not need to be pruned, no events should be pruned.
240 return;
241 }
242 }
243 }
244
dump(const char * prefix) const245 std::string LatencyTracker::dump(const char* prefix) const {
246 return StringPrintf("%sLatencyTracker:\n", prefix) +
247 StringPrintf("%s mTimelines.size() = %zu\n", prefix, mTimelines.size()) +
248 StringPrintf("%s mEventTimes.size() = %zu\n", prefix, mEventTimes.size());
249 }
250
setInputDevices(const std::vector<InputDeviceInfo> & inputDevices)251 void LatencyTracker::setInputDevices(const std::vector<InputDeviceInfo>& inputDevices) {
252 mInputDevices = inputDevices;
253 }
254
255 } // namespace android::inputdispatcher
256