Merge "SF: Use RAII for TransactionTracing"
diff --git a/libs/sensor/Sensor.cpp b/libs/sensor/Sensor.cpp
index e1560c0..da88e85 100644
--- a/libs/sensor/Sensor.cpp
+++ b/libs/sensor/Sensor.cpp
@@ -472,7 +472,15 @@
 }
 
 void Sensor::setId(int32_t id) {
-    mUuid.i64[0] = id;
+    mId = id;
+}
+
+int32_t Sensor::getId() const {
+    return mId;
+}
+
+void Sensor::anonymizeUuid() {
+    mUuid.i64[0] = mId;
     mUuid.i64[1] = 0;
 }
 
@@ -489,17 +497,14 @@
     }
 }
 
-int32_t Sensor::getId() const {
-    return int32_t(mUuid.i64[0]);
-}
-
 size_t Sensor::getFlattenedSize() const {
     size_t fixedSize =
             sizeof(mVersion) + sizeof(mHandle) + sizeof(mType) +
             sizeof(mMinValue) + sizeof(mMaxValue) + sizeof(mResolution) +
             sizeof(mPower) + sizeof(mMinDelay) + sizeof(mFifoMaxEventCount) +
             sizeof(mFifoMaxEventCount) + sizeof(mRequiredPermissionRuntime) +
-            sizeof(mRequiredAppOp) + sizeof(mMaxDelay) + sizeof(mFlags) + sizeof(mUuid);
+            sizeof(mRequiredAppOp) + sizeof(mMaxDelay) + sizeof(mFlags) +
+            sizeof(mUuid) + sizeof(mId);
 
     size_t variableSize =
             sizeof(uint32_t) + FlattenableUtils::align<4>(mName.length()) +
@@ -533,18 +538,8 @@
     FlattenableUtils::write(buffer, size, mRequiredAppOp);
     FlattenableUtils::write(buffer, size, mMaxDelay);
     FlattenableUtils::write(buffer, size, mFlags);
-    if (mUuid.i64[1] != 0) {
-        // We should never hit this case with our current API, but we
-        // could via a careless API change.  If that happens,
-        // this code will keep us from leaking our UUID (while probably
-        // breaking dynamic sensors).  See b/29547335.
-        ALOGW("Sensor with UUID being flattened; sending 0.  Expect "
-              "bad dynamic sensor behavior");
-        uuid_t tmpUuid;  // default constructor makes this 0.
-        FlattenableUtils::write(buffer, size, tmpUuid);
-    } else {
-        FlattenableUtils::write(buffer, size, mUuid);
-    }
+    FlattenableUtils::write(buffer, size, mUuid);
+    FlattenableUtils::write(buffer, size, mId);
     return NO_ERROR;
 }
 
@@ -584,7 +579,7 @@
 
     size_t fixedSize2 =
             sizeof(mRequiredPermissionRuntime) + sizeof(mRequiredAppOp) + sizeof(mMaxDelay) +
-            sizeof(mFlags) + sizeof(mUuid);
+            sizeof(mFlags) + sizeof(mUuid) + sizeof(mId);
     if (size < fixedSize2) {
         return NO_MEMORY;
     }
@@ -594,6 +589,7 @@
     FlattenableUtils::read(buffer, size, mMaxDelay);
     FlattenableUtils::read(buffer, size, mFlags);
     FlattenableUtils::read(buffer, size, mUuid);
+    FlattenableUtils::read(buffer, size, mId);
     return NO_ERROR;
 }
 
diff --git a/libs/sensor/include/sensor/Sensor.h b/libs/sensor/include/sensor/Sensor.h
index 374b68f..bae8a13 100644
--- a/libs/sensor/include/sensor/Sensor.h
+++ b/libs/sensor/include/sensor/Sensor.h
@@ -96,11 +96,8 @@
     bool isDirectChannelTypeSupported(int32_t sharedMemType) const;
     int32_t getReportingMode() const;
 
-    // Note that after setId() has been called, getUuid() no longer
-    // returns the UUID.
-    // TODO(b/29547335): Remove getUuid(), add getUuidIndex(), and
-    //     make sure setId() doesn't change the UuidIndex.
     const uuid_t& getUuid() const;
+    void  anonymizeUuid();
     int32_t getId() const;
     void setId(int32_t id);
 
@@ -132,10 +129,8 @@
     int32_t mRequiredAppOp;
     int32_t mMaxDelay;
     uint32_t mFlags;
-    // TODO(b/29547335): Get rid of this field and replace with an index.
-    //     The index will be into a separate global vector of UUIDs.
-    //     Also add an mId field (and change flatten/unflatten appropriately).
     uuid_t  mUuid;
+    int32_t mId;
     static void flattenString8(void*& buffer, size_t& size, const String8& string8);
     static bool unflattenString8(void const*& buffer, size_t& size, String8& outputString8);
 };
diff --git a/services/gpuservice/Android.bp b/services/gpuservice/Android.bp
index b9b6a19..5b4ee21 100644
--- a/services/gpuservice/Android.bp
+++ b/services/gpuservice/Android.bp
@@ -31,6 +31,7 @@
         "libcutils",
         "libgfxstats",
         "libgpumem",
+        "libgpuwork",
         "libgpumemtracer",
         "libgraphicsenv",
         "liblog",
diff --git a/services/gpuservice/GpuService.cpp b/services/gpuservice/GpuService.cpp
index 52d5d4f..7b9782f 100644
--- a/services/gpuservice/GpuService.cpp
+++ b/services/gpuservice/GpuService.cpp
@@ -25,6 +25,7 @@
 #include <binder/PermissionCache.h>
 #include <cutils/properties.h>
 #include <gpumem/GpuMem.h>
+#include <gpuwork/GpuWork.h>
 #include <gpustats/GpuStats.h>
 #include <private/android_filesystem_config.h>
 #include <tracing/GpuMemTracer.h>
@@ -50,13 +51,20 @@
 
 GpuService::GpuService()
       : mGpuMem(std::make_shared<GpuMem>()),
+        mGpuWork(std::make_shared<gpuwork::GpuWork>()),
         mGpuStats(std::make_unique<GpuStats>()),
         mGpuMemTracer(std::make_unique<GpuMemTracer>()) {
-    std::thread asyncInitThread([this]() {
+
+    std::thread gpuMemAsyncInitThread([this]() {
         mGpuMem->initialize();
         mGpuMemTracer->initialize(mGpuMem);
     });
-    asyncInitThread.detach();
+    gpuMemAsyncInitThread.detach();
+
+    std::thread gpuWorkAsyncInitThread([this]() {
+        mGpuWork->initialize();
+    });
+    gpuWorkAsyncInitThread.detach();
 };
 
 void GpuService::setGpuStats(const std::string& driverPackageName,
@@ -124,6 +132,7 @@
         bool dumpDriverInfo = false;
         bool dumpMem = false;
         bool dumpStats = false;
+        bool dumpWork = false;
         size_t numArgs = args.size();
 
         if (numArgs) {
@@ -134,9 +143,11 @@
                     dumpDriverInfo = true;
                 } else if (args[index] == String16("--gpumem")) {
                     dumpMem = true;
+                } else if (args[index] == String16("--gpuwork")) {
+                    dumpWork = true;
                 }
             }
-            dumpAll = !(dumpDriverInfo || dumpMem || dumpStats);
+            dumpAll = !(dumpDriverInfo || dumpMem || dumpStats || dumpWork);
         }
 
         if (dumpAll || dumpDriverInfo) {
@@ -151,6 +162,10 @@
             mGpuStats->dump(args, &result);
             result.append("\n");
         }
+         if (dumpAll || dumpWork) {
+            mGpuWork->dump(args, &result);
+            result.append("\n");
+        }
     }
 
     write(fd, result.c_str(), result.size());
diff --git a/services/gpuservice/GpuService.h b/services/gpuservice/GpuService.h
index 409084b..d7313d1 100644
--- a/services/gpuservice/GpuService.h
+++ b/services/gpuservice/GpuService.h
@@ -28,6 +28,10 @@
 
 namespace android {
 
+namespace gpuwork {
+class GpuWork;
+}
+
 class GpuMem;
 class GpuStats;
 class GpuMemTracer;
@@ -77,6 +81,7 @@
      * Attributes
      */
     std::shared_ptr<GpuMem> mGpuMem;
+    std::shared_ptr<gpuwork::GpuWork> mGpuWork;
     std::unique_ptr<GpuStats> mGpuStats;
     std::unique_ptr<GpuMemTracer> mGpuMemTracer;
     std::mutex mLock;
diff --git a/services/gpuservice/gpuwork/Android.bp b/services/gpuservice/gpuwork/Android.bp
new file mode 100644
index 0000000..89b31a6
--- /dev/null
+++ b/services/gpuservice/gpuwork/Android.bp
@@ -0,0 +1,61 @@
+// Copyright 2022 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 {
+    default_applicable_licenses: ["frameworks_native_license"],
+}
+
+cc_library_shared {
+    name: "libgpuwork",
+    srcs: [
+        "GpuWork.cpp",
+    ],
+    header_libs: [
+        "gpu_work_structs",
+    ],
+    shared_libs: [
+        "libbase",
+        "libbinder",
+        "libbpf_bcc",
+        "libbpf_android",
+        "libcutils",
+        "liblog",
+        "libstatslog",
+        "libstatspull",
+        "libutils",
+    ],
+    export_include_dirs: [
+        "include",
+    ],
+    export_header_lib_headers: [
+        "gpu_work_structs",
+    ],
+    export_shared_lib_headers: [
+        "libbase",
+        "libbpf_android",
+        "libstatspull",
+    ],
+    cppflags: [
+        "-Wall",
+        "-Werror",
+        "-Wformat",
+        "-Wthread-safety",
+        "-Wunused",
+        "-Wunreachable-code",
+    ],
+    required: [
+        "bpfloader",
+        "gpu_work.o",
+    ],
+}
diff --git a/services/gpuservice/gpuwork/GpuWork.cpp b/services/gpuservice/gpuwork/GpuWork.cpp
new file mode 100644
index 0000000..e7b1cd4
--- /dev/null
+++ b/services/gpuservice/gpuwork/GpuWork.cpp
@@ -0,0 +1,504 @@
+/*
+ * Copyright 2022 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.
+ */
+
+#undef LOG_TAG
+#define LOG_TAG "GpuWork"
+#define ATRACE_TAG ATRACE_TAG_GRAPHICS
+
+#include "gpuwork/GpuWork.h"
+
+#include <android-base/stringprintf.h>
+#include <binder/PermissionCache.h>
+#include <bpf/WaitForProgsLoaded.h>
+#include <libbpf.h>
+#include <libbpf_android.h>
+#include <log/log.h>
+#include <random>
+#include <stats_event.h>
+#include <statslog.h>
+#include <unistd.h>
+#include <utils/Timers.h>
+#include <utils/Trace.h>
+
+#include <bit>
+#include <chrono>
+#include <cstdint>
+#include <limits>
+#include <map>
+#include <mutex>
+#include <unordered_map>
+#include <vector>
+
+#include "gpuwork/gpu_work.h"
+
+#define MS_IN_NS (1000000)
+
+namespace android {
+namespace gpuwork {
+
+namespace {
+
+// Gets a BPF map from |mapPath|.
+template <class Key, class Value>
+bool getBpfMap(const char* mapPath, bpf::BpfMap<Key, Value>* out) {
+    errno = 0;
+    auto map = bpf::BpfMap<Key, Value>(mapPath);
+    if (!map.isValid()) {
+        ALOGW("Failed to create bpf map from %s [%d(%s)]", mapPath, errno, strerror(errno));
+        return false;
+    }
+    *out = std::move(map);
+    return true;
+}
+
+template <typename SourceType>
+inline int32_t cast_int32(SourceType) = delete;
+
+template <typename SourceType>
+inline int32_t bitcast_int32(SourceType) = delete;
+
+template <>
+inline int32_t bitcast_int32<uint32_t>(uint32_t source) {
+    int32_t result;
+    memcpy(&result, &source, sizeof(result));
+    return result;
+}
+
+template <>
+inline int32_t cast_int32<uint64_t>(uint64_t source) {
+    if (source > std::numeric_limits<int32_t>::max()) {
+        return std::numeric_limits<int32_t>::max();
+    }
+    return static_cast<int32_t>(source);
+}
+
+template <>
+inline int32_t cast_int32<long long>(long long source) {
+    if (source > std::numeric_limits<int32_t>::max()) {
+        return std::numeric_limits<int32_t>::max();
+    } else if (source < std::numeric_limits<int32_t>::min()) {
+        return std::numeric_limits<int32_t>::min();
+    }
+    return static_cast<int32_t>(source);
+}
+
+} // namespace
+
+using base::StringAppendF;
+
+GpuWork::~GpuWork() {
+    // If we created our clearer thread, then we must stop it and join it.
+    if (mMapClearerThread.joinable()) {
+        // Tell the thread to terminate.
+        {
+            std::scoped_lock<std::mutex> lock(mMutex);
+            mIsTerminating = true;
+            mIsTerminatingConditionVariable.notify_all();
+        }
+
+        // Now, we can join it.
+        mMapClearerThread.join();
+    }
+
+    {
+        std::scoped_lock<std::mutex> lock(mMutex);
+        if (mStatsdRegistered) {
+            AStatsManager_clearPullAtomCallback(android::util::GPU_FREQ_TIME_IN_STATE_PER_UID);
+        }
+    }
+
+    bpf_detach_tracepoint("power", "gpu_work_period");
+}
+
+void GpuWork::initialize() {
+    // Make sure BPF programs are loaded.
+    bpf::waitForProgsLoaded();
+
+    waitForPermissions();
+
+    // Get the BPF maps before trying to attach the BPF program; if we can't get
+    // the maps then there is no point in attaching the BPF program.
+    {
+        std::lock_guard<std::mutex> lock(mMutex);
+
+        if (!getBpfMap("/sys/fs/bpf/map_gpu_work_gpu_work_map", &mGpuWorkMap)) {
+            return;
+        }
+
+        if (!getBpfMap("/sys/fs/bpf/map_gpu_work_gpu_work_global_data", &mGpuWorkGlobalDataMap)) {
+            return;
+        }
+
+        mPreviousMapClearTimePoint = std::chrono::steady_clock::now();
+    }
+
+    // Attach the tracepoint ONLY if we got the map above.
+    if (!attachTracepoint("/sys/fs/bpf/prog_gpu_work_tracepoint_power_gpu_work_period", "power",
+                          "gpu_work_period")) {
+        return;
+    }
+
+    // Create the map clearer thread, and store it to |mMapClearerThread|.
+    std::thread thread([this]() { periodicallyClearMap(); });
+
+    mMapClearerThread.swap(thread);
+
+    {
+        std::lock_guard<std::mutex> lock(mMutex);
+        AStatsManager_setPullAtomCallback(int32_t{android::util::GPU_FREQ_TIME_IN_STATE_PER_UID},
+                                          nullptr, GpuWork::pullAtomCallback, this);
+        mStatsdRegistered = true;
+    }
+
+    ALOGI("Initialized!");
+
+    mInitialized.store(true);
+}
+
+void GpuWork::dump(const Vector<String16>& /* args */, std::string* result) {
+    if (!mInitialized.load()) {
+        result->append("GPU time in state information is not available.\n");
+        return;
+    }
+
+    // Ordered map ensures output data is sorted by UID.
+    std::map<Uid, UidTrackingInfo> dumpMap;
+
+    {
+        std::lock_guard<std::mutex> lock(mMutex);
+
+        if (!mGpuWorkMap.isValid()) {
+            result->append("GPU time in state map is not available.\n");
+            return;
+        }
+
+        // Iteration of BPF hash maps can be unreliable (no data races, but elements
+        // may be repeated), as the map is typically being modified by other
+        // threads. The buckets are all preallocated. Our eBPF program only updates
+        // entries (in-place) or adds entries. |GpuWork| only iterates or clears the
+        // map while holding |mMutex|. Given this, we should be able to iterate over
+        // all elements reliably. In the worst case, we might see elements more than
+        // once.
+
+        // Note that userspace reads of BPF maps make a copy of the value, and
+        // thus the returned value is not being concurrently accessed by the BPF
+        // program (no atomic reads needed below).
+
+        mGpuWorkMap.iterateWithValue([&dumpMap](const Uid& key, const UidTrackingInfo& value,
+                                                const android::bpf::BpfMap<Uid, UidTrackingInfo>&)
+                                             -> base::Result<void> {
+            dumpMap[key] = value;
+            return {};
+        });
+    }
+
+    // Find the largest frequency where some UID has spent time in that frequency.
+    size_t largestFrequencyWithTime = 0;
+    for (const auto& uidToUidInfo : dumpMap) {
+        for (size_t i = largestFrequencyWithTime + 1; i < kNumTrackedFrequencies; ++i) {
+            if (uidToUidInfo.second.frequency_times_ns[i] > 0) {
+                largestFrequencyWithTime = i;
+            }
+        }
+    }
+
+    // Dump time in state information.
+    // E.g.
+    // uid/freq: 0MHz 50MHz 100MHz ...
+    // 1000: 0 0 0 0 ...
+    // 1003: 0 0 3456 0 ...
+    // [errors:3]1006: 0 0 3456 0 ...
+
+    // Header.
+    result->append("GPU time in frequency state in ms.\n");
+    result->append("uid/freq: 0MHz");
+    for (size_t i = 1; i <= largestFrequencyWithTime; ++i) {
+        StringAppendF(result, " %zuMHz", i * 50);
+    }
+    result->append("\n");
+
+    for (const auto& uidToUidInfo : dumpMap) {
+        if (uidToUidInfo.second.error_count) {
+            StringAppendF(result, "[errors:%" PRIu32 "]", uidToUidInfo.second.error_count);
+        }
+        StringAppendF(result, "%" PRIu32 ":", uidToUidInfo.first);
+        for (size_t i = 0; i <= largestFrequencyWithTime; ++i) {
+            StringAppendF(result, " %" PRIu64,
+                          uidToUidInfo.second.frequency_times_ns[i] / MS_IN_NS);
+        }
+        result->append("\n");
+    }
+}
+
+bool GpuWork::attachTracepoint(const char* programPath, const char* tracepointGroup,
+                               const char* tracepointName) {
+    errno = 0;
+    base::unique_fd fd(bpf::retrieveProgram(programPath));
+    if (fd < 0) {
+        ALOGW("Failed to retrieve pinned program from %s [%d(%s)]", programPath, errno,
+              strerror(errno));
+        return false;
+    }
+
+    // Attach the program to the tracepoint. The tracepoint is automatically enabled.
+    errno = 0;
+    int count = 0;
+    while (bpf_attach_tracepoint(fd.get(), tracepointGroup, tracepointName) < 0) {
+        if (++count > kGpuWaitTimeoutSeconds) {
+            ALOGW("Failed to attach bpf program to %s/%s tracepoint [%d(%s)]", tracepointGroup,
+                  tracepointName, errno, strerror(errno));
+            return false;
+        }
+        // Retry until GPU driver loaded or timeout.
+        sleep(1);
+        errno = 0;
+    }
+
+    return true;
+}
+
+AStatsManager_PullAtomCallbackReturn GpuWork::pullAtomCallback(int32_t atomTag,
+                                                               AStatsEventList* data,
+                                                               void* cookie) {
+    ATRACE_CALL();
+
+    GpuWork* gpuWork = reinterpret_cast<GpuWork*>(cookie);
+    if (atomTag == android::util::GPU_FREQ_TIME_IN_STATE_PER_UID) {
+        return gpuWork->pullFrequencyAtoms(data);
+    }
+
+    return AStatsManager_PULL_SKIP;
+}
+
+AStatsManager_PullAtomCallbackReturn GpuWork::pullFrequencyAtoms(AStatsEventList* data) {
+    ATRACE_CALL();
+
+    if (!data || !mInitialized.load()) {
+        return AStatsManager_PULL_SKIP;
+    }
+
+    std::lock_guard<std::mutex> lock(mMutex);
+
+    if (!mGpuWorkMap.isValid()) {
+        return AStatsManager_PULL_SKIP;
+    }
+
+    std::unordered_map<Uid, UidTrackingInfo> uidInfos;
+
+    // Iteration of BPF hash maps can be unreliable (no data races, but elements
+    // may be repeated), as the map is typically being modified by other
+    // threads. The buckets are all preallocated. Our eBPF program only updates
+    // entries (in-place) or adds entries. |GpuWork| only iterates or clears the
+    // map while holding |mMutex|. Given this, we should be able to iterate over
+    // all elements reliably. In the worst case, we might see elements more than
+    // once.
+
+    // Note that userspace reads of BPF maps make a copy of the value, and thus
+    // the returned value is not being concurrently accessed by the BPF program
+    // (no atomic reads needed below).
+
+    mGpuWorkMap.iterateWithValue(
+            [&uidInfos](const Uid& key, const UidTrackingInfo& value,
+                        const android::bpf::BpfMap<Uid, UidTrackingInfo>&) -> base::Result<void> {
+                uidInfos[key] = value;
+                return {};
+            });
+
+    ALOGI("pullFrequencyAtoms: uidInfos.size() == %zu", uidInfos.size());
+
+    // Get a list of just the UIDs; the order does not matter.
+    std::vector<Uid> uids;
+    for (const auto& pair : uidInfos) {
+        uids.push_back(pair.first);
+    }
+
+    std::random_device device;
+    std::default_random_engine random_engine(device());
+
+    // If we have more than |kNumSampledUids| UIDs, choose |kNumSampledUids|
+    // random UIDs. We swap them to the front of the list. Given the list
+    // indices 0..i..n-1, we have the following inclusive-inclusive ranges:
+    // - [0, i-1] == the randomly chosen elements.
+    // - [i, n-1] == the remaining unchosen elements.
+    if (uids.size() > kNumSampledUids) {
+        for (size_t i = 0; i < kNumSampledUids; ++i) {
+            std::uniform_int_distribution<size_t> uniform_dist(i, uids.size() - 1);
+            size_t random_index = uniform_dist(random_engine);
+            std::swap(uids[i], uids[random_index]);
+        }
+        // Only keep the front |kNumSampledUids| elements.
+        uids.resize(kNumSampledUids);
+    }
+
+    ALOGI("pullFrequencyAtoms: uids.size() == %zu", uids.size());
+
+    auto now = std::chrono::steady_clock::now();
+
+    int32_t duration = cast_int32(
+            std::chrono::duration_cast<std::chrono::seconds>(now - mPreviousMapClearTimePoint)
+                    .count());
+
+    for (const Uid uid : uids) {
+        const UidTrackingInfo& info = uidInfos[uid];
+        ALOGI("pullFrequencyAtoms: adding stats for UID %" PRIu32, uid);
+        android::util::addAStatsEvent(data, int32_t{android::util::GPU_FREQ_TIME_IN_STATE_PER_UID},
+                                      // uid
+                                      bitcast_int32(uid),
+                                      // time_duration_seconds
+                                      int32_t{duration},
+                                      // max_freq_mhz
+                                      int32_t{1000},
+                                      // freq_0_mhz_time_millis
+                                      cast_int32(info.frequency_times_ns[0] / 1000000),
+                                      // freq_50_mhz_time_millis
+                                      cast_int32(info.frequency_times_ns[1] / 1000000),
+                                      // ... etc. ...
+                                      cast_int32(info.frequency_times_ns[2] / 1000000),
+                                      cast_int32(info.frequency_times_ns[3] / 1000000),
+                                      cast_int32(info.frequency_times_ns[4] / 1000000),
+                                      cast_int32(info.frequency_times_ns[5] / 1000000),
+                                      cast_int32(info.frequency_times_ns[6] / 1000000),
+                                      cast_int32(info.frequency_times_ns[7] / 1000000),
+                                      cast_int32(info.frequency_times_ns[8] / 1000000),
+                                      cast_int32(info.frequency_times_ns[9] / 1000000),
+                                      cast_int32(info.frequency_times_ns[10] / 1000000),
+                                      cast_int32(info.frequency_times_ns[11] / 1000000),
+                                      cast_int32(info.frequency_times_ns[12] / 1000000),
+                                      cast_int32(info.frequency_times_ns[13] / 1000000),
+                                      cast_int32(info.frequency_times_ns[14] / 1000000),
+                                      cast_int32(info.frequency_times_ns[15] / 1000000),
+                                      cast_int32(info.frequency_times_ns[16] / 1000000),
+                                      cast_int32(info.frequency_times_ns[17] / 1000000),
+                                      cast_int32(info.frequency_times_ns[18] / 1000000),
+                                      cast_int32(info.frequency_times_ns[19] / 1000000),
+                                      // freq_1000_mhz_time_millis
+                                      cast_int32(info.frequency_times_ns[20] / 1000000));
+    }
+    clearMap();
+    return AStatsManager_PULL_SUCCESS;
+}
+
+void GpuWork::periodicallyClearMap() {
+    std::unique_lock<std::mutex> lock(mMutex);
+
+    auto previousTime = std::chrono::steady_clock::now();
+
+    while (true) {
+        if (mIsTerminating) {
+            break;
+        }
+        auto nextTime = std::chrono::steady_clock::now();
+        auto differenceSeconds =
+                std::chrono::duration_cast<std::chrono::seconds>(nextTime - previousTime);
+        if (differenceSeconds.count() > kMapClearerWaitDurationSeconds) {
+            // It has been >1 hour, so clear the map, if needed.
+            clearMapIfNeeded();
+            // We only update |previousTime| if we actually checked the map.
+            previousTime = nextTime;
+        }
+        // Sleep for ~1 hour. It does not matter if we don't check the map for 2
+        // hours.
+        mIsTerminatingConditionVariable.wait_for(lock,
+                                                 std::chrono::seconds{
+                                                         kMapClearerWaitDurationSeconds});
+    }
+}
+
+void GpuWork::clearMapIfNeeded() {
+    if (!mInitialized.load() || !mGpuWorkMap.isValid() || !mGpuWorkGlobalDataMap.isValid()) {
+        ALOGW("Map clearing could not occur because we are not initialized properly");
+        return;
+    }
+
+    base::Result<GlobalData> globalData = mGpuWorkGlobalDataMap.readValue(0);
+    if (!globalData.ok()) {
+        ALOGW("Could not read BPF global data map entry");
+        return;
+    }
+
+    // Note that userspace reads of BPF maps make a copy of the value, and thus
+    // the return value is not being concurrently accessed by the BPF program
+    // (no atomic reads needed below).
+
+    uint64_t numEntries = globalData.value().num_map_entries;
+
+    // If the map is <=75% full, we do nothing.
+    if (numEntries <= (kMaxTrackedUids / 4) * 3) {
+        return;
+    }
+
+    clearMap();
+}
+
+void GpuWork::clearMap() {
+    if (!mInitialized.load() || !mGpuWorkMap.isValid() || !mGpuWorkGlobalDataMap.isValid()) {
+        ALOGW("Map clearing could not occur because we are not initialized properly");
+        return;
+    }
+
+    base::Result<GlobalData> globalData = mGpuWorkGlobalDataMap.readValue(0);
+    if (!globalData.ok()) {
+        ALOGW("Could not read BPF global data map entry");
+        return;
+    }
+
+    // Iterating BPF maps to delete keys is tricky. If we just repeatedly call
+    // |getFirstKey()| and delete that, we may loop forever (or for a long time)
+    // because our BPF program might be repeatedly re-adding UID keys. Also,
+    // even if we limit the number of elements we try to delete, we might only
+    // delete new entries, leaving old entries in the map. If we delete a key A
+    // and then call |getNextKey(A)|, the first key in the map is returned, so
+    // we have the same issue.
+    //
+    // Thus, we instead get the next key and then delete the previous key. We
+    // also limit the number of deletions we try, just in case.
+
+    base::Result<Uid> key = mGpuWorkMap.getFirstKey();
+
+    for (size_t i = 0; i < kMaxTrackedUids; ++i) {
+        if (!key.ok()) {
+            break;
+        }
+        base::Result<Uid> previousKey = key;
+        key = mGpuWorkMap.getNextKey(previousKey.value());
+        mGpuWorkMap.deleteValue(previousKey.value());
+    }
+
+    // Reset our counter; |globalData| is a copy of the data, so we have to use
+    // |writeValue|.
+    globalData.value().num_map_entries = 0;
+    mGpuWorkGlobalDataMap.writeValue(0, globalData.value(), BPF_ANY);
+
+    // Update |mPreviousMapClearTimePoint| so we know when we started collecting
+    // the stats.
+    mPreviousMapClearTimePoint = std::chrono::steady_clock::now();
+}
+
+void GpuWork::waitForPermissions() {
+    const String16 permissionRegisterStatsPullAtom(kPermissionRegisterStatsPullAtom);
+    int count = 0;
+    while (!PermissionCache::checkPermission(permissionRegisterStatsPullAtom, getpid(), getuid())) {
+        if (++count > kPermissionsWaitTimeoutSeconds) {
+            ALOGW("Timed out waiting for android.permission.REGISTER_STATS_PULL_ATOM");
+            return;
+        }
+        // Retry.
+        sleep(1);
+    }
+}
+
+} // namespace gpuwork
+} // namespace android
diff --git a/services/gpuservice/gpuwork/bpfprogs/Android.bp b/services/gpuservice/gpuwork/bpfprogs/Android.bp
new file mode 100644
index 0000000..b3c4eff
--- /dev/null
+++ b/services/gpuservice/gpuwork/bpfprogs/Android.bp
@@ -0,0 +1,35 @@
+// Copyright 2022 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 {
+    default_applicable_licenses: ["frameworks_native_license"],
+}
+
+bpf {
+    name: "gpu_work.o",
+    srcs: ["gpu_work.c"],
+    cflags: [
+        "-Wall",
+        "-Werror",
+        "-Wformat",
+        "-Wthread-safety",
+        "-Wunused",
+        "-Wunreachable-code",
+    ],
+}
+
+cc_library_headers {
+    name: "gpu_work_structs",
+    export_include_dirs: ["include"],
+}
diff --git a/services/gpuservice/gpuwork/bpfprogs/gpu_work.c b/services/gpuservice/gpuwork/bpfprogs/gpu_work.c
new file mode 100644
index 0000000..a0e1b22
--- /dev/null
+++ b/services/gpuservice/gpuwork/bpfprogs/gpu_work.c
@@ -0,0 +1,219 @@
+/*
+ * Copyright 2022 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.
+ */
+
+#include "include/gpuwork/gpu_work.h"
+
+#include <linux/bpf.h>
+#include <stddef.h>
+#include <stdint.h>
+
+#ifdef MOCK_BPF
+#include <test/mock_bpf_helpers.h>
+#else
+#include <bpf_helpers.h>
+#endif
+
+#define S_IN_NS (1000000000)
+#define MHZ_IN_KHZS (1000)
+
+typedef uint32_t Uid;
+
+// A map from UID to |UidTrackingInfo|.
+DEFINE_BPF_MAP_GRW(gpu_work_map, HASH, Uid, UidTrackingInfo, kMaxTrackedUids, AID_GRAPHICS);
+
+// A map containing a single entry of |GlobalData|.
+DEFINE_BPF_MAP_GRW(gpu_work_global_data, ARRAY, uint32_t, GlobalData, 1, AID_GRAPHICS);
+
+// GpuUidWorkPeriodEvent defines the structure of a kernel tracepoint under the
+// tracepoint system (also referred to as the group) "power" and name
+// "gpu_work_period". In summary, the kernel tracepoint should be
+// "power/gpu_work_period", available at:
+//
+//  /sys/kernel/tracing/events/power/gpu_work_period/
+//
+// GpuUidWorkPeriodEvent defines a non-overlapping, non-zero period of time when
+// work was running on the GPU for a given application (identified by its UID;
+// the persistent, unique ID of the application) from |start_time_ns| to
+// |end_time_ns|. Drivers should issue this tracepoint as soon as possible
+// (within 1 second) after |end_time_ns|. For a given UID, periods must not
+// overlap, but periods from different UIDs can overlap (and should overlap, if
+// and only if that is how the work was executed). The period includes
+// information such as |frequency_khz|, the frequency that the GPU was running
+// at during the period, and |includes_compute_work|, whether the work included
+// compute shader work (not just graphics work). GPUs may have multiple
+// frequencies that can be adjusted, but the driver should report the frequency
+// that most closely estimates power usage (e.g. the frequency of shader cores,
+// not a scheduling unit).
+//
+// If any information changes while work from the UID is running on the GPU
+// (e.g. the GPU frequency changes, or the work starts/stops including compute
+// work) then the driver must conceptually end the period, issue the tracepoint,
+// start tracking a new period, and eventually issue a second tracepoint when
+// the work completes or when the information changes again. In this case, the
+// |end_time_ns| of the first period must equal the |start_time_ns| of the
+// second period. The driver may also end and start a new period (without a
+// gap), even if no information changes. For example, this might be convenient
+// if there is a collection of work from a UID running on the GPU for a long
+// time; ending and starting a period as individual parts of the work complete
+// allows the consumer of the tracepoint to be updated about the ongoing work.
+//
+// For a given UID, the tracepoints must be emitted in order; that is, the
+// |start_time_ns| of each subsequent tracepoint for a given UID must be
+// monotonically increasing.
+typedef struct {
+    // Actual fields start at offset 8.
+    uint64_t reserved;
+
+    // The UID of the process (i.e. persistent, unique ID of the Android app)
+    // that submitted work to the GPU.
+    uint32_t uid;
+
+    // The GPU frequency during the period. GPUs may have multiple frequencies
+    // that can be adjusted, but the driver should report the frequency that
+    // would most closely estimate power usage (e.g. the frequency of shader
+    // cores, not a scheduling unit).
+    uint32_t frequency_khz;
+
+    // The start time of the period in nanoseconds. The clock must be
+    // CLOCK_MONOTONIC, as returned by the ktime_get_ns(void) function.
+    uint64_t start_time_ns;
+
+    // The end time of the period in nanoseconds. The clock must be
+    // CLOCK_MONOTONIC, as returned by the ktime_get_ns(void) function.
+    uint64_t end_time_ns;
+
+    // Flags about the work. Reserved for future use.
+    uint64_t flags;
+
+    // The maximum GPU frequency allowed during the period according to the
+    // thermal throttling policy. Must be 0 if no thermal throttling was
+    // enforced during the period. The value must relate to |frequency_khz|; in
+    // other words, if |frequency_khz| is the frequency of the GPU shader cores,
+    // then |thermally_throttled_max_frequency_khz| must be the maximum allowed
+    // frequency of the GPU shader cores (not the maximum allowed frequency of
+    // some other part of the GPU).
+    //
+    // Note: Unlike with other fields of this struct, if the
+    // |thermally_throttled_max_frequency_khz| value conceptually changes while
+    // work from a UID is running on the GPU then the GPU driver does NOT need
+    // to accurately report this by ending the period and starting to track a
+    // new period; instead, the GPU driver may report any one of the
+    // |thermally_throttled_max_frequency_khz| values that was enforced during
+    // the period. The motivation for this relaxation is that we assume the
+    // maximum frequency will not be changing rapidly, and so capturing the
+    // exact point at which the change occurs is unnecessary.
+    uint32_t thermally_throttled_max_frequency_khz;
+
+} GpuUidWorkPeriodEvent;
+
+_Static_assert(offsetof(GpuUidWorkPeriodEvent, uid) == 8 &&
+                       offsetof(GpuUidWorkPeriodEvent, frequency_khz) == 12 &&
+                       offsetof(GpuUidWorkPeriodEvent, start_time_ns) == 16 &&
+                       offsetof(GpuUidWorkPeriodEvent, end_time_ns) == 24 &&
+                       offsetof(GpuUidWorkPeriodEvent, flags) == 32 &&
+                       offsetof(GpuUidWorkPeriodEvent, thermally_throttled_max_frequency_khz) == 40,
+               "Field offsets of struct GpuUidWorkPeriodEvent must not be changed because they "
+               "must match the tracepoint field offsets found via adb shell cat "
+               "/sys/kernel/tracing/events/power/gpu_work_period/format");
+
+DEFINE_BPF_PROG("tracepoint/power/gpu_work_period", AID_ROOT, AID_GRAPHICS, tp_gpu_work_period)
+(GpuUidWorkPeriodEvent* const args) {
+    // Note: In BPF programs, |__sync_fetch_and_add| is translated to an atomic
+    // add.
+
+    const uint32_t uid = args->uid;
+
+    // Get |UidTrackingInfo| for |uid|.
+    UidTrackingInfo* uid_tracking_info = bpf_gpu_work_map_lookup_elem(&uid);
+    if (!uid_tracking_info) {
+        // There was no existing entry, so we add a new one.
+        UidTrackingInfo initial_info;
+        __builtin_memset(&initial_info, 0, sizeof(initial_info));
+        if (0 == bpf_gpu_work_map_update_elem(&uid, &initial_info, BPF_NOEXIST)) {
+            // We added an entry to the map, so we increment our entry counter in
+            // |GlobalData|.
+            const uint32_t zero = 0;
+            // Get the |GlobalData|.
+            GlobalData* global_data = bpf_gpu_work_global_data_lookup_elem(&zero);
+            // Getting the global data never fails because it is an |ARRAY| map,
+            // but we need to keep the verifier happy.
+            if (global_data) {
+                __sync_fetch_and_add(&global_data->num_map_entries, 1);
+            }
+        }
+        uid_tracking_info = bpf_gpu_work_map_lookup_elem(&uid);
+        if (!uid_tracking_info) {
+            // This should never happen, unless entries are getting deleted at
+            // this moment. If so, we just give up.
+            return 0;
+        }
+    }
+
+    // The period duration must be non-zero.
+    if (args->start_time_ns >= args->end_time_ns) {
+        __sync_fetch_and_add(&uid_tracking_info->error_count, 1);
+        return 0;
+    }
+
+    // The frequency must not be 0.
+    if (args->frequency_khz == 0) {
+        __sync_fetch_and_add(&uid_tracking_info->error_count, 1);
+        return 0;
+    }
+
+    // Calculate the frequency index: see |UidTrackingInfo.frequency_times_ns|.
+    // Round to the nearest 50MHz bucket.
+    uint32_t frequency_index =
+            ((args->frequency_khz / MHZ_IN_KHZS) + (kFrequencyGranularityMhz / 2)) /
+            kFrequencyGranularityMhz;
+    if (frequency_index >= kNumTrackedFrequencies) {
+        frequency_index = kNumTrackedFrequencies - 1;
+    }
+
+    // Never round down to 0MHz, as this is a special bucket (see below) and not
+    // an actual operating point.
+    if (frequency_index == 0) {
+        frequency_index = 1;
+    }
+
+    // Update time in state.
+    __sync_fetch_and_add(&uid_tracking_info->frequency_times_ns[frequency_index],
+                         args->end_time_ns - args->start_time_ns);
+
+    if (uid_tracking_info->previous_end_time_ns > args->start_time_ns) {
+        // This must not happen because per-UID periods must not overlap and
+        // must be emitted in order.
+        __sync_fetch_and_add(&uid_tracking_info->error_count, 1);
+    } else {
+        // The period appears to have been emitted after the previous, as
+        // expected, so we can calculate the gap between this and the previous
+        // period.
+        const uint64_t gap_time = args->start_time_ns - uid_tracking_info->previous_end_time_ns;
+
+        // Update |previous_end_time_ns|.
+        uid_tracking_info->previous_end_time_ns = args->end_time_ns;
+
+        // Update the special 0MHz frequency time, which stores the gaps between
+        // periods, but only if the gap is < 1 second.
+        if (gap_time > 0 && gap_time < S_IN_NS) {
+            __sync_fetch_and_add(&uid_tracking_info->frequency_times_ns[0], gap_time);
+        }
+    }
+
+    return 0;
+}
+
+LICENSE("Apache 2.0");
diff --git a/services/gpuservice/gpuwork/bpfprogs/include/gpuwork/gpu_work.h b/services/gpuservice/gpuwork/bpfprogs/include/gpuwork/gpu_work.h
new file mode 100644
index 0000000..4fe8464
--- /dev/null
+++ b/services/gpuservice/gpuwork/bpfprogs/include/gpuwork/gpu_work.h
@@ -0,0 +1,61 @@
+/*
+ * Copyright 2022 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.
+ */
+
+#pragma once
+
+#include <stdint.h>
+
+#ifdef __cplusplus
+#include <type_traits>
+
+namespace android {
+namespace gpuwork {
+#endif
+
+typedef struct {
+    // The end time of the previous period from this UID in nanoseconds.
+    uint64_t previous_end_time_ns;
+
+    // The time spent at each GPU frequency while running GPU work from the UID,
+    // in nanoseconds. Array index i stores the time for frequency i*50 MHz. So
+    // index 0 is 0Mhz, index 1 is 50MHz, index 2 is 100MHz, etc., up to index
+    // |kNumTrackedFrequencies|.
+    uint64_t frequency_times_ns[21];
+
+    // The number of times we received |GpuUidWorkPeriodEvent| events in an
+    // unexpected order. See |GpuUidWorkPeriodEvent|.
+    uint32_t error_count;
+
+} UidTrackingInfo;
+
+typedef struct {
+    // We cannot query the number of entries in BPF map |gpu_work_map|. We track
+    // the number of entries (approximately) using a counter so we can check if
+    // the map is nearly full.
+    uint64_t num_map_entries;
+} GlobalData;
+
+static const uint32_t kMaxTrackedUids = 512;
+static const uint32_t kFrequencyGranularityMhz = 50;
+static const uint32_t kNumTrackedFrequencies = 21;
+
+#ifdef __cplusplus
+static_assert(kNumTrackedFrequencies ==
+              std::extent<decltype(UidTrackingInfo::frequency_times_ns)>::value);
+
+} // namespace gpuwork
+} // namespace android
+#endif
diff --git a/services/gpuservice/gpuwork/include/gpuwork/GpuWork.h b/services/gpuservice/gpuwork/include/gpuwork/GpuWork.h
new file mode 100644
index 0000000..b6f493d
--- /dev/null
+++ b/services/gpuservice/gpuwork/include/gpuwork/GpuWork.h
@@ -0,0 +1,127 @@
+/*
+ * Copyright 2022 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.
+ */
+
+#pragma once
+
+#include <bpf/BpfMap.h>
+#include <stats_pull_atom_callback.h>
+#include <utils/Mutex.h>
+#include <utils/String16.h>
+#include <utils/Vector.h>
+
+#include <condition_variable>
+#include <cstdint>
+#include <functional>
+#include <thread>
+
+#include "gpuwork/gpu_work.h"
+
+namespace android {
+namespace gpuwork {
+
+class GpuWork {
+public:
+    using Uid = uint32_t;
+
+    GpuWork() = default;
+    ~GpuWork();
+
+    void initialize();
+
+    // Dumps the GPU time in frequency state information.
+    void dump(const Vector<String16>& args, std::string* result);
+
+private:
+    // Attaches tracepoint |tracepoint_group|/|tracepoint_name| to BPF program at path
+    // |program_path|. The tracepoint is also enabled.
+    static bool attachTracepoint(const char* program_path, const char* tracepoint_group,
+                                 const char* tracepoint_name);
+
+    // Native atom puller callback registered in statsd.
+    static AStatsManager_PullAtomCallbackReturn pullAtomCallback(int32_t atomTag,
+                                                                 AStatsEventList* data,
+                                                                 void* cookie);
+
+    AStatsManager_PullAtomCallbackReturn pullFrequencyAtoms(AStatsEventList* data);
+
+    // Periodically calls |clearMapIfNeeded| to clear the |mGpuWorkMap| map, if
+    // needed.
+    //
+    // Thread safety analysis is skipped because we need to use
+    // |std::unique_lock|, which is not currently supported by thread safety
+    // analysis.
+    void periodicallyClearMap() NO_THREAD_SAFETY_ANALYSIS;
+
+    // Checks whether the |mGpuWorkMap| map is nearly full and, if so, clears
+    // it.
+    void clearMapIfNeeded() REQUIRES(mMutex);
+
+    // Clears the |mGpuWorkMap| map.
+    void clearMap() REQUIRES(mMutex);
+
+    // Waits for required permissions to become set. This seems to be needed
+    // because platform service permissions might not be set when a service
+    // first starts. See b/214085769.
+    void waitForPermissions();
+
+    // Indicates whether our eBPF components have been initialized.
+    std::atomic<bool> mInitialized = false;
+
+    // A thread that periodically checks whether |mGpuWorkMap| is nearly full
+    // and, if so, clears it.
+    std::thread mMapClearerThread;
+
+    // Mutex for |mGpuWorkMap| and a few other fields.
+    std::mutex mMutex;
+
+    // BPF map for per-UID GPU work.
+    bpf::BpfMap<Uid, UidTrackingInfo> mGpuWorkMap GUARDED_BY(mMutex);
+
+    // BPF map containing a single element for global data.
+    bpf::BpfMap<uint32_t, GlobalData> mGpuWorkGlobalDataMap GUARDED_BY(mMutex);
+
+    // When true, we are being destructed, so |mMapClearerThread| should stop.
+    bool mIsTerminating GUARDED_BY(mMutex);
+
+    // A condition variable for |mIsTerminating|.
+    std::condition_variable mIsTerminatingConditionVariable GUARDED_BY(mMutex);
+
+    // 30 second timeout for trying to attach a BPF program to a tracepoint.
+    static constexpr int kGpuWaitTimeoutSeconds = 30;
+
+    // The wait duration for the map clearer thread; the thread checks the map
+    // every ~1 hour.
+    static constexpr uint32_t kMapClearerWaitDurationSeconds = 60 * 60;
+
+    // Whether our |pullAtomCallback| function is registered.
+    bool mStatsdRegistered GUARDED_BY(mMutex) = false;
+
+    // The number of randomly chosen (i.e. sampled) UIDs to log stats for.
+    static constexpr int kNumSampledUids = 10;
+
+    // The previous time point at which |mGpuWorkMap| was cleared.
+    std::chrono::steady_clock::time_point mPreviousMapClearTimePoint GUARDED_BY(mMutex);
+
+    // Permission to register a statsd puller.
+    static constexpr char16_t kPermissionRegisterStatsPullAtom[] =
+            u"android.permission.REGISTER_STATS_PULL_ATOM";
+
+    // Time limit for waiting for permissions.
+    static constexpr int kPermissionsWaitTimeoutSeconds = 30;
+};
+
+} // namespace gpuwork
+} // namespace android
diff --git a/services/gpuservice/vts/Android.bp b/services/gpuservice/vts/Android.bp
new file mode 100644
index 0000000..83a40e7
--- /dev/null
+++ b/services/gpuservice/vts/Android.bp
@@ -0,0 +1,30 @@
+// Copyright 2022 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 {
+    default_applicable_licenses: ["frameworks_native_license"],
+}
+
+java_test_host {
+    name: "GpuServiceVendorTests",
+    srcs: ["src/**/*.java"],
+    libs: [
+        "tradefed",
+        "vts-core-tradefed-harness",
+    ],
+    test_suites: [
+        "general-tests",
+        "vts",
+    ],
+}
diff --git a/services/gpuservice/vts/AndroidTest.xml b/services/gpuservice/vts/AndroidTest.xml
new file mode 100644
index 0000000..02ca07f
--- /dev/null
+++ b/services/gpuservice/vts/AndroidTest.xml
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright 2022 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.
+-->
+<configuration description="Runs GpuServiceVendorTests">
+    <test class="com.android.tradefed.testtype.HostTest" >
+        <option name="jar" value="GpuServiceVendorTests.jar" />
+    </test>
+</configuration>
diff --git a/services/gpuservice/vts/OWNERS b/services/gpuservice/vts/OWNERS
new file mode 100644
index 0000000..e789052
--- /dev/null
+++ b/services/gpuservice/vts/OWNERS
@@ -0,0 +1,7 @@
+# Bug component: 653544
+paulthomson@google.com
+pbaiget@google.com
+lfy@google.com
+chrisforbes@google.com
+lpy@google.com
+alecmouri@google.com
diff --git a/services/gpuservice/vts/TEST_MAPPING b/services/gpuservice/vts/TEST_MAPPING
new file mode 100644
index 0000000..b33e962
--- /dev/null
+++ b/services/gpuservice/vts/TEST_MAPPING
@@ -0,0 +1,7 @@
+{
+  "presubmit": [
+    {
+      "name": "GpuServiceVendorTests"
+    }
+  ]
+}
diff --git a/services/gpuservice/vts/src/com/android/tests/gpuservice/GpuWorkTracepointTest.java b/services/gpuservice/vts/src/com/android/tests/gpuservice/GpuWorkTracepointTest.java
new file mode 100644
index 0000000..4a77d9a
--- /dev/null
+++ b/services/gpuservice/vts/src/com/android/tests/gpuservice/GpuWorkTracepointTest.java
@@ -0,0 +1,98 @@
+/*
+ * Copyright 2022 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.tests.gpuservice;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+import static org.junit.Assume.assumeTrue;
+
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+import com.android.tradefed.testtype.junit4.BaseHostJUnit4Test;
+import com.android.tradefed.util.CommandResult;
+import com.android.tradefed.util.CommandStatus;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.Arrays;
+import java.util.stream.Collectors;
+
+
+@RunWith(DeviceJUnit4ClassRunner.class)
+public class GpuWorkTracepointTest extends BaseHostJUnit4Test {
+
+    private static final String CPU_FREQUENCY_TRACEPOINT_FORMAT_PATH =
+            "/sys/kernel/tracing/events/power/cpu_frequency/format";
+    private static final String GPU_WORK_PERIOD_TRACEPOINT_FORMAT_PATH =
+            "/sys/kernel/tracing/events/power/gpu_work_period/format";
+
+    @Test
+    public void testReadTracingEvents() throws Exception {
+        // Test |testGpuWorkPeriodTracepointFormat| is dependent on whether certain tracepoint
+        // paths exist. This means the test will vacuously pass if the tracepoint file system is
+        // inaccessible. Thus, as a basic check, we make sure the CPU frequency tracepoint format
+        // is accessible. If not, something is probably fundamentally broken about the tracing
+        // file system.
+        CommandResult commandResult = getDevice().executeShellV2Command(
+                String.format("cat %s", CPU_FREQUENCY_TRACEPOINT_FORMAT_PATH));
+
+        assertEquals(String.format(
+                        "Failed to read \"%s\". This probably means that the tracing file system "
+                                + "is fundamentally broken in some way, possibly due to bad "
+                                + "permissions.",
+                        CPU_FREQUENCY_TRACEPOINT_FORMAT_PATH),
+                commandResult.getStatus(), CommandStatus.SUCCESS);
+    }
+
+    @Test
+    public void testGpuWorkPeriodTracepointFormat() throws Exception {
+        CommandResult commandResult = getDevice().executeShellV2Command(
+                String.format("cat %s", GPU_WORK_PERIOD_TRACEPOINT_FORMAT_PATH));
+
+        // If we failed to cat the tracepoint format then the test ends here.
+        assumeTrue(String.format("Failed to cat the gpu_work_period tracepoint format at %s",
+                        GPU_WORK_PERIOD_TRACEPOINT_FORMAT_PATH),
+                commandResult.getStatus().equals(CommandStatus.SUCCESS));
+
+        // Otherwise, we check that the fields match the expected fields.
+        String actualFields = Arrays.stream(
+                commandResult.getStdout().trim().split("\n")).filter(
+                s -> s.startsWith("\tfield:")).collect(
+                Collectors.joining("\n"));
+
+        String expectedFields = String.join("\n",
+                "\tfield:unsigned short common_type;\toffset:0;\tsize:2;\tsigned:0;",
+                "\tfield:unsigned char common_flags;\toffset:2;\tsize:1;\tsigned:0;",
+                "\tfield:unsigned char common_preempt_count;\toffset:3;\tsize:1;\tsigned:0;",
+                "\tfield:int common_pid;\toffset:4;\tsize:4;\tsigned:1;",
+                "\tfield:u32 uid;\toffset:8;\tsize:4;\tsigned:0;",
+                "\tfield:u32 frequency;\toffset:12;\tsize:4;\tsigned:0;",
+                "\tfield:u64 start_time;\toffset:16;\tsize:8;\tsigned:0;",
+                "\tfield:u64 end_time;\toffset:24;\tsize:8;\tsigned:0;",
+                "\tfield:u64 flags;\toffset:32;\tsize:8;\tsigned:0;",
+                "\tfield:u32 thermally_throttled_max_frequency_khz;\toffset:40;\tsize:4;\tsigned:0;"
+        );
+
+        // We use |fail| rather than |assertEquals| because it allows us to give a clearer message.
+        if (!expectedFields.equals(actualFields)) {
+            String message = String.format(
+                    "Tracepoint format given by \"%s\" does not match the expected format.\n"
+                            + "Expected fields:\n%s\n\nActual fields:\n%s\n\n",
+                    GPU_WORK_PERIOD_TRACEPOINT_FORMAT_PATH, expectedFields, actualFields);
+            fail(message);
+        }
+    }
+}
diff --git a/services/sensorservice/SensorService.cpp b/services/sensorservice/SensorService.cpp
index 9bc7b8e..517d383 100644
--- a/services/sensorservice/SensorService.cpp
+++ b/services/sensorservice/SensorService.cpp
@@ -1254,6 +1254,11 @@
     for (auto &sensor : sensorList) {
         int32_t id = getIdFromUuid(sensor.getUuid());
         sensor.setId(id);
+        // The sensor UUID must always be anonymized here for non privileged clients.
+        // There is no other checks after this point before returning to client process.
+        if (!isAudioServerOrSystemServerUid(IPCThreadState::self()->getCallingUid())) {
+            sensor.anonymizeUuid();
+        }
     }
 }
 
diff --git a/services/sensorservice/SensorService.h b/services/sensorservice/SensorService.h
index 9b6d01a..b009829 100644
--- a/services/sensorservice/SensorService.h
+++ b/services/sensorservice/SensorService.h
@@ -26,6 +26,7 @@
 #include <binder/IUidObserver.h>
 #include <cutils/compiler.h>
 #include <cutils/multiuser.h>
+#include <private/android_filesystem_config.h>
 #include <sensor/ISensorServer.h>
 #include <sensor/ISensorEventConnection.h>
 #include <sensor/Sensor.h>
@@ -447,6 +448,10 @@
     // Removes the capped rate on active direct connections (when the mic toggle is flipped to off)
     void uncapRates(userid_t userId);
 
+    static inline bool isAudioServerOrSystemServerUid(uid_t uid) {
+        return multiuser_get_app_id(uid) == AID_SYSTEM || uid == AID_AUDIOSERVER;
+    }
+
     static uint8_t sHmacGlobalKey[128];
     static bool sHmacGlobalKeyIsValid;