Merge "Revert^3 "init: Look for super partition only on a boot device"" 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/Android.bp b/debuggerd/Android.bp
index c365cac..d4dc9a3 100644
--- a/debuggerd/Android.bp
+++ b/debuggerd/Android.bp
@@ -200,22 +200,18 @@
     ramdisk_available: true,
     recovery_available: true,
     vendor_ramdisk_available: true,
+    host_supported: true,
 
     local_include_dirs: ["libdebuggerd/include"],
     export_include_dirs: ["libdebuggerd/include"],
 
     srcs: [
         "libdebuggerd/tombstone_proto_to_text.cpp",
-    ],
-
-    header_libs: [
-        "bionic_libc_platform_headers",
+        "libdebuggerd/utility_host.cpp",
     ],
 
     static_libs: [
         "libbase",
-        "liblog_for_runtime_apex",
-        "libunwindstack",
     ],
 
     whole_static_libs: [
@@ -223,6 +219,10 @@
         "libprotobuf-cpp-lite",
     ],
 
+    shared_libs: [
+        "liblog",
+    ],
+
     apex_available: [
         "//apex_available:platform",
         "com.android.runtime",
@@ -331,15 +331,15 @@
 
 cc_binary {
     name: "pbtombstone",
+    host_supported: true,
     defaults: ["debuggerd_defaults"],
     srcs: ["pbtombstone.cpp"],
     static_libs: [
         "libbase",
-        "libdebuggerd",
+        "libdebuggerd_tombstone_proto_to_text",
         "liblog",
         "libprotobuf-cpp-lite",
         "libtombstone_proto",
-        "libunwindstack",
     ],
 }
 
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/debuggerd_test.cpp b/debuggerd/debuggerd_test.cpp
index e33cea5..13c8d70 100644
--- a/debuggerd/debuggerd_test.cpp
+++ b/debuggerd/debuggerd_test.cpp
@@ -70,6 +70,7 @@
 #include "crash_test.h"
 #include "debuggerd/handler.h"
 #include "gtest/gtest.h"
+#include "libdebuggerd/utility_host.h"
 #include "protocol.h"
 #include "tombstoned/tombstoned.h"
 #include "util.h"
@@ -741,8 +742,6 @@
 }
 
 #if defined(__aarch64__)
-constexpr size_t kTagGranuleSize = 16;
-
 static uintptr_t CreateTagMapping() {
   // Some of the MTE tag dump tests assert that there is an inaccessible page to the left and right
   // of the PROT_MTE page, so map three pages and set the two guard pages to PROT_NONE.
diff --git a/debuggerd/libdebuggerd/include/libdebuggerd/tombstone.h b/debuggerd/libdebuggerd/include/libdebuggerd/tombstone.h
index 074b095..39989c3 100644
--- a/debuggerd/libdebuggerd/include/libdebuggerd/tombstone.h
+++ b/debuggerd/libdebuggerd/include/libdebuggerd/tombstone.h
@@ -67,10 +67,6 @@
                              const Architecture* guest_arch,
                              unwindstack::AndroidUnwinder* guest_unwinder);
 
-bool tombstone_proto_to_text(
-    const Tombstone& tombstone,
-    std::function<void(const std::string& line, bool should_log)> callback);
-
 void fill_in_backtrace_frame(BacktraceFrame* f, const unwindstack::FrameData& frame);
 void set_human_readable_cause(Cause* cause, uint64_t fault_addr);
 #if defined(__aarch64__)
diff --git a/debuggerd/libdebuggerd/include/libdebuggerd/tombstone_proto_to_text.h b/debuggerd/libdebuggerd/include/libdebuggerd/tombstone_proto_to_text.h
new file mode 100644
index 0000000..515a15f
--- /dev/null
+++ b/debuggerd/libdebuggerd/include/libdebuggerd/tombstone_proto_to_text.h
@@ -0,0 +1,26 @@
+/*
+ * 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 <functional>
+#include <string>
+
+class Tombstone;
+
+bool tombstone_proto_to_text(
+    const Tombstone& tombstone,
+    std::function<void(const std::string& line, bool should_log)> callback);
diff --git a/debuggerd/libdebuggerd/include/libdebuggerd/utility.h b/debuggerd/libdebuggerd/include/libdebuggerd/utility.h
index 26c2cd4..b86c13d 100644
--- a/debuggerd/libdebuggerd/include/libdebuggerd/utility.h
+++ b/debuggerd/libdebuggerd/include/libdebuggerd/utility.h
@@ -91,10 +91,3 @@
 void get_signal_sender(char* buf, size_t n, const siginfo_t*);
 const char* get_signame(const siginfo_t*);
 const char* get_sigcode(const siginfo_t*);
-
-// Number of bytes per MTE granule.
-constexpr size_t kTagGranuleSize = 16;
-
-// Number of rows and columns to display in an MTE tag dump.
-constexpr size_t kNumTagColumns = 16;
-constexpr size_t kNumTagRows = 16;
diff --git a/debuggerd/libdebuggerd/include/libdebuggerd/utility_host.h b/debuggerd/libdebuggerd/include/libdebuggerd/utility_host.h
new file mode 100644
index 0000000..43fb8bd
--- /dev/null
+++ b/debuggerd/libdebuggerd/include/libdebuggerd/utility_host.h
@@ -0,0 +1,31 @@
+/*
+ * Copyright 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>
+
+#include <stddef.h>
+
+std::string describe_tagged_addr_ctrl(long ctrl);
+std::string describe_pac_enabled_keys(long keys);
+
+// Number of bytes per MTE granule.
+constexpr size_t kTagGranuleSize = 16;
+
+// Number of rows and columns to display in an MTE tag dump.
+constexpr size_t kNumTagColumns = 16;
+constexpr size_t kNumTagRows = 16;
diff --git a/debuggerd/libdebuggerd/scudo.cpp b/debuggerd/libdebuggerd/scudo.cpp
index 4ee87c8..71d5fcf 100644
--- a/debuggerd/libdebuggerd/scudo.cpp
+++ b/debuggerd/libdebuggerd/scudo.cpp
@@ -18,6 +18,7 @@
 
 #include "libdebuggerd/scudo.h"
 #include "libdebuggerd/tombstone.h"
+#include "libdebuggerd/utility_host.h"
 
 #include "unwindstack/AndroidUnwinder.h"
 #include "unwindstack/Memory.h"
diff --git a/debuggerd/libdebuggerd/test/tombstone_proto_to_text_test.cpp b/debuggerd/libdebuggerd/test/tombstone_proto_to_text_test.cpp
index 4fd2643..3fdb71d 100644
--- a/debuggerd/libdebuggerd/test/tombstone_proto_to_text_test.cpp
+++ b/debuggerd/libdebuggerd/test/tombstone_proto_to_text_test.cpp
@@ -22,6 +22,7 @@
 #include <android-base/test_utils.h>
 
 #include "libdebuggerd/tombstone.h"
+#include "libdebuggerd/tombstone_proto_to_text.h"
 #include "tombstone.pb.h"
 
 using CallbackType = std::function<void(const std::string& line, bool should_log)>;
diff --git a/debuggerd/libdebuggerd/tombstone.cpp b/debuggerd/libdebuggerd/tombstone.cpp
index 0ce5573..d483b98 100644
--- a/debuggerd/libdebuggerd/tombstone.cpp
+++ b/debuggerd/libdebuggerd/tombstone.cpp
@@ -17,6 +17,7 @@
 #define LOG_TAG "DEBUG"
 
 #include "libdebuggerd/tombstone.h"
+#include "libdebuggerd/tombstone_proto_to_text.h"
 
 #include <errno.h>
 #include <signal.h>
diff --git a/debuggerd/libdebuggerd/tombstone_proto.cpp b/debuggerd/libdebuggerd/tombstone_proto.cpp
index ed4fd53..d59358c 100644
--- a/debuggerd/libdebuggerd/tombstone_proto.cpp
+++ b/debuggerd/libdebuggerd/tombstone_proto.cpp
@@ -69,6 +69,7 @@
 
 #include "libdebuggerd/open_files_list.h"
 #include "libdebuggerd/utility.h"
+#include "libdebuggerd/utility_host.h"
 #include "util.h"
 
 #include "tombstone.pb.h"
diff --git a/debuggerd/libdebuggerd/tombstone_proto_to_text.cpp b/debuggerd/libdebuggerd/tombstone_proto_to_text.cpp
index c3f9470..611e237 100644
--- a/debuggerd/libdebuggerd/tombstone_proto_to_text.cpp
+++ b/debuggerd/libdebuggerd/tombstone_proto_to_text.cpp
@@ -14,7 +14,8 @@
  * limitations under the License.
  */
 
-#include <libdebuggerd/tombstone.h>
+#include <libdebuggerd/tombstone_proto_to_text.h>
+#include <libdebuggerd/utility_host.h>
 
 #include <inttypes.h>
 
@@ -30,8 +31,6 @@
 #include <android-base/stringprintf.h>
 #include <android-base/strings.h>
 #include <android-base/unique_fd.h>
-#include <bionic/macros.h>
-#include <sys/prctl.h>
 
 #include "tombstone.pb.h"
 
@@ -57,28 +56,6 @@
   return desc.empty() ? "" : " (" + desc.substr(2) + ")";
 }
 
-static std::string describe_tagged_addr_ctrl(long value) {
-  std::string desc;
-  DESCRIBE_FLAG(PR_TAGGED_ADDR_ENABLE);
-  DESCRIBE_FLAG(PR_MTE_TCF_SYNC);
-  DESCRIBE_FLAG(PR_MTE_TCF_ASYNC);
-  if (value & PR_MTE_TAG_MASK) {
-    desc += StringPrintf(", mask 0x%04lx", (value & PR_MTE_TAG_MASK) >> PR_MTE_TAG_SHIFT);
-    value &= ~PR_MTE_TAG_MASK;
-  }
-  return describe_end(value, desc);
-}
-
-static std::string describe_pac_enabled_keys(long value) {
-  std::string desc;
-  DESCRIBE_FLAG(PR_PAC_APIAKEY);
-  DESCRIBE_FLAG(PR_PAC_APIBKEY);
-  DESCRIBE_FLAG(PR_PAC_APDAKEY);
-  DESCRIBE_FLAG(PR_PAC_APDBKEY);
-  DESCRIBE_FLAG(PR_PAC_APGAKEY);
-  return describe_end(value, desc);
-}
-
 static const char* abi_string(const Architecture& arch) {
   switch (arch) {
     case Architecture::ARM32:
@@ -113,6 +90,13 @@
   }
 }
 
+static uint64_t untag_address(Architecture arch, uint64_t addr) {
+  if (arch == Architecture::ARM64) {
+    return addr & ((1ULL << 56) - 1);
+  }
+  return addr;
+}
+
 static void print_thread_header(CallbackType callback, const Tombstone& tombstone,
                                 const Thread& thread, bool should_log) {
   const char* process_name = "<unknown>";
@@ -321,7 +305,8 @@
 
   size_t tag_index = 0;
   size_t num_tags = tags.length();
-  uintptr_t fault_granule = untag_address(signal.fault_address()) & ~(kTagGranuleSize - 1);
+  uintptr_t fault_granule =
+      untag_address(tombstone.arch(), signal.fault_address()) & ~(kTagGranuleSize - 1);
   for (size_t row = 0; tag_index < num_tags; ++row) {
     uintptr_t row_addr =
         (memory_dump.begin_address() + row * kNumTagColumns * kTagGranuleSize) & kRowStartMask;
@@ -369,7 +354,7 @@
 
   const Signal& signal_info = tombstone.signal_info();
   bool has_fault_address = signal_info.has_fault_address();
-  uint64_t fault_address = untag_address(signal_info.fault_address());
+  uint64_t fault_address = untag_address(tombstone.arch(), signal_info.fault_address());
   bool preamble_printed = false;
   bool printed_fault_address_marker = false;
   for (const auto& map : tombstone.memory_mappings()) {
diff --git a/debuggerd/libdebuggerd/utility.cpp b/debuggerd/libdebuggerd/utility.cpp
index 742ac7c..b5a93b7 100644
--- a/debuggerd/libdebuggerd/utility.cpp
+++ b/debuggerd/libdebuggerd/utility.cpp
@@ -17,6 +17,7 @@
 #define LOG_TAG "DEBUG"
 
 #include "libdebuggerd/utility.h"
+#include "libdebuggerd/utility_host.h"
 
 #include <errno.h>
 #include <signal.h>
diff --git a/debuggerd/libdebuggerd/utility_host.cpp b/debuggerd/libdebuggerd/utility_host.cpp
new file mode 100644
index 0000000..72a560c
--- /dev/null
+++ b/debuggerd/libdebuggerd/utility_host.cpp
@@ -0,0 +1,101 @@
+/*
+ * Copyright 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 "libdebuggerd/utility_host.h"
+
+#include <sys/prctl.h>
+
+#include <string>
+
+#include <android-base/stringprintf.h>
+
+using android::base::StringPrintf;
+
+#ifndef PR_MTE_TAG_SHIFT
+#define PR_MTE_TAG_SHIFT 3
+#endif
+
+#ifndef PR_MTE_TAG_MASK
+#define PR_MTE_TAG_MASK (0xffffUL << PR_MTE_TAG_SHIFT)
+#endif
+
+#ifndef PR_MTE_TCF_ASYNC
+#define PR_MTE_TCF_ASYNC (1UL << 2)
+#endif
+
+#ifndef PR_MTE_TCF_SYNC
+#define PR_MTE_TCF_SYNC (1UL << 1)
+#endif
+
+#ifndef PR_PAC_APIAKEY
+#define PR_PAC_APIAKEY (1UL << 0)
+#endif
+
+#ifndef PR_PAC_APIBKEY
+#define PR_PAC_APIBKEY (1UL << 1)
+#endif
+
+#ifndef PR_PAC_APDAKEY
+#define PR_PAC_APDAKEY (1UL << 2)
+#endif
+
+#ifndef PR_PAC_APDBKEY
+#define PR_PAC_APDBKEY (1UL << 3)
+#endif
+
+#ifndef PR_PAC_APGAKEY
+#define PR_PAC_APGAKEY (1UL << 4)
+#endif
+
+#ifndef PR_TAGGED_ADDR_ENABLE
+#define PR_TAGGED_ADDR_ENABLE (1UL << 0)
+#endif
+
+#define DESCRIBE_FLAG(flag) \
+  if (value & flag) {       \
+    desc += ", ";           \
+    desc += #flag;          \
+    value &= ~flag;         \
+  }
+
+static std::string describe_end(long value, std::string& desc) {
+  if (value) {
+    desc += StringPrintf(", unknown 0x%lx", value);
+  }
+  return desc.empty() ? "" : " (" + desc.substr(2) + ")";
+}
+
+std::string describe_tagged_addr_ctrl(long value) {
+  std::string desc;
+  DESCRIBE_FLAG(PR_TAGGED_ADDR_ENABLE);
+  DESCRIBE_FLAG(PR_MTE_TCF_SYNC);
+  DESCRIBE_FLAG(PR_MTE_TCF_ASYNC);
+  if (value & PR_MTE_TAG_MASK) {
+    desc += StringPrintf(", mask 0x%04lx", (value & PR_MTE_TAG_MASK) >> PR_MTE_TAG_SHIFT);
+    value &= ~PR_MTE_TAG_MASK;
+  }
+  return describe_end(value, desc);
+}
+
+std::string describe_pac_enabled_keys(long value) {
+  std::string desc;
+  DESCRIBE_FLAG(PR_PAC_APIAKEY);
+  DESCRIBE_FLAG(PR_PAC_APIBKEY);
+  DESCRIBE_FLAG(PR_PAC_APDAKEY);
+  DESCRIBE_FLAG(PR_PAC_APDBKEY);
+  DESCRIBE_FLAG(PR_PAC_APGAKEY);
+  return describe_end(value, desc);
+}
diff --git a/debuggerd/pbtombstone.cpp b/debuggerd/pbtombstone.cpp
index 7527e31..dcb7c6c 100644
--- a/debuggerd/pbtombstone.cpp
+++ b/debuggerd/pbtombstone.cpp
@@ -20,7 +20,7 @@
 #include <unistd.h>
 
 #include <android-base/unique_fd.h>
-#include <libdebuggerd/tombstone.h>
+#include <libdebuggerd/tombstone_proto_to_text.h>
 
 #include "tombstone.pb.h"
 
diff --git a/debuggerd/proto/Android.bp b/debuggerd/proto/Android.bp
index 7b9e780..70deb3c 100644
--- a/debuggerd/proto/Android.bp
+++ b/debuggerd/proto/Android.bp
@@ -38,6 +38,7 @@
     ramdisk_available: true,
     recovery_available: true,
     vendor_ramdisk_available: true,
+    host_supported: true,
 }
 
 java_library_static {
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/fastboot/Android.bp b/fastboot/Android.bp
index bfe0768..b61fbd4 100644
--- a/fastboot/Android.bp
+++ b/fastboot/Android.bp
@@ -430,6 +430,7 @@
     ],
     data: [
         ":fastboot_test_dtb",
+        ":fastboot_test_dtb_replace",
         ":fastboot_test_bootconfig",
         ":fastboot_test_vendor_ramdisk_none",
         ":fastboot_test_vendor_ramdisk_platform",
diff --git a/fastboot/fastboot.cpp b/fastboot/fastboot.cpp
index 6b9e493..156dc3b 100644
--- a/fastboot/fastboot.cpp
+++ b/fastboot/fastboot.cpp
@@ -552,6 +552,12 @@
             "                            Secondary images may be flashed to inactive slot.\n"
             " flash PARTITION [FILENAME] Flash given partition, using the image from\n"
             "                            $ANDROID_PRODUCT_OUT if no filename is given.\n"
+            " flash vendor_boot:RAMDISK [FILENAME]\n"
+            "                            Flash vendor_boot ramdisk, fetching the existing\n"
+            "                            vendor_boot image and repackaging it with the new\n"
+            "                            ramdisk.\n"
+            " --dtb DTB                  If set with flash vendor_boot:RAMDISK, then\n"
+            "                            update the vendor_boot image with provided DTB.\n"
             "\n"
             "basics:\n"
             " devices [-l]               List devices in bootloader (-l: with device paths).\n"
@@ -1020,6 +1026,8 @@
 }
 
 int64_t get_sparse_limit(int64_t size, const FlashingPlan* fp) {
+    if (!fp) return 0;
+
     int64_t limit = int64_t(fp->sparse_limit);
     if (limit == 0) {
         // Unlimited, so see what the target device's limit is.
@@ -1465,6 +1473,7 @@
 static std::string repack_ramdisk(const char* pname, struct fastboot_buffer* buf,
                                   fastboot::IFastBootDriver* fb) {
     std::string_view pname_sv{pname};
+    struct fastboot_buffer dtb_buf = {.sz = 0, .fd = unique_fd(-1)};
 
     if (!android::base::StartsWith(pname_sv, "vendor_boot:") &&
         !android::base::StartsWith(pname_sv, "vendor_boot_a:") &&
@@ -1480,10 +1489,25 @@
     std::string partition(pname_sv.substr(0, pname_sv.find(':')));
     std::string ramdisk(pname_sv.substr(pname_sv.find(':') + 1));
 
+    if (!g_dtb_path.empty()) {
+        if (!load_buf(g_dtb_path.c_str(), &dtb_buf, nullptr)) {
+            die("cannot load '%s': %s", g_dtb_path.c_str(), strerror(errno));
+        }
+
+        if (dtb_buf.type != FB_BUFFER_FD) {
+            die("Flashing sparse vendor ramdisk image with dtb is not supported.");
+        }
+        if (dtb_buf.sz <= 0) {
+            die("repack_ramdisk() sees invalid dtb size: %" PRId64, buf->sz);
+        }
+        verbose("Updating DTB with %s", pname_sv.data());
+    }
+
     unique_fd vendor_boot(make_temporary_fd("vendor boot repack"));
     uint64_t vendor_boot_size = fetch_partition(partition, vendor_boot, fb);
     auto repack_res = replace_vendor_ramdisk(vendor_boot, vendor_boot_size, ramdisk, buf->fd,
-                                             static_cast<uint64_t>(buf->sz));
+                                             static_cast<uint64_t>(buf->sz), dtb_buf.fd,
+                                             static_cast<uint64_t>(dtb_buf.sz));
     if (!repack_res.ok()) {
         die("%s", repack_res.error().message().c_str());
     }
diff --git a/fastboot/fuzzer/fastboot_fuzzer.cpp b/fastboot/fuzzer/fastboot_fuzzer.cpp
index 60940fe..4594a8a 100644
--- a/fastboot/fuzzer/fastboot_fuzzer.cpp
+++ b/fastboot/fuzzer/fastboot_fuzzer.cpp
@@ -15,6 +15,7 @@
  *
  */
 #include <android-base/file.h>
+#include <android-base/unique_fd.h>
 #include "fastboot.h"
 #include "socket.h"
 #include "socket_mock_fuzz.h"
@@ -25,6 +26,7 @@
 #include <fuzzer/FuzzedDataProvider.h>
 
 using namespace std;
+using android::base::unique_fd;
 
 const size_t kYearMin = 2000;
 const size_t kYearMax = 2127;
@@ -255,7 +257,7 @@
     uint64_t ramdisk_size =
             fdp_->ConsumeBool() ? content_ramdisk_fd.size() : fdp_->ConsumeIntegral<uint64_t>();
     (void)replace_vendor_ramdisk(vendor_boot_fd, vendor_boot_size, ramdisk_name, ramdisk_fd,
-                                 ramdisk_size);
+                                 ramdisk_size, unique_fd(-1), 0);
     close(vendor_boot_fd);
     close(ramdisk_fd);
 }
diff --git a/fastboot/testdata/Android.bp b/fastboot/testdata/Android.bp
index a490fe2..47bf095 100644
--- a/fastboot/testdata/Android.bp
+++ b/fastboot/testdata/Android.bp
@@ -40,6 +40,14 @@
     cmd: "$(location fastboot_gen_rand) --seed dtb --length 1024 > $(out)",
 }
 
+// Fake dtb image for replacement.
+genrule {
+    name: "fastboot_test_dtb_replace",
+    defaults: ["fastboot_test_data_gen_defaults"],
+    out: ["dtb_replace.img"],
+    cmd: "$(location fastboot_gen_rand) --seed dtb --length 2048 > $(out)",
+}
+
 // Fake bootconfig image.
 genrule {
     name: "fastboot_test_bootconfig",
diff --git a/fastboot/vendor_boot_img_utils.cpp b/fastboot/vendor_boot_img_utils.cpp
index 9f05253..da547f1 100644
--- a/fastboot/vendor_boot_img_utils.cpp
+++ b/fastboot/vendor_boot_img_utils.cpp
@@ -209,7 +209,8 @@
 
 // Replace the vendor ramdisk as a whole.
 [[nodiscard]] Result<std::string> replace_default_vendor_ramdisk(const std::string& vendor_boot,
-                                                                 const std::string& new_ramdisk) {
+                                                                 const std::string& new_ramdisk,
+                                                                 const std::string& new_dtb) {
     if (auto res = check_vendor_boot_hdr(vendor_boot, 3); !res.ok()) return res.error();
     auto hdr = reinterpret_cast<const vendor_boot_img_hdr_v3*>(vendor_boot.data());
     auto hdr_size = get_vendor_boot_header_size(hdr);
@@ -244,8 +245,19 @@
         return res.error();
     if (auto res = updater.CheckOffset(o + p, o + new_p); !res.ok()) return res.error();
 
-    // Copy DTB (Q bytes).
-    if (auto res = updater.Copy(q); !res.ok()) return res.error();
+    // Copy DTB (Q bytes). Replace if a new one was provided.
+    new_hdr->dtb_size = !new_dtb.empty() ? new_dtb.size() : hdr->dtb_size;
+    const uint32_t new_q = round_up(new_hdr->dtb_size, new_hdr->page_size);
+    if (new_dtb.empty()) {
+        if (auto res = updater.Copy(q); !res.ok()) return res.error();
+    } else {
+        if (auto res = updater.Replace(hdr->dtb_size, new_dtb); !res.ok()) return res.error();
+        if (auto res = updater.Skip(q - hdr->dtb_size, new_q - new_hdr->dtb_size); !res.ok())
+            return res.error();
+    }
+    if (auto res = updater.CheckOffset(o + p + q, o + new_p + new_q); !res.ok()) {
+        return res.error();
+    }
 
     if (new_hdr->header_version >= 4) {
         auto hdr_v4 = static_cast<const vendor_boot_img_hdr_v4*>(hdr);
@@ -256,7 +268,7 @@
         auto new_hdr_v4 = static_cast<const vendor_boot_img_hdr_v4*>(new_hdr);
         auto new_r = round_up(new_hdr_v4->vendor_ramdisk_table_size, new_hdr->page_size);
         if (auto res = updater.Skip(r, new_r); !res.ok()) return res.error();
-        if (auto res = updater.CheckOffset(o + p + q + r, o + new_p + q + new_r); !res.ok())
+        if (auto res = updater.CheckOffset(o + p + q + r, o + new_p + new_q + new_r); !res.ok())
             return res.error();
 
         // Replace table with single entry representing the full ramdisk.
@@ -303,7 +315,8 @@
 // replace it with the content of |new_ramdisk|.
 [[nodiscard]] Result<std::string> replace_vendor_ramdisk_fragment(const std::string& ramdisk_name,
                                                                   const std::string& vendor_boot,
-                                                                  const std::string& new_ramdisk) {
+                                                                  const std::string& new_ramdisk,
+                                                                  const std::string& new_dtb) {
     if (auto res = check_vendor_boot_hdr(vendor_boot, 4); !res.ok()) return res.error();
     auto hdr = reinterpret_cast<const vendor_boot_img_hdr_v4*>(vendor_boot.data());
     auto hdr_size = get_vendor_boot_header_size(hdr);
@@ -368,8 +381,19 @@
         return res.error();
     if (auto res = updater.CheckOffset(o + p, o + new_p); !res.ok()) return res.error();
 
-    // Copy DTB (Q bytes).
-    if (auto res = updater.Copy(q); !res.ok()) return res.error();
+    // Copy DTB (Q bytes). Replace if a new one was provided.
+    new_hdr->dtb_size = !new_dtb.empty() ? new_dtb.size() : hdr->dtb_size;
+    const uint32_t new_q = round_up(new_hdr->dtb_size, new_hdr->page_size);
+    if (new_dtb.empty()) {
+        if (auto res = updater.Copy(q); !res.ok()) return res.error();
+    } else {
+        if (auto res = updater.Replace(hdr->dtb_size, new_dtb); !res.ok()) return res.error();
+        if (auto res = updater.Skip(q - hdr->dtb_size, new_q - new_hdr->dtb_size); !res.ok())
+            return res.error();
+    }
+    if (auto res = updater.CheckOffset(o + p + q, o + new_p + new_q); !res.ok()) {
+        return res.error();
+    }
 
     // Copy table, but with corresponding entries modified, including:
     // - ramdisk_size of the entry replaced
@@ -392,7 +416,7 @@
                                             hdr->vendor_ramdisk_table_entry_size);
         !res.ok())
         return res.error();
-    if (auto res = updater.CheckOffset(o + p + q + r, o + new_p + q + r); !res.ok())
+    if (auto res = updater.CheckOffset(o + p + q + r, o + new_p + new_q + r); !res.ok())
         return res.error();
 
     // Copy bootconfig (S bytes).
@@ -404,11 +428,11 @@
 
 }  // namespace
 
-[[nodiscard]] Result<void> replace_vendor_ramdisk(android::base::borrowed_fd vendor_boot_fd,
-                                                  uint64_t vendor_boot_size,
-                                                  const std::string& ramdisk_name,
-                                                  android::base::borrowed_fd new_ramdisk_fd,
-                                                  uint64_t new_ramdisk_size) {
+[[nodiscard]] Result<void> replace_vendor_ramdisk(
+        android::base::borrowed_fd vendor_boot_fd, uint64_t vendor_boot_size,
+        const std::string& ramdisk_name, android::base::borrowed_fd new_ramdisk_fd,
+        uint64_t new_ramdisk_size, android::base::borrowed_fd new_dtb_fd, uint64_t new_dtb_size) {
+    Result<std::string> new_dtb = {""};
     if (new_ramdisk_size > std::numeric_limits<uint32_t>::max()) {
         return Errorf("New vendor ramdisk is too big");
     }
@@ -417,12 +441,17 @@
     if (!vendor_boot.ok()) return vendor_boot.error();
     auto new_ramdisk = load_file(new_ramdisk_fd, new_ramdisk_size, "new vendor ramdisk");
     if (!new_ramdisk.ok()) return new_ramdisk.error();
+    if (new_dtb_size > 0 && new_dtb_fd >= 0) {
+        new_dtb = load_file(new_dtb_fd, new_dtb_size, "new dtb");
+        if (!new_dtb.ok()) return new_dtb.error();
+    }
 
     Result<std::string> new_vendor_boot;
     if (ramdisk_name == "default") {
-        new_vendor_boot = replace_default_vendor_ramdisk(*vendor_boot, *new_ramdisk);
+        new_vendor_boot = replace_default_vendor_ramdisk(*vendor_boot, *new_ramdisk, *new_dtb);
     } else {
-        new_vendor_boot = replace_vendor_ramdisk_fragment(ramdisk_name, *vendor_boot, *new_ramdisk);
+        new_vendor_boot =
+                replace_vendor_ramdisk_fragment(ramdisk_name, *vendor_boot, *new_ramdisk, *new_dtb);
     }
     if (!new_vendor_boot.ok()) return new_vendor_boot.error();
     if (auto res = store_file(vendor_boot_fd, *new_vendor_boot, "new vendor boot image"); !res.ok())
diff --git a/fastboot/vendor_boot_img_utils.h b/fastboot/vendor_boot_img_utils.h
index 0b702bc..0ca78da 100644
--- a/fastboot/vendor_boot_img_utils.h
+++ b/fastboot/vendor_boot_img_utils.h
@@ -31,4 +31,4 @@
 [[nodiscard]] android::base::Result<void> replace_vendor_ramdisk(
         android::base::borrowed_fd vendor_boot_fd, uint64_t vendor_boot_size,
         const std::string& ramdisk_name, android::base::borrowed_fd new_ramdisk_fd,
-        uint64_t new_ramdisk_size);
+        uint64_t new_ramdisk_size, android::base::borrowed_fd new_dtb_fd, uint64_t new_dtb_size);
diff --git a/fastboot/vendor_boot_img_utils_test.cpp b/fastboot/vendor_boot_img_utils_test.cpp
index 8107270..841e532 100644
--- a/fastboot/vendor_boot_img_utils_test.cpp
+++ b/fastboot/vendor_boot_img_utils_test.cpp
@@ -241,6 +241,7 @@
 
 struct RepackVendorBootImgTestParam {
     std::string vendor_boot_file_name;
+    std::string dtb_file_name;
     uint32_t expected_header_version;
     friend std::ostream& operator<<(std::ostream& os, const RepackVendorBootImgTestParam& param) {
         return os << param.vendor_boot_file_name;
@@ -252,22 +253,50 @@
     virtual void SetUp() {
         vboot = std::make_unique<ReadWriteTestFileHandle>(GetParam().vendor_boot_file_name);
         ASSERT_RESULT_OK(vboot->Open());
+
+        if (!GetParam().dtb_file_name.empty()) {
+            dtb_replacement = std::make_unique<ReadOnlyTestFileHandle>(GetParam().dtb_file_name);
+            ASSERT_RESULT_OK(dtb_replacement->Open());
+        }
     }
     std::unique_ptr<TestFileHandle> vboot;
+    std::unique_ptr<TestFileHandle> dtb_replacement;
 };
 
 TEST_P(RepackVendorBootImgTest, InvalidSize) {
-    EXPECT_ERROR(replace_vendor_ramdisk(vboot->fd(), vboot->size() + 1, "default",
-                                        env->replace->fd(), env->replace->size()),
-                 HasSubstr("Size of vendor boot does not match"));
-    EXPECT_ERROR(replace_vendor_ramdisk(vboot->fd(), vboot->size(), "default", env->replace->fd(),
-                                        env->replace->size() + 1),
-                 HasSubstr("Size of new vendor ramdisk does not match"));
+    EXPECT_ERROR(
+            replace_vendor_ramdisk(vboot->fd(), vboot->size() + 1, "default", env->replace->fd(),
+                                   env->replace->size(),
+                                   !GetParam().dtb_file_name.empty() ? dtb_replacement->fd()
+                                                                     : android::base::unique_fd(-1),
+                                   !GetParam().dtb_file_name.empty() ? dtb_replacement->size() : 0),
+            HasSubstr("Size of vendor boot does not match"));
+    EXPECT_ERROR(
+            replace_vendor_ramdisk(vboot->fd(), vboot->size(), "default", env->replace->fd(),
+                                   env->replace->size() + 1,
+                                   !GetParam().dtb_file_name.empty() ? dtb_replacement->fd()
+                                                                     : android::base::unique_fd(-1),
+                                   !GetParam().dtb_file_name.empty() ? dtb_replacement->size() : 0),
+            HasSubstr("Size of new vendor ramdisk does not match"));
+    if (!GetParam().dtb_file_name.empty()) {
+        EXPECT_ERROR(replace_vendor_ramdisk(vboot->fd(), vboot->size(), "default",
+                                            env->replace->fd(), env->replace->size(),
+                                            dtb_replacement->fd(), dtb_replacement->size() + 1),
+                     HasSubstr("Size of new dtb does not match"));
+    }
+    EXPECT_ERROR(
+            replace_vendor_ramdisk(
+                    vboot->fd(), vboot->size(), "default", env->replace->fd(), env->replace->size(),
+                    android::base::unique_fd(std::numeric_limits<int32_t>::max()), 1),
+            HasSubstr("Can't seek to the beginning of new dtb image"));
 }
 
 TEST_P(RepackVendorBootImgTest, ReplaceUnknown) {
-    auto res = replace_vendor_ramdisk(vboot->fd(), vboot->size(), "unknown", env->replace->fd(),
-                                      env->replace->size());
+    auto res = replace_vendor_ramdisk(
+            vboot->fd(), vboot->size(), "unknown", env->replace->fd(), env->replace->size(),
+            !GetParam().dtb_file_name.empty() ? dtb_replacement->fd()
+                                              : android::base::unique_fd(-1),
+            !GetParam().dtb_file_name.empty() ? dtb_replacement->size() : 0);
     if (GetParam().expected_header_version == 3) {
         EXPECT_ERROR(res, Eq("Require vendor boot header V4 but is V3"));
     } else if (GetParam().expected_header_version == 4) {
@@ -279,8 +308,11 @@
     auto old_content = vboot->Read();
     ASSERT_RESULT_OK(old_content);
 
-    ASSERT_RESULT_OK(replace_vendor_ramdisk(vboot->fd(), vboot->size(), "default",
-                                            env->replace->fd(), env->replace->size()));
+    ASSERT_RESULT_OK(replace_vendor_ramdisk(
+            vboot->fd(), vboot->size(), "default", env->replace->fd(), env->replace->size(),
+            !GetParam().dtb_file_name.empty() ? dtb_replacement->fd()
+                                              : android::base::unique_fd(-1),
+            !GetParam().dtb_file_name.empty() ? dtb_replacement->size() : 0));
     EXPECT_RESULT(vboot->fsize(), vboot->size()) << "File size should not change after repack";
 
     auto new_content_res = vboot->Read();
@@ -291,14 +323,23 @@
     ASSERT_EQ(0, memcmp(VENDOR_BOOT_MAGIC, hdr->magic, VENDOR_BOOT_MAGIC_SIZE));
     ASSERT_EQ(GetParam().expected_header_version, hdr->header_version);
     EXPECT_EQ(hdr->vendor_ramdisk_size, env->replace->size());
-    EXPECT_EQ(hdr->dtb_size, env->dtb->size());
+    if (GetParam().dtb_file_name.empty()) {
+        EXPECT_EQ(hdr->dtb_size, env->dtb->size());
+    } else {
+        EXPECT_EQ(hdr->dtb_size, dtb_replacement->size());
+    }
 
     auto o = round_up(sizeof(vendor_boot_img_hdr_v3), hdr->page_size);
     auto p = round_up(hdr->vendor_ramdisk_size, hdr->page_size);
     auto q = round_up(hdr->dtb_size, hdr->page_size);
 
     EXPECT_THAT(new_content.substr(o, p), IsPadded(env->replace_content));
-    EXPECT_THAT(new_content.substr(o + p, q), IsPadded(env->dtb_content));
+    if (GetParam().dtb_file_name.empty()) {
+        EXPECT_THAT(new_content.substr(o + p, q), IsPadded(env->dtb_content));
+    } else {
+        auto dtb_content_res = dtb_replacement->Read();
+        EXPECT_THAT(new_content.substr(o + p, q), IsPadded(*dtb_content_res));
+    }
 
     if (hdr->header_version < 4) return;
 
@@ -321,11 +362,17 @@
 
 INSTANTIATE_TEST_SUITE_P(
         RepackVendorBootImgTest, RepackVendorBootImgTest,
-        ::testing::Values(RepackVendorBootImgTestParam{"vendor_boot_v3.img", 3},
-                          RepackVendorBootImgTestParam{"vendor_boot_v4_with_frag.img", 4},
-                          RepackVendorBootImgTestParam{"vendor_boot_v4_without_frag.img", 4}),
+        ::testing::Values(RepackVendorBootImgTestParam{"vendor_boot_v3.img", "", 3},
+                          RepackVendorBootImgTestParam{"vendor_boot_v4_with_frag.img", "", 4},
+                          RepackVendorBootImgTestParam{"vendor_boot_v4_without_frag.img", "", 4},
+                          RepackVendorBootImgTestParam{"vendor_boot_v4_with_frag.img",
+                                                       "dtb_replace.img", 4},
+                          RepackVendorBootImgTestParam{"vendor_boot_v4_without_frag.img",
+                                                       "dtb_replace.img", 4}),
         [](const auto& info) {
-            return android::base::StringReplace(info.param.vendor_boot_file_name, ".", "_", false);
+            std::string test_name =
+                    android::base::StringReplace(info.param.vendor_boot_file_name, ".", "_", false);
+            return test_name + (!info.param.dtb_file_name.empty() ? "_replace_dtb" : "");
         });
 
 std::string_view GetRamdiskName(const vendor_ramdisk_table_entry_v4* entry) {
@@ -368,7 +415,8 @@
     ASSERT_RESULT_OK(old_content);
 
     ASSERT_RESULT_OK(replace_vendor_ramdisk(vboot->fd(), vboot->size(), replace_ramdisk_name,
-                                            env->replace->fd(), env->replace->size()));
+                                            env->replace->fd(), env->replace->size(),
+                                            android::base::unique_fd(-1), 0));
     EXPECT_RESULT(vboot->fsize(), vboot->size()) << "File size should not change after repack";
 
     auto new_content_res = vboot->Read();
diff --git a/fs_mgr/fs_mgr.cpp b/fs_mgr/fs_mgr.cpp
index fbd990b..9f52f44 100644
--- a/fs_mgr/fs_mgr.cpp
+++ b/fs_mgr/fs_mgr.cpp
@@ -1603,7 +1603,8 @@
                                    attempted_entry.fs_type,
                                    attempted_entry.fs_mgr_flags.is_zoned ? "true" : "false",
                                    std::to_string(attempted_entry.length),
-                                   android::base::Join(attempted_entry.user_devices, ' ')},
+                                   android::base::Join(attempted_entry.user_devices, ' '),
+                                   android::base::Join(attempted_entry.device_aliased, ' ')},
                                   nullptr)) {
                         LERROR << "Encryption failed";
                         set_type_property(encryptable);
@@ -1655,7 +1656,8 @@
                                formattable_entry->fs_type,
                                formattable_entry->fs_mgr_flags.is_zoned ? "true" : "false",
                                std::to_string(formattable_entry->length),
-                               android::base::Join(formattable_entry->user_devices, ' ')},
+                               android::base::Join(formattable_entry->user_devices, ' '),
+                               android::base::Join(formattable_entry->device_aliased, ' ')},
                               nullptr)) {
                     LERROR << "Encryption failed";
                 } else {
@@ -2213,11 +2215,11 @@
 
 #if ALLOW_ADBD_DISABLE_VERITY == 0
     // Allowlist the mount point if user build.
-    static const std::vector<const std::string> kAllowedPaths = {
+    static const std::vector<std::string> kAllowedPaths = {
             "/odm",         "/odm_dlkm",   "/oem",    "/product",
             "/system_dlkm", "/system_ext", "/vendor", "/vendor_dlkm",
     };
-    static const std::vector<const std::string> kAllowedPrefixes = {
+    static const std::vector<std::string> kAllowedPrefixes = {
             "/mnt/product/",
             "/mnt/vendor/",
     };
@@ -2314,6 +2316,14 @@
     return context;
 }
 
+int fs_mgr_f2fs_ideal_block_size() {
+#if defined(__i386__) || defined(__x86_64__)
+    return 4096;
+#else
+    return getpagesize();
+#endif
+}
+
 namespace android {
 namespace fs_mgr {
 
diff --git a/fs_mgr/fs_mgr_format.cpp b/fs_mgr/fs_mgr_format.cpp
index 0dde1d3..57e35a2 100644
--- a/fs_mgr/fs_mgr_format.cpp
+++ b/fs_mgr/fs_mgr_format.cpp
@@ -32,6 +32,7 @@
 #include <selinux/android.h>
 #include <selinux/label.h>
 #include <selinux/selinux.h>
+#include <filesystem>
 #include <string>
 
 #include "fs_mgr_priv.h"
@@ -126,7 +127,8 @@
 
 static int format_f2fs(const std::string& fs_blkdev, uint64_t dev_sz, bool needs_projid,
                        bool needs_casefold, bool fs_compress, bool is_zoned,
-                       const std::vector<std::string>& user_devices) {
+                       const std::vector<std::string>& user_devices,
+                       const std::vector<int>& device_aliased) {
     if (!dev_sz) {
         int rc = get_dev_sz(fs_blkdev, &dev_sz);
         if (rc) {
@@ -164,9 +166,15 @@
     if (is_zoned) {
         args.push_back("-m");
     }
-    for (auto& device : user_devices) {
+    for (size_t i = 0; i < user_devices.size(); i++) {
+        std::string device_name = user_devices[i];
+
         args.push_back("-c");
-        args.push_back(device.c_str());
+        if (device_aliased[i]) {
+            std::filesystem::path path = device_name;
+            device_name += "@" + path.filename().string();
+        }
+        args.push_back(device_name.c_str());
     }
 
     if (user_devices.empty()) {
@@ -191,7 +199,7 @@
     if (entry.fs_type == "f2fs") {
         return format_f2fs(entry.blk_device, entry.length, needs_projid, needs_casefold,
                            entry.fs_mgr_flags.fs_compress, entry.fs_mgr_flags.is_zoned,
-                           entry.user_devices);
+                           entry.user_devices, entry.device_aliased);
     } else if (entry.fs_type == "ext4") {
         return format_ext4(entry.blk_device, entry.mount_point, needs_projid,
                            entry.fs_mgr_flags.ext_meta_csum);
diff --git a/fs_mgr/fs_mgr_overlayfs_control.cpp b/fs_mgr/fs_mgr_overlayfs_control.cpp
index 08ad80c..489b32e 100644
--- a/fs_mgr/fs_mgr_overlayfs_control.cpp
+++ b/fs_mgr/fs_mgr_overlayfs_control.cpp
@@ -387,10 +387,8 @@
     auto command = ""s;
     if (!access(kMkF2fs, X_OK) && fs_mgr_filesystem_available("f2fs")) {
         fs_type = "f2fs";
-        command = kMkF2fs + " -w "s;
-        command += std::to_string(getpagesize());
         command = kMkF2fs + " -b "s;
-        command += std::to_string(getpagesize());
+        command += std::to_string(fs_mgr_f2fs_ideal_block_size());
         command += " -f -d1 -l" + android::base::Basename(kScratchMountPoint);
     } else if (!access(kMkExt4, X_OK) && fs_mgr_filesystem_available("ext4")) {
         fs_type = "ext4";
diff --git a/fs_mgr/include/fs_mgr.h b/fs_mgr/include/fs_mgr.h
index 9cfa93f..7969087 100644
--- a/fs_mgr/include/fs_mgr.h
+++ b/fs_mgr/include/fs_mgr.h
@@ -137,3 +137,6 @@
 // File name used to track if encryption was interrupted, leading to a known bad fs state
 std::string fs_mgr_metadata_encryption_in_progress_file_name(
         const android::fs_mgr::FstabEntry& entry);
+
+// Returns the ideal block size for make_f2fs. Returns -1 on failure.
+int fs_mgr_f2fs_ideal_block_size();
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/libfiemap/fiemap_writer_test.cpp b/fs_mgr/libfiemap/fiemap_writer_test.cpp
index c37329c..115f53e 100644
--- a/fs_mgr/libfiemap/fiemap_writer_test.cpp
+++ b/fs_mgr/libfiemap/fiemap_writer_test.cpp
@@ -66,7 +66,11 @@
         testfile = gTestDir + "/"s + tinfo->name();
     }
 
-    void TearDown() override { unlink(testfile.c_str()); }
+    void TearDown() override {
+        truncate(testfile.c_str(), 0);
+        unlink(testfile.c_str());
+        sync();
+    }
 
     // name of the file we use for testing
     std::string testfile;
diff --git a/fs_mgr/libfiemap/split_fiemap_writer.cpp b/fs_mgr/libfiemap/split_fiemap_writer.cpp
index 0df6125..1f32d2f 100644
--- a/fs_mgr/libfiemap/split_fiemap_writer.cpp
+++ b/fs_mgr/libfiemap/split_fiemap_writer.cpp
@@ -196,10 +196,13 @@
             if (access(file.c_str(), F_OK) != 0 && (errno == ENOENT || errno == ENAMETOOLONG)) {
                 continue;
             }
+            truncate(file.c_str(), 0);
             ok &= android::base::RemoveFileIfExists(file, message);
         }
     }
+    truncate(file_path.c_str(), 0);
     ok &= android::base::RemoveFileIfExists(file_path, message);
+    sync();
     return ok;
 }
 
diff --git a/fs_mgr/libfstab/fstab.cpp b/fs_mgr/libfstab/fstab.cpp
index d344b2d..6e4cae1 100644
--- a/fs_mgr/libfstab/fstab.cpp
+++ b/fs_mgr/libfstab/fstab.cpp
@@ -173,6 +173,7 @@
         entry->fs_mgr_flags.is_zoned = true;
     }
     entry->user_devices.push_back(param[1]);
+    entry->device_aliased.push_back(param[0] == "exp_alias" ? 1 : 0);
 }
 
 bool ParseFsMgrFlags(const std::string& flags, FstabEntry* entry) {
diff --git a/fs_mgr/libfstab/include/fstab/fstab.h b/fs_mgr/libfstab/include/fstab/fstab.h
index 21fe017..070dd91 100644
--- a/fs_mgr/libfstab/include/fstab/fstab.h
+++ b/fs_mgr/libfstab/include/fstab/fstab.h
@@ -33,6 +33,7 @@
 struct FstabEntry {
     std::string blk_device;
     std::vector<std::string> user_devices;
+    std::vector<int> device_aliased;
     std::string logical_partition_name;
     std::string mount_point;
     std::string fs_type;
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/liblp/super_layout_builder.cpp b/fs_mgr/liblp/super_layout_builder.cpp
index fd7416b..bff26ea 100644
--- a/fs_mgr/liblp/super_layout_builder.cpp
+++ b/fs_mgr/liblp/super_layout_builder.cpp
@@ -184,7 +184,7 @@
                 return {};
             }
 
-            size_t size = e.num_sectors * LP_SECTOR_SIZE;
+            uint64_t size = e.num_sectors * LP_SECTOR_SIZE;
             uint64_t super_offset = e.target_data * LP_SECTOR_SIZE;
             extents.emplace_back(super_offset, size, image_name, image_offset);
 
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/android/snapshot/snapshot.proto b/fs_mgr/libsnapshot/android/snapshot/snapshot.proto
index 62f9901..5fb71a3 100644
--- a/fs_mgr/libsnapshot/android/snapshot/snapshot.proto
+++ b/fs_mgr/libsnapshot/android/snapshot/snapshot.proto
@@ -233,6 +233,8 @@
     // Number of cow operations to be merged at once
     uint32 cow_op_merge_size = 13;
 
+    // Number of worker threads to serve I/O from dm-user
+    uint32 num_worker_threads = 14;
 }
 
 // Next: 10
diff --git a/fs_mgr/libsnapshot/include/libsnapshot/snapshot.h b/fs_mgr/libsnapshot/include/libsnapshot/snapshot.h
index 7ae55db..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;
@@ -838,6 +839,10 @@
 
     // Get value of maximum cow op merge size
     uint32_t GetUpdateCowOpMergeSize(LockedFile* lock);
+
+    // Get number of threads to perform post OTA boot verification
+    uint32_t GetUpdateWorkerCount(LockedFile* lock);
+
     // Wrapper around libdm, with diagnostics.
     bool DeleteDeviceIfExists(const std::string& name,
                               const std::chrono::milliseconds& timeout_ms = {});
diff --git a/fs_mgr/libsnapshot/scripts/apply-update.sh b/fs_mgr/libsnapshot/scripts/apply-update.sh
new file mode 100755
index 0000000..90b0119
--- /dev/null
+++ b/fs_mgr/libsnapshot/scripts/apply-update.sh
@@ -0,0 +1,77 @@
+#!/bin/bash
+
+# This is a debug script to quicky test end-to-end flow
+# of snapshot updates without going through update-engine.
+#
+# Usage:
+#
+#  To update both dynamic and static partitions:
+#
+# ./system/core/fs_mgr/libsnapshot/apply_update.sh [--update-static-partitions] [--wipe]
+#
+# --update-static-partitions: This will update bootloader and static A/B
+# partitions
+# --wipe: Allows data wipe as part of update flow
+#
+#  To update dynamic partitions only (this should be used when static
+#  partitions are present in both the slots):
+#
+#  ./system/core/fs_mgr/libsnapshot/apply_update.sh
+#
+#
+
+rm -f $OUT/*.patch
+
+# Compare images and create snapshot patches. Currently, this
+# just compares two identical images in $OUT. In general, any source
+# and target images could be passed to create snapshot patches. However,
+# care must be taken to ensure source images are already present on the device.
+#
+# create_snapshot is a host side binary. Build it with `m create_snapshot`
+create_snapshot --source=$OUT/system.img --target=$OUT/system.img &
+create_snapshot --source=$OUT/product.img --target=$OUT/product.img &
+create_snapshot --source=$OUT/vendor.img --target=$OUT/vendor.img &
+create_snapshot --source=$OUT/system_ext.img --target=$OUT/system_ext.img &
+create_snapshot --source=$OUT/vendor_dlkm.img --target=$OUT/vendor_dlkm.img &
+create_snapshot --source=$OUT/system_dlkm.img --target=$OUT/system_dlkm.img &
+
+echo "Waiting for snapshot patch creation"
+wait $(jobs -p)
+echo "Snapshot patch creation completed"
+
+mv *.patch $OUT/
+
+adb root
+adb wait-for-device
+adb shell mkdir -p /data/update/
+adb push $OUT/*.patch /data/update/
+
+if [[ "$2" == "--wipe" ]]; then
+  adb shell snapshotctl apply-update /data/update/ -w
+else
+  adb shell snapshotctl apply-update /data/update/
+fi
+
+# Check if the --update-static-partitions option is provided.
+# For quick developer workflow, there is no need to repeatedly
+# apply static partitions.
+if [[ "$1" == "--update-static-partitions" ]]; then
+  adb reboot bootloader
+  sleep 5
+  if [[ "$2" == "--wipe" ]]; then
+      fastboot -w
+  fi
+  fastboot flash bootloader $OUT/bootloader.img
+  sleep 1
+  fastboot reboot bootloader
+  sleep 1
+  fastboot flash radio $OUT/radio.img
+  sleep 1
+  fastboot reboot bootloader
+  sleep 1
+  fastboot flashall --exclude-dynamic-partitions --disable-super-optimization
+else
+  adb reboot
+fi
+
+echo "Update completed"
diff --git a/fs_mgr/libsnapshot/snapshot.cpp b/fs_mgr/libsnapshot/snapshot.cpp
index 6c3bedd..acabd67 100644
--- a/fs_mgr/libsnapshot/snapshot.cpp
+++ b/fs_mgr/libsnapshot/snapshot.cpp
@@ -1235,8 +1235,8 @@
                 wrong_phase = true;
                 break;
             default:
-                LOG(ERROR) << "Unknown merge status for \"" << snapshot << "\": "
-                           << "\"" << result.state << "\"";
+                LOG(ERROR) << "Unknown merge status for \"" << snapshot << "\": " << "\""
+                           << result.state << "\"";
                 if (failure_code == MergeFailureCode::Ok) {
                     failure_code = MergeFailureCode::UnexpectedMergeState;
                 }
@@ -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;
@@ -1725,6 +1746,10 @@
         if (cow_op_merge_size != 0) {
             snapuserd_argv->emplace_back("-cow_op_merge_size=" + std::to_string(cow_op_merge_size));
         }
+        uint32_t worker_count = GetUpdateWorkerCount(lock.get());
+        if (worker_count != 0) {
+            snapuserd_argv->emplace_back("-worker_count=" + std::to_string(worker_count));
+        }
     }
 
     size_t num_cows = 0;
@@ -2152,6 +2177,11 @@
     return update_status.cow_op_merge_size();
 }
 
+uint32_t SnapshotManager::GetUpdateWorkerCount(LockedFile* lock) {
+    SnapshotUpdateStatus update_status = ReadSnapshotUpdateStatus(lock);
+    return update_status.num_worker_threads();
+}
+
 bool SnapshotManager::MarkSnapuserdFromSystem() {
     auto path = GetSnapuserdFromSystemPath();
 
@@ -3140,6 +3170,7 @@
         status.set_legacy_snapuserd(old_status.legacy_snapuserd());
         status.set_o_direct(old_status.o_direct());
         status.set_cow_op_merge_size(old_status.cow_op_merge_size());
+        status.set_num_worker_threads(old_status.num_worker_threads());
     }
     return WriteSnapshotUpdateStatus(lock, status);
 }
@@ -3524,6 +3555,9 @@
         }
         status.set_cow_op_merge_size(
                 android::base::GetUintProperty<uint32_t>("ro.virtual_ab.cow_op_merge_size", 0));
+        status.set_num_worker_threads(
+                android::base::GetUintProperty<uint32_t>("ro.virtual_ab.num_worker_threads", 0));
+
     } else if (legacy_compression) {
         LOG(INFO) << "Virtual A/B using legacy snapuserd";
     } else {
@@ -3960,6 +3994,7 @@
     ss << "Using io_uring: " << update_status.io_uring_enabled() << std::endl;
     ss << "Using o_direct: " << update_status.o_direct() << std::endl;
     ss << "Cow op merge size (0 for uncapped): " << update_status.cow_op_merge_size() << std::endl;
+    ss << "Worker thread count: " << update_status.num_worker_threads() << std::endl;
     ss << "Using XOR compression: " << GetXorCompressionEnabledProperty() << std::endl;
     ss << "Current slot: " << device_->GetSlotSuffix() << std::endl;
     ss << "Boot indicator: booting from " << GetCurrentSlot() << " slot" << std::endl;
@@ -4576,8 +4611,7 @@
         }
     }
 
-    LOG(ERROR) << "Device-mapper device " << name << "(" << full_path << ")"
-               << " still in use."
+    LOG(ERROR) << "Device-mapper device " << name << "(" << full_path << ")" << " still in use."
                << "  Probably a file descriptor was leaked or held open, or a loop device is"
                << " attached.";
     return false;
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/snapshotctl.cpp b/fs_mgr/libsnapshot/snapshotctl.cpp
index 97a8cb2..46de991 100644
--- a/fs_mgr/libsnapshot/snapshotctl.cpp
+++ b/fs_mgr/libsnapshot/snapshotctl.cpp
@@ -105,7 +105,7 @@
     bool FinishSnapshotWrites();
     bool UnmapCowImagePath(std::string& name);
     bool DeleteSnapshots();
-    bool CleanupSnapshot() { return sm_->PrepareDeviceToBootWithoutSnapshot(); }
+    bool CleanupSnapshot();
     bool BeginUpdate();
     bool ApplyUpdate();
 
@@ -495,6 +495,11 @@
     return sm_->UnmapCowImage(name);
 }
 
+bool MapSnapshots::CleanupSnapshot() {
+    sm_ = SnapshotManager::New();
+    return sm_->PrepareDeviceToBootWithoutSnapshot();
+}
+
 bool MapSnapshots::DeleteSnapshots() {
     sm_ = SnapshotManager::New();
     lock_ = sm_->LockExclusive();
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/fs_mgr/libsnapshot/snapuserd/snapuserd_daemon.cpp b/fs_mgr/libsnapshot/snapuserd/snapuserd_daemon.cpp
index dd2dd56..32e16cc 100644
--- a/fs_mgr/libsnapshot/snapuserd/snapuserd_daemon.cpp
+++ b/fs_mgr/libsnapshot/snapuserd/snapuserd_daemon.cpp
@@ -31,6 +31,7 @@
 DEFINE_bool(io_uring, false, "If true, io_uring feature is enabled");
 DEFINE_bool(o_direct, false, "If true, enable direct reads on source device");
 DEFINE_int32(cow_op_merge_size, 0, "number of operations to be processed at once");
+DEFINE_int32(worker_count, 4, "number of worker threads used to serve I/O requests to dm-user");
 
 namespace android {
 namespace snapshot {
@@ -114,8 +115,9 @@
             LOG(ERROR) << "Malformed message, expected at least four sub-arguments.";
             return false;
         }
-        auto handler = user_server_.AddHandler(parts[0], parts[1], parts[2], parts[3],
-                                               FLAGS_o_direct, FLAGS_cow_op_merge_size);
+        auto handler =
+                user_server_.AddHandler(parts[0], parts[1], parts[2], parts[3], FLAGS_worker_count,
+                                        FLAGS_o_direct, FLAGS_cow_op_merge_size);
         if (!handler || !user_server_.StartHandler(parts[0])) {
             return false;
         }
diff --git a/fs_mgr/libsnapshot/snapuserd/user-space-merge/read_worker.cpp b/fs_mgr/libsnapshot/snapuserd/user-space-merge/read_worker.cpp
index ef311d4..33767d6 100644
--- a/fs_mgr/libsnapshot/snapuserd/user-space-merge/read_worker.cpp
+++ b/fs_mgr/libsnapshot/snapuserd/user-space-merge/read_worker.cpp
@@ -104,6 +104,8 @@
 }
 
 bool ReadWorker::ProcessXorOp(const CowOperation* cow_op, void* buffer) {
+    using WordType = std::conditional_t<sizeof(void*) == sizeof(uint64_t), uint64_t, uint32_t>;
+
     if (!ReadFromSourceDevice(cow_op, buffer)) {
         return false;
     }
@@ -120,9 +122,12 @@
         return false;
     }
 
-    auto xor_out = reinterpret_cast<uint8_t*>(buffer);
-    for (size_t i = 0; i < BLOCK_SZ; i++) {
-        xor_out[i] ^= xor_buffer_[i];
+    auto xor_in = reinterpret_cast<const WordType*>(xor_buffer_.data());
+    auto xor_out = reinterpret_cast<WordType*>(buffer);
+    auto num_words = BLOCK_SZ / sizeof(WordType);
+
+    for (auto i = 0; i < num_words; i++) {
+        xor_out[i] ^= xor_in[i];
     }
     return true;
 }
diff --git a/fs_mgr/libsnapshot/snapuserd/user-space-merge/snapuserd_readahead.cpp b/fs_mgr/libsnapshot/snapuserd/user-space-merge/snapuserd_readahead.cpp
index 6b1ed0c..9a1d441 100644
--- a/fs_mgr/libsnapshot/snapuserd/user-space-merge/snapuserd_readahead.cpp
+++ b/fs_mgr/libsnapshot/snapuserd/user-space-merge/snapuserd_readahead.cpp
@@ -458,6 +458,7 @@
 void ReadAhead::ProcessXorData(size_t& block_xor_index, size_t& xor_index,
                                std::vector<const CowOperation*>& xor_op_vec, void* buffer,
                                loff_t& buffer_offset) {
+    using WordType = std::conditional_t<sizeof(void*) == sizeof(uint64_t), uint64_t, uint32_t>;
     loff_t xor_buf_offset = 0;
 
     while (block_xor_index < blocks_.size()) {
@@ -470,13 +471,14 @@
             // Check if this block is an XOR op
             if (xor_op->new_block == new_block) {
                 // Pointer to the data read from base device
-                uint8_t* buffer = reinterpret_cast<uint8_t*>(bufptr);
+                auto buffer_words = reinterpret_cast<WordType*>(bufptr);
                 // Get the xor'ed data read from COW device
-                uint8_t* xor_data = reinterpret_cast<uint8_t*>((char*)bufsink_.GetPayloadBufPtr() +
-                                                               xor_buf_offset);
+                auto xor_data_words = reinterpret_cast<WordType*>(
+                        (char*)bufsink_.GetPayloadBufPtr() + xor_buf_offset);
+                auto num_words = BLOCK_SZ / sizeof(WordType);
 
-                for (size_t byte_offset = 0; byte_offset < BLOCK_SZ; byte_offset++) {
-                    buffer[byte_offset] ^= xor_data[byte_offset];
+                for (auto i = 0; i < num_words; i++) {
+                    buffer_words[i] ^= xor_data_words[i];
                 }
 
                 // Move to next XOR op
diff --git a/fs_mgr/libsnapshot/snapuserd/user-space-merge/snapuserd_server.cpp b/fs_mgr/libsnapshot/snapuserd/user-space-merge/snapuserd_server.cpp
index 013df35..3bb8a30 100644
--- a/fs_mgr/libsnapshot/snapuserd/user-space-merge/snapuserd_server.cpp
+++ b/fs_mgr/libsnapshot/snapuserd/user-space-merge/snapuserd_server.cpp
@@ -35,6 +35,7 @@
 #include <snapuserd/dm_user_block_server.h>
 #include <snapuserd/snapuserd_client.h>
 #include "snapuserd_server.h"
+#include "user-space-merge/snapuserd_core.h"
 
 namespace android {
 namespace snapshot {
@@ -125,7 +126,7 @@
             return Sendmsg(fd, "fail");
         }
 
-        auto handler = AddHandler(out[1], out[2], out[3], out[4]);
+        auto handler = AddHandler(out[1], out[2], out[3], out[4], std::nullopt);
         if (!handler) {
             return Sendmsg(fd, "fail");
         }
@@ -341,12 +342,11 @@
     SetTerminating();
 }
 
-std::shared_ptr<HandlerThread> UserSnapshotServer::AddHandler(const std::string& misc_name,
-                                                              const std::string& cow_device_path,
-                                                              const std::string& backing_device,
-                                                              const std::string& base_path_merge,
-                                                              const bool o_direct,
-                                                              uint32_t cow_op_merge_size) {
+std::shared_ptr<HandlerThread> UserSnapshotServer::AddHandler(
+        const std::string& misc_name, const std::string& cow_device_path,
+        const std::string& backing_device, const std::string& base_path_merge,
+        std::optional<uint32_t> num_worker_threads, const bool o_direct,
+        uint32_t cow_op_merge_size) {
     // We will need multiple worker threads only during
     // device boot after OTA. For all other purposes,
     // one thread is sufficient. We don't want to consume
@@ -355,7 +355,9 @@
     //
     // During boot up, we need multiple threads primarily for
     // update-verification.
-    int num_worker_threads = kNumWorkerThreads;
+    if (!num_worker_threads.has_value()) {
+        num_worker_threads = kNumWorkerThreads;
+    }
     if (is_socket_present_) {
         num_worker_threads = 1;
     }
@@ -368,7 +370,7 @@
     auto opener = block_server_factory_->CreateOpener(misc_name);
 
     return handlers_->AddHandler(misc_name, cow_device_path, backing_device, base_path_merge,
-                                 opener, num_worker_threads, io_uring_enabled_, o_direct,
+                                 opener, num_worker_threads.value(), io_uring_enabled_, o_direct,
                                  cow_op_merge_size);
 }
 
diff --git a/fs_mgr/libsnapshot/snapuserd/user-space-merge/snapuserd_server.h b/fs_mgr/libsnapshot/snapuserd/user-space-merge/snapuserd_server.h
index ceea36a..f002e8d 100644
--- a/fs_mgr/libsnapshot/snapuserd/user-space-merge/snapuserd_server.h
+++ b/fs_mgr/libsnapshot/snapuserd/user-space-merge/snapuserd_server.h
@@ -87,6 +87,7 @@
                                               const std::string& cow_device_path,
                                               const std::string& backing_device,
                                               const std::string& base_path_merge,
+                                              std::optional<uint32_t> num_worker_threads,
                                               bool o_direct = false,
                                               uint32_t cow_op_merge_size = 0);
     bool StartHandler(const std::string& misc_name);
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/apex_init_util.cpp b/init/apex_init_util.cpp
index e5a7fbc..809c805 100644
--- a/init/apex_init_util.cpp
+++ b/init/apex_init_util.cpp
@@ -101,14 +101,21 @@
     return apex_list;
 }
 
+static int GetCurrentSdk() {
+    bool is_preview = base::GetProperty("ro.build.version.codename", "") != "REL";
+    if (is_preview) {
+        return __ANDROID_API_FUTURE__;
+    }
+    return android::base::GetIntProperty("ro.build.version.sdk", __ANDROID_API_FUTURE__);
+}
+
 static Result<void> ParseRcScripts(const std::vector<std::string>& files) {
     if (files.empty()) {
         return {};
     }
     // APEXes can have versioned RC files. These should be filtered based on
     // SDK version.
-    int sdk = android::base::GetIntProperty("ro.build.version.sdk", INT_MAX);
-    if (sdk < 35) sdk = 35;  // aosp/main merges only into sdk=35+ (ie. __ANDROID_API_V__+)
+    static int sdk = GetCurrentSdk();
     auto filtered = FilterVersionedConfigs(files, sdk);
     if (filtered.empty()) {
         return {};
diff --git a/init/epoll.cpp b/init/epoll.cpp
index cd73a0c..719a532 100644
--- a/init/epoll.cpp
+++ b/init/epoll.cpp
@@ -47,8 +47,8 @@
 
     auto [it, inserted] = epoll_handlers_.emplace(
             fd, Info{
-                        .events = events,
                         .handler = std::move(handler),
+                        .events = events,
                 });
     if (!inserted) {
         return Error() << "Cannot specify two epoll handlers for a given FD";
diff --git a/init/first_stage_mount.cpp b/init/first_stage_mount.cpp
index ece430b..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)";
@@ -305,11 +313,6 @@
             return false;
         }
     }
-
-    if (IsArcvm() && !block_dev_init_.InitHvcDevice("hvc1")) {
-        return false;
-    }
-
     return true;
 }
 
@@ -883,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/selinux.cpp b/init/selinux.cpp
index 01af2b6..c2d9b8d 100644
--- a/init/selinux.cpp
+++ b/init/selinux.cpp
@@ -474,8 +474,6 @@
     RestoreconIfExists(SnapshotManager::GetGlobalRollbackIndicatorPath().c_str(), 0);
     RestoreconIfExists("/metadata/gsi",
                        SELINUX_ANDROID_RESTORECON_RECURSE | SELINUX_ANDROID_RESTORECON_SKIP_SEHASH);
-
-    RestoreconIfExists("/dev/hvc1", 0);
 }
 
 int SelinuxKlogCallback(int type, const char* fmt, ...) {
diff --git a/init/service_parser.cpp b/init/service_parser.cpp
index e6f3af6..ec3b176 100644
--- a/init/service_parser.cpp
+++ b/init/service_parser.cpp
@@ -538,12 +538,9 @@
 // when we migrate to cgroups v2 while these hardcoded paths stay the same.
 static std::optional<const std::string> ConvertTaskFileToProfile(const std::string& file) {
     static const std::map<const std::string, const std::string> map = {
-            {"/dev/stune/top-app/tasks", "MaxPerformance"},
-            {"/dev/stune/foreground/tasks", "HighPerformance"},
             {"/dev/cpuset/camera-daemon/tasks", "CameraServiceCapacity"},
             {"/dev/cpuset/foreground/tasks", "ProcessCapacityHigh"},
             {"/dev/cpuset/system-background/tasks", "ServiceCapacityLow"},
-            {"/dev/stune/nnapi-hal/tasks", "NNApiHALPerformance"},
             {"/dev/blkio/background/tasks", "LowIoPriority"},
     };
     auto iter = map.find(file);
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/init/util.h b/init/util.h
index 0565391..aa24123 100644
--- a/init/util.h
+++ b/init/util.h
@@ -18,7 +18,6 @@
 
 #include <sys/stat.h>
 #include <sys/types.h>
-#include <sys/unistd.h>
 
 #include <chrono>
 #include <functional>
@@ -109,10 +108,6 @@
 #endif
 }
 
-inline bool IsArcvm() {
-    return !access("/is_arcvm", F_OK);
-}
-
 bool Has32BitAbi();
 
 std::string GetApexNameFromFileName(const std::string& path);
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/libcutils/sched_policy_test.cpp b/libcutils/sched_policy_test.cpp
index 50bd6d0..2641743 100644
--- a/libcutils/sched_policy_test.cpp
+++ b/libcutils/sched_policy_test.cpp
@@ -67,13 +67,6 @@
 }
 
 TEST(SchedPolicy, set_sched_policy) {
-    if (!schedboost_enabled()) {
-        // schedboost_enabled() (i.e. CONFIG_CGROUP_SCHEDTUNE) is optional;
-        // it's only needed on devices using energy-aware scheduler.
-        GTEST_LOG_(INFO) << "skipping test that requires CONFIG_CGROUP_SCHEDTUNE";
-        return;
-    }
-
     ASSERT_EQ(0, set_sched_policy(0, SP_BACKGROUND));
     ASSERT_EQ(0, set_cpuset_policy(0, SP_BACKGROUND));
     AssertPolicy(SP_BACKGROUND);
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/include/processgroup/sched_policy.h b/libprocessgroup/include/processgroup/sched_policy.h
index 1b6ea66..92cd367 100644
--- a/libprocessgroup/include/processgroup/sched_policy.h
+++ b/libprocessgroup/include/processgroup/sched_policy.h
@@ -29,14 +29,6 @@
  */
 extern bool cpusets_enabled();
 
-/*
- * Check if Linux kernel enables SCHEDTUNE feature (only available in Android
- * common kernel or Linaro LSK, not in mainline Linux as of v4.9)
- *
- * Return value: 1 if Linux kernel CONFIG_CGROUP_SCHEDTUNE=y; 0 otherwise.
- */
-extern bool schedboost_enabled();
-
 /* Keep in sync with THREAD_GROUP_* in frameworks/base/core/java/android/os/Process.java */
 typedef enum {
     SP_DEFAULT = -1,
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..9522159 100644
--- a/libprocessgroup/processgroup.cpp
+++ b/libprocessgroup/processgroup.cpp
@@ -37,19 +37,18 @@
 #include <mutex>
 #include <set>
 #include <string>
+#include <string_view>
 #include <thread>
 
 #include <android-base/file.h>
 #include <android-base/logging.h>
 #include <android-base/properties.h>
 #include <android-base/stringprintf.h>
-#include <android-base/strings.h>
 #include <cutils/android_filesystem_config.h>
 #include <processgroup/processgroup.h>
 #include <task_profiles.h>
 
 using android::base::GetBoolProperty;
-using android::base::StartsWith;
 using android::base::StringPrintf;
 using android::base::WriteStringToFile;
 
@@ -255,7 +254,7 @@
                 continue;
             }
 
-            if (!StartsWith(dir->d_name, "pid_")) {
+            if (!std::string_view(dir->d_name).starts_with("pid_")) {
                 continue;
             }
 
@@ -296,7 +295,7 @@
                     continue;
                 }
 
-                if (!StartsWith(dir->d_name, "uid_")) {
+                if (!std::string_view(dir->d_name).starts_with("uid_")) {
                     continue;
                 }
 
@@ -662,10 +661,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 885971a..baa4546 100644
--- a/libprocessgroup/profiles/Android.bp
+++ b/libprocessgroup/profiles/Android.bp
@@ -13,17 +13,13 @@
 // limitations under the License.
 
 package {
+    default_team: "trendy_team_android_kernel",
     default_applicable_licenses: ["Android-Apache-2.0"],
 }
 
 prebuilt_etc {
     name: "cgroups.json",
     src: "cgroups.json",
-    required: [
-        "cgroups_28.json",
-        "cgroups_29.json",
-        "cgroups_30.json",
-    ],
 }
 
 prebuilt_etc {
@@ -34,49 +30,8 @@
 }
 
 prebuilt_etc {
-    name: "cgroups_28.json",
-    src: "cgroups_28.json",
-    sub_dir: "task_profiles",
-}
-
-prebuilt_etc {
-    name: "cgroups_29.json",
-    src: "cgroups_29.json",
-    sub_dir: "task_profiles",
-}
-
-prebuilt_etc {
-    name: "cgroups_30.json",
-    src: "cgroups_30.json",
-    sub_dir: "task_profiles",
-}
-
-prebuilt_etc {
     name: "task_profiles.json",
     src: "task_profiles.json",
-    required: [
-        "task_profiles_28.json",
-        "task_profiles_29.json",
-        "task_profiles_30.json",
-    ],
-}
-
-prebuilt_etc {
-    name: "task_profiles_28.json",
-    src: "task_profiles_28.json",
-    sub_dir: "task_profiles",
-}
-
-prebuilt_etc {
-    name: "task_profiles_29.json",
-    src: "task_profiles_29.json",
-    sub_dir: "task_profiles",
-}
-
-prebuilt_etc {
-    name: "task_profiles_30.json",
-    src: "task_profiles_30.json",
-    sub_dir: "task_profiles",
 }
 
 cc_defaults {
diff --git a/libprocessgroup/profiles/cgroups_28.json b/libprocessgroup/profiles/cgroups_28.json
deleted file mode 100644
index 17d4929..0000000
--- a/libprocessgroup/profiles/cgroups_28.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
-  "Cgroups": [
-    {
-      "Controller": "schedtune",
-      "Path": "/dev/stune",
-      "Mode": "0755",
-      "UID": "system",
-      "GID": "system"
-    }
-  ]
-}
diff --git a/libprocessgroup/profiles/cgroups_29.json b/libprocessgroup/profiles/cgroups_29.json
deleted file mode 100644
index 17d4929..0000000
--- a/libprocessgroup/profiles/cgroups_29.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
-  "Cgroups": [
-    {
-      "Controller": "schedtune",
-      "Path": "/dev/stune",
-      "Mode": "0755",
-      "UID": "system",
-      "GID": "system"
-    }
-  ]
-}
diff --git a/libprocessgroup/profiles/cgroups_30.json b/libprocessgroup/profiles/cgroups_30.json
deleted file mode 100644
index 80a074b..0000000
--- a/libprocessgroup/profiles/cgroups_30.json
+++ /dev/null
@@ -1,12 +0,0 @@
-{
-  "Cgroups": [
-    {
-      "Controller": "schedtune",
-      "Path": "/dev/stune",
-      "Mode": "0755",
-      "UID": "system",
-      "GID": "system",
-      "Optional": true
-    }
-  ]
-}
diff --git a/libprocessgroup/profiles/task_profiles.json b/libprocessgroup/profiles/task_profiles.json
index 411c38c..d61939f 100644
--- a/libprocessgroup/profiles/task_profiles.json
+++ b/libprocessgroup/profiles/task_profiles.json
@@ -203,6 +203,19 @@
       ]
     },
     {
+      "Name": "RealTimeInputScheduling",
+      "Actions": [
+        {
+          "Name": "SetSchedulerPolicy",
+          "Params":
+          {
+            "Policy": "SCHED_FIFO",
+            "Priority": "98"
+          }
+        }
+      ]
+    },
+    {
       "Name": "CameraServicePerformance",
       "Actions": [
         {
@@ -572,33 +585,6 @@
     },
 
     {
-      "Name": "PerfBoost",
-      "Actions": [
-        {
-          "Name": "SetClamps",
-          "Params":
-          {
-            "Boost": "50%",
-            "Clamp": "0"
-          }
-        }
-      ]
-    },
-    {
-      "Name": "PerfClamp",
-      "Actions": [
-        {
-          "Name": "SetClamps",
-          "Params":
-          {
-            "Boost": "0",
-            "Clamp": "30%"
-          }
-        }
-      ]
-    },
-
-    {
       "Name": "LowMemoryUsage",
       "Actions": [
         {
@@ -731,7 +717,7 @@
     },
     {
       "Name": "InputPolicy",
-      "Profiles": [ "MaxPerformance", "ProcessCapacityMax", "TimerSlackNormal" ]
+      "Profiles": [ "RealTimeInputScheduling", "MaxPerformance", "ProcessCapacityMax", "TimerSlackNormal" ]
     }
   ]
 }
diff --git a/libprocessgroup/profiles/task_profiles_28.json b/libprocessgroup/profiles/task_profiles_28.json
deleted file mode 100644
index e7be548..0000000
--- a/libprocessgroup/profiles/task_profiles_28.json
+++ /dev/null
@@ -1,160 +0,0 @@
-{
-  "Attributes": [
-    {
-      "Name": "STuneBoost",
-      "Controller": "schedtune",
-      "File": "schedtune.boost"
-    },
-    {
-      "Name": "STunePreferIdle",
-      "Controller": "schedtune",
-      "File": "schedtune.prefer_idle"
-    }
-  ],
-
-  "Profiles": [
-    {
-      "Name": "HighEnergySaving",
-      "Actions": [
-        {
-          "Name": "JoinCgroup",
-          "Params":
-          {
-            "Controller": "schedtune",
-            "Path": "background"
-          }
-        }
-      ]
-    },
-    {
-      "Name": "NormalPerformance",
-      "Actions": [
-        {
-          "Name": "JoinCgroup",
-          "Params":
-          {
-            "Controller": "schedtune",
-            "Path": ""
-          }
-        }
-      ]
-    },
-    {
-      "Name": "ServicePerformance",
-      "Actions": [
-        {
-          "Name": "JoinCgroup",
-          "Params":
-          {
-            "Controller": "schedtune",
-            "Path": "background"
-          }
-        }
-      ]
-    },
-    {
-      "Name": "HighPerformance",
-      "Actions": [
-        {
-          "Name": "JoinCgroup",
-          "Params":
-          {
-            "Controller": "schedtune",
-            "Path": "foreground"
-          }
-        }
-      ]
-    },
-    {
-      "Name": "MaxPerformance",
-      "Actions": [
-        {
-          "Name": "JoinCgroup",
-          "Params":
-          {
-            "Controller": "schedtune",
-            "Path": "top-app"
-          }
-        }
-      ]
-    },
-    {
-      "Name": "RealtimePerformance",
-      "Actions": [
-        {
-          "Name": "JoinCgroup",
-          "Params":
-          {
-            "Controller": "schedtune",
-            "Path": "rt"
-          }
-        }
-      ]
-    },
-    {
-      "Name": "CameraServicePerformance",
-      "Actions": [
-        {
-          "Name": "JoinCgroup",
-          "Params":
-          {
-            "Controller": "schedtune",
-            "Path": "camera-daemon"
-          }
-        }
-      ]
-    },
-    {
-      "Name": "NNApiHALPerformance",
-      "Actions": [
-        {
-          "Name": "JoinCgroup",
-          "Params":
-          {
-            "Controller": "schedtune",
-            "Path": "nnapi-hal"
-          }
-        }
-      ]
-    },
-    {
-      "Name": "Dex2oatPerformance",
-      "Actions": [
-        {
-          "Name": "JoinCgroup",
-          "Params":
-          {
-            "Controller": "schedtune",
-            "Path": "background"
-          }
-        }
-      ]
-    },
-    {
-      "Name": "CpuPolicySpread",
-      "Actions": [
-        {
-          "Name": "SetAttribute",
-          "Params":
-          {
-            "Name": "STunePreferIdle",
-            "Value": "1"
-          }
-        }
-      ]
-    },
-    {
-      "Name": "CpuPolicyPack",
-      "Actions": [
-        {
-          "Name": "SetAttribute",
-          "Params":
-          {
-            "Name": "STunePreferIdle",
-            "Value": "0"
-          }
-        }
-      ]
-    }
-  ]
-}
diff --git a/libprocessgroup/profiles/task_profiles_29.json b/libprocessgroup/profiles/task_profiles_29.json
deleted file mode 100644
index 6174c8d..0000000
--- a/libprocessgroup/profiles/task_profiles_29.json
+++ /dev/null
@@ -1,160 +0,0 @@
-{
-  "Attributes": [
-    {
-      "Name": "STuneBoost",
-      "Controller": "schedtune",
-      "File": "schedtune.boost"
-    },
-    {
-      "Name": "STunePreferIdle",
-      "Controller": "schedtune",
-      "File": "schedtune.prefer_idle"
-    }
-  ],
-
-  "Profiles": [
-    {
-      "Name": "HighEnergySaving",
-      "Actions": [
-        {
-          "Name": "JoinCgroup",
-          "Params":
-          {
-            "Controller": "schedtune",
-            "Path": "background"
-          }
-        }
-      ]
-    },
-    {
-      "Name": "NormalPerformance",
-      "Actions": [
-        {
-          "Name": "JoinCgroup",
-          "Params":
-          {
-            "Controller": "schedtune",
-            "Path": ""
-          }
-        }
-      ]
-    },
-    {
-      "Name": "HighPerformance",
-      "Actions": [
-        {
-          "Name": "JoinCgroup",
-          "Params":
-          {
-            "Controller": "schedtune",
-            "Path": "foreground"
-          }
-        }
-      ]
-    },
-    {
-      "Name": "ServicePerformance",
-      "Actions": [
-        {
-          "Name": "JoinCgroup",
-          "Params":
-          {
-            "Controller": "schedtune",
-            "Path": "background"
-          }
-        }
-      ]
-    },
-    {
-      "Name": "MaxPerformance",
-      "Actions": [
-        {
-          "Name": "JoinCgroup",
-          "Params":
-          {
-            "Controller": "schedtune",
-            "Path": "top-app"
-          }
-        }
-      ]
-    },
-    {
-      "Name": "RealtimePerformance",
-      "Actions": [
-        {
-          "Name": "JoinCgroup",
-          "Params":
-          {
-            "Controller": "schedtune",
-            "Path": "rt"
-          }
-        }
-      ]
-    },
-    {
-      "Name": "CameraServicePerformance",
-      "Actions": [
-        {
-          "Name": "JoinCgroup",
-          "Params":
-          {
-            "Controller": "schedtune",
-            "Path": "camera-daemon"
-          }
-        }
-      ]
-    },
-    {
-      "Name": "NNApiHALPerformance",
-      "Actions": [
-        {
-          "Name": "JoinCgroup",
-          "Params":
-          {
-            "Controller": "schedtune",
-            "Path": "nnapi-hal"
-          }
-        }
-      ]
-    },
-    {
-      "Name": "Dex2oatPerformance",
-      "Actions": [
-        {
-          "Name": "JoinCgroup",
-          "Params":
-          {
-            "Controller": "schedtune",
-            "Path": "background"
-          }
-        }
-      ]
-    },
-    {
-      "Name": "CpuPolicySpread",
-      "Actions": [
-        {
-          "Name": "SetAttribute",
-          "Params":
-          {
-            "Name": "STunePreferIdle",
-            "Value": "1"
-          }
-        }
-      ]
-    },
-    {
-      "Name": "CpuPolicyPack",
-      "Actions": [
-        {
-          "Name": "SetAttribute",
-          "Params":
-          {
-            "Name": "STunePreferIdle",
-            "Value": "0"
-          }
-        }
-      ]
-    }
-  ]
-}
diff --git a/libprocessgroup/profiles/task_profiles_30.json b/libprocessgroup/profiles/task_profiles_30.json
deleted file mode 100644
index e7be548..0000000
--- a/libprocessgroup/profiles/task_profiles_30.json
+++ /dev/null
@@ -1,160 +0,0 @@
-{
-  "Attributes": [
-    {
-      "Name": "STuneBoost",
-      "Controller": "schedtune",
-      "File": "schedtune.boost"
-    },
-    {
-      "Name": "STunePreferIdle",
-      "Controller": "schedtune",
-      "File": "schedtune.prefer_idle"
-    }
-  ],
-
-  "Profiles": [
-    {
-      "Name": "HighEnergySaving",
-      "Actions": [
-        {
-          "Name": "JoinCgroup",
-          "Params":
-          {
-            "Controller": "schedtune",
-            "Path": "background"
-          }
-        }
-      ]
-    },
-    {
-      "Name": "NormalPerformance",
-      "Actions": [
-        {
-          "Name": "JoinCgroup",
-          "Params":
-          {
-            "Controller": "schedtune",
-            "Path": ""
-          }
-        }
-      ]
-    },
-    {
-      "Name": "ServicePerformance",
-      "Actions": [
-        {
-          "Name": "JoinCgroup",
-          "Params":
-          {
-            "Controller": "schedtune",
-            "Path": "background"
-          }
-        }
-      ]
-    },
-    {
-      "Name": "HighPerformance",
-      "Actions": [
-        {
-          "Name": "JoinCgroup",
-          "Params":
-          {
-            "Controller": "schedtune",
-            "Path": "foreground"
-          }
-        }
-      ]
-    },
-    {
-      "Name": "MaxPerformance",
-      "Actions": [
-        {
-          "Name": "JoinCgroup",
-          "Params":
-          {
-            "Controller": "schedtune",
-            "Path": "top-app"
-          }
-        }
-      ]
-    },
-    {
-      "Name": "RealtimePerformance",
-      "Actions": [
-        {
-          "Name": "JoinCgroup",
-          "Params":
-          {
-            "Controller": "schedtune",
-            "Path": "rt"
-          }
-        }
-      ]
-    },
-    {
-      "Name": "CameraServicePerformance",
-      "Actions": [
-        {
-          "Name": "JoinCgroup",
-          "Params":
-          {
-            "Controller": "schedtune",
-            "Path": "camera-daemon"
-          }
-        }
-      ]
-    },
-    {
-      "Name": "NNApiHALPerformance",
-      "Actions": [
-        {
-          "Name": "JoinCgroup",
-          "Params":
-          {
-            "Controller": "schedtune",
-            "Path": "nnapi-hal"
-          }
-        }
-      ]
-    },
-    {
-      "Name": "Dex2oatPerformance",
-      "Actions": [
-        {
-          "Name": "JoinCgroup",
-          "Params":
-          {
-            "Controller": "schedtune",
-            "Path": "background"
-          }
-        }
-      ]
-    },
-    {
-      "Name": "CpuPolicySpread",
-      "Actions": [
-        {
-          "Name": "SetAttribute",
-          "Params":
-          {
-            "Name": "STunePreferIdle",
-            "Value": "1"
-          }
-        }
-      ]
-    },
-    {
-      "Name": "CpuPolicyPack",
-      "Actions": [
-        {
-          "Name": "SetAttribute",
-          "Params":
-          {
-            "Name": "STunePreferIdle",
-            "Value": "0"
-          }
-        }
-      ]
-    }
-  ]
-}
diff --git a/libprocessgroup/sched_policy.cpp b/libprocessgroup/sched_policy.cpp
index 042bcd2..5a53c35 100644
--- a/libprocessgroup/sched_policy.cpp
+++ b/libprocessgroup/sched_policy.cpp
@@ -148,20 +148,10 @@
     return enabled;
 }
 
-static bool schedtune_enabled() {
-    return (CgroupMap::GetInstance().FindController("schedtune").IsUsable());
-}
-
 static bool cpuctl_enabled() {
     return (CgroupMap::GetInstance().FindController("cpu").IsUsable());
 }
 
-bool schedboost_enabled() {
-    static bool enabled = schedtune_enabled() || cpuctl_enabled();
-
-    return enabled;
-}
-
 static int getCGroupSubsys(pid_t tid, const char* subsys, std::string& subgroup) {
     auto controller = CgroupMap::GetInstance().FindController(subsys);
 
@@ -201,9 +191,8 @@
     }
 
     std::string group;
-    if (schedboost_enabled()) {
-        if ((getCGroupSubsys(tid, "schedtune", group) < 0) &&
-            (getCGroupSubsys(tid, "cpu", group) < 0)) {
+    if (cpuctl_enabled()) {
+        if (getCGroupSubsys(tid, "cpu", group) < 0) {
             LOG(ERROR) << "Failed to find cpu cgroup for tid " << tid;
             return -1;
         }
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 67ecc1d..dc6c8c0 100644
--- a/libprocessgroup/task_profiles.cpp
+++ b/libprocessgroup/task_profiles.cpp
@@ -17,11 +17,17 @@
 //#define LOG_NDEBUG 0
 #define LOG_TAG "libprocessgroup"
 
+#include <task_profiles.h>
+
+#include <map>
+#include <optional>
+#include <string>
+
 #include <dirent.h>
 #include <fcntl.h>
+#include <sched.h>
+#include <sys/resource.h>
 #include <unistd.h>
-#include <task_profiles.h>
-#include <string>
 
 #include <android-base/file.h>
 #include <android-base/logging.h>
@@ -30,18 +36,13 @@
 #include <android-base/strings.h>
 #include <android-base/threads.h>
 
+#include <build_flags.h>
+
 #include <cutils/android_filesystem_config.h>
 
 #include <json/reader.h>
 #include <json/value.h>
 
-#include <build_flags.h>
-
-// To avoid issues in sdk_mac build
-#if defined(__ANDROID__)
-#include <sys/prctl.h>
-#endif
-
 using android::base::GetThreadId;
 using android::base::GetUintProperty;
 using android::base::StringPrintf;
@@ -54,6 +55,7 @@
 
 static constexpr const char* TEMPLATE_TASK_PROFILE_API_FILE =
         "/etc/task_profiles/task_profiles_%u.json";
+namespace {
 
 class FdCacheHelper {
   public:
@@ -64,8 +66,11 @@
     };
 
     static void Cache(const std::string& path, android::base::unique_fd& fd);
+
     static void Drop(android::base::unique_fd& fd);
+
     static void Init(const std::string& path, android::base::unique_fd& fd);
+
     static bool IsCached(const android::base::unique_fd& fd) { return fd > FDS_INACCESSIBLE; }
 
   private:
@@ -116,6 +121,17 @@
     return path.find("<uid>", 0) != std::string::npos || path.find("<pid>", 0) != std::string::npos;
 }
 
+std::optional<long> readLong(const std::string& str) {
+    char* end;
+    const long result = strtol(str.c_str(), &end, 10);
+    if (end > str.c_str()) {
+        return result;
+    }
+    return std::nullopt;
+}
+
+}  // namespace
+
 IProfileAttribute::~IProfileAttribute() = default;
 
 const std::string& ProfileAttribute::file_name() const {
@@ -188,61 +204,20 @@
     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__)
-
-bool SetTimerSlackAction::IsTimerSlackSupported(pid_t tid) {
-    auto file = StringPrintf("/proc/%d/timerslack_ns", tid);
-
-    return (access(file.c_str(), W_OK) == 0);
-}
-
 bool SetTimerSlackAction::ExecuteForTask(pid_t tid) const {
-    static bool sys_supports_timerslack = IsTimerSlackSupported(tid);
-
-    // v4.6+ kernels support the /proc/<tid>/timerslack_ns interface.
-    // TODO: once we've backported this, log if the open(2) fails.
-    if (sys_supports_timerslack) {
-        auto file = StringPrintf("/proc/%d/timerslack_ns", tid);
-        if (!WriteStringToFile(std::to_string(slack_), file)) {
-            if (errno == ENOENT) {
-                // This happens when process is already dead
-                return true;
-            }
-            PLOG(ERROR) << "set_timerslack_ns write failed";
+    const auto file = StringPrintf("/proc/%d/timerslack_ns", tid);
+    if (!WriteStringToFile(std::to_string(slack_), file)) {
+        if (errno == ENOENT) {
+            // This happens when process is already dead
+            return true;
         }
-    }
-
-    // TODO: Remove when /proc/<tid>/timerslack_ns interface is backported.
-    if (tid == 0 || tid == GetThreadId()) {
-        if (prctl(PR_SET_TIMERSLACK, slack_) == -1) {
-            PLOG(ERROR) << "set_timerslack_ns prctl failed";
-        }
+        PLOG(ERROR) << "set_timerslack_ns write failed";
+        return false;
     }
 
     return true;
 }
 
-#else
-
-bool SetTimerSlackAction::ExecuteForTask(int) const {
-    return true;
-};
-
-#endif
-
 bool SetAttributeAction::WriteValueToFile(const std::string& path) const {
     if (!WriteStringToFile(value_, path)) {
         if (access(path.c_str(), F_OK) < 0) {
@@ -672,6 +647,57 @@
     return access(task_path_.c_str(), W_OK) == 0;
 }
 
+bool SetSchedulerPolicyAction::isNormalPolicy(int policy) {
+    return policy == SCHED_OTHER || policy == SCHED_BATCH || policy == SCHED_IDLE;
+}
+
+bool SetSchedulerPolicyAction::toPriority(int policy, int virtual_priority, int& priority_out) {
+    constexpr int VIRTUAL_PRIORITY_MIN = 1;
+    constexpr int VIRTUAL_PRIORITY_MAX = 99;
+
+    if (virtual_priority < VIRTUAL_PRIORITY_MIN || virtual_priority > VIRTUAL_PRIORITY_MAX) {
+        LOG(WARNING) << "SetSchedulerPolicy: invalid priority (" << virtual_priority
+                     << ") for policy (" << policy << ")";
+        return false;
+    }
+
+    const int min = sched_get_priority_min(policy);
+    if (min == -1) {
+        PLOG(ERROR) << "SetSchedulerPolicy: Cannot get min sched priority for policy " << policy;
+        return false;
+    }
+
+    const int max = sched_get_priority_max(policy);
+    if (max == -1) {
+        PLOG(ERROR) << "SetSchedulerPolicy: Cannot get max sched priority for policy " << policy;
+        return false;
+    }
+
+    priority_out = min + (virtual_priority - VIRTUAL_PRIORITY_MIN) * (max - min) /
+        (VIRTUAL_PRIORITY_MAX - VIRTUAL_PRIORITY_MIN);
+
+    return true;
+}
+
+bool SetSchedulerPolicyAction::ExecuteForTask(pid_t tid) const {
+    struct sched_param param = {};
+    param.sched_priority = isNormalPolicy(policy_) ? 0 : *priority_or_nice_;
+    if (sched_setscheduler(tid, policy_, &param) == -1) {
+        PLOG(WARNING) << "SetSchedulerPolicy: Failed to apply scheduler policy (" << policy_
+                      << ") with priority (" << *priority_or_nice_ << ") to tid " << tid;
+        return false;
+    }
+
+    if (isNormalPolicy(policy_) && priority_or_nice_ &&
+        setpriority(PRIO_PROCESS, tid, *priority_or_nice_) == -1) {
+        PLOG(WARNING) << "SetSchedulerPolicy: Failed to apply nice (" << *priority_or_nice_
+                      << ") to tid " << tid;
+        return false;
+    }
+
+    return true;
+}
+
 bool ApplyProfileAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
     for (const auto& profile : profiles_) {
         profile->ExecuteForProcess(uid, pid);
@@ -903,15 +929,12 @@
                     LOG(WARNING) << "JoinCgroup: controller " << controller_name << " is not found";
                 }
             } else if (action_name == "SetTimerSlack") {
-                std::string slack_value = params_val["Slack"].asString();
-                char* end;
-                unsigned long slack;
-
-                slack = strtoul(slack_value.c_str(), &end, 10);
-                if (end > slack_value.c_str()) {
-                    profile->Add(std::make_unique<SetTimerSlackAction>(slack));
+                const std::string slack_string = params_val["Slack"].asString();
+                std::optional<long> slack = readLong(slack_string);
+                if (slack && *slack >= 0) {
+                    profile->Add(std::make_unique<SetTimerSlackAction>(*slack));
                 } else {
-                    LOG(WARNING) << "SetTimerSlack: invalid parameter: " << slack_value;
+                    LOG(WARNING) << "SetTimerSlack: invalid parameter: " << slack_string;
                 }
             } else if (action_name == "SetAttribute") {
                 std::string attr_name = params_val["Name"].asString();
@@ -925,23 +948,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();
@@ -959,6 +965,73 @@
                     LOG(WARNING) << "WriteFile: invalid parameter: "
                                  << "empty value";
                 }
+            } else if (action_name == "SetSchedulerPolicy") {
+                const std::map<std::string, int> POLICY_MAP = {
+                    {"SCHED_OTHER", SCHED_OTHER},
+                    {"SCHED_BATCH", SCHED_BATCH},
+                    {"SCHED_IDLE", SCHED_IDLE},
+                    {"SCHED_FIFO", SCHED_FIFO},
+                    {"SCHED_RR", SCHED_RR},
+                };
+                const std::string policy_str = params_val["Policy"].asString();
+
+                const auto it = POLICY_MAP.find(policy_str);
+                if (it == POLICY_MAP.end()) {
+                    LOG(WARNING) << "SetSchedulerPolicy: invalid policy " << policy_str;
+                    continue;
+                }
+
+                const int policy = it->second;
+
+                if (SetSchedulerPolicyAction::isNormalPolicy(policy)) {
+                    if (params_val.isMember("Priority")) {
+                        LOG(WARNING) << "SetSchedulerPolicy: Normal policies (" << policy_str
+                                     << ") use Nice values, not Priority values";
+                    }
+
+                    if (params_val.isMember("Nice")) {
+                        // If present, this optional value will be passed in an additional syscall
+                        // to setpriority(), since the sched_priority value must be 0 for calls to
+                        // sched_setscheduler() with "normal" policies.
+                        const std::string nice_string = params_val["Nice"].asString();
+                        const std::optional<int> nice = readLong(nice_string);
+
+                        if (!nice) {
+                            LOG(FATAL) << "Invalid nice value specified: " << nice_string;
+                        }
+                        const int LINUX_MIN_NICE = -20;
+                        const int LINUX_MAX_NICE = 19;
+                        if (*nice < LINUX_MIN_NICE || *nice > LINUX_MAX_NICE) {
+                            LOG(WARNING) << "SetSchedulerPolicy: Provided nice (" << *nice
+                                         << ") appears out of range.";
+                        }
+                        profile->Add(std::make_unique<SetSchedulerPolicyAction>(policy, *nice));
+                    } else {
+                        profile->Add(std::make_unique<SetSchedulerPolicyAction>(policy));
+                    }
+                } else {
+                    if (params_val.isMember("Nice")) {
+                        LOG(WARNING) << "SetSchedulerPolicy: Real-time policies (" << policy_str
+                                     << ") use Priority values, not Nice values";
+                    }
+
+                    // This is a "virtual priority" as described by `man 2 sched_get_priority_min`
+                    // that will be mapped onto the following range for the provided policy:
+                    // [sched_get_priority_min(), sched_get_priority_max()]
+
+                    const std::string priority_string = params_val["Priority"].asString();
+                    std::optional<long> virtual_priority = readLong(priority_string);
+                    if (virtual_priority && *virtual_priority > 0) {
+                        int priority;
+                        if (SetSchedulerPolicyAction::toPriority(policy, *virtual_priority,
+                                                                 priority)) {
+                            profile->Add(
+                                    std::make_unique<SetSchedulerPolicyAction>(policy, priority));
+                        }
+                    } else {
+                        LOG(WARNING) << "Invalid priority value: " << priority_string;
+                    }
+                }
             } else {
                 LOG(WARNING) << "Unknown profile action: " << action_name;
             }
diff --git a/libprocessgroup/task_profiles.h b/libprocessgroup/task_profiles.h
index abb3ca5..d0b5043 100644
--- a/libprocessgroup/task_profiles.h
+++ b/libprocessgroup/task_profiles.h
@@ -21,6 +21,7 @@
 #include <map>
 #include <memory>
 #include <mutex>
+#include <optional>
 #include <span>
 #include <string>
 #include <string_view>
@@ -77,7 +78,7 @@
 
     // Default implementations will fail
     virtual bool ExecuteForProcess(uid_t, pid_t) const { return false; }
-    virtual bool ExecuteForTask(int) const { return false; }
+    virtual bool ExecuteForTask(pid_t) const { return false; }
     virtual bool ExecuteForUID(uid_t) const { return false; }
 
     virtual void EnableResourceCaching(ResourceCacheType) {}
@@ -90,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) {}
@@ -114,8 +102,6 @@
 
   private:
     unsigned long slack_;
-
-    static bool IsTimerSlackSupported(pid_t tid);
 };
 
 // Set attribute profile element
@@ -189,6 +175,25 @@
     CacheUseResult UseCachedFd(ResourceCacheType cache_type, const std::string& value) const;
 };
 
+// Set scheduler policy action
+class SetSchedulerPolicyAction : public ProfileAction {
+  public:
+    SetSchedulerPolicyAction(int policy)
+        : policy_(policy) {}
+    SetSchedulerPolicyAction(int policy, int priority_or_nice)
+        : policy_(policy), priority_or_nice_(priority_or_nice) {}
+
+    const char* Name() const override { return "SetSchedulerPolicy"; }
+    bool ExecuteForTask(pid_t tid) const override;
+
+    static bool isNormalPolicy(int policy);
+    static bool toPriority(int policy, int virtual_priority, int& priority_out);
+
+  private:
+    int policy_;
+    std::optional<int> priority_or_nice_;
+};
+
 class TaskProfile {
   public:
     TaskProfile(const std::string& name) : name_(name), res_cached_(false) {}
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/libstats/pull_lazy/Android.bp b/libstats/pull_lazy/Android.bp
index 65dce26..71af170 100644
--- a/libstats/pull_lazy/Android.bp
+++ b/libstats/pull_lazy/Android.bp
@@ -32,7 +32,7 @@
         "-Wall",
         "-Werror",
     ],
-    test_suites: ["device-tests", "mts-statsd"],
+    test_suites: ["device-tests"],
     test_config: "libstatspull_lazy_test.xml",
     // TODO(b/153588990): Remove when the build system properly separates.
     // 32bit and 64bit architectures.
diff --git a/libstats/socket_lazy/Android.bp b/libstats/socket_lazy/Android.bp
index 241e87a..945a7c4 100644
--- a/libstats/socket_lazy/Android.bp
+++ b/libstats/socket_lazy/Android.bp
@@ -36,7 +36,6 @@
     ],
     test_suites: [
         "device-tests",
-        "mts-statsd",
     ],
     test_config: "libstatssocket_lazy_test.xml",
     // TODO(b/153588990): Remove when the build system properly separates.
diff --git a/libutils/Threads.cpp b/libutils/Threads.cpp
index d8d75ac..111d46a 100644
--- a/libutils/Threads.cpp
+++ b/libutils/Threads.cpp
@@ -313,11 +313,6 @@
 int androidSetThreadPriority(pid_t tid, int pri)
 {
     int rc = 0;
-    int curr_pri = getpriority(PRIO_PROCESS, tid);
-
-    if (curr_pri == pri) {
-        return rc;
-    }
 
     if (setpriority(PRIO_PROCESS, tid, pri) < 0) {
         rc = INVALID_OPERATION;
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/libutils/binder/VectorImpl.cpp b/libutils/binder/VectorImpl.cpp
index d951b8b..a62664f 100644
--- a/libutils/binder/VectorImpl.cpp
+++ b/libutils/binder/VectorImpl.cpp
@@ -463,7 +463,8 @@
     size_t new_size;
     LOG_ALWAYS_FATAL_IF(__builtin_sub_overflow(mCount, amount, &new_size));
 
-    if (new_size < (capacity() / 2)) {
+    const size_t prev_capacity = capacity();
+    if (new_size < (prev_capacity / 2) && prev_capacity > kMinVectorCapacity) {
         // NOTE: (new_size * 2) is safe because capacity didn't overflow and
         // new_size < (capacity / 2)).
         const size_t new_capacity = max(kMinVectorCapacity, new_size * 2);
diff --git a/libvendorsupport/include_llndk/android/llndk-versioning.h b/libvendorsupport/include_llndk/android/llndk-versioning.h
index cf82fb7..81d165f 100644
--- a/libvendorsupport/include_llndk/android/llndk-versioning.h
+++ b/libvendorsupport/include_llndk/android/llndk-versioning.h
@@ -25,15 +25,15 @@
     __attribute__((annotate("introduced_in_llndk=" #vendor_api_level)))
 #endif
 
-#if defined(__ANDROID_VENDOR__)
-
+#if defined(__ANDROID_VENDOR_API__)
+// __ANDROID_VENDOR_API__ is defined only for vendor or product variant modules.
 // Use this macro as an `if` statement to call an API that are available to both NDK and LLNDK.
-// This returns true for the vendor modules if the vendor_api_level is less than or equal to the
-// ro.board.api_level.
+// This returns true for vendor or product modules if the vendor_api_level is less than or equal to
+// the ro.board.api_level.
 #define API_LEVEL_AT_LEAST(sdk_api_level, vendor_api_level) \
     constexpr(__ANDROID_VENDOR_API__ >= vendor_api_level)
 
-#else  // __ANDROID_VENDOR__
+#else  // __ANDROID_VENDOR_API__
 
 // For non-vendor modules, API_LEVEL_AT_LEAST is replaced with __builtin_available(sdk_api_level) to
 // guard the API for __INTRODUCED_IN.
@@ -42,4 +42,4 @@
     (__builtin_available(android sdk_api_level, *))
 #endif
 
-#endif  // __ANDROID_VENDOR__
+#endif  // __ANDROID_VENDOR_API__
diff --git a/mkbootfs/Android.bp b/mkbootfs/Android.bp
index cd2a624..e0191f0 100644
--- a/mkbootfs/Android.bp
+++ b/mkbootfs/Android.bp
@@ -6,7 +6,7 @@
 
 cc_binary_host {
     name: "mkbootfs",
-    srcs: ["mkbootfs.c"],
+    srcs: ["mkbootfs.cpp"],
     cflags: ["-Werror"],
     static_libs: [
         "libbase",
diff --git a/mkbootfs/mkbootfs.c b/mkbootfs/mkbootfs.cpp
similarity index 93%
rename from mkbootfs/mkbootfs.c
rename to mkbootfs/mkbootfs.cpp
index 84a0a4e..a45c6a2 100644
--- a/mkbootfs/mkbootfs.c
+++ b/mkbootfs/mkbootfs.cpp
@@ -19,6 +19,9 @@
 #include <private/android_filesystem_config.h>
 #include <private/fs_config.h>
 
+#include <android-base/file.h>
+#include <string>
+
 /* NOTES
 **
 ** - see https://www.kernel.org/doc/Documentation/early-userspace/buffer-format.txt
@@ -75,7 +78,7 @@
     }
 }
 
-static void _eject(struct stat *s, char *out, int olen, char *data, unsigned datasize)
+static void _eject(struct stat *s, const char *out, int olen, char *data, unsigned datasize)
 {
     // Nothing is special about this value, just picked something in the
     // approximate range that was being used already, and avoiding small
@@ -151,9 +154,10 @@
     DIR* d = opendir(in);
     if (d == NULL) err(1, "cannot open directory '%s'", in);
 
+    // TODO: switch to std::vector
     int size = 32;
     int entries = 0;
-    char** names = malloc(size * sizeof(char*));
+    char** names = (char**) malloc(size * sizeof(char*));
     if (names == NULL) {
       errx(1, "failed to allocate dir names array (size %d)", size);
     }
@@ -167,7 +171,7 @@
 
         if (entries >= size) {
           size *= 2;
-          names = realloc(names, size * sizeof(char*));
+          names = (char**) realloc(names, size * sizeof(char*));
           if (names == NULL) {
             errx(1, "failed to reallocate dir names array (size %d)", size);
           }
@@ -211,20 +215,12 @@
     if(lstat(in, &s)) err(1, "could not stat '%s'", in);
 
     if(S_ISREG(s.st_mode)){
-        int fd = open(in, O_RDONLY);
-        if(fd < 0) err(1, "cannot open '%s' for read", in);
-
-        char* tmp = (char*) malloc(s.st_size);
-        if(tmp == 0) errx(1, "cannot allocate %zd bytes", s.st_size);
-
-        if(read(fd, tmp, s.st_size) != s.st_size) {
-            err(1, "cannot read %zd bytes", s.st_size);
+        std::string content;
+        if (!android::base::ReadFileToString(in, &content)) {
+            err(1, "cannot read '%s'", in);
         }
 
-        _eject(&s, out, olen, tmp, s.st_size);
-
-        free(tmp);
-        close(fd);
+        _eject(&s, out, olen, content.data(), content.size());
     } else if(S_ISDIR(s.st_mode)) {
         _eject(&s, out, olen, 0, 0);
         _archive_dir(in, out, ilen, olen);
@@ -445,15 +441,12 @@
     int num_dirs = argc - optind;
     argv += optind;
 
-    while(num_dirs-- > 0){
+    while (num_dirs-- > 0){
         char *x = strchr(*argv, '=');
-        if(x != 0) {
-            *x++ = 0;
-        } else {
-            x = "";
+        if (x != nullptr) {
+            *x++ = '\0';
         }
-
-        archive(*argv, x);
+        archive(*argv, x ?: "");
 
         argv++;
     }
diff --git a/rootdir/init.rc b/rootdir/init.rc
index 1acd637..5bb64cc 100644
--- a/rootdir/init.rc
+++ b/rootdir/init.rc
@@ -70,6 +70,9 @@
 
     start ueventd
 
+    # Mount tracefs (with GID=AID_READTRACEFS)
+    mount tracefs tracefs /sys/kernel/tracing gid=3012
+
     # Run apexd-bootstrap so that APEXes that provide critical libraries
     # become available. Note that this is executed as exec_start to ensure that
     # the libraries are available to the processes started after this statement.
@@ -80,9 +83,6 @@
     mkdir /dev/boringssl 0755 root root
     mkdir /dev/boringssl/selftest 0755 root root
 
-    # Mount tracefs (with GID=AID_READTRACEFS)
-    mount tracefs tracefs /sys/kernel/tracing gid=3012
-
     # create sys dirctory
     mkdir /dev/sys 0755 system system
     mkdir /dev/sys/fs 0755 system system
@@ -112,37 +112,6 @@
     # Create socket dir for ot-daemon
     mkdir /dev/socket/ot-daemon 0770 thread_network thread_network
 
-    # Create energy-aware scheduler tuning nodes
-    mkdir /dev/stune/foreground
-    mkdir /dev/stune/background
-    mkdir /dev/stune/top-app
-    mkdir /dev/stune/rt
-    chown system system /dev/stune
-    chown system system /dev/stune/foreground
-    chown system system /dev/stune/background
-    chown system system /dev/stune/top-app
-    chown system system /dev/stune/rt
-    chown system system /dev/stune/tasks
-    chown system system /dev/stune/foreground/tasks
-    chown system system /dev/stune/background/tasks
-    chown system system /dev/stune/top-app/tasks
-    chown system system /dev/stune/rt/tasks
-    chown system system /dev/stune/cgroup.procs
-    chown system system /dev/stune/foreground/cgroup.procs
-    chown system system /dev/stune/background/cgroup.procs
-    chown system system /dev/stune/top-app/cgroup.procs
-    chown system system /dev/stune/rt/cgroup.procs
-    chmod 0664 /dev/stune/tasks
-    chmod 0664 /dev/stune/foreground/tasks
-    chmod 0664 /dev/stune/background/tasks
-    chmod 0664 /dev/stune/top-app/tasks
-    chmod 0664 /dev/stune/rt/tasks
-    chmod 0664 /dev/stune/cgroup.procs
-    chmod 0664 /dev/stune/foreground/cgroup.procs
-    chmod 0664 /dev/stune/background/cgroup.procs
-    chmod 0664 /dev/stune/top-app/cgroup.procs
-    chmod 0664 /dev/stune/rt/cgroup.procs
-
     # cpuctl hierarchy for devices using utilclamp
     mkdir /dev/cpuctl/foreground
     mkdir /dev/cpuctl/foreground_window
@@ -216,24 +185,6 @@
     chmod 0664 /dev/cpuctl/camera-daemon/tasks
     chmod 0664 /dev/cpuctl/camera-daemon/cgroup.procs
 
-    # Create an stune group for camera-specific processes
-    mkdir /dev/stune/camera-daemon
-    chown system system /dev/stune/camera-daemon
-    chown system system /dev/stune/camera-daemon/tasks
-    chown system system /dev/stune/camera-daemon/cgroup.procs
-    chmod 0664 /dev/stune/camera-daemon/tasks
-    chmod 0664 /dev/stune/camera-daemon/cgroup.procs
-
-    # Create an stune group for NNAPI HAL processes
-    mkdir /dev/stune/nnapi-hal
-    chown system system /dev/stune/nnapi-hal
-    chown system system /dev/stune/nnapi-hal/tasks
-    chown system system /dev/stune/nnapi-hal/cgroup.procs
-    chmod 0664 /dev/stune/nnapi-hal/tasks
-    chmod 0664 /dev/stune/nnapi-hal/cgroup.procs
-    write /dev/stune/nnapi-hal/schedtune.boost 1
-    write /dev/stune/nnapi-hal/schedtune.prefer_idle 1
-
     # Create blkio group and apply initial settings.
     # This feature needs kernel to support it, and the
     # device's init.rc must actually set the correct values.
@@ -644,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
@@ -1243,6 +1195,9 @@
     chown system system /sys/kernel/ipv4/tcp_rmem_min
     chown system system /sys/kernel/ipv4/tcp_rmem_def
     chown system system /sys/kernel/ipv4/tcp_rmem_max
+    chown system system /sys/firmware/acpi/tables
+    chown system system /sys/firmware/acpi/tables/BERT
+    chown system system /sys/firmware/acpi/tables/data/BERT
     chown root radio /proc/cmdline
     chown root system /proc/bootconfig
 
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
diff --git a/trusty/keymaster/Android.bp b/trusty/keymaster/Android.bp
index aca59b6..cb07829 100644
--- a/trusty/keymaster/Android.bp
+++ b/trusty/keymaster/Android.bp
@@ -105,19 +105,17 @@
         "keymint/TrustySharedSecret.cpp",
         "keymint/service.cpp",
     ],
-    defaults: [
-        "keymint_use_latest_hal_aidl_ndk_shared",
-    ],
     shared_libs: [
+        "android.hardware.security.keymint-V3-ndk",
         "android.hardware.security.rkp-V3-ndk",
         "android.hardware.security.secureclock-V1-ndk",
         "android.hardware.security.sharedsecret-V1-ndk",
-        "lib_android_keymaster_keymint_utils",
+        "lib_android_keymaster_keymint_utils_V3",
         "libbase",
         "libbinder_ndk",
         "libhardware",
         "libkeymaster_messages",
-        "libkeymint",
+        "libkeymasterconfig",
         "liblog",
         "libtrusty",
         "libutils",
diff --git a/trusty/libtrusty/tipc-test/tipc_test.c b/trusty/libtrusty/tipc-test/tipc_test.c
index 3cf0c05..121837d 100644
--- a/trusty/libtrusty/tipc-test/tipc_test.c
+++ b/trusty/libtrusty/tipc-test/tipc_test.c
@@ -67,7 +67,7 @@
 static const char* receiver_name = "com.android.trusty.memref.receiver";
 static const size_t memref_chunk_size = 4096;
 
-static const char* _sopts = "hsvDS:t:r:m:b:B:";
+static const char* _sopts = "hsvD:S:t:r:m:b:B:";
 /* clang-format off */
 static const struct option _lopts[] =  {
     {"help",    no_argument,       0, 'h'},
diff --git a/trusty/utils/trusty-ut-ctrl/ut-ctrl.c b/trusty/utils/trusty-ut-ctrl/ut-ctrl.c
index 6cc6670..31cfd4c 100644
--- a/trusty/utils/trusty-ut-ctrl/ut-ctrl.c
+++ b/trusty/utils/trusty-ut-ctrl/ut-ctrl.c
@@ -95,12 +95,26 @@
     TEST_FAILED = 1,
     TEST_MESSAGE = 2,
     TEST_TEXT = 3,
+    TEST_OPCODE_COUNT,
 };
 
+static int get_msg_len(const char* buf, int max_buf_len) {
+    int buf_len;
+    for (buf_len = 0; buf_len < max_buf_len; buf_len++) {
+        if ((unsigned char)buf[buf_len] < TEST_OPCODE_COUNT) {
+            break;
+        }
+    }
+    return buf_len;
+}
+
 static int run_trusty_unitest(const char* utapp) {
     int fd;
-    int rc;
-    char rx_buf[1024];
+    char read_buf[1024];
+    int read_len;
+    char* rx_buf;
+    int rx_buf_len;
+    int cmd = -1;
 
     /* connect to unitest app */
     fd = tipc_connect(dev_name, utapp);
@@ -110,22 +124,39 @@
     }
 
     /* wait for test to complete */
+    rx_buf_len = 0;
     for (;;) {
-        rc = read(fd, rx_buf, sizeof(rx_buf));
-        if (rc <= 0 || rc >= (int)sizeof(rx_buf)) {
-            fprintf(stderr, "%s: Read failed: %d\n", __func__, rc);
-            tipc_close(fd);
-            return -1;
+        if (rx_buf_len == 0) {
+            read_len = read(fd, read_buf, sizeof(read_buf));
+            if (read_len <= 0 || read_len > (int)sizeof(read_buf)) {
+                fprintf(stderr, "%s: Read failed: %d, %s\n", __func__, read_len,
+                        read_len < 0 ? strerror(errno) : "");
+                tipc_close(fd);
+                return -1;
+            }
+            rx_buf = read_buf;
+            rx_buf_len = read_len;
         }
 
-        if (rx_buf[0] == TEST_PASSED) {
+        int msg_len = get_msg_len(rx_buf, rx_buf_len);
+        if (msg_len == 0) {
+            cmd = rx_buf[0];
+            rx_buf++;
+            rx_buf_len--;
+        }
+
+        if (cmd == TEST_PASSED) {
             break;
-        } else if (rx_buf[0] == TEST_FAILED) {
+        } else if (cmd == TEST_FAILED) {
             break;
-        } else if (rx_buf[0] == TEST_MESSAGE || rx_buf[0] == TEST_TEXT) {
-            write(STDOUT_FILENO, rx_buf + 1, rc - 1);
+        } else if (cmd == TEST_MESSAGE || cmd == TEST_TEXT) {
+            if (msg_len) {
+                write(STDOUT_FILENO, rx_buf, msg_len);
+                rx_buf += msg_len;
+                rx_buf_len -= msg_len;
+            }
         } else {
-            fprintf(stderr, "%s: Bad message header: %d\n", __func__, rx_buf[0]);
+            fprintf(stderr, "%s: Bad message header: %d\n", __func__, cmd);
             break;
         }
     }
@@ -133,7 +164,7 @@
     /* close connection to unitest app */
     tipc_close(fd);
 
-    return rx_buf[0] == TEST_PASSED ? 0 : -1;
+    return cmd == TEST_PASSED ? 0 : -1;
 }
 
 int main(int argc, char** argv) {