Merge "Fix type of android_thread_func typedef" into main
diff --git a/fastboot/fuzzy_fastboot/transport_sniffer.cpp b/fastboot/fuzzy_fastboot/transport_sniffer.cpp
index b55ffd3..0aef350 100644
--- a/fastboot/fuzzy_fastboot/transport_sniffer.cpp
+++ b/fastboot/fuzzy_fastboot/transport_sniffer.cpp
@@ -90,7 +90,7 @@
     // and be printed as a string, or just a raw byte-buffer
     const auto msg = [&ret, no_print](const std::vector<char>& buf) {
         ret += android::base::StringPrintf("(%lu bytes): ", buf.size());
-        std::vector<const char>::iterator iter = buf.end();
+        std::vector<char>::const_iterator iter = buf.end();
         const unsigned max_chars = 50;
         if (buf.size() > max_chars) {
             iter = buf.begin() + max_chars;
diff --git a/fs_mgr/fs_mgr.cpp b/fs_mgr/fs_mgr.cpp
index 76578dd..fbd990b 100644
--- a/fs_mgr/fs_mgr.cpp
+++ b/fs_mgr/fs_mgr.cpp
@@ -38,10 +38,8 @@
 
 #include <array>
 #include <chrono>
-#include <functional>
 #include <map>
 #include <memory>
-#include <numeric>
 #include <string>
 #include <string_view>
 #include <thread>
@@ -66,6 +64,7 @@
 #include <fs_mgr/file_wait.h>
 #include <fs_mgr_overlayfs.h>
 #include <fscrypt/fscrypt.h>
+#include <fstab/fstab.h>
 #include <libdm/dm.h>
 #include <libdm/loop_control.h>
 #include <liblp/metadata_format.h>
@@ -82,7 +81,7 @@
 #define F2FS_FSCK_BIN   "/system/bin/fsck.f2fs"
 #define MKSWAP_BIN      "/system/bin/mkswap"
 #define TUNE2FS_BIN     "/system/bin/tune2fs"
-#define RESIZE2FS_BIN "/system/bin/resize2fs"
+#define RESIZE2FS_BIN   "/system/bin/resize2fs"
 
 #define FSCK_LOG_FILE   "/dev/fscklogs/log"
 
@@ -138,8 +137,8 @@
 static void log_fs_stat(const std::string& blk_device, int fs_stat) {
     std::string msg =
             android::base::StringPrintf("\nfs_stat,%s,0x%x\n", blk_device.c_str(), fs_stat);
-    android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(FSCK_LOG_FILE, O_WRONLY | O_CLOEXEC |
-                                                        O_APPEND | O_CREAT, 0664)));
+    android::base::unique_fd fd(TEMP_FAILURE_RETRY(
+            open(FSCK_LOG_FILE, O_WRONLY | O_CLOEXEC | O_APPEND | O_CREAT, 0664)));
     if (fd == -1 || !android::base::WriteStringToFd(msg, fd)) {
         LWARNING << __FUNCTION__ << "() cannot log " << msg;
     }
@@ -593,7 +592,7 @@
 
     // Must give `-T now` to prevent last_fsck_time from growing too large,
     // otherwise, tune2fs won't enable metadata_csum.
-    const char* tune2fs_args[] = {TUNE2FS_BIN, "-O",        "metadata_csum,64bit,extent",
+    const char* tune2fs_args[] = {TUNE2FS_BIN, "-O",  "metadata_csum,64bit,extent",
                                   "-T",        "now", blk_device.c_str()};
     const char* resize2fs_args[] = {RESIZE2FS_BIN, "-b", blk_device.c_str()};
 
@@ -1430,6 +1429,37 @@
     return access(fs_mgr_metadata_encryption_in_progress_file_name(entry).c_str(), R_OK) == 0;
 }
 
+static FstabEntry* LocateFormattableEntry(FstabEntry* const begin, FstabEntry* const end) {
+    if (begin == end) {
+        return nullptr;
+    }
+    const bool dev_option_enabled =
+            android::base::GetBoolProperty("ro.product.build.16k_page.enabled", false);
+    FstabEntry* f2fs_entry = nullptr;
+    for (auto iter = begin; iter != end && iter->blk_device == begin->blk_device; iter++) {
+        if (iter->fs_mgr_flags.formattable) {
+            if (getpagesize() != 4096 && is_f2fs(iter->fs_type) && dev_option_enabled) {
+                f2fs_entry = iter;
+                continue;
+            }
+            if (f2fs_entry) {
+                LOG(INFO) << "Skipping F2FS format for block device " << iter->blk_device << " @ "
+                          << iter->mount_point
+                          << " in non-4K mode for dev option enabled devices, "
+                             "as these devices need to toggle between 4K/16K mode, and F2FS does "
+                             "not support page_size != block_size configuration.";
+            }
+            return iter;
+        }
+    }
+    if (f2fs_entry) {
+        LOG(INFO) << "Using F2FS for " << f2fs_entry->blk_device << " @ " << f2fs_entry->mount_point
+                  << " even though we are in non-4K mode. Device might require a data wipe after "
+                     "going back to 4K mode, as F2FS does not support page_size != block_size";
+    }
+    return f2fs_entry;
+}
+
 // When multiple fstab records share the same mount_point, it will try to mount each
 // one in turn, and ignore any duplicates after a first successful mount.
 // Returns -1 on error, and  FS_MGR_MNTALL_* otherwise.
@@ -1540,8 +1570,8 @@
             }
         }
 
-        int last_idx_inspected;
-        int top_idx = i;
+        int last_idx_inspected = -1;
+        const int top_idx = i;
         int attempted_idx = -1;
 
         bool encryption_interrupted = WasMetadataEncryptionInterrupted(current_entry);
@@ -1591,7 +1621,8 @@
             // Success!  Go get the next one.
             continue;
         }
-
+        auto formattable_entry =
+                LocateFormattableEntry(fstab->data() + top_idx, fstab->data() + fstab->size());
         // Mounting failed, understand why and retry.
         wiped = partition_wiped(current_entry.blk_device.c_str());
         if (mount_errno != EBUSY && mount_errno != EACCES &&
@@ -1619,12 +1650,12 @@
                 encryptable = FS_MGR_MNTALL_DEV_IS_METADATA_ENCRYPTED;
                 set_type_property(encryptable);
 
-                if (!call_vdc({"cryptfs", "encryptFstab", current_entry.blk_device,
-                               current_entry.mount_point, "true" /* shouldFormat */,
-                               current_entry.fs_type,
-                               current_entry.fs_mgr_flags.is_zoned ? "true" : "false",
-                               std::to_string(current_entry.length),
-                               android::base::Join(current_entry.user_devices, ' ')},
+                if (!call_vdc({"cryptfs", "encryptFstab", formattable_entry->blk_device,
+                               formattable_entry->mount_point, "true" /* shouldFormat */,
+                               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, ' ')},
                               nullptr)) {
                     LERROR << "Encryption failed";
                 } else {
@@ -1633,7 +1664,7 @@
                 }
             }
 
-            if (fs_mgr_do_format(current_entry) == 0) {
+            if (fs_mgr_do_format(*formattable_entry) == 0) {
                 // Let's replay the mount actions.
                 i = top_idx - 1;
                 continue;
@@ -1749,12 +1780,12 @@
     int ret = prepare_fs_for_mount(entry.blk_device, entry, mount_point);
     // Wiped case doesn't require to try __mount below.
     if (ret & FS_STAT_INVALID_MAGIC) {
-      return FS_MGR_DOMNT_FAILED;
+        return FS_MGR_DOMNT_FAILED;
     }
 
     ret = __mount(entry.blk_device, mount_point, entry);
     if (ret) {
-      ret = (errno == EBUSY) ? FS_MGR_DOMNT_BUSY : FS_MGR_DOMNT_FAILED;
+        ret = (errno == EBUSY) ? FS_MGR_DOMNT_BUSY : FS_MGR_DOMNT_FAILED;
     }
 
     return ret;
diff --git a/fs_mgr/libfstab/fstab.cpp b/fs_mgr/libfstab/fstab.cpp
index 21d2e2e..d344b2d 100644
--- a/fs_mgr/libfstab/fstab.cpp
+++ b/fs_mgr/libfstab/fstab.cpp
@@ -39,6 +39,10 @@
 #include "fstab_priv.h"
 #include "logging_macros.h"
 
+#if !defined(MS_LAZYTIME)
+#define MS_LAZYTIME (1 << 25)
+#endif
+
 using android::base::EndsWith;
 using android::base::ParseByteCount;
 using android::base::ParseInt;
@@ -74,6 +78,7 @@
         {"private", MS_PRIVATE},
         {"slave", MS_SLAVE},
         {"shared", MS_SHARED},
+        {"lazytime", MS_LAZYTIME},
         {"defaults", 0},
 };
 
diff --git a/fs_mgr/libsnapshot/snapshotctl.cpp b/fs_mgr/libsnapshot/snapshotctl.cpp
index 23c3ccf..97a8cb2 100644
--- a/fs_mgr/libsnapshot/snapshotctl.cpp
+++ b/fs_mgr/libsnapshot/snapshotctl.cpp
@@ -255,6 +255,8 @@
     }
 
     LOG(INFO) << "Failed to find cow path: " << cow_device << " Checking the device for -img path";
+    // If the COW device exists only on /data
+    cow_device = partition_name + "-cow-img";
     if (!dm.GetDmDevicePathByName(cow_device, cow_path)) {
         LOG(ERROR) << "Failed to cow path: " << cow_device;
         return false;
diff --git a/fs_mgr/libsnapshot/snapuserd/Android.bp b/fs_mgr/libsnapshot/snapuserd/Android.bp
index 8d0bf7d..298fd9f 100644
--- a/fs_mgr/libsnapshot/snapuserd/Android.bp
+++ b/fs_mgr/libsnapshot/snapuserd/Android.bp
@@ -170,7 +170,7 @@
     recovery_available: true,
 }
 
-// This target will install to /system/bin/snapuserd_ramdisk
+// This target will install to /system/bin/snapuserd_ramdisk 
 // It will also create a symblink on /system/bin/snapuserd that point to
 // /system/bin/snapuserd_ramdisk .
 // This way, init can check if generic ramdisk copy exists.
diff --git a/fs_mgr/tests/fs_mgr_test.cpp b/fs_mgr/tests/fs_mgr_test.cpp
index bd3d6b5..6522c02 100644
--- a/fs_mgr/tests/fs_mgr_test.cpp
+++ b/fs_mgr/tests/fs_mgr_test.cpp
@@ -37,6 +37,10 @@
 using namespace android::fs_mgr;
 using namespace testing;
 
+#if !defined(MS_LAZYTIME)
+#define MS_LAZYTIME (1 << 25)
+#endif
+
 namespace {
 
 const std::string cmdline =
@@ -329,6 +333,7 @@
                 {"private", MS_PRIVATE},
                 {"slave", MS_SLAVE},
                 {"shared", MS_SHARED},
+                {"lazytime", MS_LAZYTIME},
                 {"defaults", 0},
                 {0, 0},
         };
diff --git a/init/keychords_test.cpp b/init/keychords_test.cpp
index 5789bf5..2b1d428 100644
--- a/init/keychords_test.cpp
+++ b/init/keychords_test.cpp
@@ -168,16 +168,16 @@
 const std::vector<int> triple1_chord = {KEY_BACKSPACE, KEY_VOLUMEDOWN, KEY_VOLUMEUP};
 const std::vector<int> triple2_chord = {KEY_VOLUMEDOWN, KEY_VOLUMEUP, KEY_BACK};
 
-const std::vector<const std::vector<int>> empty_chords;
-const std::vector<const std::vector<int>> chords = {
-    escape_chord,
-    triple1_chord,
-    triple2_chord,
+const std::vector<std::vector<int>> empty_chords;
+const std::vector<std::vector<int>> chords = {
+        escape_chord,
+        triple1_chord,
+        triple2_chord,
 };
 
 class TestFrame {
   public:
-    TestFrame(const std::vector<const std::vector<int>>& chords, EventHandler* ev = nullptr);
+    TestFrame(const std::vector<std::vector<int>>& chords, EventHandler* ev = nullptr);
 
     void RelaxForMs(std::chrono::milliseconds wait = 1ms);
 
@@ -194,16 +194,15 @@
     std::string Format() const;
 
   private:
-    static std::string Format(const std::vector<const std::vector<int>>& chords);
+    static std::string Format(const std::vector<std::vector<int>>& chords);
 
     Epoll epoll_;
     Keychords keychords_;
-    std::vector<const std::vector<int>> keycodes_;
+    std::vector<std::vector<int>> keycodes_;
     EventHandler* ev_;
 };
 
-TestFrame::TestFrame(const std::vector<const std::vector<int>>& chords, EventHandler* ev)
-    : ev_(ev) {
+TestFrame::TestFrame(const std::vector<std::vector<int>>& chords, EventHandler* ev) : ev_(ev) {
     if (!epoll_.Open().ok()) return;
     for (const auto& keycodes : chords) keychords_.Register(keycodes);
     keychords_.Start(&epoll_, [this](const std::vector<int>& keycodes) {
@@ -262,7 +261,7 @@
     for (int retry = 1000; retry && !IsChord(chord); --retry) RelaxForMs();
 }
 
-std::string TestFrame::Format(const std::vector<const std::vector<int>>& chords) {
+std::string TestFrame::Format(const std::vector<std::vector<int>>& chords) {
     std::string ret("{");
     if (!chords.empty()) {
         ret += android::base::Join(chords.front(), ' ');
diff --git a/libcutils/include/private/android_filesystem_config.h b/libcutils/include/private/android_filesystem_config.h
index ea61cc2..eeb0394 100644
--- a/libcutils/include/private/android_filesystem_config.h
+++ b/libcutils/include/private/android_filesystem_config.h
@@ -142,6 +142,7 @@
 #define AID_SECURITY_LOG_WRITER 1091 /* write to security log */
 #define AID_PRNG_SEEDER 1092         /* PRNG seeder daemon */
 #define AID_UPROBESTATS 1093         /* uid for uprobestats */
+#define AID_CROS_EC 1094             /* uid for accessing ChromeOS EC (cros_ec) */
 /* Changes to this file must be made in AOSP, *not* in internal branches. */
 
 #define AID_SHELL 2000 /* adb and debug shell user */
diff --git a/trusty/keymint/Android.bp b/trusty/keymint/Android.bp
index 1b87d80..5cdd381 100644
--- a/trusty/keymint/Android.bp
+++ b/trusty/keymint/Android.bp
@@ -20,7 +20,6 @@
 rust_defaults {
     name: "android.hardware.security.keymint-service.rust.trusty.default",
     relative_install_path: "hw",
-    vendor: true,
     srcs: [
         "src/keymint_hal_main.rs",
     ],
@@ -39,6 +38,7 @@
 
 rust_binary {
     name: "android.hardware.security.keymint-service.rust.trusty",
+    vendor: true,
     defaults: ["android.hardware.security.keymint-service.rust.trusty.default"],
     init_rc: ["android.hardware.security.keymint-service.rust.trusty.rc"],
     vintf_fragments: ["android.hardware.security.keymint-service.rust.trusty.xml"],
@@ -48,8 +48,10 @@
 }
 
 rust_binary {
-    name: "android.hardware.security.keymint-service.rust.trusty.nonsecure",
+    name: "android.hardware.security.keymint-service.rust.trusty.system.nonsecure",
+    system_ext_specific: true,
     defaults: ["android.hardware.security.keymint-service.rust.trusty.default"],
+    init_rc: ["android.hardware.security.keymint-service.rust.trusty.system.nonsecure.rc"],
     features: ["nonsecure"],
     rustlibs: [
         "libkmr_hal_nonsecure",
diff --git a/trusty/keymint/android.hardware.security.keymint-service.rust.trusty.system.nonsecure.rc b/trusty/keymint/android.hardware.security.keymint-service.rust.trusty.system.nonsecure.rc
new file mode 100644
index 0000000..318c13b
--- /dev/null
+++ b/trusty/keymint/android.hardware.security.keymint-service.rust.trusty.system.nonsecure.rc
@@ -0,0 +1,17 @@
+service system.keymint.rust-trusty.nonsecure \
+  /system_ext/bin/hw/android.hardware.security.keymint-service.rust.trusty.system.nonsecure \
+  --dev ${ro.hardware.trusty_ipc_dev.keymint:-/dev/trusty-ipc-dev0}
+    disabled
+    user nobody
+    group drmrpc
+    # The keymint service is not allowed to restart.
+    # If it crashes, a device restart is required.
+    oneshot
+
+# Only starts the non-secure KeyMint HALs when the KeyMint VM feature is enabled
+# TODO(b/357821690): Start the KeyMint HALs when the KeyMint VM is ready once the Trusty VM
+# has a mechanism to notify the host.
+on late-fs && property:ro.hardware.security.keymint.trusty.system=1 && \
+   property:ro.hardware.trusty_vm_cid=*
+    setprop ro.hardware.trusty_ipc_dev.keymint VSOCK:${ro.hardware.trusty_vm_cid}:1
+    start system.keymint.rust-trusty.nonsecure
diff --git a/trusty/keymint/trusty-keymint.mk b/trusty/keymint/trusty-keymint.mk
new file mode 100644
index 0000000..d5791ea
--- /dev/null
+++ b/trusty/keymint/trusty-keymint.mk
@@ -0,0 +1,43 @@
+#
+# 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.
+#
+
+#
+# This makefile should be included by devices that use Trusty TEE
+# to pull in a set of Trusty KeyMint specific modules.
+#
+# Allow KeyMint HAL service implementation selection at build time. This must be
+# synchronized with the TA implementation included in Trusty. Possible values:
+#
+# - Rust implementation for Trusty VM (requires Trusty VM support):
+#   export TRUSTY_KEYMINT_IMPL=rust
+#   export TRUSTY_SYSTEM_VM=nonsecure
+# - Rust implementation for Trusty TEE (no Trusty VM support):
+#   export TRUSTY_KEYMINT_IMPL=rust
+# - C++ implementation (default): (any other value or unset TRUSTY_KEYMINT_IMPL)
+
+ifeq ($(TRUSTY_KEYMINT_IMPL),rust)
+    ifeq ($(TRUSTY_SYSTEM_VM),nonsecure)
+        LOCAL_KEYMINT_PRODUCT_PACKAGE := android.hardware.security.keymint-service.rust.trusty.system.nonsecure
+    else
+        LOCAL_KEYMINT_PRODUCT_PACKAGE := android.hardware.security.keymint-service.rust.trusty
+    endif
+else
+    # Default to the C++ implementation
+    LOCAL_KEYMINT_PRODUCT_PACKAGE := android.hardware.security.keymint-service.trusty
+endif
+
+PRODUCT_PACKAGES += \
+    $(LOCAL_KEYMINT_PRODUCT_PACKAGE) \
diff --git a/trusty/trusty-base.mk b/trusty/trusty-base.mk
index b21eca6..9d810dc 100644
--- a/trusty/trusty-base.mk
+++ b/trusty/trusty-base.mk
@@ -22,18 +22,7 @@
 # For gatekeeper, we include the generic -service and -impl to use legacy
 # HAL loading of gatekeeper.trusty.
 
-# Allow the KeyMint HAL service implementation to be selected at build time.  This needs to be
-# done in sync with the TA implementation included in Trusty.  Possible values are:
-#
-# - Rust implementation:   export TRUSTY_KEYMINT_IMPL=rust
-# - C++ implementation:    (any other value of TRUSTY_KEYMINT_IMPL)
-
-ifeq ($(TRUSTY_KEYMINT_IMPL),rust)
-    LOCAL_KEYMINT_PRODUCT_PACKAGE := android.hardware.security.keymint-service.rust.trusty
-else
-    # Default to the C++ implementation
-    LOCAL_KEYMINT_PRODUCT_PACKAGE := android.hardware.security.keymint-service.trusty
-endif
+$(call inherit-product, system/core/trusty/keymint/trusty-keymint.mk)
 
 ifeq ($(SECRETKEEPER_ENABLED),true)
     LOCAL_SECRETKEEPER_PRODUCT_PACKAGE := android.hardware.security.secretkeeper.trusty
@@ -42,7 +31,6 @@
 endif
 
 PRODUCT_PACKAGES += \
-	$(LOCAL_KEYMINT_PRODUCT_PACKAGE) \
 	$(LOCAL_SECRETKEEPER_PRODUCT_PACKAGE) \
 	android.hardware.gatekeeper-service.trusty \
 	trusty_apploader \