1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
|
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.os;
import static com.android.internal.annotations.VisibleForTesting.Visibility.PACKAGE;
import android.annotation.NonNull;
import android.util.Slog;
import android.util.SparseArray;
import com.android.internal.annotations.GuardedBy;
import com.android.internal.annotations.VisibleForTesting;
import dalvik.annotation.optimization.CriticalNative;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
@VisibleForTesting(visibility = PACKAGE)
public class KernelSingleUidTimeReader {
private static final String TAG = KernelSingleUidTimeReader.class.getName();
private static final boolean DBG = false;
private static final String PROC_FILE_DIR = "/proc/uid/";
private static final String PROC_FILE_NAME = "/time_in_state";
private static final String UID_TIMES_PROC_FILE = "/proc/uid_time_in_state";
@VisibleForTesting
public static final int TOTAL_READ_ERROR_COUNT = 5;
@GuardedBy("this")
private final int mCpuFreqsCount;
@GuardedBy("this")
private SparseArray<long[]> mLastUidCpuTimeMs = new SparseArray<>();
@GuardedBy("this")
private int mReadErrorCounter;
@GuardedBy("this")
private boolean mSingleUidCpuTimesAvailable = true;
@GuardedBy("this")
private boolean mBpfTimesAvailable = true;
// We use the freq count obtained from /proc/uid_time_in_state to decide how many longs
// to read from each /proc/uid/<uid>/time_in_state. On the first read, verify if this is
// correct and if not, set {@link #mSingleUidCpuTimesAvailable} to false. This flag will
// indicate whether we checked for validity or not.
@GuardedBy("this")
private boolean mCpuFreqsCountVerified;
private final Injector mInjector;
private static final native boolean canReadBpfTimes();
KernelSingleUidTimeReader(int cpuFreqsCount) {
this(cpuFreqsCount, new Injector());
}
public KernelSingleUidTimeReader(int cpuFreqsCount, Injector injector) {
mInjector = injector;
mCpuFreqsCount = cpuFreqsCount;
if (mCpuFreqsCount == 0) {
mSingleUidCpuTimesAvailable = false;
}
}
public boolean singleUidCpuTimesAvailable() {
return mSingleUidCpuTimesAvailable;
}
public long[] readDeltaMs(int uid) {
synchronized (this) {
if (!mSingleUidCpuTimesAvailable) {
return null;
}
if (mBpfTimesAvailable) {
final long[] cpuTimesMs = mInjector.readBpfData(uid);
if (cpuTimesMs.length == 0) {
mBpfTimesAvailable = false;
} else if (!mCpuFreqsCountVerified && cpuTimesMs.length != mCpuFreqsCount) {
mSingleUidCpuTimesAvailable = false;
return null;
} else {
mCpuFreqsCountVerified = true;
return computeDelta(uid, cpuTimesMs);
}
}
// Read total cpu times from the proc file.
final String procFile = new StringBuilder(PROC_FILE_DIR)
.append(uid)
.append(PROC_FILE_NAME).toString();
final long[] cpuTimesMs;
try {
final byte[] data = mInjector.readData(procFile);
if (!mCpuFreqsCountVerified) {
verifyCpuFreqsCount(data.length, procFile);
}
final ByteBuffer buffer = ByteBuffer.wrap(data);
buffer.order(ByteOrder.nativeOrder());
cpuTimesMs = readCpuTimesFromByteBuffer(buffer);
} catch (Exception e) {
if (++mReadErrorCounter >= TOTAL_READ_ERROR_COUNT) {
mSingleUidCpuTimesAvailable = false;
}
if (DBG) Slog.e(TAG, "Some error occured while reading " + procFile, e);
return null;
}
return computeDelta(uid, cpuTimesMs);
}
}
private void verifyCpuFreqsCount(int numBytes, String procFile) {
final int actualCount = (numBytes / Long.BYTES);
if (mCpuFreqsCount != actualCount) {
mSingleUidCpuTimesAvailable = false;
throw new IllegalStateException("Freq count didn't match,"
+ "count from " + UID_TIMES_PROC_FILE + "=" + mCpuFreqsCount + ", but"
+ "count from " + procFile + "=" + actualCount);
}
mCpuFreqsCountVerified = true;
}
private long[] readCpuTimesFromByteBuffer(ByteBuffer buffer) {
final long[] cpuTimesMs;
cpuTimesMs = new long[mCpuFreqsCount];
for (int i = 0; i < mCpuFreqsCount; ++i) {
// Times read will be in units of 10ms
cpuTimesMs[i] = buffer.getLong() * 10;
}
return cpuTimesMs;
}
/**
* Compute and return cpu times delta of an uid using previously read cpu times and
* {@param latestCpuTimesMs}.
*
* @return delta of cpu times if at least one of the cpu time at a freq is +ve, otherwise null.
*/
public long[] computeDelta(int uid, @NonNull long[] latestCpuTimesMs) {
synchronized (this) {
if (!mSingleUidCpuTimesAvailable) {
return null;
}
// Subtract the last read cpu times to get deltas.
final long[] lastCpuTimesMs = mLastUidCpuTimeMs.get(uid);
final long[] deltaTimesMs = getDeltaLocked(lastCpuTimesMs, latestCpuTimesMs);
if (deltaTimesMs == null) {
if (DBG) Slog.e(TAG, "Malformed data read for uid=" + uid
+ "; last=" + Arrays.toString(lastCpuTimesMs)
+ "; latest=" + Arrays.toString(latestCpuTimesMs));
return null;
}
// If all elements are zero, return null to avoid unnecessary work on the caller side.
boolean hasNonZero = false;
for (int i = deltaTimesMs.length - 1; i >= 0; --i) {
if (deltaTimesMs[i] > 0) {
hasNonZero = true;
break;
}
}
if (hasNonZero) {
mLastUidCpuTimeMs.put(uid, latestCpuTimesMs);
return deltaTimesMs;
} else {
return null;
}
}
}
/**
* Returns null if the latest cpu times are not valid**, otherwise delta of
* {@param latestCpuTimesMs} and {@param lastCpuTimesMs}.
*
* **latest cpu times are considered valid if all the cpu times are +ve and
* greater than or equal to previously read cpu times.
*/
@GuardedBy("this")
@VisibleForTesting(visibility = PACKAGE)
public long[] getDeltaLocked(long[] lastCpuTimesMs, @NonNull long[] latestCpuTimesMs) {
for (int i = latestCpuTimesMs.length - 1; i >= 0; --i) {
if (latestCpuTimesMs[i] < 0) {
return null;
}
}
if (lastCpuTimesMs == null) {
return latestCpuTimesMs;
}
final long[] deltaTimesMs = new long[latestCpuTimesMs.length];
for (int i = latestCpuTimesMs.length - 1; i >= 0; --i) {
deltaTimesMs[i] = latestCpuTimesMs[i] - lastCpuTimesMs[i];
if (deltaTimesMs[i] < 0) {
return null;
}
}
return deltaTimesMs;
}
public void setAllUidsCpuTimesMs(SparseArray<long[]> allUidsCpuTimesMs) {
synchronized (this) {
mLastUidCpuTimeMs.clear();
for (int i = allUidsCpuTimesMs.size() - 1; i >= 0; --i) {
final long[] cpuTimesMs = allUidsCpuTimesMs.valueAt(i);
if (cpuTimesMs != null) {
mLastUidCpuTimeMs.put(allUidsCpuTimesMs.keyAt(i), cpuTimesMs.clone());
}
}
}
}
public void removeUid(int uid) {
synchronized (this) {
mLastUidCpuTimeMs.delete(uid);
}
}
public void removeUidsInRange(int startUid, int endUid) {
if (endUid < startUid) {
return;
}
synchronized (this) {
mLastUidCpuTimeMs.put(startUid, null);
mLastUidCpuTimeMs.put(endUid, null);
final int startIdx = mLastUidCpuTimeMs.indexOfKey(startUid);
final int endIdx = mLastUidCpuTimeMs.indexOfKey(endUid);
mLastUidCpuTimeMs.removeAtRange(startIdx, endIdx - startIdx + 1);
}
}
/**
* Retrieves CPU time-in-state data for the specified UID and adds the accumulated
* delta to the supplied counter.
*/
public void addDelta(int uid, LongArrayMultiStateCounter counter, long timestampMs) {
mInjector.addDelta(uid, counter, timestampMs, null);
}
/**
* Same as {@link #addDelta(int, LongArrayMultiStateCounter, long)}, also returning
* the delta in the supplied array container.
*/
public void addDelta(int uid, LongArrayMultiStateCounter counter, long timestampMs,
LongArrayMultiStateCounter.LongArrayContainer deltaContainer) {
mInjector.addDelta(uid, counter, timestampMs, deltaContainer);
}
@VisibleForTesting
public static class Injector {
public byte[] readData(String procFile) throws IOException {
return Files.readAllBytes(Paths.get(procFile));
}
public native long[] readBpfData(int uid);
/**
* Reads CPU time-in-state data for the specified UID and adds the delta since the
* previous call to the current state stats in the LongArrayMultiStateCounter.
*
* The delta is also returned via the optional deltaOut parameter.
*/
public boolean addDelta(int uid, LongArrayMultiStateCounter counter, long timestampMs,
LongArrayMultiStateCounter.LongArrayContainer deltaOut) {
return addDeltaFromBpf(uid, counter.mNativeObject, timestampMs,
deltaOut != null ? deltaOut.mNativeObject : 0);
}
@CriticalNative
private static native boolean addDeltaFromBpf(int uid,
long longArrayMultiStateCounterNativePointer, long timestampMs,
long longArrayContainerNativePointer);
/**
* Used for testing.
*
* Takes mock cpu-time-in-frequency data and uses it the same way eBPF data would be used.
*/
public boolean addDeltaForTest(int uid, LongArrayMultiStateCounter counter,
long timestampMs, long[][] timeInFreqDataNanos,
LongArrayMultiStateCounter.LongArrayContainer deltaOut) {
return addDeltaForTest(uid, counter.mNativeObject, timestampMs, timeInFreqDataNanos,
deltaOut != null ? deltaOut.mNativeObject : 0);
}
private static native boolean addDeltaForTest(int uid,
long longArrayMultiStateCounterNativePointer, long timestampMs,
long[][] timeInFreqDataNanos, long longArrayContainerNativePointer);
}
@VisibleForTesting
public SparseArray<long[]> getLastUidCpuTimeMs() {
return mLastUidCpuTimeMs;
}
@VisibleForTesting
public void setSingleUidCpuTimesAvailable(boolean singleUidCpuTimesAvailable) {
mSingleUidCpuTimesAvailable = singleUidCpuTimesAvailable;
}
}
|