1 /*
2  * Copyright (C) 2020 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 #include <cputimeinstate.h>
18 #include <nativehelper/ScopedPrimitiveArray.h>
19 
20 #include "LongArrayMultiStateCounter.h"
21 #include "core_jni_helpers.h"
22 
23 namespace android {
24 
25 static constexpr uint64_t NSEC_PER_MSEC = 1000000;
26 
copyVecsToArray(JNIEnv * env,std::vector<std::vector<uint64_t>> & vec)27 static jlongArray copyVecsToArray(JNIEnv *env, std::vector<std::vector<uint64_t>> &vec) {
28     jsize s = 0;
29     for (const auto &subVec : vec) s += subVec.size();
30     jlongArray ar = env->NewLongArray(s);
31     jsize start = 0;
32     for (auto &subVec : vec) {
33         for (uint32_t i = 0; i < subVec.size(); ++i) subVec[i] /= NSEC_PER_MSEC;
34         env->SetLongArrayRegion(ar, start, subVec.size(),
35                                 reinterpret_cast<const jlong*>(subVec.data()));
36         start += subVec.size();
37     }
38     return ar;
39 }
40 
getUidCpuFreqTimeMs(JNIEnv * env,jclass,jint uid)41 static jlongArray getUidCpuFreqTimeMs(JNIEnv *env, jclass, jint uid) {
42     auto out = android::bpf::getUidCpuFreqTimes(uid);
43     if (!out) return env->NewLongArray(0);
44     return copyVecsToArray(env, out.value());
45 }
46 
47 /**
48  * Computes delta of CPU time-in-freq from the previously supplied counts and adds the delta
49  * to the supplied multi-state counter in accordance with the counter's state.
50  */
addCpuTimeInFreqDelta(jint uid,jlong counterNativePtr,jlong timestampMs,std::optional<std::vector<std::vector<uint64_t>>> timeInFreqDataNanos,jlong deltaOutContainerNativePtr)51 static jboolean addCpuTimeInFreqDelta(
52         jint uid, jlong counterNativePtr, jlong timestampMs,
53         std::optional<std::vector<std::vector<uint64_t>>> timeInFreqDataNanos,
54         jlong deltaOutContainerNativePtr) {
55     if (!timeInFreqDataNanos) {
56         return false;
57     }
58 
59     battery::LongArrayMultiStateCounter *counter =
60             reinterpret_cast<battery::LongArrayMultiStateCounter *>(counterNativePtr);
61     size_t s = 0;
62     for (const auto &cluster : *timeInFreqDataNanos) s += cluster.size();
63 
64     std::vector<uint64_t> flattened;
65     flattened.reserve(s);
66     auto offset = flattened.begin();
67     for (const auto &cluster : *timeInFreqDataNanos) {
68         flattened.insert(offset, cluster.begin(), cluster.end());
69         offset += cluster.size();
70     }
71     for (size_t i = 0; i < s; ++i) {
72         flattened[i] /= NSEC_PER_MSEC;
73     }
74     if (s != counter->getCount(0).size()) { // Counter has at least one state
75         ALOGE("Mismatch between eBPF data size (%d) and the counter size (%d)", (int)s,
76               (int)counter->getCount(0).size());
77         return false;
78     }
79 
80     const std::vector<uint64_t> &delta = counter->updateValue(flattened, timestampMs);
81     if (deltaOutContainerNativePtr) {
82         std::vector<uint64_t> *vector =
83                 reinterpret_cast<std::vector<uint64_t> *>(deltaOutContainerNativePtr);
84         *vector = delta;
85     }
86 
87     return true;
88 }
89 
addDeltaFromBpf(jint uid,jlong counterNativePtr,jlong timestampMs,jlong deltaOutContainerNativePtr)90 static jboolean addDeltaFromBpf(jint uid, jlong counterNativePtr, jlong timestampMs,
91                                 jlong deltaOutContainerNativePtr) {
92     return addCpuTimeInFreqDelta(uid, counterNativePtr, timestampMs,
93                                  android::bpf::getUidCpuFreqTimes(uid), deltaOutContainerNativePtr);
94 }
95 
addDeltaForTest(JNIEnv * env,jclass,jint uid,jlong counterNativePtr,jlong timestampMs,jobjectArray timeInFreqDataNanos,jlong deltaOutContainerNativePtr)96 static jboolean addDeltaForTest(JNIEnv *env, jclass, jint uid, jlong counterNativePtr,
97                                 jlong timestampMs, jobjectArray timeInFreqDataNanos,
98                                 jlong deltaOutContainerNativePtr) {
99     if (!timeInFreqDataNanos) {
100         return addCpuTimeInFreqDelta(uid, counterNativePtr, timestampMs,
101                                      std::optional<std::vector<std::vector<uint64_t>>>(),
102                                      deltaOutContainerNativePtr);
103     }
104 
105     std::vector<std::vector<uint64_t>> timeInFreqData;
106     jsize len = env->GetArrayLength(timeInFreqDataNanos);
107     for (jsize i = 0; i < len; i++) {
108         std::vector<uint64_t> cluster;
109         ScopedLongArrayRO row(env, (jlongArray)env->GetObjectArrayElement(timeInFreqDataNanos, i));
110         cluster.reserve(row.size());
111         for (size_t j = 0; j < row.size(); j++) {
112             cluster.push_back(row[j]);
113         }
114         timeInFreqData.push_back(cluster);
115     }
116     return addCpuTimeInFreqDelta(uid, counterNativePtr, timestampMs, std::optional(timeInFreqData),
117                                  deltaOutContainerNativePtr);
118 }
119 
120 static const JNINativeMethod g_single_methods[] = {
121         {"readBpfData", "(I)[J", (void *)getUidCpuFreqTimeMs},
122 
123         // @CriticalNative
124         {"addDeltaFromBpf", "(IJJJ)Z", (void *)addDeltaFromBpf},
125 
126         // Used for testing
127         {"addDeltaForTest", "(IJJ[[JJ)Z", (void *)addDeltaForTest},
128 };
129 
register_com_android_internal_os_KernelSingleUidTimeReader(JNIEnv * env)130 int register_com_android_internal_os_KernelSingleUidTimeReader(JNIEnv *env) {
131     return RegisterMethodsOrDie(env, "com/android/internal/os/KernelSingleUidTimeReader$Injector",
132                                 g_single_methods, NELEM(g_single_methods));
133 }
134 
135 }
136