Merge "init: filter .##rc with preview SDK version" into main
diff --git a/Android.bp b/Android.bp
new file mode 100644
index 0000000..c77a803
--- /dev/null
+++ b/Android.bp
@@ -0,0 +1,5 @@
+dirgroup {
+    name: "trusty_dirgroup_system_core",
+    dirs: ["."],
+    visibility: ["//trusty/vendor/google/aosp/scripts"],
+}
diff --git a/debuggerd/crash_dump.cpp b/debuggerd/crash_dump.cpp
index c9235ee..15e8319 100644
--- a/debuggerd/crash_dump.cpp
+++ b/debuggerd/crash_dump.cpp
@@ -470,14 +470,12 @@
   }
 
   NativeBridgeGuestStateHeader header;
-  if (!process_memory->ReadFully(header_ptr, &header, sizeof(NativeBridgeGuestStateHeader))) {
-    PLOG(ERROR) << "failed to get the guest state header for thread " << tid;
-    return false;
-  }
-  if (header.signature != NATIVE_BRIDGE_GUEST_STATE_SIGNATURE) {
+  if (!process_memory->ReadFully(header_ptr, &header, sizeof(NativeBridgeGuestStateHeader)) ||
+      header.signature != NATIVE_BRIDGE_GUEST_STATE_SIGNATURE) {
     // Return when ptr points to unmapped memory or no valid guest state.
     return false;
   }
+
   auto guest_state_data_copy = std::make_unique<unsigned char[]>(header.guest_state_data_size);
   if (!process_memory->ReadFully(reinterpret_cast<uintptr_t>(header.guest_state_data),
                                  guest_state_data_copy.get(), header.guest_state_data_size)) {
diff --git a/debuggerd/test_permissive_mte/Android.bp b/debuggerd/test_permissive_mte/Android.bp
index 0ad3243..f333242 100644
--- a/debuggerd/test_permissive_mte/Android.bp
+++ b/debuggerd/test_permissive_mte/Android.bp
@@ -39,7 +39,7 @@
         "src/**/PermissiveMteTest.java",
         ":libtombstone_proto-src",
     ],
-    data: [":mte_crash"],
+    device_first_data: [":mte_crash"],
     test_config: "AndroidTest.xml",
     test_suites: ["general-tests"],
 }
diff --git a/fs_mgr/libdm/Android.bp b/fs_mgr/libdm/Android.bp
index c3ca758..1efd7de 100644
--- a/fs_mgr/libdm/Android.bp
+++ b/fs_mgr/libdm/Android.bp
@@ -15,6 +15,7 @@
 //
 
 package {
+    default_team: "trendy_team_android_kernel",
     default_applicable_licenses: ["Android-Apache-2.0"],
 }
 
diff --git a/fs_mgr/libfiemap/Android.bp b/fs_mgr/libfiemap/Android.bp
index c8d5756..a6be585 100644
--- a/fs_mgr/libfiemap/Android.bp
+++ b/fs_mgr/libfiemap/Android.bp
@@ -15,6 +15,7 @@
 //
 
 package {
+    default_team: "trendy_team_android_kernel",
     default_applicable_licenses: ["Android-Apache-2.0"],
 }
 
diff --git a/fs_mgr/liblp/Android.bp b/fs_mgr/liblp/Android.bp
index 24eebdf..b211e83 100644
--- a/fs_mgr/liblp/Android.bp
+++ b/fs_mgr/liblp/Android.bp
@@ -15,6 +15,7 @@
 //
 
 package {
+    default_team: "trendy_team_android_kernel",
     default_applicable_licenses: ["Android-Apache-2.0"],
 }
 
diff --git a/fs_mgr/libsnapshot/Android.bp b/fs_mgr/libsnapshot/Android.bp
index 50efb03..966696b 100644
--- a/fs_mgr/libsnapshot/Android.bp
+++ b/fs_mgr/libsnapshot/Android.bp
@@ -15,6 +15,7 @@
 //
 
 package {
+    default_team: "trendy_team_android_kernel",
     default_applicable_licenses: ["Android-Apache-2.0"],
 }
 
diff --git a/fs_mgr/libsnapshot/include/libsnapshot/snapshot.h b/fs_mgr/libsnapshot/include/libsnapshot/snapshot.h
index 8ff41db..de20526 100644
--- a/fs_mgr/libsnapshot/include/libsnapshot/snapshot.h
+++ b/fs_mgr/libsnapshot/include/libsnapshot/snapshot.h
@@ -442,6 +442,7 @@
     FRIEND_TEST(SnapshotUpdateTest, QueryStatusError);
     FRIEND_TEST(SnapshotUpdateTest, SnapshotStatusFileWithoutCow);
     FRIEND_TEST(SnapshotUpdateTest, SpaceSwapUpdate);
+    FRIEND_TEST(SnapshotUpdateTest, InterruptMergeDuringPhaseUpdate);
     FRIEND_TEST(SnapshotUpdateTest, MapAllSnapshotsWithoutSlotSwitch);
     friend class SnapshotTest;
     friend class SnapshotUpdateTest;
diff --git a/fs_mgr/libsnapshot/snapshot.cpp b/fs_mgr/libsnapshot/snapshot.cpp
index 05dec68..acabd67 100644
--- a/fs_mgr/libsnapshot/snapshot.cpp
+++ b/fs_mgr/libsnapshot/snapshot.cpp
@@ -1343,10 +1343,25 @@
         }
 
         if (merge_status == "snapshot" &&
-            DecideMergePhase(snapshot_status) == MergePhase::SECOND_PHASE &&
-            update_status.merge_phase() == MergePhase::FIRST_PHASE) {
-            // The snapshot is not being merged because it's in the wrong phase.
-            return MergeResult(UpdateState::None);
+            DecideMergePhase(snapshot_status) == MergePhase::SECOND_PHASE) {
+            if (update_status.merge_phase() == MergePhase::FIRST_PHASE) {
+                // The snapshot is not being merged because it's in the wrong phase.
+                return MergeResult(UpdateState::None);
+            } else {
+                // update_status is already in second phase but the
+                // snapshot_status is still not set to SnapshotState::MERGING.
+                //
+                // Resume the merge at this point. see b/374225913
+                LOG(INFO) << "SwitchSnapshotToMerge: " << name << " after resuming merge";
+                auto code = SwitchSnapshotToMerge(lock, name);
+                if (code != MergeFailureCode::Ok) {
+                    LOG(ERROR) << "Failed to switch snapshot: " << name
+                               << " to merge during second phase";
+                    return MergeResult(UpdateState::MergeFailed,
+                                       MergeFailureCode::UnknownTargetType);
+                }
+                return MergeResult(UpdateState::Merging);
+            }
         }
 
         if (merge_status == "snapshot-merge") {
@@ -1442,8 +1457,14 @@
         return MergeFailureCode::WriteStatus;
     }
 
+    auto current_slot_suffix = device_->GetSlotSuffix();
     MergeFailureCode result = MergeFailureCode::Ok;
     for (const auto& snapshot : snapshots) {
+        if (!android::base::EndsWith(snapshot, current_slot_suffix)) {
+            LOG(ERROR) << "Skipping invalid snapshot: " << snapshot
+                       << " during MergeSecondPhaseSnapshots";
+            continue;
+        }
         SnapshotStatus snapshot_status;
         if (!ReadSnapshotStatus(lock, snapshot, &snapshot_status)) {
             return MergeFailureCode::ReadStatus;
diff --git a/fs_mgr/libsnapshot/snapshot_test.cpp b/fs_mgr/libsnapshot/snapshot_test.cpp
index 46c3a35..1a0d559 100644
--- a/fs_mgr/libsnapshot/snapshot_test.cpp
+++ b/fs_mgr/libsnapshot/snapshot_test.cpp
@@ -1607,6 +1607,146 @@
     }
 }
 
+// Test that shrinking and growing partitions at the same time is handled
+// correctly in VABC.
+TEST_F(SnapshotUpdateTest, InterruptMergeDuringPhaseUpdate) {
+    if (!snapuserd_required_) {
+        // b/179111359
+        GTEST_SKIP() << "Skipping snapuserd test";
+    }
+
+    auto old_sys_size = GetSize(sys_);
+    auto old_prd_size = GetSize(prd_);
+
+    // Grow |sys| but shrink |prd|.
+    SetSize(sys_, old_sys_size * 2);
+    sys_->set_estimate_cow_size(8_MiB);
+    SetSize(prd_, old_prd_size / 2);
+    prd_->set_estimate_cow_size(1_MiB);
+
+    AddOperationForPartitions();
+
+    ASSERT_TRUE(sm->BeginUpdate());
+    ASSERT_TRUE(sm->CreateUpdateSnapshots(manifest_));
+
+    // Check that the old partition sizes were saved correctly.
+    {
+        ASSERT_TRUE(AcquireLock());
+        auto local_lock = std::move(lock_);
+
+        SnapshotStatus status;
+        ASSERT_TRUE(sm->ReadSnapshotStatus(local_lock.get(), "prd_b", &status));
+        ASSERT_EQ(status.old_partition_size(), 3145728);
+        ASSERT_TRUE(sm->ReadSnapshotStatus(local_lock.get(), "sys_b", &status));
+        ASSERT_EQ(status.old_partition_size(), 3145728);
+    }
+
+    ASSERT_TRUE(WriteSnapshotAndHash(sys_));
+    ASSERT_TRUE(WriteSnapshotAndHash(vnd_));
+    ASSERT_TRUE(ShiftAllSnapshotBlocks("prd_b", old_prd_size));
+
+    sync();
+
+    // Assert that source partitions aren't affected.
+    for (const auto& name : {"sys_a", "vnd_a", "prd_a"}) {
+        ASSERT_TRUE(IsPartitionUnchanged(name));
+    }
+
+    ASSERT_TRUE(sm->FinishedSnapshotWrites(false));
+
+    // Simulate shutting down the device.
+    ASSERT_TRUE(UnmapAll());
+
+    // After reboot, init does first stage mount.
+    auto init = NewManagerForFirstStageMount("_b");
+    ASSERT_NE(init, nullptr);
+    ASSERT_TRUE(init->NeedSnapshotsInFirstStageMount());
+    ASSERT_TRUE(init->CreateLogicalAndSnapshotPartitions("super", snapshot_timeout_));
+
+    // Check that the target partitions have the same content.
+    for (const auto& name : {"sys_b", "vnd_b", "prd_b"}) {
+        ASSERT_TRUE(IsPartitionUnchanged(name));
+    }
+
+    // Initiate the merge and wait for it to be completed.
+    if (ShouldSkipLegacyMerging()) {
+        LOG(INFO) << "Skipping legacy merge in test";
+        return;
+    }
+    ASSERT_TRUE(init->InitiateMerge());
+    ASSERT_EQ(init->IsSnapuserdRequired(), snapuserd_required_);
+    {
+        // Check that the merge phase is FIRST_PHASE until at least one call
+        // to ProcessUpdateState() occurs.
+        ASSERT_TRUE(AcquireLock());
+        auto local_lock = std::move(lock_);
+        auto status = init->ReadSnapshotUpdateStatus(local_lock.get());
+        ASSERT_EQ(status.merge_phase(), MergePhase::FIRST_PHASE);
+    }
+
+    // Wait until prd_b merge is completed which is part of first phase
+    std::chrono::milliseconds timeout(6000);
+    auto start = std::chrono::steady_clock::now();
+    // Keep polling until the merge is complete or timeout is reached
+    while (true) {
+        // Query the merge status
+        const auto merge_status = init->snapuserd_client()->QuerySnapshotStatus("prd_b");
+        if (merge_status == "snapshot-merge-complete") {
+            break;
+        }
+
+        auto now = std::chrono::steady_clock::now();
+        auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(now - start);
+
+        ASSERT_TRUE(elapsed < timeout);
+        // sleep for a second and allow merge to complete
+        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
+    }
+
+    // Now, forcefully update the snapshot-update status to SECOND PHASE
+    // This will not update the snapshot status of sys_b to MERGING
+    if (init->UpdateUsesUserSnapshots()) {
+        ASSERT_TRUE(AcquireLock());
+        auto local_lock = std::move(lock_);
+        auto status = init->ReadSnapshotUpdateStatus(local_lock.get());
+        status.set_merge_phase(MergePhase::SECOND_PHASE);
+        ASSERT_TRUE(init->WriteSnapshotUpdateStatus(local_lock.get(), status));
+    }
+
+    // Simulate shutting down the device and creating partitions again.
+    ASSERT_TRUE(UnmapAll());
+    ASSERT_TRUE(init->CreateLogicalAndSnapshotPartitions("super", snapshot_timeout_));
+
+    DeviceMapper::TargetInfo target;
+    ASSERT_TRUE(init->IsSnapshotDevice("prd_b", &target));
+
+    ASSERT_EQ(DeviceMapper::GetTargetType(target.spec), "user");
+    ASSERT_TRUE(init->IsSnapshotDevice("sys_b", &target));
+    ASSERT_EQ(DeviceMapper::GetTargetType(target.spec), "user");
+    ASSERT_TRUE(init->IsSnapshotDevice("vnd_b", &target));
+    ASSERT_EQ(DeviceMapper::GetTargetType(target.spec), "user");
+
+    // Complete the merge; "sys" and "vnd" should resume the merge
+    // even though merge was interrupted after update_status was updated to
+    // SECOND_PHASE
+    ASSERT_EQ(UpdateState::MergeCompleted, init->ProcessUpdateState());
+
+    // Make sure the second phase ran and deleted snapshots.
+    {
+        ASSERT_TRUE(AcquireLock());
+        auto local_lock = std::move(lock_);
+        std::vector<std::string> snapshots;
+        ASSERT_TRUE(init->ListSnapshots(local_lock.get(), &snapshots));
+        ASSERT_TRUE(snapshots.empty());
+    }
+
+    // Check that the target partitions have the same content after the merge.
+    for (const auto& name : {"sys_b", "vnd_b", "prd_b"}) {
+        ASSERT_TRUE(IsPartitionUnchanged(name))
+                << "Content of " << name << " changes after the merge";
+    }
+}
+
 // Test that if new system partitions uses empty space in super, that region is not snapshotted.
 TEST_F(SnapshotUpdateTest, DirectWriteEmptySpace) {
     GTEST_SKIP() << "b/141889746";
@@ -2518,9 +2658,6 @@
     // Remove the indicators
     ASSERT_TRUE(sm->PrepareDeviceToBootWithoutSnapshot());
 
-    // Ensure snapshots are still mounted
-    ASSERT_TRUE(sm->IsUserspaceSnapshotUpdateInProgress());
-
     // Cleanup snapshots
     ASSERT_TRUE(sm->UnmapAllSnapshots());
 }
diff --git a/fs_mgr/libsnapshot/snapuserd/Android.bp b/fs_mgr/libsnapshot/snapuserd/Android.bp
index 298fd9f..e4d2d04 100644
--- a/fs_mgr/libsnapshot/snapuserd/Android.bp
+++ b/fs_mgr/libsnapshot/snapuserd/Android.bp
@@ -15,6 +15,7 @@
 //
 
 package {
+    default_team: "trendy_team_android_kernel",
     default_applicable_licenses: ["Android-Apache-2.0"],
 }
 
@@ -85,9 +86,9 @@
         "libsnapshot_cow",
         "liburing",
         "libprocessgroup",
+        "libprocessgroup_util",
         "libjsoncpp",
         "libcgrouprc",
-        "libcgrouprc_format",
     ],
     include_dirs: ["bionic/libc/kernel"],
     export_include_dirs: ["include"],
@@ -129,9 +130,9 @@
         "libsnapshot_cow",
         "libsnapuserd",
         "libprocessgroup",
+        "libprocessgroup_util",
         "libjsoncpp",
         "libcgrouprc",
-        "libcgrouprc_format",
         "libsnapuserd_client",
         "libz",
         "liblz4",
@@ -221,9 +222,9 @@
         "libsnapshot_cow",
         "libsnapuserd",
         "libprocessgroup",
+        "libprocessgroup_util",
         "libjsoncpp",
         "libcgrouprc",
-        "libcgrouprc_format",
         "liburing",
         "libz",
     ],
@@ -319,7 +320,6 @@
         "libprocessgroup",
         "libjsoncpp",
         "libcgrouprc",
-        "libcgrouprc_format",
         "liburing",
         "libz",
     ],
diff --git a/init/Android.bp b/init/Android.bp
index 18a79d6..4025a6b 100644
--- a/init/Android.bp
+++ b/init/Android.bp
@@ -163,7 +163,6 @@
         "libavb",
         "libavf_cc_flags",
         "libbootloader_message",
-        "libcgrouprc_format",
         "liblmkd_utils",
         "liblz4",
         "libzstd",
@@ -390,6 +389,7 @@
         "libsnapshot_init",
         "update_metadata-protos",
         "libprocinfo",
+        "libbootloader_message",
     ],
 
     static_executable: true,
diff --git a/init/first_stage_mount.cpp b/init/first_stage_mount.cpp
index 99bf0de..4f1af30 100644
--- a/init/first_stage_mount.cpp
+++ b/init/first_stage_mount.cpp
@@ -32,9 +32,12 @@
 #include <android-base/chrono_utils.h>
 #include <android-base/file.h>
 #include <android-base/logging.h>
+#include <android-base/parseint.h>
 #include <android-base/stringprintf.h>
 #include <android-base/strings.h>
 #include <android/avf_cc_flags.h>
+#include <bootloader_message/bootloader_message.h>
+#include <cutils/android_reboot.h>
 #include <fs_avb/fs_avb.h>
 #include <fs_mgr.h>
 #include <fs_mgr_dm_linear.h>
@@ -46,6 +49,7 @@
 
 #include "block_dev_initializer.h"
 #include "devices.h"
+#include "reboot_utils.h"
 #include "result.h"
 #include "snapuserd_transition.h"
 #include "switch_root.h"
@@ -111,6 +115,8 @@
     bool GetDmVerityDevices(std::set<std::string>* devices);
     bool SetUpDmVerity(FstabEntry* fstab_entry);
 
+    void RequestTradeInModeWipeIfNeeded();
+
     bool InitAvbHandle();
 
     bool need_dm_verity_;
@@ -263,6 +269,8 @@
 }
 
 bool FirstStageMountVBootV2::DoFirstStageMount() {
+    RequestTradeInModeWipeIfNeeded();
+
     if (!IsDmLinearEnabled() && fstab_.empty()) {
         // Nothing to mount.
         LOG(INFO) << "First stage mount skipped (missing/incompatible/empty fstab in device tree)";
@@ -878,6 +886,55 @@
     return true;
 }
 
+void FirstStageMountVBootV2::RequestTradeInModeWipeIfNeeded() {
+    static constexpr const char* kWipeIndicator = "/metadata/tradeinmode/wipe";
+    static constexpr size_t kWipeAttempts = 3;
+
+    if (access(kWipeIndicator, R_OK) == -1) {
+        return;
+    }
+
+    // Write a counter to the wipe indicator, to try and prevent boot loops if
+    // recovery fails to wipe data.
+    uint32_t counter = 0;
+    std::string contents;
+    if (ReadFileToString(kWipeIndicator, &contents)) {
+        android::base::ParseUint(contents, &counter);
+        contents = std::to_string(++counter);
+        if (android::base::WriteStringToFile(contents, kWipeIndicator)) {
+            sync();
+        } else {
+            PLOG(ERROR) << "Failed to update " << kWipeIndicator;
+        }
+    } else {
+        PLOG(ERROR) << "Failed to read " << kWipeIndicator;
+    }
+
+    std::string err;
+    auto misc_device = get_misc_blk_device(&err);
+    if (misc_device.empty()) {
+        LOG(FATAL) << "Could not find misc device: " << err;
+    }
+
+    auto misc_name = android::base::Basename(misc_device);
+    if (!block_dev_init_.InitDevices({misc_name})) {
+        LOG(FATAL) << "Could not find misc device: " << misc_device;
+    }
+
+    // If we've failed to wipe three times, don't include the wipe command. This
+    // will force us to boot into the recovery menu instead where a manual wipe
+    // can be attempted.
+    std::vector<std::string> options;
+    if (counter <= kWipeAttempts) {
+        options.emplace_back("--wipe_data");
+        options.emplace_back("--reason=tradeinmode");
+    }
+    if (!write_bootloader_message(options, &err)) {
+        LOG(FATAL) << "Could not issue wipe: " << err;
+    }
+    RebootSystem(ANDROID_RB_RESTART2, "recovery", "reboot,tradeinmode,wipe");
+}
+
 void SetInitAvbVersionInRecovery() {
     if (!IsRecoveryMode()) {
         LOG(INFO) << "Skipped setting INIT_AVB_VERSION (not in recovery mode)";
diff --git a/init/init.cpp b/init/init.cpp
index 6c80899..17498da 100644
--- a/init/init.cpp
+++ b/init/init.cpp
@@ -636,9 +636,6 @@
         LOG(INFO) << "Cgroups support in kernel is not enabled";
         return {};
     }
-    // Have to create <CGROUPS_RC_DIR> using make_dir function
-    // for appropriate sepolicy to be set for it
-    make_dir(android::base::Dirname(CGROUPS_RC_PATH), 0711);
     if (!CgroupSetup()) {
         return ErrnoError() << "Failed to setup cgroups";
     }
diff --git a/init/test_upgrade_mte/Android.bp b/init/test_upgrade_mte/Android.bp
index 1bfc76c..dfea325 100644
--- a/init/test_upgrade_mte/Android.bp
+++ b/init/test_upgrade_mte/Android.bp
@@ -17,25 +17,34 @@
 }
 
 cc_binary {
-  name: "mte_upgrade_test_helper",
-  srcs: ["mte_upgrade_test_helper.cpp"],
-  sanitize: {
-    memtag_heap: true,
-    diag: {
-      memtag_heap: false,
+    name: "mte_upgrade_test_helper",
+    srcs: ["mte_upgrade_test_helper.cpp"],
+    sanitize: {
+        memtag_heap: true,
+        diag: {
+            memtag_heap: false,
+        },
     },
-  },
-  init_rc: [
-    "mte_upgrade_test.rc",
-  ],
+    init_rc: [
+        "mte_upgrade_test.rc",
+    ],
 }
 
 java_test_host {
     name: "mte_upgrade_test",
     libs: ["tradefed"],
-    static_libs: ["frameworks-base-hostutils", "cts-install-lib-host"],
-    srcs:  ["src/**/MteUpgradeTest.java", ":libtombstone_proto-src"],
-    data: [":mte_upgrade_test_helper", "mte_upgrade_test.rc" ],
+    static_libs: [
+        "frameworks-base-hostutils",
+        "cts-install-lib-host",
+    ],
+    srcs: [
+        "src/**/MteUpgradeTest.java",
+        ":libtombstone_proto-src",
+    ],
+    device_first_data: [
+        ":mte_upgrade_test_helper",
+        "mte_upgrade_test.rc",
+    ],
     test_config: "AndroidTest.xml",
     test_suites: ["general-tests"],
 }
diff --git a/libcutils/Android.bp b/libcutils/Android.bp
index 3c3eeb6..fc4c571 100644
--- a/libcutils/Android.bp
+++ b/libcutils/Android.bp
@@ -301,7 +301,7 @@
         android: {
             static_executable: true,
             static_libs: [
-                "libcgrouprc_format",
+                "libprocessgroup_util",
             ] + test_libraries + always_static_test_libraries,
         },
         not_windows: {
diff --git a/libprocessgroup/Android.bp b/libprocessgroup/Android.bp
index a60bfe9..8448a39 100644
--- a/libprocessgroup/Android.bp
+++ b/libprocessgroup/Android.bp
@@ -17,7 +17,7 @@
 
 libprocessgroup_flag_aware_cc_defaults {
     name: "libprocessgroup_build_flags_cc",
-    cpp_std: "gnu++20",
+    cpp_std: "gnu++23",
     soong_config_variables: {
         memcg_v2_force_enabled: {
             cflags: [
@@ -75,7 +75,6 @@
     double_loadable: true,
     shared_libs: [
         "libbase",
-        "libcgrouprc",
     ],
     static_libs: [
         "libjsoncpp",
@@ -116,5 +115,6 @@
     ],
     static_libs: [
         "libgmock",
+        "libprocessgroup_util",
     ],
 }
diff --git a/libprocessgroup/OWNERS b/libprocessgroup/OWNERS
index d5aa721..accd7df 100644
--- a/libprocessgroup/OWNERS
+++ b/libprocessgroup/OWNERS
@@ -1,4 +1,3 @@
 # Bug component: 1293033
 surenb@google.com
-tjmercier@google.com
-carlosgalo@google.com
+tjmercier@google.com
\ No newline at end of file
diff --git a/libprocessgroup/cgroup_map.cpp b/libprocessgroup/cgroup_map.cpp
index fb01cfd..32bef13 100644
--- a/libprocessgroup/cgroup_map.cpp
+++ b/libprocessgroup/cgroup_map.cpp
@@ -25,12 +25,10 @@
 #include <android-base/file.h>
 #include <android-base/logging.h>
 #include <android-base/stringprintf.h>
-#include <android-base/strings.h>
 #include <cgroup_map.h>
 #include <processgroup/processgroup.h>
 #include <processgroup/util.h>
 
-using android::base::StartsWith;
 using android::base::StringPrintf;
 using android::base::WriteStringToFile;
 
@@ -40,17 +38,17 @@
 
 uint32_t CgroupControllerWrapper::version() const {
     CHECK(HasValue());
-    return ACgroupController_getVersion(controller_);
+    return controller_->version();
 }
 
 const char* CgroupControllerWrapper::name() const {
     CHECK(HasValue());
-    return ACgroupController_getName(controller_);
+    return controller_->name();
 }
 
 const char* CgroupControllerWrapper::path() const {
     CHECK(HasValue());
-    return ACgroupController_getPath(controller_);
+    return controller_->path();
 }
 
 bool CgroupControllerWrapper::HasValue() const {
@@ -62,7 +60,7 @@
 
     if (state_ == UNKNOWN) {
         if (__builtin_available(android 30, *)) {
-            uint32_t flags = ACgroupController_getFlags(controller_);
+            uint32_t flags = controller_->flags();
             state_ = (flags & CGROUPRC_CONTROLLER_FLAG_MOUNTED) != 0 ? USABLE : MISSING;
         } else {
             state_ = access(GetProcsFilePath("", 0, 0).c_str(), F_OK) == 0 ? USABLE : MISSING;
@@ -129,8 +127,8 @@
 }
 
 CgroupMap::CgroupMap() {
-    if (!LoadRcFile()) {
-        LOG(ERROR) << "CgroupMap::LoadRcFile called for [" << getpid() << "] failed";
+    if (!LoadDescriptors()) {
+        LOG(ERROR) << "CgroupMap::LoadDescriptors called for [" << getpid() << "] failed";
     }
 }
 
@@ -141,9 +139,9 @@
     return *instance;
 }
 
-bool CgroupMap::LoadRcFile() {
+bool CgroupMap::LoadDescriptors() {
     if (!loaded_) {
-        loaded_ = (ACgroupFile_getVersion() != 0);
+        loaded_ = ReadDescriptors(&descriptors_);
     }
     return loaded_;
 }
@@ -151,43 +149,30 @@
 void CgroupMap::Print() const {
     if (!loaded_) {
         LOG(ERROR) << "CgroupMap::Print called for [" << getpid()
-                   << "] failed, RC file was not initialized properly";
+                   << "] failed, cgroups were not initialized properly";
         return;
     }
-    LOG(INFO) << "File version = " << ACgroupFile_getVersion();
-    LOG(INFO) << "File controller count = " << ACgroupFile_getControllerCount();
+    LOG(INFO) << "Controller count = " << descriptors_.size();
 
     LOG(INFO) << "Mounted cgroups:";
 
-    auto controller_count = ACgroupFile_getControllerCount();
-    for (uint32_t i = 0; i < controller_count; ++i) {
-        const ACgroupController* controller = ACgroupFile_getController(i);
-        if (__builtin_available(android 30, *)) {
-            LOG(INFO) << "\t" << ACgroupController_getName(controller) << " ver "
-                      << ACgroupController_getVersion(controller) << " path "
-                      << ACgroupController_getPath(controller) << " flags "
-                      << ACgroupController_getFlags(controller);
-        } else {
-            LOG(INFO) << "\t" << ACgroupController_getName(controller) << " ver "
-                      << ACgroupController_getVersion(controller) << " path "
-                      << ACgroupController_getPath(controller);
-        }
+    for (const auto& [name, descriptor] : descriptors_) {
+        LOG(INFO) << "\t" << descriptor.controller()->name() << " ver "
+                  << descriptor.controller()->version() << " path "
+                  << descriptor.controller()->path() << " flags "
+                  << descriptor.controller()->flags();
     }
 }
 
 CgroupControllerWrapper CgroupMap::FindController(const std::string& name) const {
     if (!loaded_) {
         LOG(ERROR) << "CgroupMap::FindController called for [" << getpid()
-                   << "] failed, RC file was not initialized properly";
+                   << "] failed, cgroups were not initialized properly";
         return CgroupControllerWrapper(nullptr);
     }
 
-    auto controller_count = ACgroupFile_getControllerCount();
-    for (uint32_t i = 0; i < controller_count; ++i) {
-        const ACgroupController* controller = ACgroupFile_getController(i);
-        if (name == ACgroupController_getName(controller)) {
-            return CgroupControllerWrapper(controller);
-        }
+    if (const auto it = descriptors_.find(name); it != descriptors_.end()) {
+        return CgroupControllerWrapper(it->second.controller());
     }
 
     return CgroupControllerWrapper(nullptr);
@@ -196,47 +181,19 @@
 CgroupControllerWrapper CgroupMap::FindControllerByPath(const std::string& path) const {
     if (!loaded_) {
         LOG(ERROR) << "CgroupMap::FindControllerByPath called for [" << getpid()
-                   << "] failed, RC file was not initialized properly";
+                   << "] failed, cgroups were not initialized properly";
         return CgroupControllerWrapper(nullptr);
     }
 
-    auto controller_count = ACgroupFile_getControllerCount();
-    for (uint32_t i = 0; i < controller_count; ++i) {
-        const ACgroupController* controller = ACgroupFile_getController(i);
-        if (StartsWith(path, ACgroupController_getPath(controller))) {
-            return CgroupControllerWrapper(controller);
+    for (const auto& [name, descriptor] : descriptors_) {
+        if (path.starts_with(descriptor.controller()->path())) {
+            return CgroupControllerWrapper(descriptor.controller());
         }
     }
 
     return CgroupControllerWrapper(nullptr);
 }
 
-int CgroupMap::ActivateControllers(const std::string& path) const {
-    if (__builtin_available(android 30, *)) {
-        auto controller_count = ACgroupFile_getControllerCount();
-        for (uint32_t i = 0; i < controller_count; ++i) {
-            const ACgroupController* controller = ACgroupFile_getController(i);
-            const uint32_t flags = ACgroupController_getFlags(controller);
-            uint32_t max_activation_depth = UINT32_MAX;
-            if (__builtin_available(android 36, *)) {
-                max_activation_depth = ACgroupController_getMaxActivationDepth(controller);
-            }
-            const int depth = util::GetCgroupDepth(ACgroupController_getPath(controller), path);
-
-            if (flags & CGROUPRC_CONTROLLER_FLAG_NEEDS_ACTIVATION && depth < max_activation_depth) {
-                std::string str("+");
-                str.append(ACgroupController_getName(controller));
-                if (!WriteStringToFile(str, path + "/cgroup.subtree_control")) {
-                    if (flags & CGROUPRC_CONTROLLER_FLAG_OPTIONAL) {
-                        PLOG(WARNING) << "Activation of cgroup controller " << str
-                                      << " failed in path " << path;
-                    } else {
-                        return -errno;
-                    }
-                }
-            }
-        }
-        return 0;
-    }
-    return -ENOSYS;
+bool CgroupMap::ActivateControllers(const std::string& path) const {
+    return ::ActivateControllers(path, descriptors_);
 }
diff --git a/libprocessgroup/cgroup_map.h b/libprocessgroup/cgroup_map.h
index 3642794..fb99076 100644
--- a/libprocessgroup/cgroup_map.h
+++ b/libprocessgroup/cgroup_map.h
@@ -18,15 +18,17 @@
 
 #include <sys/types.h>
 
+#include <cstdint>
 #include <string>
 
-#include <android/cgrouprc.h>
+#include <processgroup/cgroup_controller.h>
+#include <processgroup/util.h>
 
-// Convenient wrapper of an ACgroupController pointer.
+// Convenient wrapper of a CgroupController pointer.
 class CgroupControllerWrapper {
   public:
     // Does not own controller
-    explicit CgroupControllerWrapper(const ACgroupController* controller)
+    explicit CgroupControllerWrapper(const CgroupController* controller)
         : controller_(controller) {}
 
     uint32_t version() const;
@@ -47,7 +49,7 @@
         MISSING = 2,
     };
 
-    const ACgroupController* controller_ = nullptr;
+    const CgroupController* controller_ = nullptr; // CgroupMap owns the object behind this pointer
     ControllerState state_ = ControllerState::UNKNOWN;
 };
 
@@ -56,11 +58,12 @@
     static CgroupMap& GetInstance();
     CgroupControllerWrapper FindController(const std::string& name) const;
     CgroupControllerWrapper FindControllerByPath(const std::string& path) const;
-    int ActivateControllers(const std::string& path) const;
+    bool ActivateControllers(const std::string& path) const;
 
   private:
     bool loaded_ = false;
+    CgroupDescriptorMap descriptors_;
     CgroupMap();
-    bool LoadRcFile();
+    bool LoadDescriptors();
     void Print() const;
 };
diff --git a/libprocessgroup/cgrouprc/Android.bp b/libprocessgroup/cgrouprc/Android.bp
index cb91247..38b2fa3 100644
--- a/libprocessgroup/cgrouprc/Android.bp
+++ b/libprocessgroup/cgrouprc/Android.bp
@@ -49,7 +49,8 @@
         "libbase",
     ],
     static_libs: [
-        "libcgrouprc_format",
+        "libjsoncpp",
+        "libprocessgroup_util",
     ],
     stubs: {
         symbol_file: "libcgrouprc.map.txt",
diff --git a/libprocessgroup/cgrouprc/a_cgroup_controller.cpp b/libprocessgroup/cgrouprc/a_cgroup_controller.cpp
index 889b3be..5a326e5 100644
--- a/libprocessgroup/cgrouprc/a_cgroup_controller.cpp
+++ b/libprocessgroup/cgrouprc/a_cgroup_controller.cpp
@@ -32,11 +32,6 @@
     return controller->flags();
 }
 
-uint32_t ACgroupController_getMaxActivationDepth(const ACgroupController* controller) {
-    CHECK(controller != nullptr);
-    return controller->max_activation_depth();
-}
-
 const char* ACgroupController_getName(const ACgroupController* controller) {
     CHECK(controller != nullptr);
     return controller->name();
diff --git a/libprocessgroup/cgrouprc/a_cgroup_file.cpp b/libprocessgroup/cgrouprc/a_cgroup_file.cpp
index e26d841..33c8376 100644
--- a/libprocessgroup/cgrouprc/a_cgroup_file.cpp
+++ b/libprocessgroup/cgrouprc/a_cgroup_file.cpp
@@ -14,93 +14,51 @@
  * limitations under the License.
  */
 
-#include <sys/mman.h>
-#include <sys/stat.h>
-
-#include <memory>
+#include <iterator>
 
 #include <android-base/logging.h>
-#include <android-base/stringprintf.h>
-#include <android-base/unique_fd.h>
 #include <android/cgrouprc.h>
-#include <processgroup/processgroup.h>
+#include <processgroup/util.h>
 
 #include "cgrouprc_internal.h"
 
-using android::base::StringPrintf;
-using android::base::unique_fd;
-
-using android::cgrouprc::format::CgroupController;
-using android::cgrouprc::format::CgroupFile;
-
-static CgroupFile* LoadRcFile() {
-    struct stat sb;
-
-    unique_fd fd(TEMP_FAILURE_RETRY(open(CGROUPS_RC_PATH, O_RDONLY | O_CLOEXEC)));
-    if (fd < 0) {
-        PLOG(ERROR) << "open() failed for " << CGROUPS_RC_PATH;
+static CgroupDescriptorMap* LoadDescriptors() {
+    CgroupDescriptorMap* descriptors = new CgroupDescriptorMap;
+    if (!ReadDescriptors(descriptors)) {
+        LOG(ERROR) << "Failed to load cgroup description file";
         return nullptr;
     }
-
-    if (fstat(fd, &sb) < 0) {
-        PLOG(ERROR) << "fstat() failed for " << CGROUPS_RC_PATH;
-        return nullptr;
-    }
-
-    size_t file_size = sb.st_size;
-    if (file_size < sizeof(CgroupFile)) {
-        LOG(ERROR) << "Invalid file format " << CGROUPS_RC_PATH;
-        return nullptr;
-    }
-
-    CgroupFile* file_data = (CgroupFile*)mmap(nullptr, file_size, PROT_READ, MAP_SHARED, fd, 0);
-    if (file_data == MAP_FAILED) {
-        PLOG(ERROR) << "Failed to mmap " << CGROUPS_RC_PATH;
-        return nullptr;
-    }
-
-    if (file_data->version_ != CgroupFile::FILE_CURR_VERSION) {
-        LOG(ERROR) << CGROUPS_RC_PATH << " file version mismatch";
-        munmap(file_data, file_size);
-        return nullptr;
-    }
-
-    auto expected = sizeof(CgroupFile) + file_data->controller_count_ * sizeof(CgroupController);
-    if (file_size != expected) {
-        LOG(ERROR) << CGROUPS_RC_PATH << " file has invalid size, expected " << expected
-                   << ", actual " << file_size;
-        munmap(file_data, file_size);
-        return nullptr;
-    }
-
-    return file_data;
+    return descriptors;
 }
 
-static CgroupFile* GetInstance() {
+static const CgroupDescriptorMap* GetInstance() {
     // Deliberately leak this object (not munmap) to avoid a race between destruction on
     // process exit and concurrent access from another thread.
-    static auto* file = LoadRcFile();
-    return file;
+    static const CgroupDescriptorMap* descriptors = LoadDescriptors();
+    return descriptors;
 }
 
 uint32_t ACgroupFile_getVersion() {
-    auto file = GetInstance();
-    if (file == nullptr) return 0;
-    return file->version_;
+    static constexpr uint32_t FILE_VERSION_1 = 1;
+    auto descriptors = GetInstance();
+    if (descriptors == nullptr) return 0;
+    // There has only ever been one version, and there will be no more since cgroup.rc is no more
+    return FILE_VERSION_1;
 }
 
 uint32_t ACgroupFile_getControllerCount() {
-    auto file = GetInstance();
-    if (file == nullptr) return 0;
-    return file->controller_count_;
+    auto descriptors = GetInstance();
+    if (descriptors == nullptr) return 0;
+    return descriptors->size();
 }
 
 const ACgroupController* ACgroupFile_getController(uint32_t index) {
-    auto file = GetInstance();
-    if (file == nullptr) return nullptr;
-    CHECK(index < file->controller_count_);
+    auto descriptors = GetInstance();
+    if (descriptors == nullptr) return nullptr;
+    CHECK(index < descriptors->size());
     // Although the object is not actually an ACgroupController object, all ACgroupController_*
     // functions implicitly convert ACgroupController* back to CgroupController* before invoking
     // member functions.
-    return static_cast<ACgroupController*>(&file->controllers_[index]);
+    const CgroupController* p = std::next(descriptors->begin(), index)->second.controller();
+    return static_cast<const ACgroupController*>(p);
 }
diff --git a/libprocessgroup/cgrouprc/cgrouprc_internal.h b/libprocessgroup/cgrouprc/cgrouprc_internal.h
index cd02f03..d517703 100644
--- a/libprocessgroup/cgrouprc/cgrouprc_internal.h
+++ b/libprocessgroup/cgrouprc/cgrouprc_internal.h
@@ -16,9 +16,6 @@
 
 #pragma once
 
-#include <android/cgrouprc.h>
+#include <processgroup/cgroup_controller.h>
 
-#include <processgroup/format/cgroup_controller.h>
-#include <processgroup/format/cgroup_file.h>
-
-struct ACgroupController : android::cgrouprc::format::CgroupController {};
+struct ACgroupController : CgroupController {};
diff --git a/libprocessgroup/cgrouprc/include/android/cgrouprc.h b/libprocessgroup/cgrouprc/include/android/cgrouprc.h
index 3a57df5..e704a36 100644
--- a/libprocessgroup/cgrouprc/include/android/cgrouprc.h
+++ b/libprocessgroup/cgrouprc/include/android/cgrouprc.h
@@ -79,14 +79,6 @@
         const ACgroupController*) __INTRODUCED_IN(30);
 
 /**
- * Returns the maximum activation depth of the given controller.
- * Only applicable to cgroup v2 controllers.
- * Returns UINT32_MAX if no maximum activation depth is set.
- */
-__attribute__((warn_unused_result, weak)) uint32_t ACgroupController_getMaxActivationDepth(
-        const ACgroupController* controller) __INTRODUCED_IN(36);
-
-/**
  * Returns the name of the given controller.
  * If the given controller is null, return nullptr.
  */
diff --git a/libprocessgroup/cgrouprc/libcgrouprc.map.txt b/libprocessgroup/cgrouprc/libcgrouprc.map.txt
index 30bd25f..b62b10f 100644
--- a/libprocessgroup/cgrouprc/libcgrouprc.map.txt
+++ b/libprocessgroup/cgrouprc/libcgrouprc.map.txt
@@ -16,10 +16,3 @@
   local:
     *;
 };
-
-LIBCGROUPRC_36 { # introduced=36
-  global:
-    ACgroupController_getMaxActivationDepth; # llndk=202504 systemapi
-  local:
-    *;
-};
diff --git a/libprocessgroup/cgrouprc_format/Android.bp b/libprocessgroup/cgrouprc_format/Android.bp
index 0590924..6f9ab3e 100644
--- a/libprocessgroup/cgrouprc_format/Android.bp
+++ b/libprocessgroup/cgrouprc_format/Android.bp
@@ -23,17 +23,4 @@
     vendor_ramdisk_available: true,
     recovery_available: true,
     native_bridge_supported: true,
-    srcs: [
-        "cgroup_controller.cpp",
-    ],
-    cflags: [
-        "-Wall",
-        "-Werror",
-    ],
-    export_include_dirs: [
-        "include",
-    ],
-    shared_libs: [
-        "libbase",
-    ],
 }
diff --git a/libprocessgroup/cgrouprc_format/include/processgroup/format/cgroup_file.h b/libprocessgroup/cgrouprc_format/include/processgroup/format/cgroup_file.h
deleted file mode 100644
index 2d9786f..0000000
--- a/libprocessgroup/cgrouprc_format/include/processgroup/format/cgroup_file.h
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (C) 2019 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 <cstdint>
-
-#include <processgroup/format/cgroup_controller.h>
-
-namespace android {
-namespace cgrouprc {
-namespace format {
-
-struct CgroupFile {
-    uint32_t version_;
-    uint32_t controller_count_;
-    CgroupController controllers_[];
-
-    static constexpr uint32_t FILE_VERSION_1 = 1;
-    static constexpr uint32_t FILE_CURR_VERSION = FILE_VERSION_1;
-};
-
-}  // namespace format
-}  // namespace cgrouprc
-}  // namespace android
diff --git a/libprocessgroup/include/processgroup/processgroup.h b/libprocessgroup/include/processgroup/processgroup.h
index ffffeb4..8057757 100644
--- a/libprocessgroup/include/processgroup/processgroup.h
+++ b/libprocessgroup/include/processgroup/processgroup.h
@@ -57,7 +57,7 @@
 
 bool SetProcessProfilesCached(uid_t uid, pid_t pid, const std::vector<std::string>& profiles);
 
-static constexpr const char* CGROUPS_RC_PATH = "/dev/cgroup_info/cgroup.rc";
+[[deprecated]] static constexpr const char* CGROUPS_RC_PATH = "/dev/cgroup_info/cgroup.rc";
 
 bool UsePerAppMemcg();
 
diff --git a/libprocessgroup/internal.h b/libprocessgroup/internal.h
new file mode 100644
index 0000000..ef85579
--- /dev/null
+++ b/libprocessgroup/internal.h
@@ -0,0 +1,21 @@
+/*
+ * Copyright (C) 2024 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 <string>
+
+static const std::string CGROUP_V2_ROOT_DEFAULT = "/sys/fs/cgroup";
\ No newline at end of file
diff --git a/libprocessgroup/processgroup.cpp b/libprocessgroup/processgroup.cpp
index 83a2258..d3719ee 100644
--- a/libprocessgroup/processgroup.cpp
+++ b/libprocessgroup/processgroup.cpp
@@ -662,10 +662,9 @@
         return -errno;
     }
     if (activate_controllers) {
-        ret = CgroupMap::GetInstance().ActivateControllers(uid_path);
-        if (ret) {
-            LOG(ERROR) << "Failed to activate controllers in " << uid_path;
-            return ret;
+        if (!CgroupMap::GetInstance().ActivateControllers(uid_path)) {
+            PLOG(ERROR) << "Failed to activate controllers in " << uid_path;
+            return -errno;
         }
     }
 
diff --git a/libprocessgroup/profiles/Android.bp b/libprocessgroup/profiles/Android.bp
index 1ec9f7f..baa4546 100644
--- a/libprocessgroup/profiles/Android.bp
+++ b/libprocessgroup/profiles/Android.bp
@@ -13,6 +13,7 @@
 // limitations under the License.
 
 package {
+    default_team: "trendy_team_android_kernel",
     default_applicable_licenses: ["Android-Apache-2.0"],
 }
 
diff --git a/libprocessgroup/profiles/task_profiles.json b/libprocessgroup/profiles/task_profiles.json
index 411c38c..feda3b4 100644
--- a/libprocessgroup/profiles/task_profiles.json
+++ b/libprocessgroup/profiles/task_profiles.json
@@ -572,33 +572,6 @@
     },
 
     {
-      "Name": "PerfBoost",
-      "Actions": [
-        {
-          "Name": "SetClamps",
-          "Params":
-          {
-            "Boost": "50%",
-            "Clamp": "0"
-          }
-        }
-      ]
-    },
-    {
-      "Name": "PerfClamp",
-      "Actions": [
-        {
-          "Name": "SetClamps",
-          "Params":
-          {
-            "Boost": "0",
-            "Clamp": "30%"
-          }
-        }
-      ]
-    },
-
-    {
       "Name": "LowMemoryUsage",
       "Actions": [
         {
diff --git a/libprocessgroup/setup/Android.bp b/libprocessgroup/setup/Android.bp
index 1a4ad01..cc6c67c 100644
--- a/libprocessgroup/setup/Android.bp
+++ b/libprocessgroup/setup/Android.bp
@@ -33,7 +33,6 @@
         "libjsoncpp",
     ],
     static_libs: [
-        "libcgrouprc_format",
         "libprocessgroup_util",
     ],
     header_libs: [
diff --git a/libprocessgroup/setup/cgroup_descriptor.h b/libprocessgroup/setup/cgroup_descriptor.h
index 06ce186..1afd2ee 100644
--- a/libprocessgroup/setup/cgroup_descriptor.h
+++ b/libprocessgroup/setup/cgroup_descriptor.h
@@ -21,10 +21,7 @@
 
 #include <sys/stat.h>
 
-#include <processgroup/format/cgroup_controller.h>
-
-namespace android {
-namespace cgrouprc {
+#include <processgroup/cgroup_controller.h>
 
 // Complete controller description for mounting cgroups
 class CgroupDescriptor {
@@ -33,7 +30,7 @@
                      mode_t mode, const std::string& uid, const std::string& gid, uint32_t flags,
                      uint32_t max_activation_depth);
 
-    const format::CgroupController* controller() const { return &controller_; }
+    const CgroupController* controller() const { return &controller_; }
     mode_t mode() const { return mode_; }
     std::string uid() const { return uid_; }
     std::string gid() const { return gid_; }
@@ -41,11 +38,8 @@
     void set_mounted(bool mounted);
 
   private:
-    format::CgroupController controller_;
+    CgroupController controller_;
     mode_t mode_ = 0;
     std::string uid_;
     std::string gid_;
 };
-
-}  // namespace cgrouprc
-}  // namespace android
diff --git a/libprocessgroup/setup/cgroup_map_write.cpp b/libprocessgroup/setup/cgroup_map_write.cpp
index bd41874..d05bf24 100644
--- a/libprocessgroup/setup/cgroup_map_write.cpp
+++ b/libprocessgroup/setup/cgroup_map_write.cpp
@@ -22,45 +22,28 @@
 #include <fcntl.h>
 #include <grp.h>
 #include <pwd.h>
-#include <sys/mman.h>
 #include <sys/mount.h>
 #include <sys/stat.h>
 #include <sys/types.h>
-#include <time.h>
 #include <unistd.h>
 
 #include <optional>
 
 #include <android-base/file.h>
 #include <android-base/logging.h>
-#include <android-base/properties.h>
-#include <android-base/stringprintf.h>
-#include <android-base/unique_fd.h>
-#include <android/cgrouprc.h>
-#include <json/reader.h>
-#include <json/value.h>
-#include <processgroup/format/cgroup_file.h>
+#include <processgroup/cgroup_descriptor.h>
 #include <processgroup/processgroup.h>
 #include <processgroup/setup.h>
 #include <processgroup/util.h>
 
 #include "../build_flags.h"
-#include "cgroup_descriptor.h"
-
-using android::base::GetUintProperty;
-using android::base::StringPrintf;
-using android::base::unique_fd;
-
-namespace android {
-namespace cgrouprc {
+#include "../internal.h"
 
 static constexpr const char* CGROUPS_DESC_FILE = "/etc/cgroups.json";
 static constexpr const char* CGROUPS_DESC_VENDOR_FILE = "/vendor/etc/cgroups.json";
 
 static constexpr const char* TEMPLATE_CGROUPS_DESC_API_FILE = "/etc/task_profiles/cgroups_%u.json";
 
-static const std::string CGROUP_V2_ROOT_DEFAULT = "/sys/fs/cgroup";
-
 static bool ChangeDirModeAndOwner(const std::string& path, mode_t mode, const std::string& uid,
                                   const std::string& gid, bool permissive_mode = false) {
     uid_t pw_uid = -1;
@@ -148,149 +131,15 @@
     return true;
 }
 
-static void MergeCgroupToDescriptors(std::map<std::string, CgroupDescriptor>* descriptors,
-                                     const Json::Value& cgroup, const std::string& name,
-                                     const std::string& root_path, int cgroups_version) {
-    const std::string cgroup_path = cgroup["Path"].asString();
-    std::string path;
-
-    if (!root_path.empty()) {
-        path = root_path;
-        if (cgroup_path != ".") {
-            path += "/";
-            path += cgroup_path;
-        }
-    } else {
-        path = cgroup_path;
-    }
-
-    uint32_t controller_flags = 0;
-
-    if (cgroup["NeedsActivation"].isBool() && cgroup["NeedsActivation"].asBool()) {
-        controller_flags |= CGROUPRC_CONTROLLER_FLAG_NEEDS_ACTIVATION;
-    }
-
-    if (cgroup["Optional"].isBool() && cgroup["Optional"].asBool()) {
-        controller_flags |= CGROUPRC_CONTROLLER_FLAG_OPTIONAL;
-    }
-
-    uint32_t max_activation_depth = UINT32_MAX;
-    if (cgroup.isMember("MaxActivationDepth")) {
-        max_activation_depth = cgroup["MaxActivationDepth"].asUInt();
-    }
-
-    CgroupDescriptor descriptor(
-            cgroups_version, name, path, std::strtoul(cgroup["Mode"].asString().c_str(), 0, 8),
-            cgroup["UID"].asString(), cgroup["GID"].asString(), controller_flags,
-            max_activation_depth);
-
-    auto iter = descriptors->find(name);
-    if (iter == descriptors->end()) {
-        descriptors->emplace(name, descriptor);
-    } else {
-        iter->second = descriptor;
-    }
-}
-
-static const bool force_memcg_v2 = android::libprocessgroup_flags::force_memcg_v2();
-
-static bool ReadDescriptorsFromFile(const std::string& file_name,
-                                    std::map<std::string, CgroupDescriptor>* descriptors) {
-    std::vector<CgroupDescriptor> result;
-    std::string json_doc;
-
-    if (!android::base::ReadFileToString(file_name, &json_doc)) {
-        PLOG(ERROR) << "Failed to read task profiles from " << file_name;
-        return false;
-    }
-
-    Json::CharReaderBuilder builder;
-    std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
-    Json::Value root;
-    std::string errorMessage;
-    if (!reader->parse(&*json_doc.begin(), &*json_doc.end(), &root, &errorMessage)) {
-        LOG(ERROR) << "Failed to parse cgroups description: " << errorMessage;
-        return false;
-    }
-
-    if (root.isMember("Cgroups")) {
-        const Json::Value& cgroups = root["Cgroups"];
-        for (Json::Value::ArrayIndex i = 0; i < cgroups.size(); ++i) {
-            std::string name = cgroups[i]["Controller"].asString();
-
-            if (force_memcg_v2 && name == "memory") continue;
-
-            MergeCgroupToDescriptors(descriptors, cgroups[i], name, "", 1);
-        }
-    }
-
-    bool memcgv2_present = false;
-    std::string root_path;
-    if (root.isMember("Cgroups2")) {
-        const Json::Value& cgroups2 = root["Cgroups2"];
-        root_path = cgroups2["Path"].asString();
-        MergeCgroupToDescriptors(descriptors, cgroups2, CGROUPV2_HIERARCHY_NAME, "", 2);
-
-        const Json::Value& childGroups = cgroups2["Controllers"];
-        for (Json::Value::ArrayIndex i = 0; i < childGroups.size(); ++i) {
-            std::string name = childGroups[i]["Controller"].asString();
-
-            if (force_memcg_v2 && name == "memory") memcgv2_present = true;
-
-            MergeCgroupToDescriptors(descriptors, childGroups[i], name, root_path, 2);
-        }
-    }
-
-    if (force_memcg_v2 && !memcgv2_present) {
-        LOG(INFO) << "Forcing memcg to v2 hierarchy";
-        Json::Value memcgv2;
-        memcgv2["Controller"] = "memory";
-        memcgv2["NeedsActivation"] = true;
-        memcgv2["Path"] = ".";
-        memcgv2["Optional"] = true;  // In case of cgroup_disabled=memory, so we can still boot
-        MergeCgroupToDescriptors(descriptors, memcgv2, "memory",
-                                 root_path.empty() ? CGROUP_V2_ROOT_DEFAULT : root_path, 2);
-    }
-
-    return true;
-}
-
-static bool ReadDescriptors(std::map<std::string, CgroupDescriptor>* descriptors) {
-    // load system cgroup descriptors
-    if (!ReadDescriptorsFromFile(CGROUPS_DESC_FILE, descriptors)) {
-        return false;
-    }
-
-    // load API-level specific system cgroups descriptors if available
-    unsigned int api_level = GetUintProperty<unsigned int>("ro.product.first_api_level", 0);
-    if (api_level > 0) {
-        std::string api_cgroups_path =
-                android::base::StringPrintf(TEMPLATE_CGROUPS_DESC_API_FILE, api_level);
-        if (!access(api_cgroups_path.c_str(), F_OK) || errno != ENOENT) {
-            if (!ReadDescriptorsFromFile(api_cgroups_path, descriptors)) {
-                return false;
-            }
-        }
-    }
-
-    // load vendor cgroup descriptors if the file exists
-    if (!access(CGROUPS_DESC_VENDOR_FILE, F_OK) &&
-        !ReadDescriptorsFromFile(CGROUPS_DESC_VENDOR_FILE, descriptors)) {
-        return false;
-    }
-
-    return true;
-}
-
 // To avoid issues in sdk_mac build
 #if defined(__ANDROID__)
 
-static bool IsOptionalController(const format::CgroupController* controller) {
+static bool IsOptionalController(const CgroupController* controller) {
     return controller->flags() & CGROUPRC_CONTROLLER_FLAG_OPTIONAL;
 }
 
 static bool MountV2CgroupController(const CgroupDescriptor& descriptor) {
-    const format::CgroupController* controller = descriptor.controller();
+    const CgroupController* controller = descriptor.controller();
 
     // /sys/fs/cgroup is created by cgroup2 with specific selinux permissions,
     // try to create again in case the mount point is changed
@@ -324,36 +173,18 @@
 }
 
 static bool ActivateV2CgroupController(const CgroupDescriptor& descriptor) {
-    const format::CgroupController* controller = descriptor.controller();
+    const CgroupController* controller = descriptor.controller();
 
     if (!Mkdir(controller->path(), descriptor.mode(), descriptor.uid(), descriptor.gid())) {
         LOG(ERROR) << "Failed to create directory for " << controller->name() << " cgroup";
         return false;
     }
 
-    if (controller->flags() & CGROUPRC_CONTROLLER_FLAG_NEEDS_ACTIVATION &&
-        controller->max_activation_depth() > 0) {
-        std::string str = "+";
-        str += controller->name();
-        std::string path = controller->path();
-        path += "/cgroup.subtree_control";
-
-        if (!base::WriteStringToFile(str, path)) {
-            if (IsOptionalController(controller)) {
-                PLOG(INFO) << "Failed to activate optional controller " << controller->name()
-                           << " at " << path;
-                return true;
-            }
-            PLOG(ERROR) << "Failed to activate controller " << controller->name();
-            return false;
-        }
-    }
-
-    return true;
+    return ::ActivateControllers(controller->path(), {{controller->name(), descriptor}});
 }
 
 static bool MountV1CgroupController(const CgroupDescriptor& descriptor) {
-    const format::CgroupController* controller = descriptor.controller();
+    const CgroupController* controller = descriptor.controller();
 
     // mkdir <path> [mode] [owner] [group]
     if (!Mkdir(controller->path(), descriptor.mode(), descriptor.uid(), descriptor.gid())) {
@@ -388,7 +219,7 @@
 }
 
 static bool SetupCgroup(const CgroupDescriptor& descriptor) {
-    const format::CgroupController* controller = descriptor.controller();
+    const CgroupController* controller = descriptor.controller();
 
     if (controller->version() == 2) {
         if (!strcmp(controller->name(), CGROUPV2_HIERARCHY_NAME)) {
@@ -410,35 +241,6 @@
 
 #endif
 
-static bool WriteRcFile(const std::map<std::string, CgroupDescriptor>& descriptors) {
-    unique_fd fd(TEMP_FAILURE_RETRY(open(CGROUPS_RC_PATH, O_CREAT | O_WRONLY | O_TRUNC | O_CLOEXEC,
-                                         S_IRUSR | S_IRGRP | S_IROTH)));
-    if (fd < 0) {
-        PLOG(ERROR) << "open() failed for " << CGROUPS_RC_PATH;
-        return false;
-    }
-
-    format::CgroupFile fl;
-    fl.version_ = format::CgroupFile::FILE_CURR_VERSION;
-    fl.controller_count_ = descriptors.size();
-    int ret = TEMP_FAILURE_RETRY(write(fd, &fl, sizeof(fl)));
-    if (ret < 0) {
-        PLOG(ERROR) << "write() failed for " << CGROUPS_RC_PATH;
-        return false;
-    }
-
-    for (const auto& [name, descriptor] : descriptors) {
-        ret = TEMP_FAILURE_RETRY(
-                write(fd, descriptor.controller(), sizeof(format::CgroupController)));
-        if (ret < 0) {
-            PLOG(ERROR) << "write() failed for " << CGROUPS_RC_PATH;
-            return false;
-        }
-    }
-
-    return true;
-}
-
 CgroupDescriptor::CgroupDescriptor(uint32_t version, const std::string& name,
                                    const std::string& path, mode_t mode, const std::string& uid,
                                    const std::string& gid, uint32_t flags,
@@ -458,9 +260,6 @@
     controller_.set_flags(flags);
 }
 
-}  // namespace cgrouprc
-}  // namespace android
-
 static std::optional<bool> MGLRUDisabled() {
     const std::string file_name = "/sys/kernel/mm/lru_gen/enabled";
     std::string content;
@@ -472,9 +271,8 @@
     return content == "0x0000";
 }
 
-static std::optional<bool> MEMCGDisabled(
-        const std::map<std::string, android::cgrouprc::CgroupDescriptor>& descriptors) {
-    std::string cgroup_v2_root = android::cgrouprc::CGROUP_V2_ROOT_DEFAULT;
+static std::optional<bool> MEMCGDisabled(const CgroupDescriptorMap& descriptors) {
+    std::string cgroup_v2_root = CGROUP_V2_ROOT_DEFAULT;
     const auto it = descriptors.find(CGROUPV2_HIERARCHY_NAME);
     if (it == descriptors.end()) {
         LOG(WARNING) << "No Cgroups2 path found in cgroups.json. Vendor has modified Android, and "
@@ -495,14 +293,10 @@
     return content.find("memory") == std::string::npos;
 }
 
-static bool CreateV2SubHierarchy(
-        const std::string& path,
-        const std::map<std::string, android::cgrouprc::CgroupDescriptor>& descriptors) {
-    using namespace android::cgrouprc;
-
+static bool CreateV2SubHierarchy(const std::string& path, const CgroupDescriptorMap& descriptors) {
     const auto cgv2_iter = descriptors.find(CGROUPV2_HIERARCHY_NAME);
     if (cgv2_iter == descriptors.end()) return false;
-    const android::cgrouprc::CgroupDescriptor cgv2_descriptor = cgv2_iter->second;
+    const CgroupDescriptor cgv2_descriptor = cgv2_iter->second;
 
     if (!Mkdir(path, cgv2_descriptor.mode(), cgv2_descriptor.uid(), cgv2_descriptor.gid())) {
         PLOG(ERROR) << "Failed to create directory for " << path;
@@ -511,46 +305,17 @@
 
     // Activate all v2 controllers in path so they can be activated in
     // children as they are created.
-    for (const auto& [name, descriptor] : descriptors) {
-        const format::CgroupController* controller = descriptor.controller();
-        std::uint32_t flags = controller->flags();
-        std::uint32_t max_activation_depth = controller->max_activation_depth();
-        const int depth = util::GetCgroupDepth(controller->path(), path);
-
-        if (controller->version() == 2 && name != CGROUPV2_HIERARCHY_NAME &&
-            flags & CGROUPRC_CONTROLLER_FLAG_NEEDS_ACTIVATION && depth < max_activation_depth) {
-            std::string str("+");
-            str += controller->name();
-            if (!android::base::WriteStringToFile(str, path + "/cgroup.subtree_control")) {
-                if (flags & CGROUPRC_CONTROLLER_FLAG_OPTIONAL) {
-                    PLOG(WARNING) << "Activation of cgroup controller " << str << " failed in path "
-                                  << path;
-                } else {
-                    return false;
-                }
-            }
-        }
-    }
-    return true;
+    return ::ActivateControllers(path, descriptors);
 }
 
 bool CgroupSetup() {
-    using namespace android::cgrouprc;
-
-    std::map<std::string, CgroupDescriptor> descriptors;
+    CgroupDescriptorMap descriptors;
 
     if (getpid() != 1) {
         LOG(ERROR) << "Cgroup setup can be done only by init process";
         return false;
     }
 
-    // Make sure we do this only one time. No need for std::call_once because
-    // init is a single-threaded process
-    if (access(CGROUPS_RC_PATH, F_OK) == 0) {
-        LOG(WARNING) << "Attempt to call CgroupSetup() more than once";
-        return true;
-    }
-
     // load cgroups.json file
     if (!ReadDescriptors(&descriptors)) {
         LOG(ERROR) << "Failed to load cgroup description file";
@@ -559,15 +324,18 @@
 
     // setup cgroups
     for (auto& [name, descriptor] : descriptors) {
-        if (SetupCgroup(descriptor)) {
-            descriptor.set_mounted(true);
-        } else {
+        if (descriptor.controller()->flags() & CGROUPRC_CONTROLLER_FLAG_MOUNTED) {
+            LOG(WARNING) << "Attempt to call CgroupSetup() more than once";
+            return true;
+        }
+
+        if (!SetupCgroup(descriptor)) {
             // issue a warning and proceed with the next cgroup
             LOG(WARNING) << "Failed to setup " << name << " cgroup";
         }
     }
 
-    if (force_memcg_v2) {
+    if (android::libprocessgroup_flags::force_memcg_v2()) {
         if (MGLRUDisabled().value_or(false)) {
             LOG(WARNING) << "Memcg forced to v2 hierarchy with MGLRU disabled! "
                          << "Global reclaim performance will suffer.";
@@ -593,26 +361,5 @@
         }
     }
 
-    // mkdir <CGROUPS_RC_DIR> 0711 system system
-    if (!Mkdir(android::base::Dirname(CGROUPS_RC_PATH), 0711, "system", "system")) {
-        LOG(ERROR) << "Failed to create directory for " << CGROUPS_RC_PATH << " file";
-        return false;
-    }
-
-    // Generate <CGROUPS_RC_FILE> file which can be directly mmapped into
-    // process memory. This optimizes performance, memory usage
-    // and limits infrormation shared with unprivileged processes
-    // to the minimum subset of information from cgroups.json
-    if (!WriteRcFile(descriptors)) {
-        LOG(ERROR) << "Failed to write " << CGROUPS_RC_PATH << " file";
-        return false;
-    }
-
-    // chmod 0644 <CGROUPS_RC_PATH>
-    if (fchmodat(AT_FDCWD, CGROUPS_RC_PATH, 0644, AT_SYMLINK_NOFOLLOW) < 0) {
-        PLOG(ERROR) << "fchmodat() failed";
-        return false;
-    }
-
     return true;
 }
diff --git a/libprocessgroup/task_profiles.cpp b/libprocessgroup/task_profiles.cpp
index 110ef52..cc675b3 100644
--- a/libprocessgroup/task_profiles.cpp
+++ b/libprocessgroup/task_profiles.cpp
@@ -188,18 +188,6 @@
     return true;
 }
 
-bool SetClampsAction::ExecuteForProcess(uid_t, pid_t) const {
-    // TODO: add support when kernel supports util_clamp
-    LOG(WARNING) << "SetClampsAction::ExecuteForProcess is not supported";
-    return false;
-}
-
-bool SetClampsAction::ExecuteForTask(int) const {
-    // TODO: add support when kernel supports util_clamp
-    LOG(WARNING) << "SetClampsAction::ExecuteForTask is not supported";
-    return false;
-}
-
 // To avoid issues in sdk_mac build
 #if defined(__ANDROID__)
 
@@ -958,23 +946,6 @@
                 } else {
                     LOG(WARNING) << "SetAttribute: unknown attribute: " << attr_name;
                 }
-            } else if (action_name == "SetClamps") {
-                std::string boost_value = params_val["Boost"].asString();
-                std::string clamp_value = params_val["Clamp"].asString();
-                char* end;
-                unsigned long boost;
-
-                boost = strtoul(boost_value.c_str(), &end, 10);
-                if (end > boost_value.c_str()) {
-                    unsigned long clamp = strtoul(clamp_value.c_str(), &end, 10);
-                    if (end > clamp_value.c_str()) {
-                        profile->Add(std::make_unique<SetClampsAction>(boost, clamp));
-                    } else {
-                        LOG(WARNING) << "SetClamps: invalid parameter " << clamp_value;
-                    }
-                } else {
-                    LOG(WARNING) << "SetClamps: invalid parameter: " << boost_value;
-                }
             } else if (action_name == "WriteFile") {
                 std::string attr_filepath = params_val["FilePath"].asString();
                 std::string attr_procfilepath = params_val["ProcFilePath"].asString();
diff --git a/libprocessgroup/task_profiles.h b/libprocessgroup/task_profiles.h
index ea948b5..d0b5043 100644
--- a/libprocessgroup/task_profiles.h
+++ b/libprocessgroup/task_profiles.h
@@ -91,19 +91,6 @@
 };
 
 // Profile actions
-class SetClampsAction : public ProfileAction {
-  public:
-    SetClampsAction(int boost, int clamp) noexcept : boost_(boost), clamp_(clamp) {}
-
-    const char* Name() const override { return "SetClamps"; }
-    bool ExecuteForProcess(uid_t uid, pid_t pid) const override;
-    bool ExecuteForTask(pid_t tid) const override;
-
-  protected:
-    int boost_;
-    int clamp_;
-};
-
 class SetTimerSlackAction : public ProfileAction {
   public:
     SetTimerSlackAction(unsigned long slack) noexcept : slack_(slack) {}
diff --git a/libprocessgroup/util/Android.bp b/libprocessgroup/util/Android.bp
index 54ba69b..1c74d4e 100644
--- a/libprocessgroup/util/Android.bp
+++ b/libprocessgroup/util/Android.bp
@@ -37,8 +37,16 @@
         "include",
     ],
     srcs: [
+        "cgroup_controller.cpp",
+        "cgroup_descriptor.cpp",
         "util.cpp",
     ],
+    shared_libs: [
+        "libbase",
+    ],
+    static_libs: [
+        "libjsoncpp",
+    ],
     defaults: ["libprocessgroup_build_flags_cc"],
 }
 
diff --git a/libprocessgroup/cgrouprc_format/cgroup_controller.cpp b/libprocessgroup/util/cgroup_controller.cpp
similarity index 89%
rename from libprocessgroup/cgrouprc_format/cgroup_controller.cpp
rename to libprocessgroup/util/cgroup_controller.cpp
index 0dd909a..fb41680 100644
--- a/libprocessgroup/cgrouprc_format/cgroup_controller.cpp
+++ b/libprocessgroup/util/cgroup_controller.cpp
@@ -14,11 +14,9 @@
  * limitations under the License.
  */
 
-#include <processgroup/format/cgroup_controller.h>
+#include <processgroup/cgroup_controller.h>
 
-namespace android {
-namespace cgrouprc {
-namespace format {
+#include <cstring>
 
 CgroupController::CgroupController(uint32_t version, uint32_t flags, const std::string& name,
                                    const std::string& path, uint32_t max_activation_depth)
@@ -54,8 +52,4 @@
 
 void CgroupController::set_flags(uint32_t flags) {
     flags_ = flags;
-}
-
-}  // namespace format
-}  // namespace cgrouprc
-}  // namespace android
+}
\ No newline at end of file
diff --git a/libprocessgroup/util/cgroup_descriptor.cpp b/libprocessgroup/util/cgroup_descriptor.cpp
new file mode 100644
index 0000000..4d3347f
--- /dev/null
+++ b/libprocessgroup/util/cgroup_descriptor.cpp
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2024 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 <processgroup/cgroup_descriptor.h>
+
+#include <processgroup/util.h>  // For flag values
+
+CgroupDescriptor::CgroupDescriptor(uint32_t version, const std::string& name,
+                                   const std::string& path, mode_t mode, const std::string& uid,
+                                   const std::string& gid, uint32_t flags,
+                                   uint32_t max_activation_depth)
+    : controller_(version, flags, name, path, max_activation_depth),
+      mode_(mode),
+      uid_(uid),
+      gid_(gid) {}
+
+void CgroupDescriptor::set_mounted(bool mounted) {
+    uint32_t flags = controller_.flags();
+    if (mounted) {
+        flags |= CGROUPRC_CONTROLLER_FLAG_MOUNTED;
+    } else {
+        flags &= ~CGROUPRC_CONTROLLER_FLAG_MOUNTED;
+    }
+    controller_.set_flags(flags);
+}
diff --git a/libprocessgroup/cgrouprc_format/include/processgroup/format/cgroup_controller.h b/libprocessgroup/util/include/processgroup/cgroup_controller.h
similarity index 86%
rename from libprocessgroup/cgrouprc_format/include/processgroup/format/cgroup_controller.h
rename to libprocessgroup/util/include/processgroup/cgroup_controller.h
index c0c1f60..fe6a829 100644
--- a/libprocessgroup/cgrouprc_format/include/processgroup/format/cgroup_controller.h
+++ b/libprocessgroup/util/include/processgroup/cgroup_controller.h
@@ -20,11 +20,7 @@
 #include <cstdint>
 #include <string>
 
-namespace android {
-namespace cgrouprc {
-namespace format {
-
-// Minimal controller description to be mmapped into process address space
+// Minimal controller description
 struct CgroupController {
   public:
     CgroupController() = default;
@@ -48,8 +44,4 @@
     uint32_t max_activation_depth_ = UINT32_MAX;
     char name_[CGROUP_NAME_BUF_SZ] = {};
     char path_[CGROUP_PATH_BUF_SZ] = {};
-};
-
-}  // namespace format
-}  // namespace cgrouprc
-}  // namespace android
+};
\ No newline at end of file
diff --git a/libprocessgroup/util/include/processgroup/cgroup_descriptor.h b/libprocessgroup/util/include/processgroup/cgroup_descriptor.h
new file mode 100644
index 0000000..1afd2ee
--- /dev/null
+++ b/libprocessgroup/util/include/processgroup/cgroup_descriptor.h
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2019 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 <cstdint>
+#include <string>
+
+#include <sys/stat.h>
+
+#include <processgroup/cgroup_controller.h>
+
+// Complete controller description for mounting cgroups
+class CgroupDescriptor {
+  public:
+    CgroupDescriptor(uint32_t version, const std::string& name, const std::string& path,
+                     mode_t mode, const std::string& uid, const std::string& gid, uint32_t flags,
+                     uint32_t max_activation_depth);
+
+    const CgroupController* controller() const { return &controller_; }
+    mode_t mode() const { return mode_; }
+    std::string uid() const { return uid_; }
+    std::string gid() const { return gid_; }
+
+    void set_mounted(bool mounted);
+
+  private:
+    CgroupController controller_;
+    mode_t mode_ = 0;
+    std::string uid_;
+    std::string gid_;
+};
diff --git a/libprocessgroup/util/include/processgroup/util.h b/libprocessgroup/util/include/processgroup/util.h
index 8d013af..2c7b329 100644
--- a/libprocessgroup/util/include/processgroup/util.h
+++ b/libprocessgroup/util/include/processgroup/util.h
@@ -16,10 +16,20 @@
 
 #pragma once
 
+#include <map>
 #include <string>
 
-namespace util {
+#include "cgroup_descriptor.h"
+
+// Duplicated from cgrouprc.h. Don't depend on libcgrouprc here.
+#define CGROUPRC_CONTROLLER_FLAG_MOUNTED 0x1
+#define CGROUPRC_CONTROLLER_FLAG_NEEDS_ACTIVATION 0x2
+#define CGROUPRC_CONTROLLER_FLAG_OPTIONAL 0x4
 
 unsigned int GetCgroupDepth(const std::string& controller_root, const std::string& cgroup_path);
 
-}  // namespace util
+using CgroupControllerName = std::string;
+using CgroupDescriptorMap = std::map<CgroupControllerName, CgroupDescriptor>;
+bool ReadDescriptors(CgroupDescriptorMap* descriptors);
+
+bool ActivateControllers(const std::string& path, const CgroupDescriptorMap& descriptors);
diff --git a/libprocessgroup/util/tests/util.cpp b/libprocessgroup/util/tests/util.cpp
index 1de7d6f..6caef8e 100644
--- a/libprocessgroup/util/tests/util.cpp
+++ b/libprocessgroup/util/tests/util.cpp
@@ -18,8 +18,6 @@
 
 #include "gtest/gtest.h"
 
-using util::GetCgroupDepth;
-
 TEST(EmptyInputs, bothEmpty) {
     EXPECT_EQ(GetCgroupDepth({}, {}), 0);
 }
diff --git a/libprocessgroup/util/util.cpp b/libprocessgroup/util/util.cpp
index 9b88a22..1401675 100644
--- a/libprocessgroup/util/util.cpp
+++ b/libprocessgroup/util/util.cpp
@@ -18,9 +18,33 @@
 
 #include <algorithm>
 #include <iterator>
+#include <optional>
+#include <string_view>
+
+#include <mntent.h>
+
+#include <android-base/file.h>
+#include <android-base/logging.h>
+#include <android-base/properties.h>
+#include <android-base/stringprintf.h>
+#include <json/reader.h>
+#include <json/value.h>
+
+#include "../build_flags.h"
+#include "../internal.h"
+
+using android::base::GetUintProperty;
 
 namespace {
 
+constexpr const char* CGROUPS_DESC_FILE = "/etc/cgroups.json";
+constexpr const char* CGROUPS_DESC_VENDOR_FILE = "/vendor/etc/cgroups.json";
+constexpr const char* TEMPLATE_CGROUPS_DESC_API_FILE = "/etc/task_profiles/cgroups_%u.json";
+
+// This should match the publicly declared value in processgroup.h,
+// but we don't want this library to depend on libprocessgroup.
+constexpr std::string CGROUPV2_HIERARCHY_NAME_INTERNAL = "cgroup2";
+
 const char SEP = '/';
 
 std::string DeduplicateAndTrimSeparators(const std::string& path) {
@@ -42,9 +66,135 @@
     return ret;
 }
 
+void MergeCgroupToDescriptors(CgroupDescriptorMap* descriptors, const Json::Value& cgroup,
+                              const std::string& name, const std::string& root_path,
+                              int cgroups_version) {
+    const std::string cgroup_path = cgroup["Path"].asString();
+    std::string path;
+
+    if (!root_path.empty()) {
+        path = root_path;
+        if (cgroup_path != ".") {
+            path += "/";
+            path += cgroup_path;
+        }
+    } else {
+        path = cgroup_path;
+    }
+
+    uint32_t controller_flags = 0;
+
+    if (cgroup["NeedsActivation"].isBool() && cgroup["NeedsActivation"].asBool()) {
+        controller_flags |= CGROUPRC_CONTROLLER_FLAG_NEEDS_ACTIVATION;
+    }
+
+    if (cgroup["Optional"].isBool() && cgroup["Optional"].asBool()) {
+        controller_flags |= CGROUPRC_CONTROLLER_FLAG_OPTIONAL;
+    }
+
+    uint32_t max_activation_depth = UINT32_MAX;
+    if (cgroup.isMember("MaxActivationDepth")) {
+        max_activation_depth = cgroup["MaxActivationDepth"].asUInt();
+    }
+
+    CgroupDescriptor descriptor(
+            cgroups_version, name, path, std::strtoul(cgroup["Mode"].asString().c_str(), 0, 8),
+            cgroup["UID"].asString(), cgroup["GID"].asString(), controller_flags,
+            max_activation_depth);
+
+    auto iter = descriptors->find(name);
+    if (iter == descriptors->end()) {
+        descriptors->emplace(name, descriptor);
+    } else {
+        iter->second = descriptor;
+    }
+}
+
+bool ReadDescriptorsFromFile(const std::string& file_name, CgroupDescriptorMap* descriptors) {
+    static constexpr bool force_memcg_v2 = android::libprocessgroup_flags::force_memcg_v2();
+    std::vector<CgroupDescriptor> result;
+    std::string json_doc;
+
+    if (!android::base::ReadFileToString(file_name, &json_doc)) {
+        PLOG(ERROR) << "Failed to read task profiles from " << file_name;
+        return false;
+    }
+
+    Json::CharReaderBuilder builder;
+    std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
+    Json::Value root;
+    std::string errorMessage;
+    if (!reader->parse(&*json_doc.begin(), &*json_doc.end(), &root, &errorMessage)) {
+        LOG(ERROR) << "Failed to parse cgroups description: " << errorMessage;
+        return false;
+    }
+
+    if (root.isMember("Cgroups")) {
+        const Json::Value& cgroups = root["Cgroups"];
+        for (Json::Value::ArrayIndex i = 0; i < cgroups.size(); ++i) {
+            std::string name = cgroups[i]["Controller"].asString();
+
+            if (force_memcg_v2 && name == "memory") continue;
+
+            MergeCgroupToDescriptors(descriptors, cgroups[i], name, "", 1);
+        }
+    }
+
+    bool memcgv2_present = false;
+    std::string root_path;
+    if (root.isMember("Cgroups2")) {
+        const Json::Value& cgroups2 = root["Cgroups2"];
+        root_path = cgroups2["Path"].asString();
+        MergeCgroupToDescriptors(descriptors, cgroups2, CGROUPV2_HIERARCHY_NAME_INTERNAL, "", 2);
+
+        const Json::Value& childGroups = cgroups2["Controllers"];
+        for (Json::Value::ArrayIndex i = 0; i < childGroups.size(); ++i) {
+            std::string name = childGroups[i]["Controller"].asString();
+
+            if (force_memcg_v2 && name == "memory") memcgv2_present = true;
+
+            MergeCgroupToDescriptors(descriptors, childGroups[i], name, root_path, 2);
+        }
+    }
+
+    if (force_memcg_v2 && !memcgv2_present) {
+        LOG(INFO) << "Forcing memcg to v2 hierarchy";
+        Json::Value memcgv2;
+        memcgv2["Controller"] = "memory";
+        memcgv2["NeedsActivation"] = true;
+        memcgv2["Path"] = ".";
+        memcgv2["Optional"] = true;  // In case of cgroup_disabled=memory, so we can still boot
+        MergeCgroupToDescriptors(descriptors, memcgv2, "memory",
+                                 root_path.empty() ? CGROUP_V2_ROOT_DEFAULT : root_path, 2);
+    }
+
+    return true;
+}
+
+using MountDir = std::string;
+using MountOpts = std::string;
+static std::optional<std::map<MountDir, MountOpts>> ReadCgroupV1Mounts() {
+    FILE* fp = setmntent("/proc/mounts", "r");
+    if (fp == nullptr) {
+        PLOG(ERROR) << "Failed to read mounts";
+        return std::nullopt;
+    }
+
+    std::map<MountDir, MountOpts> mounts;
+    const std::string_view CGROUP_V1_TYPE = "cgroup";
+    for (mntent* mentry = getmntent(fp); mentry != nullptr; mentry = getmntent(fp)) {
+        if (mentry->mnt_type && CGROUP_V1_TYPE == mentry->mnt_type &&
+            mentry->mnt_dir && mentry->mnt_opts) {
+            mounts[mentry->mnt_dir] = mentry->mnt_opts;
+        }
+    }
+    endmntent(fp);
+
+    return mounts;
+}
+
 }  // anonymous namespace
 
-namespace util {
 
 unsigned int GetCgroupDepth(const std::string& controller_root, const std::string& cgroup_path) {
     const std::string deduped_root = DeduplicateAndTrimSeparators(controller_root);
@@ -56,4 +206,70 @@
     return std::count(deduped_path.begin() + deduped_root.size(), deduped_path.end(), SEP);
 }
 
-}  // namespace util
+bool ReadDescriptors(CgroupDescriptorMap* descriptors) {
+    // load system cgroup descriptors
+    if (!ReadDescriptorsFromFile(CGROUPS_DESC_FILE, descriptors)) {
+        return false;
+    }
+
+    // load API-level specific system cgroups descriptors if available
+    unsigned int api_level = GetUintProperty<unsigned int>("ro.product.first_api_level", 0);
+    if (api_level > 0) {
+        std::string api_cgroups_path =
+                android::base::StringPrintf(TEMPLATE_CGROUPS_DESC_API_FILE, api_level);
+        if (!access(api_cgroups_path.c_str(), F_OK) || errno != ENOENT) {
+            if (!ReadDescriptorsFromFile(api_cgroups_path, descriptors)) {
+                return false;
+            }
+        }
+    }
+
+    // load vendor cgroup descriptors if the file exists
+    if (!access(CGROUPS_DESC_VENDOR_FILE, F_OK) &&
+        !ReadDescriptorsFromFile(CGROUPS_DESC_VENDOR_FILE, descriptors)) {
+        return false;
+    }
+
+    // check for v1 mount/usability status
+    std::optional<std::map<MountDir, MountOpts>> v1Mounts;
+    for (auto& [name, descriptor] : *descriptors) {
+        const CgroupController* const controller = descriptor.controller();
+
+        if (controller->version() != 1) continue;
+
+        // Read only once, and only if we have at least one v1 controller
+        if (!v1Mounts) {
+            v1Mounts = ReadCgroupV1Mounts();
+            if (!v1Mounts) return false;
+        }
+
+        if (const auto it = v1Mounts->find(controller->path()); it != v1Mounts->end()) {
+            if (it->second.contains(controller->name())) descriptor.set_mounted(true);
+        }
+    }
+
+    return true;
+}
+
+bool ActivateControllers(const std::string& path, const CgroupDescriptorMap& descriptors) {
+    for (const auto& [name, descriptor] : descriptors) {
+        const uint32_t flags = descriptor.controller()->flags();
+        const uint32_t max_activation_depth = descriptor.controller()->max_activation_depth();
+        const unsigned int depth = GetCgroupDepth(descriptor.controller()->path(), path);
+
+        if (flags & CGROUPRC_CONTROLLER_FLAG_NEEDS_ACTIVATION && depth < max_activation_depth) {
+            std::string str("+");
+            str.append(descriptor.controller()->name());
+            if (!android::base::WriteStringToFile(str, path + "/cgroup.subtree_control")) {
+                if (flags & CGROUPRC_CONTROLLER_FLAG_OPTIONAL) {
+                    PLOG(WARNING) << "Activation of cgroup controller " << str
+                                  << " failed in path " << path;
+                } else {
+                    return false;
+                }
+            }
+        }
+    }
+    return true;
+}
+
diff --git a/libutils/binder/RefBase.cpp b/libutils/binder/RefBase.cpp
index 2d2e40b..4291f1e 100644
--- a/libutils/binder/RefBase.cpp
+++ b/libutils/binder/RefBase.cpp
@@ -787,7 +787,7 @@
             // sp<T>(T*) constructor, assuming that if the object is around, it is already
             // owned by an sp<>.
             ALOGW("RefBase: Explicit destruction, weak count = %d (in %p). Use sp<> to manage this "
-                  "object.",
+                  "object. Note - if weak count is 0, this leaks mRefs (weakref_impl).",
                   mRefs->mWeak.load(), this);
 
 #if ANDROID_UTILS_CALLSTACK_ENABLED
diff --git a/rootdir/init.rc b/rootdir/init.rc
index 3e1d481..12d9c43 100644
--- a/rootdir/init.rc
+++ b/rootdir/init.rc
@@ -595,6 +595,7 @@
     mkdir /metadata/ota 0750 root system
     mkdir /metadata/ota/snapshots 0750 root system
     mkdir /metadata/watchdog 0770 root system
+    mkdir /metadata/tradeinmode 0770 root system
 
     mkdir /metadata/apex 0700 root system
     mkdir /metadata/apex/sessions 0700 root system
diff --git a/shell_and_utilities/Android.bp b/shell_and_utilities/Android.bp
index d5893de..1f5c179 100644
--- a/shell_and_utilities/Android.bp
+++ b/shell_and_utilities/Android.bp
@@ -58,6 +58,7 @@
         "toolbox_vendor",
         "toybox_vendor",
     ],
+    vendor: true,
 }
 
 // shell and utilities for first stage console. The list of binaries are