blob: 112fb850512792cfb6d129ce43571e333ca8d14e [file] [log] [blame]
Dmitri Plotnikov5effd852021-08-11 14:55:58 -07001/*
2 * Copyright (C) 2021 The Android Open Source Project
3 * Android BPF library - public API
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18#pragma once
19
20#include <inttypes.h>
21#include <log/log.h>
22#include <time.h>
23#include <sstream>
24#include <string>
25
26/**
27 * An object that can track changes of some value over time, taking into account an additional
28 * dimension: the object's state. As the tracked value changes, the deltas are distributed
29 * among the object states in accordance with the time spent in those states.
30 */
31namespace android {
32namespace battery {
33
34typedef uint16_t state_t;
35
36template <class T>
37class MultiStateCounter {
38 uint16_t stateCount;
39 state_t currentState;
40 time_t lastStateChangeTimestamp;
41 T emptyValue;
42 T lastValue;
43 time_t lastUpdateTimestamp;
44 T deltaValue;
Dmitri Plotnikov99d7c712021-09-03 19:07:23 -070045 bool isEnabled;
Dmitri Plotnikov5effd852021-08-11 14:55:58 -070046
47 struct State {
48 time_t timeInStateSinceUpdate;
49 T counter;
50 };
51
52 State* states;
53
54public:
Dmitri Plotnikov12aaf8e2021-09-03 19:07:23 -070055 MultiStateCounter(uint16_t stateCount, const T& emptyValue);
Dmitri Plotnikov5effd852021-08-11 14:55:58 -070056
57 virtual ~MultiStateCounter();
58
Dmitri Plotnikov99d7c712021-09-03 19:07:23 -070059 void setEnabled(bool enabled, time_t timestamp);
60
Dmitri Plotnikov5effd852021-08-11 14:55:58 -070061 void setState(state_t state, time_t timestamp);
62
Dmitri Plotnikov12aaf8e2021-09-03 19:07:23 -070063 void setValue(state_t state, const T& value);
64
Dmitri Plotnikov8940e5d2021-09-23 14:56:30 -070065 /**
66 * Updates the value for the current state and returns the delta from the previously
67 * set value.
68 */
69 const T& updateValue(const T& value, time_t timestamp);
70
71 void addValue(const T& value);
Dmitri Plotnikov5effd852021-08-11 14:55:58 -070072
Dmitri Plotnikov99d7c712021-09-03 19:07:23 -070073 void reset();
74
Dmitri Plotnikov12aaf8e2021-09-03 19:07:23 -070075 uint16_t getStateCount();
76
Dmitri Plotnikov5effd852021-08-11 14:55:58 -070077 const T& getCount(state_t state);
78
79 std::string toString();
80
81private:
82 /**
83 * Subtracts previousValue from newValue and returns the result in outValue.
84 * Returns true iff the combination of previousValue and newValue is valid
85 * (newValue >= prevValue)
86 */
87 bool delta(const T& previousValue, const T& newValue, T* outValue) const;
88
89 /**
90 * Adds value2 to value1 and stores the result in value1. Denominator is
91 * guaranteed to be non-zero.
92 */
93 void add(T* value1, const T& value2, const uint64_t numerator,
94 const uint64_t denominator) const;
95
96 std::string valueToString(const T& value) const;
97};
98
99// ---------------------- MultiStateCounter Implementation -------------------------
100// Since MultiStateCounter is a template, the implementation must be inlined.
101
102template <class T>
Dmitri Plotnikov12aaf8e2021-09-03 19:07:23 -0700103MultiStateCounter<T>::MultiStateCounter(uint16_t stateCount, const T& emptyValue)
Dmitri Plotnikov5effd852021-08-11 14:55:58 -0700104 : stateCount(stateCount),
Dmitri Plotnikov12aaf8e2021-09-03 19:07:23 -0700105 currentState(0),
106 lastStateChangeTimestamp(-1),
Dmitri Plotnikov5effd852021-08-11 14:55:58 -0700107 emptyValue(emptyValue),
108 lastValue(emptyValue),
Dmitri Plotnikov12aaf8e2021-09-03 19:07:23 -0700109 lastUpdateTimestamp(-1),
Dmitri Plotnikov99d7c712021-09-03 19:07:23 -0700110 deltaValue(emptyValue),
111 isEnabled(true) {
Dmitri Plotnikov5effd852021-08-11 14:55:58 -0700112 states = new State[stateCount];
113 for (int i = 0; i < stateCount; i++) {
114 states[i].timeInStateSinceUpdate = 0;
115 states[i].counter = emptyValue;
116 }
117}
118
119template <class T>
120MultiStateCounter<T>::~MultiStateCounter() {
121 delete[] states;
122};
123
124template <class T>
Dmitri Plotnikov99d7c712021-09-03 19:07:23 -0700125void MultiStateCounter<T>::setEnabled(bool enabled, time_t timestamp) {
126 if (enabled == isEnabled) {
127 return;
128 }
129
130 if (!enabled) {
131 // Confirm the current state for the side-effect of updating the time-in-state
132 // counter for the current state.
133 setState(currentState, timestamp);
134 }
135
136 isEnabled = enabled;
137
Dmitri Plotnikov12aaf8e2021-09-03 19:07:23 -0700138 if (lastStateChangeTimestamp >= 0) {
Dmitri Plotnikov99d7c712021-09-03 19:07:23 -0700139 lastStateChangeTimestamp = timestamp;
140 }
141}
142
143template <class T>
144void MultiStateCounter<T>::setState(state_t state, time_t timestamp) {
145 if (isEnabled && lastStateChangeTimestamp >= 0) {
Dmitri Plotnikov12aaf8e2021-09-03 19:07:23 -0700146 if (timestamp >= lastStateChangeTimestamp) {
147 states[currentState].timeInStateSinceUpdate += timestamp - lastStateChangeTimestamp;
148 } else {
149 ALOGE("setState is called with an earlier timestamp: %lu, previous timestamp: %lu\n",
150 (unsigned long)timestamp, (unsigned long)lastStateChangeTimestamp);
151 // The accumulated durations have become unreliable. For example, if the timestamp
152 // sequence was 1000, 2000, 1000, 3000, if we accumulated the positive deltas,
153 // we would get 4000, which is greater than (last - first). This could lead to
154 // counts exceeding 100%.
155 for (int i = 0; i < stateCount; i++) {
156 states[i].timeInStateSinceUpdate = 0;
157 }
Dmitri Plotnikov5effd852021-08-11 14:55:58 -0700158 }
159 }
160 currentState = state;
161 lastStateChangeTimestamp = timestamp;
162}
163
164template <class T>
Dmitri Plotnikov12aaf8e2021-09-03 19:07:23 -0700165void MultiStateCounter<T>::setValue(state_t state, const T& value) {
166 states[state].counter = value;
167}
168
169template <class T>
Dmitri Plotnikov8940e5d2021-09-23 14:56:30 -0700170const T& MultiStateCounter<T>::updateValue(const T& value, time_t timestamp) {
Dmitri Plotnikov99d7c712021-09-03 19:07:23 -0700171 // If the counter is disabled, we ignore the update, except when the counter got disabled after
172 // the previous update, in which case we still need to pick up the residual delta.
173 if (isEnabled || lastUpdateTimestamp < lastStateChangeTimestamp) {
174 // Confirm the current state for the side-effect of updating the time-in-state
175 // counter for the current state.
176 setState(currentState, timestamp);
Dmitri Plotnikov5effd852021-08-11 14:55:58 -0700177
Dmitri Plotnikov99d7c712021-09-03 19:07:23 -0700178 if (lastUpdateTimestamp >= 0) {
179 if (timestamp > lastUpdateTimestamp) {
180 if (delta(lastValue, value, &deltaValue)) {
181 time_t timeSinceUpdate = timestamp - lastUpdateTimestamp;
182 for (int i = 0; i < stateCount; i++) {
183 time_t timeInState = states[i].timeInStateSinceUpdate;
184 if (timeInState) {
185 add(&states[i].counter, deltaValue, timeInState, timeSinceUpdate);
186 states[i].timeInStateSinceUpdate = 0;
187 }
Dmitri Plotnikov12aaf8e2021-09-03 19:07:23 -0700188 }
Dmitri Plotnikov99d7c712021-09-03 19:07:23 -0700189 } else {
190 std::stringstream str;
191 str << "updateValue is called with a value " << valueToString(value)
192 << ", which is lower than the previous value " << valueToString(lastValue)
193 << "\n";
194 ALOGE("%s", str.str().c_str());
Dmitri Plotnikov5effd852021-08-11 14:55:58 -0700195 }
Dmitri Plotnikov99d7c712021-09-03 19:07:23 -0700196 } else if (timestamp < lastUpdateTimestamp) {
197 ALOGE("updateValue is called with an earlier timestamp: %lu, previous: %lu\n",
198 (unsigned long)timestamp, (unsigned long)lastUpdateTimestamp);
Dmitri Plotnikov5effd852021-08-11 14:55:58 -0700199 }
Dmitri Plotnikov5effd852021-08-11 14:55:58 -0700200 }
Dmitri Plotnikov5effd852021-08-11 14:55:58 -0700201 }
202 lastValue = value;
203 lastUpdateTimestamp = timestamp;
Dmitri Plotnikov8940e5d2021-09-23 14:56:30 -0700204 return deltaValue;
205}
206
207template <class T>
208void MultiStateCounter<T>::addValue(const T& value) {
209 if (!isEnabled) {
210 return;
211 }
212
213 add(&states[currentState].counter, value, 1 /* numerator */, 1 /* denominator */);
Dmitri Plotnikov5effd852021-08-11 14:55:58 -0700214}
215
216template <class T>
Dmitri Plotnikov99d7c712021-09-03 19:07:23 -0700217void MultiStateCounter<T>::reset() {
218 lastStateChangeTimestamp = -1;
219 lastUpdateTimestamp = -1;
220 for (int i = 0; i < stateCount; i++) {
221 states[i].timeInStateSinceUpdate = 0;
222 states[i].counter = emptyValue;
223 }
224}
225
226template <class T>
Dmitri Plotnikov12aaf8e2021-09-03 19:07:23 -0700227uint16_t MultiStateCounter<T>::getStateCount() {
228 return stateCount;
229}
230
231template <class T>
Dmitri Plotnikov5effd852021-08-11 14:55:58 -0700232const T& MultiStateCounter<T>::getCount(state_t state) {
233 return states[state].counter;
234}
235
236template <class T>
237std::string MultiStateCounter<T>::toString() {
238 std::stringstream str;
Dmitri Plotnikov12aaf8e2021-09-03 19:07:23 -0700239 str << "[";
Dmitri Plotnikov5effd852021-08-11 14:55:58 -0700240 for (int i = 0; i < stateCount; i++) {
241 if (i != 0) {
242 str << ", ";
243 }
Dmitri Plotnikov12aaf8e2021-09-03 19:07:23 -0700244 str << i << ": " << valueToString(states[i].counter);
245 if (states[i].timeInStateSinceUpdate > 0) {
246 str << " timeInStateSinceUpdate: " << states[i].timeInStateSinceUpdate;
247 }
Dmitri Plotnikov5effd852021-08-11 14:55:58 -0700248 }
249 str << "]";
Dmitri Plotnikov12aaf8e2021-09-03 19:07:23 -0700250 if (lastUpdateTimestamp >= 0) {
251 str << " updated: " << lastUpdateTimestamp;
252 }
253 if (lastStateChangeTimestamp >= 0) {
254 str << " currentState: " << currentState;
255 if (lastStateChangeTimestamp > lastUpdateTimestamp) {
256 str << " stateChanged: " << lastStateChangeTimestamp;
257 }
258 } else {
259 str << " currentState: none";
260 }
Dmitri Plotnikov8940e5d2021-09-23 14:56:30 -0700261 if (!isEnabled) {
262 str << " disabled";
263 }
Dmitri Plotnikov5effd852021-08-11 14:55:58 -0700264 return str.str();
265}
266
267} // namespace battery
268} // namespace android