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 
20 #include <inttypes.h>
21 
22 #include <android-base/properties.h>
23 #include <android-base/stringprintf.h>
24 #include <android/os/IInputConstants.h>
25 #include <input/Input.h>
26 #include <log/log.h>
27 
28 using android::base::HwTimeoutMultiplier;
29 using android::base::StringPrintf;
30 
31 namespace android::inputdispatcher {
32 
33 /**
34  * Events that are older than this time will be considered mature, at which point we will stop
35  * waiting for the apps to provide further information about them.
36  * It's likely that the apps will ANR if the events are not received by this deadline, and we
37  * already track ANR metrics separately.
38  */
39 const std::chrono::duration ANR_TIMEOUT = std::chrono::milliseconds(
40         android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
41         HwTimeoutMultiplier());
42 
isMatureEvent(nsecs_t eventTime,nsecs_t now)43 static bool isMatureEvent(nsecs_t eventTime, nsecs_t now) {
44     std::chrono::duration age = std::chrono::nanoseconds(now) - std::chrono::nanoseconds(eventTime);
45     return age > ANR_TIMEOUT;
46 }
47 
48 /**
49  * A multimap allows to have several entries with the same key. This function just erases a specific
50  * key-value pair. Equivalent to the imaginary std api std::multimap::erase(key, value).
51  */
52 template <typename K, typename V>
eraseByKeyAndValue(std::multimap<K,V> & map,K key,V value)53 static void eraseByKeyAndValue(std::multimap<K, V>& map, K key, V value) {
54     auto iterpair = map.equal_range(key);
55 
56     for (auto it = iterpair.first; it != iterpair.second; ++it) {
57         if (it->second == value) {
58             map.erase(it);
59             break;
60         }
61     }
62 }
63 
LatencyTracker(InputEventTimelineProcessor * processor)64 LatencyTracker::LatencyTracker(InputEventTimelineProcessor* processor)
65       : mTimelineProcessor(processor) {
66     LOG_ALWAYS_FATAL_IF(processor == nullptr);
67 }
68 
trackListener(int32_t inputEventId,bool isDown,nsecs_t eventTime,nsecs_t readTime)69 void LatencyTracker::trackListener(int32_t inputEventId, bool isDown, nsecs_t eventTime,
70                                    nsecs_t readTime) {
71     reportAndPruneMatureRecords(eventTime);
72     const auto it = mTimelines.find(inputEventId);
73     if (it != mTimelines.end()) {
74         // Input event ids are randomly generated, so it's possible that two events have the same
75         // event id. Drop this event, and also drop the existing event because the apps would
76         // confuse us by reporting the rest of the timeline for one of them. This should happen
77         // rarely, so we won't lose much data
78         mTimelines.erase(it);
79         // In case we have another input event with a different id and at the same eventTime,
80         // only erase this specific inputEventId.
81         eraseByKeyAndValue(mEventTimes, eventTime, inputEventId);
82         return;
83     }
84     mTimelines.emplace(inputEventId, InputEventTimeline(isDown, eventTime, readTime));
85     mEventTimes.emplace(eventTime, inputEventId);
86 }
87 
trackFinishedEvent(int32_t inputEventId,const sp<IBinder> & connectionToken,nsecs_t deliveryTime,nsecs_t consumeTime,nsecs_t finishTime)88 void LatencyTracker::trackFinishedEvent(int32_t inputEventId, const sp<IBinder>& connectionToken,
89                                         nsecs_t deliveryTime, nsecs_t consumeTime,
90                                         nsecs_t finishTime) {
91     const auto it = mTimelines.find(inputEventId);
92     if (it == mTimelines.end()) {
93         // It's possible that an app sends a bad (or late)'Finish' signal, since it's free to do
94         // anything in its process. Just drop the report and move on.
95         return;
96     }
97 
98     InputEventTimeline& timeline = it->second;
99     const auto connectionIt = timeline.connectionTimelines.find(connectionToken);
100     if (connectionIt == timeline.connectionTimelines.end()) {
101         // Most likely case: app calls 'finishInputEvent' before it reports the graphics timeline
102         timeline.connectionTimelines.emplace(connectionToken,
103                                              ConnectionTimeline{deliveryTime, consumeTime,
104                                                                 finishTime});
105     } else {
106         // Already have a record for this connectionToken
107         ConnectionTimeline& connectionTimeline = connectionIt->second;
108         const bool success =
109                 connectionTimeline.setDispatchTimeline(deliveryTime, consumeTime, finishTime);
110         if (!success) {
111             // We are receiving unreliable data from the app. Just delete the entire connection
112             // timeline for this event
113             timeline.connectionTimelines.erase(connectionIt);
114         }
115     }
116 }
117 
trackGraphicsLatency(int32_t inputEventId,const sp<IBinder> & connectionToken,std::array<nsecs_t,GraphicsTimeline::SIZE> graphicsTimeline)118 void LatencyTracker::trackGraphicsLatency(
119         int32_t inputEventId, const sp<IBinder>& connectionToken,
120         std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline) {
121     const auto it = mTimelines.find(inputEventId);
122     if (it == mTimelines.end()) {
123         // It's possible that an app sends a bad (or late) 'Timeline' signal, since it's free to do
124         // anything in its process. Just drop the report and move on.
125         return;
126     }
127 
128     InputEventTimeline& timeline = it->second;
129     const auto connectionIt = timeline.connectionTimelines.find(connectionToken);
130     if (connectionIt == timeline.connectionTimelines.end()) {
131         timeline.connectionTimelines.emplace(connectionToken, std::move(graphicsTimeline));
132     } else {
133         // Most likely case
134         ConnectionTimeline& connectionTimeline = connectionIt->second;
135         const bool success = connectionTimeline.setGraphicsTimeline(std::move(graphicsTimeline));
136         if (!success) {
137             // We are receiving unreliable data from the app. Just delete the entire connection
138             // timeline for this event
139             timeline.connectionTimelines.erase(connectionIt);
140         }
141     }
142 }
143 
144 /**
145  * We should use the current time 'now()' here to determine the age of the event, but instead we
146  * are using the latest 'eventTime' for efficiency since this time is already acquired, and
147  * 'trackListener' should happen soon after the event occurs.
148  */
reportAndPruneMatureRecords(nsecs_t newEventTime)149 void LatencyTracker::reportAndPruneMatureRecords(nsecs_t newEventTime) {
150     while (!mEventTimes.empty()) {
151         const auto& [oldestEventTime, oldestInputEventId] = *mEventTimes.begin();
152         if (isMatureEvent(oldestEventTime, newEventTime /*now*/)) {
153             // Report and drop this event
154             const auto it = mTimelines.find(oldestInputEventId);
155             LOG_ALWAYS_FATAL_IF(it == mTimelines.end(),
156                                 "Event %" PRId32 " is in mEventTimes, but not in mTimelines",
157                                 oldestInputEventId);
158             const InputEventTimeline& timeline = it->second;
159             mTimelineProcessor->processTimeline(timeline);
160             mTimelines.erase(it);
161             mEventTimes.erase(mEventTimes.begin());
162         } else {
163             // If the oldest event does not need to be pruned, no events should be pruned.
164             return;
165         }
166     }
167 }
168 
reportNow()169 void LatencyTracker::reportNow() {
170     for (const auto& [inputEventId, timeline] : mTimelines) {
171         mTimelineProcessor->processTimeline(timeline);
172     }
173     mTimelines.clear();
174     mEventTimes.clear();
175 }
176 
dump(const char * prefix)177 std::string LatencyTracker::dump(const char* prefix) {
178     return StringPrintf("%sLatencyTracker:\n", prefix) +
179             StringPrintf("%s  mTimelines.size() = %zu\n", prefix, mTimelines.size()) +
180             StringPrintf("%s  mEventTimes.size() = %zu\n", prefix, mEventTimes.size());
181 }
182 
183 } // namespace android::inputdispatcher
184