Snap for 8730993 from 3631a30920e393cd9608cc51ed2a3ea49d0bd620 to mainline-tzdata3-release

Change-Id: Ifd564ddb3b0a591e5a66362810b40596b807f286
diff --git a/Android.bp b/Android.bp
index 50618f9..6b0f829 100644
--- a/Android.bp
+++ b/Android.bp
@@ -39,8 +39,6 @@
 
 cc_library {
     name: "libgsi",
-    ramdisk_available: true,
-    vendor_ramdisk_available: true,
     recovery_available: true,
     host_supported: true,
     srcs: [
@@ -69,8 +67,6 @@
 cc_library_headers {
     name: "libgsi_headers",
     host_supported: true,
-    ramdisk_available: true,
-    vendor_ramdisk_available: true,
     recovery_available: true,
     vendor_available: true,
     export_include_dirs: ["include"],
diff --git a/OWNERS b/OWNERS
index 09f4d71..8a0a10e 100644
--- a/OWNERS
+++ b/OWNERS
@@ -1,4 +1,3 @@
-# Bug component: 30545
 dvander@google.com
 sspatil@google.com
 elsk@google.com
diff --git a/aidl/android/gsi/IGsiService.aidl b/aidl/android/gsi/IGsiService.aidl
index 3b5d6c0..c889987 100644
--- a/aidl/android/gsi/IGsiService.aidl
+++ b/aidl/android/gsi/IGsiService.aidl
@@ -74,10 +74,8 @@
     boolean commitGsiChunkFromAshmem(long bytes);
 
     /**
-     * Mark a completed DSU installation as bootable. The caller is responsible
-     * for rebooting the device as soon as possible.
-     *
-     * Could leave the installation in "disabled" state if failure.
+     * Complete a GSI installation and mark it as bootable. The caller is
+     * responsible for rebooting the device as soon as possible.
      *
      * @param oneShot       If true, the GSI will boot once and then disable itself.
      *                      It can still be re-enabled again later with setGsiBootable.
diff --git a/aidl/android/gsi/IImageService.aidl b/aidl/android/gsi/IImageService.aidl
index 363a919..c8c5a9d 100644
--- a/aidl/android/gsi/IImageService.aidl
+++ b/aidl/android/gsi/IImageService.aidl
@@ -135,11 +135,6 @@
     void removeDisabledImages();
 
     /**
-     * Return whether an image is disabled.
-     */
-    boolean isImageDisabled(@utf8InCpp String name);
-
-    /**
      * Return the block device path of a mapped image, or an empty string if not mapped.
      */
     @utf8InCpp String getMappedImageDevice(@utf8InCpp String name);
diff --git a/daemon.cpp b/daemon.cpp
index 2123599..a1ee809 100644
--- a/daemon.cpp
+++ b/daemon.cpp
@@ -59,9 +59,6 @@
         } else if (argv[1] == "dump-device-mapper"s) {
             int rc = DumpDeviceMapper();
             exit(rc);
-        } else if (argv[1] == "verify-image-maps"s) {
-            android::gsi::GsiService::VerifyImageMaps();
-            exit(0);
         }
     }
 
diff --git a/gsi_service.cpp b/gsi_service.cpp
index 3392a1d..939f603 100644
--- a/gsi_service.cpp
+++ b/gsi_service.cpp
@@ -36,7 +36,6 @@
 #include <android/os/IVold.h>
 #include <binder/IServiceManager.h>
 #include <binder/LazyServiceRegistrar.h>
-#include <cutils/android_reboot.h>
 #include <ext4_utils/ext4_utils.h>
 #include <fs_mgr.h>
 #include <libavb/libavb.h>
@@ -155,34 +154,13 @@
 binder::Status GsiService::closeInstall(int* _aidl_return) {
     ENFORCE_SYSTEM;
     std::lock_guard<std::mutex> guard(lock_);
-
-    installer_ = {};
-
     auto dsu_slot = GetDsuSlot(install_dir_);
     std::string file = GetCompleteIndication(dsu_slot);
     if (!WriteStringToFile("OK", file)) {
         PLOG(ERROR) << "write failed: " << file;
-        *_aidl_return = IGsiService::INSTALL_ERROR_GENERIC;
-        return binder::Status::ok();
+        *_aidl_return = INSTALL_ERROR_GENERIC;
     }
-
-    // Create installation complete marker files, but set disabled immediately.
-    if (!WriteStringToFile(dsu_slot, kDsuActiveFile)) {
-        PLOG(ERROR) << "cannot write active DSU slot (" << dsu_slot << "): " << kDsuActiveFile;
-        *_aidl_return = IGsiService::INSTALL_ERROR_GENERIC;
-        return binder::Status::ok();
-    }
-    RestoreconMetadataFiles();
-
-    // DisableGsi() creates the DSU install status file and mark it as "disabled".
-    if (!DisableGsi()) {
-        PLOG(ERROR) << "cannot write DSU status file: " << kDsuInstallStatusFile;
-        *_aidl_return = IGsiService::INSTALL_ERROR_GENERIC;
-        return binder::Status::ok();
-    }
-
-    SetProperty(kGsiInstalledProp, "1");
-    *_aidl_return = IGsiService::INSTALL_OK;
+    *_aidl_return = INSTALL_OK;
     return binder::Status::ok();
 }
 
@@ -238,8 +216,7 @@
         return binder::Status::ok();
     }
     // It is important to not reset |installer_| here because other methods such
-    // as isGsiInstallInProgress() relies on the state of |installer_|.
-    // TODO: Maybe don't do this, use a dedicated |in_progress_| flag?
+    // as enableGsi() relies on the state of |installer_|.
     *_aidl_return = installer_->FinishInstall();
     return binder::Status::ok();
 }
@@ -314,19 +291,41 @@
 
 binder::Status GsiService::enableGsiAsync(bool one_shot, const std::string& dsuSlot,
                                           const sp<IGsiServiceCallback>& resultCallback) {
-    ENFORCE_SYSTEM_OR_SHELL;
-    std::lock_guard<std::mutex> guard(lock_);
-
-    const auto result = EnableGsi(one_shot, dsuSlot);
+    int result;
+    auto status = enableGsi(one_shot, dsuSlot, &result);
+    if (!status.isOk()) {
+        LOG(ERROR) << "Could not enableGsi: " << status.exceptionMessage().string();
+        result = IGsiService::INSTALL_ERROR_GENERIC;
+    }
     resultCallback->onResult(result);
     return binder::Status::ok();
 }
 
 binder::Status GsiService::enableGsi(bool one_shot, const std::string& dsuSlot, int* _aidl_return) {
-    ENFORCE_SYSTEM_OR_SHELL;
     std::lock_guard<std::mutex> guard(lock_);
 
-    *_aidl_return = EnableGsi(one_shot, dsuSlot);
+    if (!WriteStringToFile(dsuSlot, kDsuActiveFile)) {
+        PLOG(ERROR) << "write failed: " << GetDsuSlot(install_dir_);
+        *_aidl_return = INSTALL_ERROR_GENERIC;
+        return binder::Status::ok();
+    }
+    RestoreconMetadataFiles();
+    if (installer_) {
+        ENFORCE_SYSTEM;
+        installer_ = {};
+        // Note: create the install status file last, since this is the actual boot
+        // indicator.
+        if (!SetBootMode(one_shot) || !CreateInstallStatusFile()) {
+            *_aidl_return = IGsiService::INSTALL_ERROR_GENERIC;
+        } else {
+            *_aidl_return = INSTALL_OK;
+        }
+    } else {
+        ENFORCE_SYSTEM_OR_SHELL;
+        *_aidl_return = ReenableGsi(one_shot);
+    }
+
+    installer_ = nullptr;
     return binder::Status::ok();
 }
 
@@ -516,12 +515,12 @@
     if (statvfs(install_dir_.c_str(), &info)) {
         PLOG(ERROR) << "Could not statvfs(" << install_dir_ << ")";
     } else {
-        uint64_t free_space = static_cast<uint64_t>(info.f_bavail) * info.f_frsize;
-        const auto free_space_threshold =
-                PartitionInstaller::GetMinimumFreeSpaceThreshold(install_dir_);
-        if (free_space_threshold.has_value() && free_space > *free_space_threshold) {
-            // Round down to multiples of filesystem block size.
-            size = (free_space - *free_space_threshold) / info.f_frsize * info.f_frsize;
+        // Keep the storage device at least 40% free, plus 1% for jitter.
+        constexpr int jitter = 1;
+        const uint64_t reserved_blocks =
+                static_cast<uint64_t>(info.f_blocks) * (kMinimumFreeSpaceThreshold + jitter) / 100;
+        if (info.f_bavail > reserved_blocks) {
+            size = (info.f_bavail - reserved_blocks) * info.f_frsize;
         }
     }
 
@@ -530,7 +529,7 @@
     return binder::Status::ok();
 }
 
-bool GsiService::ResetBootAttemptCounter() {
+bool GsiService::CreateInstallStatusFile() {
     if (!android::base::WriteStringToFile("0", kDsuInstallStatusFile)) {
         PLOG(ERROR) << "write " << kDsuInstallStatusFile;
         return false;
@@ -579,7 +578,6 @@
     binder::Status removeAllImages() override;
     binder::Status removeDisabledImages() override;
     binder::Status getMappedImageDevice(const std::string& name, std::string* device) override;
-    binder::Status isImageDisabled(const std::string& name, bool* _aidl_return) override;
 
   private:
     bool CheckUid();
@@ -750,14 +748,6 @@
     return binder::Status::ok();
 }
 
-binder::Status ImageService::isImageDisabled(const std::string& name, bool* _aidl_return) {
-    if (!CheckUid()) return UidSecurityError();
-
-    std::lock_guard<std::mutex> guard(service_->lock());
-    *_aidl_return = impl_->IsImageDisabled(name);
-    return binder::Status::ok();
-}
-
 binder::Status ImageService::getMappedImageDevice(const std::string& name, std::string* device) {
     if (!CheckUid()) return UidSecurityError();
 
@@ -931,6 +921,32 @@
     return kDefaultDsuImageFolder;
 }
 
+int GsiService::ReenableGsi(bool one_shot) {
+    if (!android::gsi::IsGsiInstalled()) {
+        LOG(ERROR) << "no gsi installed - cannot re-enable";
+        return INSTALL_ERROR_GENERIC;
+    }
+    std::string boot_key;
+    if (!GetInstallStatus(&boot_key)) {
+        PLOG(ERROR) << "read " << kDsuInstallStatusFile;
+        return INSTALL_ERROR_GENERIC;
+    }
+    if (boot_key != kInstallStatusDisabled) {
+        LOG(ERROR) << "GSI is not currently disabled";
+        return INSTALL_ERROR_GENERIC;
+    }
+    if (IsGsiRunning()) {
+        if (!SetBootMode(one_shot) || !CreateInstallStatusFile()) {
+            return IGsiService::INSTALL_ERROR_GENERIC;
+        }
+        return IGsiService::INSTALL_OK;
+    }
+    if (!SetBootMode(one_shot) || !CreateInstallStatusFile()) {
+        return IGsiService::INSTALL_ERROR_GENERIC;
+    }
+    return IGsiService::INSTALL_OK;
+}
+
 static android::sp<android::os::IVold> GetVoldService() {
     return android::waitForService<android::os::IVold>(android::String16("vold"));
 }
@@ -986,35 +1002,6 @@
     return ok;
 }
 
-int GsiService::EnableGsi(bool one_shot, const std::string& dsu_slot) {
-    if (!android::gsi::IsGsiInstalled()) {
-        LOG(ERROR) << "no gsi installed - cannot enable";
-        return IGsiService::INSTALL_ERROR_GENERIC;
-    }
-    if (installer_) {
-        LOG(ERROR) << "cannot enable an ongoing installation, was closeInstall() called?";
-        return IGsiService::INSTALL_ERROR_GENERIC;
-    }
-
-    if (!DisableGsi()) {
-        PLOG(ERROR) << "cannot write DSU status file";
-        return IGsiService::INSTALL_ERROR_GENERIC;
-    }
-    if (!SetBootMode(one_shot)) {
-        return IGsiService::INSTALL_ERROR_GENERIC;
-    }
-    if (!ResetBootAttemptCounter()) {
-        return IGsiService::INSTALL_ERROR_GENERIC;
-    }
-
-    if (!WriteStringToFile(dsu_slot, kDsuActiveFile)) {
-        PLOG(ERROR) << "cannot write active DSU slot (" << dsu_slot << "): " << kDsuActiveFile;
-        return IGsiService::INSTALL_ERROR_GENERIC;
-    }
-    RestoreconMetadataFiles();
-    return IGsiService::INSTALL_OK;
-}
-
 bool GsiService::DisableGsiInstall() {
     if (!android::gsi::IsGsiInstalled()) {
         LOG(ERROR) << "cannot disable gsi install - no install detected";
@@ -1113,28 +1100,6 @@
     }
 }
 
-void GsiService::VerifyImageMaps() {
-    std::vector<std::pair<std::string, std::string>> paths = {
-            {"/metadata/gsi/remount", "/data/gsi/remount"},
-            {"/metadata/gsi/ota", "/data/gsi/ota"},
-    };
-
-    for (const auto& [metadata_dir, data_dir] : paths) {
-        auto impl = ImageManager::Open(metadata_dir, data_dir);
-        if (!impl) {
-            LOG(ERROR) << "Could not open ImageManager for " << metadata_dir << " and " << data_dir;
-            continue;
-        }
-        if (!impl->ValidateImageMaps()) {
-            LOG(ERROR) << "ImageManager for " << metadata_dir
-                       << " failed validation, device data is at risk. Rebooting.";
-            android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,fastboot");
-            continue;
-        }
-        LOG(INFO) << "ImageManager verification passed for " << metadata_dir;
-    }
-}
-
 static bool GetAvbPublicKeyFromFd(int fd, AvbPublicKey* dst) {
     // Read the AVB footer from EOF.
     int64_t total_size = get_block_device_size(fd);
diff --git a/gsi_service.h b/gsi_service.h
index c50c101..c9e4e05 100644
--- a/gsi_service.h
+++ b/gsi_service.h
@@ -80,7 +80,6 @@
     bool should_abort() const { return should_abort_; }
 
     static void RunStartupTasks();
-    static void VerifyImageMaps();
     static std::string GetInstalledImageDir();
     std::string GetActiveDsuSlot();
     std::string GetActiveInstalledImageDir();
@@ -92,8 +91,8 @@
 
     GsiService();
     static int ValidateInstallParams(std::string& install_dir);
-    int EnableGsi(bool one_shot, const std::string& dsu_slot);
     bool DisableGsiInstall();
+    int ReenableGsi(bool one_shot);
     static void CleanCorruptedInstallation();
     static int SaveInstallation(const std::string&);
     static bool IsInstallationComplete(const std::string&);
@@ -101,11 +100,7 @@
 
     enum class AccessLevel { System, SystemOrShell };
     binder::Status CheckUid(AccessLevel level = AccessLevel::System);
-
-    // Mark install completion, and reset boot attempt counter.
-    // Next boot will try to boot into DSU.
-    bool ResetBootAttemptCounter();
-
+    bool CreateInstallStatusFile();
     bool SetBootMode(bool one_shot);
 
     static android::wp<GsiService> sInstance;
diff --git a/libgsi_private.h b/libgsi_private.h
index 51c7915..82814a9 100644
--- a/libgsi_private.h
+++ b/libgsi_private.h
@@ -28,5 +28,8 @@
 static constexpr char kInstallStatusWipe[] = "wipe";
 static constexpr char kInstallStatusDisabled[] = "disabled";
 
+// We are looking for /data to have at least 40% free space.
+static constexpr uint32_t kMinimumFreeSpaceThreshold = 40;
+
 }  // namespace gsi
 }  // namespace android
diff --git a/partition_installer.cpp b/partition_installer.cpp
index 5450169..79af71a 100644
--- a/partition_installer.cpp
+++ b/partition_installer.cpp
@@ -22,11 +22,9 @@
 #include <android-base/logging.h>
 #include <android-base/unique_fd.h>
 #include <ext4_utils/ext4_utils.h>
-#include <fs_mgr.h>
 #include <fs_mgr_dm_linear.h>
 #include <libdm/dm.h>
 #include <libgsi/libgsi.h>
-#include <liblp/partition_opener.h>
 
 #include "file_paths.h"
 #include "gsi_service.h"
@@ -129,18 +127,17 @@
     // This is the same as android::vold::GetFreebytes() but we also
     // need the total file system size so we open code it here.
     uint64_t free_space = static_cast<uint64_t>(sb.f_bavail) * sb.f_frsize;
+    uint64_t fs_size = static_cast<uint64_t>(sb.f_blocks) * sb.f_frsize;
     if (free_space <= (size_)) {
         LOG(ERROR) << "not enough free space (only " << free_space << " bytes available)";
         return IGsiService::INSTALL_ERROR_NO_SPACE;
     }
-
-    const auto free_space_threshold = GetMinimumFreeSpaceThreshold(install_dir_);
-    if (!free_space_threshold.has_value()) {
-        return IGsiService::INSTALL_ERROR_GENERIC;
-    }
-    if (free_space < size_ + *free_space_threshold) {
-        LOG(ERROR) << "post-installation free space (" << free_space << " - " << size_
-                   << ") would be below the minimum threshold of " << *free_space_threshold;
+    // We are asking for 40% of the /data to be empty.
+    // TODO: may be not hard code it like this
+    double free_space_percent = ((1.0 * free_space) / fs_size) * 100;
+    if (free_space_percent < kMinimumFreeSpaceThreshold) {
+        LOG(ERROR) << "free space " << static_cast<uint64_t>(free_space_percent)
+                   << "% is below the minimum threshold of " << kMinimumFreeSpaceThreshold << "%";
         return IGsiService::INSTALL_ERROR_FILE_SYSTEM_CLUTTERED;
     }
     return IGsiService::INSTALL_OK;
@@ -348,23 +345,5 @@
     return IGsiService::INSTALL_OK;
 }
 
-std::optional<uint64_t> PartitionInstaller::GetMinimumFreeSpaceThreshold(
-        const std::string& install_dir) {
-    // No need to retain any space if we were not installing to the internal storage.
-    if (!android::base::StartsWith(install_dir, "/data"s)) {
-        return 0;
-    }
-    // Dynamic Partitions device must have a "super" block device.
-    BlockDeviceInfo info;
-    PartitionOpener opener;
-    if (!opener.GetInfo(fs_mgr_get_super_partition_name(), &info)) {
-        // We shouldn't reach here, but handle it just in case.
-        LOG(ERROR) << "could not get block device info of super";
-        return std::nullopt;
-    }
-    // Reserve |super partition| of storage space so we don't disable VAB.
-    return info.size;
-}
-
 }  // namespace gsi
 }  // namespace android
diff --git a/partition_installer.h b/partition_installer.h
index 1cb9535..920af47 100644
--- a/partition_installer.h
+++ b/partition_installer.h
@@ -53,9 +53,6 @@
     static int WipeWritable(const std::string& active_dsu, const std::string& install_dir,
                             const std::string& name);
 
-    // Returns the minimum free space to reserve for /data.
-    static std::optional<uint64_t> GetMinimumFreeSpaceThreshold(const std::string& install_dir);
-
     // Finish a partition installation and release resources.
     // If the installation is incomplete or corrupted, the backing image would
     // be cleaned up and an error code is returned.
diff --git a/tests/Android.bp b/tests/Android.bp
index 5d90fd4..2cb67ab 100644
--- a/tests/Android.bp
+++ b/tests/Android.bp
@@ -51,9 +51,7 @@
         "vts",
     ],
     auto_gen_config: true,
-    test_options: {
-        min_shipping_api_level: 29,
-    },
+    test_min_api_level: 29,
     require_root: true,
 }
 
diff --git a/tests/boot_tests.cpp b/tests/boot_tests.cpp
index d002c89..a00e798 100644
--- a/tests/boot_tests.cpp
+++ b/tests/boot_tests.cpp
@@ -14,14 +14,6 @@
 // limitations under the License.
 //
 
-#include <linux/fs.h>
-#include <sys/stat.h>
-#include <sys/sysmacros.h>
-#include <sys/types.h>
-#include <sys/vfs.h>
-#include <unistd.h>
-
-#include <android-base/properties.h>
 #include <android-base/unique_fd.h>
 #include <android/hardware/weaver/1.0/IWeaver.h>
 #include <ext4_utils/ext4_utils.h>
@@ -48,10 +40,6 @@
     }
 }
 
-static int GetVsrLevel() {
-    return android::base::GetIntProperty("ro.vendor.api_level", -1);
-}
-
 TEST(MetadataPartition, MinimumSize) {
     Fstab fstab;
     ASSERT_TRUE(ReadDefaultFstab(&fstab));
@@ -63,11 +51,7 @@
     ASSERT_GE(fd, 0);
 
     uint64_t size = get_block_device_size(fd);
-    if (GetVsrLevel() >= __ANDROID_API_T__) {
-        ASSERT_GE(size, 67108864);
-    } else {
-        ASSERT_GE(size, 16777216);
-    }
+    EXPECT_GE(size, 16777216);
 }
 
 TEST(Weaver, MinimumSlots) {
@@ -87,30 +71,3 @@
     ASSERT_EQ(hw_status, WeaverStatus::OK);
     EXPECT_GE(hw_config.slots, 16);
 }
-
-TEST(MetadataPartition, FsType) {
-    if (GetVsrLevel() < __ANDROID_API_T__) {
-        GTEST_SKIP();
-    }
-
-    Fstab fstab;
-    ASSERT_TRUE(ReadDefaultFstab(&fstab));
-
-    std::vector<std::string> mount_points = {"/data", "/metadata"};
-    for (const auto& mount_point : mount_points) {
-        auto path = mount_point + "/gsi";
-
-        // These paths should not be symlinks.
-        struct stat s;
-        ASSERT_GE(lstat(path.c_str(), &s), 0) << path;
-        ASSERT_FALSE(S_ISLNK(s.st_mode));
-
-        struct statfs64 fs;
-        ASSERT_GE(statfs64(path.c_str(), &fs), 0) << path;
-        ASSERT_EQ(fs.f_type, F2FS_SUPER_MAGIC);
-
-        auto entry = GetEntryForMountPoint(&fstab, mount_point);
-        ASSERT_NE(entry, nullptr);
-        ASSERT_EQ(entry->fs_type, "f2fs");
-    }
-}