blob: 0caf005a9a7a394ff7e3b37a728c266d87a4bb51 [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 /**
Dmitri Plotnikov40dcce22021-12-10 15:38:17 -080066 * Updates the value by distributing the delta from the previously set value
67 * among states according to their respective time-in-state.
68 * Returns the delta from the previously set value.
Dmitri Plotnikov8940e5d2021-09-23 14:56:30 -070069 */
70 const T& updateValue(const T& value, time_t timestamp);
71
Dmitri Plotnikov40dcce22021-12-10 15:38:17 -080072 /**
73 * Updates the value by distributing the specified increment among states according
74 * to their respective time-in-state.
75 */
76 void incrementValue(const T& increment, time_t timestamp);
77
78 /**
79 * Adds the specified increment to the value for the current state, without affecting
80 * the last updated value or timestamp. Ignores partial time-in-state: the entirety of
81 * the increment is given to the current state.
82 */
83 void addValue(const T& increment);
Dmitri Plotnikov5effd852021-08-11 14:55:58 -070084
Dmitri Plotnikov99d7c712021-09-03 19:07:23 -070085 void reset();
86
Dmitri Plotnikov12aaf8e2021-09-03 19:07:23 -070087 uint16_t getStateCount();
88
Dmitri Plotnikov5effd852021-08-11 14:55:58 -070089 const T& getCount(state_t state);
90
91 std::string toString();
92
93private:
94 /**
95 * Subtracts previousValue from newValue and returns the result in outValue.
96 * Returns true iff the combination of previousValue and newValue is valid
97 * (newValue >= prevValue)
98 */
99 bool delta(const T& previousValue, const T& newValue, T* outValue) const;
100
101 /**
102 * Adds value2 to value1 and stores the result in value1. Denominator is
103 * guaranteed to be non-zero.
104 */
105 void add(T* value1, const T& value2, const uint64_t numerator,
106 const uint64_t denominator) const;
107
108 std::string valueToString(const T& value) const;
109};
110
111// ---------------------- MultiStateCounter Implementation -------------------------
112// Since MultiStateCounter is a template, the implementation must be inlined.
113
114template <class T>
Dmitri Plotnikov12aaf8e2021-09-03 19:07:23 -0700115MultiStateCounter<T>::MultiStateCounter(uint16_t stateCount, const T& emptyValue)
Dmitri Plotnikov5effd852021-08-11 14:55:58 -0700116 : stateCount(stateCount),
Dmitri Plotnikov12aaf8e2021-09-03 19:07:23 -0700117 currentState(0),
118 lastStateChangeTimestamp(-1),
Dmitri Plotnikov5effd852021-08-11 14:55:58 -0700119 emptyValue(emptyValue),
120 lastValue(emptyValue),
Dmitri Plotnikov12aaf8e2021-09-03 19:07:23 -0700121 lastUpdateTimestamp(-1),
Dmitri Plotnikov99d7c712021-09-03 19:07:23 -0700122 deltaValue(emptyValue),
123 isEnabled(true) {
Dmitri Plotnikov5effd852021-08-11 14:55:58 -0700124 states = new State[stateCount];
125 for (int i = 0; i < stateCount; i++) {
126 states[i].timeInStateSinceUpdate = 0;
127 states[i].counter = emptyValue;
128 }
129}
130
131template <class T>
132MultiStateCounter<T>::~MultiStateCounter() {
133 delete[] states;
134};
135
136template <class T>
Dmitri Plotnikov99d7c712021-09-03 19:07:23 -0700137void MultiStateCounter<T>::setEnabled(bool enabled, time_t timestamp) {
138 if (enabled == isEnabled) {
139 return;
140 }
141
142 if (!enabled) {
143 // Confirm the current state for the side-effect of updating the time-in-state
144 // counter for the current state.
145 setState(currentState, timestamp);
146 }
147
148 isEnabled = enabled;
149
Dmitri Plotnikov12aaf8e2021-09-03 19:07:23 -0700150 if (lastStateChangeTimestamp >= 0) {
Dmitri Plotnikov99d7c712021-09-03 19:07:23 -0700151 lastStateChangeTimestamp = timestamp;
152 }
153}
154
155template <class T>
156void MultiStateCounter<T>::setState(state_t state, time_t timestamp) {
157 if (isEnabled && lastStateChangeTimestamp >= 0) {
Dmitri Plotnikov12aaf8e2021-09-03 19:07:23 -0700158 if (timestamp >= lastStateChangeTimestamp) {
159 states[currentState].timeInStateSinceUpdate += timestamp - lastStateChangeTimestamp;
160 } else {
161 ALOGE("setState is called with an earlier timestamp: %lu, previous timestamp: %lu\n",
162 (unsigned long)timestamp, (unsigned long)lastStateChangeTimestamp);
163 // The accumulated durations have become unreliable. For example, if the timestamp
164 // sequence was 1000, 2000, 1000, 3000, if we accumulated the positive deltas,
165 // we would get 4000, which is greater than (last - first). This could lead to
166 // counts exceeding 100%.
167 for (int i = 0; i < stateCount; i++) {
168 states[i].timeInStateSinceUpdate = 0;
169 }
Dmitri Plotnikov5effd852021-08-11 14:55:58 -0700170 }
171 }
172 currentState = state;
173 lastStateChangeTimestamp = timestamp;
174}
175
176template <class T>
Dmitri Plotnikov12aaf8e2021-09-03 19:07:23 -0700177void MultiStateCounter<T>::setValue(state_t state, const T& value) {
178 states[state].counter = value;
179}
180
181template <class T>
Dmitri Plotnikov8940e5d2021-09-23 14:56:30 -0700182const T& MultiStateCounter<T>::updateValue(const T& value, time_t timestamp) {
Dmitri Plotnikov41f56632021-09-28 17:21:54 -0700183 T* returnValue = &emptyValue;
184
Dmitri Plotnikov99d7c712021-09-03 19:07:23 -0700185 // If the counter is disabled, we ignore the update, except when the counter got disabled after
186 // the previous update, in which case we still need to pick up the residual delta.
187 if (isEnabled || lastUpdateTimestamp < lastStateChangeTimestamp) {
188 // Confirm the current state for the side-effect of updating the time-in-state
189 // counter for the current state.
190 setState(currentState, timestamp);
Dmitri Plotnikov5effd852021-08-11 14:55:58 -0700191
Dmitri Plotnikov99d7c712021-09-03 19:07:23 -0700192 if (lastUpdateTimestamp >= 0) {
193 if (timestamp > lastUpdateTimestamp) {
194 if (delta(lastValue, value, &deltaValue)) {
Dmitri Plotnikov41f56632021-09-28 17:21:54 -0700195 returnValue = &deltaValue;
Dmitri Plotnikov99d7c712021-09-03 19:07:23 -0700196 time_t timeSinceUpdate = timestamp - lastUpdateTimestamp;
197 for (int i = 0; i < stateCount; i++) {
198 time_t timeInState = states[i].timeInStateSinceUpdate;
199 if (timeInState) {
200 add(&states[i].counter, deltaValue, timeInState, timeSinceUpdate);
201 states[i].timeInStateSinceUpdate = 0;
202 }
Dmitri Plotnikov12aaf8e2021-09-03 19:07:23 -0700203 }
Dmitri Plotnikov99d7c712021-09-03 19:07:23 -0700204 } else {
205 std::stringstream str;
206 str << "updateValue is called with a value " << valueToString(value)
207 << ", which is lower than the previous value " << valueToString(lastValue)
208 << "\n";
209 ALOGE("%s", str.str().c_str());
Dmitri Plotnikov4b238fb2021-11-09 11:52:08 -0800210
211 for (int i = 0; i < stateCount; i++) {
212 states[i].timeInStateSinceUpdate = 0;
213 }
Dmitri Plotnikov5effd852021-08-11 14:55:58 -0700214 }
Dmitri Plotnikov99d7c712021-09-03 19:07:23 -0700215 } else if (timestamp < lastUpdateTimestamp) {
216 ALOGE("updateValue is called with an earlier timestamp: %lu, previous: %lu\n",
217 (unsigned long)timestamp, (unsigned long)lastUpdateTimestamp);
Dmitri Plotnikov4b238fb2021-11-09 11:52:08 -0800218
219 for (int i = 0; i < stateCount; i++) {
220 states[i].timeInStateSinceUpdate = 0;
221 }
Dmitri Plotnikov5effd852021-08-11 14:55:58 -0700222 }
Dmitri Plotnikov5effd852021-08-11 14:55:58 -0700223 }
Dmitri Plotnikov5effd852021-08-11 14:55:58 -0700224 }
225 lastValue = value;
226 lastUpdateTimestamp = timestamp;
Dmitri Plotnikov41f56632021-09-28 17:21:54 -0700227 return *returnValue;
Dmitri Plotnikov8940e5d2021-09-23 14:56:30 -0700228}
229
230template <class T>
Dmitri Plotnikov40dcce22021-12-10 15:38:17 -0800231void MultiStateCounter<T>::incrementValue(const T& increment, time_t timestamp) {
232 T newValue = lastValue;
233 add(&newValue, increment, 1 /* numerator */, 1 /* denominator */);
234 updateValue(newValue, timestamp);
235}
236
237template <class T>
Dmitri Plotnikov8940e5d2021-09-23 14:56:30 -0700238void MultiStateCounter<T>::addValue(const T& value) {
239 if (!isEnabled) {
240 return;
241 }
Dmitri Plotnikov8940e5d2021-09-23 14:56:30 -0700242 add(&states[currentState].counter, value, 1 /* numerator */, 1 /* denominator */);
Dmitri Plotnikov5effd852021-08-11 14:55:58 -0700243}
244
245template <class T>
Dmitri Plotnikov99d7c712021-09-03 19:07:23 -0700246void MultiStateCounter<T>::reset() {
247 lastStateChangeTimestamp = -1;
248 lastUpdateTimestamp = -1;
249 for (int i = 0; i < stateCount; i++) {
250 states[i].timeInStateSinceUpdate = 0;
251 states[i].counter = emptyValue;
252 }
253}
254
255template <class T>
Dmitri Plotnikov12aaf8e2021-09-03 19:07:23 -0700256uint16_t MultiStateCounter<T>::getStateCount() {
257 return stateCount;
258}
259
260template <class T>
Dmitri Plotnikov5effd852021-08-11 14:55:58 -0700261const T& MultiStateCounter<T>::getCount(state_t state) {
262 return states[state].counter;
263}
264
265template <class T>
266std::string MultiStateCounter<T>::toString() {
267 std::stringstream str;
Dmitri Plotnikov12aaf8e2021-09-03 19:07:23 -0700268 str << "[";
Dmitri Plotnikov5effd852021-08-11 14:55:58 -0700269 for (int i = 0; i < stateCount; i++) {
270 if (i != 0) {
271 str << ", ";
272 }
Dmitri Plotnikov12aaf8e2021-09-03 19:07:23 -0700273 str << i << ": " << valueToString(states[i].counter);
274 if (states[i].timeInStateSinceUpdate > 0) {
275 str << " timeInStateSinceUpdate: " << states[i].timeInStateSinceUpdate;
276 }
Dmitri Plotnikov5effd852021-08-11 14:55:58 -0700277 }
278 str << "]";
Dmitri Plotnikov12aaf8e2021-09-03 19:07:23 -0700279 if (lastUpdateTimestamp >= 0) {
280 str << " updated: " << lastUpdateTimestamp;
281 }
282 if (lastStateChangeTimestamp >= 0) {
283 str << " currentState: " << currentState;
284 if (lastStateChangeTimestamp > lastUpdateTimestamp) {
285 str << " stateChanged: " << lastStateChangeTimestamp;
286 }
287 } else {
288 str << " currentState: none";
289 }
Dmitri Plotnikov8940e5d2021-09-23 14:56:30 -0700290 if (!isEnabled) {
291 str << " disabled";
292 }
Dmitri Plotnikov5effd852021-08-11 14:55:58 -0700293 return str.str();
294}
295
296} // namespace battery
297} // namespace android