Snap for 12296955 from 2edac1a8ddd4cab7d95618c32aa8ac2f7b1aedeb to 24Q4-release

Change-Id: I033d7189112006ec7782d46c4adb9cf929b685f2
diff --git a/fs_mgr/fs_mgr.cpp b/fs_mgr/fs_mgr.cpp
index 76578dd..6052699 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,34 @@
     return access(fs_mgr_metadata_encryption_in_progress_file_name(entry).c_str(), R_OK) == 0;
 }
 
+FstabEntry* LocateFormattableEntry(FstabEntry* const begin, FstabEntry* const end) {
+    const bool dev_option_enabled =
+            android::base::GetBoolProperty("ro.product.build.16k_page.enabled", false);
+    FstabEntry* f2fs_entry = nullptr;
+    for (auto iter = begin; iter->blk_device == begin->blk_device && iter < end; 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 +1567,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 +1618,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 +1647,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 +1661,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 +1777,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/include/fs_mgr/roots.h b/fs_mgr/include/fs_mgr/roots.h
index 65c59cf..e19f9ad 100644
--- a/fs_mgr/include/fs_mgr/roots.h
+++ b/fs_mgr/include/fs_mgr/roots.h
@@ -29,6 +29,8 @@
 // first match or nullptr.
 FstabEntry* GetEntryForPath(Fstab* fstab, const std::string& path);
 
+std::vector<FstabEntry*> GetEntriesForPath(Fstab* fstab, const std::string& path);
+
 // Make sure that the volume 'path' is on is mounted.
 // * If 'mount_point' is nullptr, use mount point in fstab. Caller can call
 //   fs_mgr_ensure_path_unmounted() with the same 'path' argument to unmount.
diff --git a/fs_mgr/libsnapshot/libsnapshot_cow/writer_v3.h b/fs_mgr/libsnapshot/libsnapshot_cow/writer_v3.h
index 871ed27..9e7cf7a2 100644
--- a/fs_mgr/libsnapshot/libsnapshot_cow/writer_v3.h
+++ b/fs_mgr/libsnapshot/libsnapshot_cow/writer_v3.h
@@ -82,7 +82,7 @@
                                                  CowOperationType type);
     size_t GetCompressionFactor(const size_t blocks_to_compress, CowOperationType type) const;
 
-    constexpr bool IsBlockAligned(const size_t size) {
+    constexpr bool IsBlockAligned(const uint64_t size) {
         // These are the only block size supported. Block size beyond 256k
         // may impact random read performance post OTA boot.
         const size_t values[] = {4_KiB, 8_KiB, 16_KiB, 32_KiB, 64_KiB, 128_KiB, 256_KiB};
diff --git a/fs_mgr/libsnapshot/snapuserd/user-space-merge/read_worker.h b/fs_mgr/libsnapshot/snapuserd/user-space-merge/read_worker.h
index 04b2736..378d809 100644
--- a/fs_mgr/libsnapshot/snapuserd/user-space-merge/read_worker.h
+++ b/fs_mgr/libsnapshot/snapuserd/user-space-merge/read_worker.h
@@ -57,7 +57,7 @@
     bool ReadFromSourceDevice(const CowOperation* cow_op, void* buffer);
     bool ReadDataFromBaseDevice(sector_t sector, void* buffer, size_t read_size);
 
-    constexpr bool IsBlockAligned(size_t size) { return ((size & (BLOCK_SZ - 1)) == 0); }
+    constexpr bool IsBlockAligned(uint64_t size) { return ((size & (BLOCK_SZ - 1)) == 0); }
     constexpr sector_t ChunkToSector(chunk_t chunk) { return chunk << CHUNK_SHIFT; }
     constexpr chunk_t SectorToChunk(sector_t sector) { return sector >> CHUNK_SHIFT; }
 
diff --git a/init/property_service.cpp b/init/property_service.cpp
index 4d3742a..f2606e3 100644
--- a/init/property_service.cpp
+++ b/init/property_service.cpp
@@ -1251,6 +1251,16 @@
     update_sys_usb_config();
 }
 
+void PropertyLoadDerivedDefaults() {
+    const char* PAGE_PROP = "ro.boot.hardware.cpu.pagesize";
+    if (GetProperty(PAGE_PROP, "").empty()) {
+        std::string error;
+        if (PropertySetNoSocket(PAGE_PROP, std::to_string(getpagesize()), &error) != PROP_SUCCESS) {
+            LOG(ERROR) << "Could not set '" << PAGE_PROP << "' because: " << error;
+        }
+    }
+}
+
 bool LoadPropertyInfoFromFile(const std::string& filename,
                               std::vector<PropertyInfoEntry>* property_infos) {
     auto file_contents = std::string();
@@ -1421,6 +1431,7 @@
     ExportKernelBootProps();
 
     PropertyLoadBootDefaults();
+    PropertyLoadDerivedDefaults();
 }
 
 static void HandleInitSocket() {
diff --git a/trusty/keymint/Android.bp b/trusty/keymint/Android.bp
index 92d9c6f..1b87d80 100644
--- a/trusty/keymint/Android.bp
+++ b/trusty/keymint/Android.bp
@@ -17,12 +17,10 @@
     default_applicable_licenses: ["Android-Apache-2.0"],
 }
 
-rust_binary {
-    name: "android.hardware.security.keymint-service.rust.trusty",
+rust_defaults {
+    name: "android.hardware.security.keymint-service.rust.trusty.default",
     relative_install_path: "hw",
     vendor: true,
-    init_rc: ["android.hardware.security.keymint-service.rust.trusty.rc"],
-    vintf_fragments: ["android.hardware.security.keymint-service.rust.trusty.xml"],
     srcs: [
         "src/keymint_hal_main.rs",
     ],
@@ -37,7 +35,23 @@
         "liblog_rust",
     ],
     prefer_rlib: true,
+}
+
+rust_binary {
+    name: "android.hardware.security.keymint-service.rust.trusty",
+    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"],
     required: [
         "android.hardware.hardware_keystore.xml",
     ],
 }
+
+rust_binary {
+    name: "android.hardware.security.keymint-service.rust.trusty.nonsecure",
+    defaults: ["android.hardware.security.keymint-service.rust.trusty.default"],
+    features: ["nonsecure"],
+    rustlibs: [
+        "libkmr_hal_nonsecure",
+    ],
+}
diff --git a/trusty/keymint/src/keymint_hal_main.rs b/trusty/keymint/src/keymint_hal_main.rs
index 3c5627b..a0b1d79 100644
--- a/trusty/keymint/src/keymint_hal_main.rs
+++ b/trusty/keymint/src/keymint_hal_main.rs
@@ -18,7 +18,7 @@
 use kmr_hal::{
     extract_rsp, keymint, rpc, secureclock, send_hal_info, sharedsecret, SerializedChannel,
 };
-use log::{error, info};
+use log::{error, info, warn};
 use std::{
     ffi::CString,
     ops::DerefMut,
@@ -109,7 +109,11 @@
         error!("{}", panic_info);
     }));
 
-    info!("Trusty KM HAL service is starting.");
+    if cfg!(feature = "nonsecure") {
+        warn!("Non-secure Trusty KM HAL service is starting.");
+    } else {
+        info!("Trusty KM HAL service is starting.");
+    }
 
     info!("Starting thread pool now.");
     binder::ProcessState::start_thread_pool();
@@ -126,6 +130,29 @@
         )?;
     let tipc_channel = Arc::new(Mutex::new(TipcChannel(connection)));
 
+    #[cfg(feature = "nonsecure")]
+    {
+        // When the non-secure feature is enabled, retrieve root-of-trust information
+        // (with the exception of the verified boot key hash) from Android properties, and
+        // populate the TA with this information. On a real device, the bootloader should
+        // provide this data to the TA directly.
+        let boot_req = kmr_hal_nonsecure::get_boot_info();
+        info!("boot/HAL->TA: boot info is {:?}", boot_req);
+        kmr_hal::send_boot_info(tipc_channel.lock().unwrap().deref_mut(), boot_req)
+            .map_err(|e| HalServiceError(format!("Failed to send boot info: {:?}", e)))?;
+        // When the non-secure feature is enabled, also retrieve device ID information
+        // (except for IMEI/MEID values) from Android properties and populate the TA with
+        // this information. On a real device, a factory provisioning process would populate
+        // this information.
+        let attest_ids = kmr_hal_nonsecure::attestation_id_info();
+        if let Err(e) =
+            kmr_hal::send_attest_ids(tipc_channel.lock().unwrap().deref_mut(), attest_ids)
+        {
+            error!("Failed to send attestation ID info: {:?}", e);
+        }
+        info!("Successfully sent non-secure boot info and attestation IDs to the TA.");
+    }
+
     // Register the Keymint service
     let km_service = keymint::Device::new_as_binder(tipc_channel.clone());
     let km_service_name = format!("{}/{}", KM_SERVICE_NAME, SERVICE_INSTANCE);