Merge "Revert^2 "Revise KeymasterMessage versioning system""
diff --git a/fastboot/fs.cpp b/fastboot/fs.cpp
index 8addcb6..458a7a1 100644
--- a/fastboot/fs.cpp
+++ b/fastboot/fs.cpp
@@ -168,6 +168,19 @@
     return exec_cmd(e2fsdroid_args[0], e2fsdroid_args.data(), nullptr);
 }
 
+enum {
+    // clang-format off
+    FSCK_SUCCESS                 = 0,
+    FSCK_ERROR_CORRECTED         = 1 << 0,
+    FSCK_SYSTEM_SHOULD_REBOOT    = 1 << 1,
+    FSCK_ERRORS_LEFT_UNCORRECTED = 1 << 2,
+    FSCK_OPERATIONAL_ERROR       = 1 << 3,
+    FSCK_USAGE_OR_SYNTAX_ERROR   = 1 << 4,
+    FSCK_USER_CANCELLED          = 1 << 5,
+    FSCK_SHARED_LIB_ERROR        = 1 << 7,
+    // clang-format on
+};
+
 static int generate_f2fs_image(const char* fileName, long long partSize,
                                const std::string& initial_dir, unsigned /* unused */,
                                unsigned /* unused */, const unsigned fsOptions) {
@@ -216,7 +229,11 @@
     std::vector<const char*> sload_args = {sload_path.c_str(), "-S",
                                        "-f", initial_dir.c_str(), fileName, nullptr};
 
-    return exec_cmd(sload_args[0], sload_args.data(), nullptr);
+    ret = exec_cmd(sload_args[0], sload_args.data(), nullptr);
+    if (ret != 0 && ret != FSCK_ERROR_CORRECTED) {
+        return -1;
+    }
+    return 0;
 }
 
 static const struct fs_generator {
diff --git a/fs_mgr/README.overlayfs.md b/fs_mgr/README.overlayfs.md
index ca782b9..94b2f8c 100644
--- a/fs_mgr/README.overlayfs.md
+++ b/fs_mgr/README.overlayfs.md
@@ -8,8 +8,8 @@
 system partition as read-write and then add or modify any number of files
 without reflashing the system image, which is efficient for a development cycle.
 
-Limited memory systems use read-only types of file systems or logical resizable
-Android partitions (LRAPs). These file systems land system partition images
+Limited memory systems use read-only types of file systems or dynamic
+Android partitions (DAPs). These file systems land system partition images
 right-sized, and have been deduped at the block level to compress the content.
 This means that a remount either isn’t possible, or isn't useful because of
 space limitations or support logistics.
diff --git a/fs_mgr/fs_mgr.cpp b/fs_mgr/fs_mgr.cpp
index 4c9fd9b..2876094 100644
--- a/fs_mgr/fs_mgr.cpp
+++ b/fs_mgr/fs_mgr.cpp
@@ -1324,6 +1324,7 @@
     int error_count = 0;
     CheckpointManager checkpoint_manager;
     AvbUniquePtr avb_handle(nullptr);
+    bool wiped = false;
 
     bool userdata_mounted = false;
     if (fstab->empty()) {
@@ -1457,7 +1458,8 @@
                 encryptable = status;
                 if (status == FS_MGR_MNTALL_DEV_NEEDS_METADATA_ENCRYPTION) {
                     if (!call_vdc({"cryptfs", "encryptFstab", attempted_entry.blk_device,
-                                   attempted_entry.mount_point},
+                                   attempted_entry.mount_point, wiped ? "true" : "false",
+                                   attempted_entry.fs_type},
                                   nullptr)) {
                         LERROR << "Encryption failed";
                         set_type_property(encryptable);
@@ -1474,7 +1476,7 @@
         }
 
         // Mounting failed, understand why and retry.
-        bool wiped = partition_wiped(current_entry.blk_device.c_str());
+        wiped = partition_wiped(current_entry.blk_device.c_str());
         bool crypt_footer = false;
         if (mount_errno != EBUSY && mount_errno != EACCES &&
             current_entry.fs_mgr_flags.formattable && wiped) {
@@ -1499,6 +1501,27 @@
             } else if (current_entry.is_encryptable() && current_entry.key_loc == KEY_IN_FOOTER) {
                 crypt_footer = true;
             }
+
+            // EncryptInplace will be used when vdc gives an error or needs to format partitions
+            // other than /data
+            if (should_use_metadata_encryption(current_entry) &&
+                current_entry.mount_point == "/data") {
+
+                // vdc->Format requires "ro.crypto.type" to set an encryption flag
+                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},
+                              nullptr)) {
+                    LERROR << "Encryption failed";
+                } else {
+                    userdata_mounted = true;
+                    continue;
+                }
+            }
+
             if (fs_mgr_do_format(current_entry, crypt_footer) == 0) {
                 // Let's replay the mount actions.
                 i = top_idx - 1;
diff --git a/fs_mgr/libsnapshot/Android.bp b/fs_mgr/libsnapshot/Android.bp
index f0adbea..d36a7f0 100644
--- a/fs_mgr/libsnapshot/Android.bp
+++ b/fs_mgr/libsnapshot/Android.bp
@@ -441,6 +441,7 @@
     system_shared_libs: [],
     ramdisk_available: true,
     vendor_ramdisk_available: true,
+    recovery_available: true,
 }
 
 cc_test {
diff --git a/fs_mgr/libsnapshot/cow_api_test.cpp b/fs_mgr/libsnapshot/cow_api_test.cpp
index 35020f4..defe8d4 100644
--- a/fs_mgr/libsnapshot/cow_api_test.cpp
+++ b/fs_mgr/libsnapshot/cow_api_test.cpp
@@ -171,6 +171,70 @@
     ASSERT_TRUE(iter->Done());
 }
 
+TEST_F(CowTest, ClusterCompressGz) {
+    CowOptions options;
+    options.compression = "gz";
+    options.cluster_ops = 2;
+    CowWriter writer(options);
+
+    ASSERT_TRUE(writer.Initialize(cow_->fd));
+
+    std::string data = "This is some data, believe it";
+    data.resize(options.block_size, '\0');
+    ASSERT_TRUE(writer.AddRawBlocks(50, data.data(), data.size()));
+
+    std::string data2 = "More data!";
+    data2.resize(options.block_size, '\0');
+    ASSERT_TRUE(writer.AddRawBlocks(51, data2.data(), data2.size()));
+
+    ASSERT_TRUE(writer.Finalize());
+
+    ASSERT_EQ(lseek(cow_->fd, 0, SEEK_SET), 0);
+
+    CowReader reader;
+    ASSERT_TRUE(reader.Parse(cow_->fd));
+
+    auto iter = reader.GetOpIter();
+    ASSERT_NE(iter, nullptr);
+    ASSERT_FALSE(iter->Done());
+    auto op = &iter->Get();
+
+    StringSink sink;
+
+    ASSERT_EQ(op->type, kCowReplaceOp);
+    ASSERT_EQ(op->compression, kCowCompressGz);
+    ASSERT_EQ(op->data_length, 56);  // compressed!
+    ASSERT_EQ(op->new_block, 50);
+    ASSERT_TRUE(reader.ReadData(*op, &sink));
+    ASSERT_EQ(sink.stream(), data);
+
+    iter->Next();
+    ASSERT_FALSE(iter->Done());
+    op = &iter->Get();
+
+    ASSERT_EQ(op->type, kCowClusterOp);
+
+    iter->Next();
+    ASSERT_FALSE(iter->Done());
+    op = &iter->Get();
+
+    sink.Reset();
+    ASSERT_EQ(op->compression, kCowCompressGz);
+    ASSERT_EQ(op->data_length, 41);  // compressed!
+    ASSERT_EQ(op->new_block, 51);
+    ASSERT_TRUE(reader.ReadData(*op, &sink));
+    ASSERT_EQ(sink.stream(), data2);
+
+    iter->Next();
+    ASSERT_FALSE(iter->Done());
+    op = &iter->Get();
+
+    ASSERT_EQ(op->type, kCowClusterOp);
+
+    iter->Next();
+    ASSERT_TRUE(iter->Done());
+}
+
 TEST_F(CowTest, CompressTwoBlocks) {
     CowOptions options;
     options.compression = "gz";
diff --git a/fs_mgr/libsnapshot/cow_writer.cpp b/fs_mgr/libsnapshot/cow_writer.cpp
index 8535252..c1a5f32 100644
--- a/fs_mgr/libsnapshot/cow_writer.cpp
+++ b/fs_mgr/libsnapshot/cow_writer.cpp
@@ -433,11 +433,6 @@
 }
 
 bool CowWriter::WriteOperation(const CowOperation& op, const void* data, size_t size) {
-    // If there isn't room for this op and the cluster end op, end the current cluster
-    if (cluster_size_ && op.type != kCowClusterOp &&
-        cluster_size_ < current_cluster_size_ + 2 * sizeof(op)) {
-        if (!EmitCluster()) return false;
-    }
     if (lseek(fd_.get(), next_op_pos_, SEEK_SET) < 0) {
         PLOG(ERROR) << "lseek failed for writing operation.";
         return false;
@@ -449,6 +444,11 @@
         if (!WriteRawData(data, size)) return false;
     }
     AddOperation(op);
+    // If there isn't room for another op and the cluster end op, end the current cluster
+    if (cluster_size_ && op.type != kCowClusterOp &&
+        cluster_size_ < current_cluster_size_ + 2 * sizeof(op)) {
+        if (!EmitCluster()) return false;
+    }
     return true;
 }
 
diff --git a/fs_mgr/libsnapshot/inspect_cow.cpp b/fs_mgr/libsnapshot/inspect_cow.cpp
index 5ad61f3..453b5c6 100644
--- a/fs_mgr/libsnapshot/inspect_cow.cpp
+++ b/fs_mgr/libsnapshot/inspect_cow.cpp
@@ -36,10 +36,30 @@
 }
 
 static void usage(void) {
-    LOG(ERROR) << "Usage: inspect_cow [-s] <COW_FILE>";
+    LOG(ERROR) << "Usage: inspect_cow [-sd] <COW_FILE>";
+    LOG(ERROR) << "\t -s Run Silent";
+    LOG(ERROR) << "\t -d Attempt to decompress\n";
 }
 
-static bool Inspect(const std::string& path, bool silent) {
+// Sink that always appends to the end of a string.
+class StringSink : public IByteSink {
+  public:
+    void* GetBuffer(size_t requested, size_t* actual) override {
+        size_t old_size = stream_.size();
+        stream_.resize(old_size + requested, '\0');
+        *actual = requested;
+        return stream_.data() + old_size;
+    }
+    bool ReturnData(void*, size_t) override { return true; }
+    void Reset() { stream_.clear(); }
+
+    std::string& stream() { return stream_; }
+
+  private:
+    std::string stream_;
+};
+
+static bool Inspect(const std::string& path, bool silent, bool decompress) {
     android::base::unique_fd fd(open(path.c_str(), O_RDONLY));
     if (fd < 0) {
         PLOG(ERROR) << "open failed: " << path;
@@ -76,15 +96,25 @@
     }
 
     auto iter = reader.GetOpIter();
+    StringSink sink;
+    bool success = true;
     while (!iter->Done()) {
         const CowOperation& op = iter->Get();
 
         if (!silent) std::cout << op << "\n";
 
+        if (decompress && op.type == kCowReplaceOp && op.compression != kCowCompressNone) {
+            if (!reader.ReadData(op, &sink)) {
+                std::cerr << "Failed to decompress for :" << op << "\n";
+                success = false;
+            }
+            sink.Reset();
+        }
+
         iter->Next();
     }
 
-    return true;
+    return success;
 }
 
 }  // namespace snapshot
@@ -93,11 +123,15 @@
 int main(int argc, char** argv) {
     int ch;
     bool silent = false;
-    while ((ch = getopt(argc, argv, "s")) != -1) {
+    bool decompress = false;
+    while ((ch = getopt(argc, argv, "sd")) != -1) {
         switch (ch) {
             case 's':
                 silent = true;
                 break;
+            case 'd':
+                decompress = true;
+                break;
             default:
                 android::snapshot::usage();
         }
@@ -109,7 +143,7 @@
         return 1;
     }
 
-    if (!android::snapshot::Inspect(argv[optind], silent)) {
+    if (!android::snapshot::Inspect(argv[optind], silent, decompress)) {
         return 1;
     }
     return 0;
diff --git a/init/mount_namespace.cpp b/init/mount_namespace.cpp
index 59cc140..ec48cde 100644
--- a/init/mount_namespace.cpp
+++ b/init/mount_namespace.cpp
@@ -115,22 +115,29 @@
         return {};
     }
     dirent* entry;
+    std::vector<std::string> entries;
+
     while ((entry = readdir(dir.get())) != nullptr) {
         if (entry->d_name[0] == '.') continue;
         if (entry->d_type == DT_DIR) {
-            const std::string apex_path = from_dir + "/" + entry->d_name;
-            const auto apex_manifest = GetApexManifest(apex_path);
-            if (!apex_manifest.ok()) {
-                LOG(ERROR) << apex_path << " is not an APEX directory: " << apex_manifest.error();
-                continue;
-            }
-            const std::string mount_path = to_dir + "/" + apex_manifest->name();
-            if (auto result = MountDir(apex_path, mount_path); !result.ok()) {
-                return result;
-            }
-            on_activate(apex_path, *apex_manifest);
+            entries.push_back(entry->d_name);
         }
     }
+
+    std::sort(entries.begin(), entries.end());
+    for (const auto& name : entries) {
+        const std::string apex_path = from_dir + "/" + name;
+        const auto apex_manifest = GetApexManifest(apex_path);
+        if (!apex_manifest.ok()) {
+            LOG(ERROR) << apex_path << " is not an APEX directory: " << apex_manifest.error();
+            continue;
+        }
+        const std::string mount_path = to_dir + "/" + apex_manifest->name();
+        if (auto result = MountDir(apex_path, mount_path); !result.ok()) {
+            return result;
+        }
+        on_activate(apex_path, *apex_manifest);
+    }
     return {};
 }
 
diff --git a/libnetutils/Android.bp b/libnetutils/Android.bp
index 65371fa..eec2415 100644
--- a/libnetutils/Android.bp
+++ b/libnetutils/Android.bp
@@ -21,6 +21,11 @@
     cflags: ["-Werror"],
 
     export_include_dirs: ["include"],
+    // TODO: remove connectivity module dependency, or have this lib build against the ndk
+    apex_available: [
+        "//apex_available:platform",
+        "com.android.tethering",
+    ],
 }
 
 cc_library_static {
diff --git a/libprocessgroup/profiles/cgroups.json b/libprocessgroup/profiles/cgroups.json
index 792af6f..5b7a28a 100644
--- a/libprocessgroup/profiles/cgroups.json
+++ b/libprocessgroup/profiles/cgroups.json
@@ -42,7 +42,7 @@
     "Controllers": [
       {
         "Controller": "freezer",
-        "Path": ".",
+        "Path": "freezer",
         "Mode": "0755",
         "UID": "system",
         "GID": "system"
diff --git a/libprocessgroup/profiles/task_profiles.json b/libprocessgroup/profiles/task_profiles.json
index 628098b..5b57bdd 100644
--- a/libprocessgroup/profiles/task_profiles.json
+++ b/libprocessgroup/profiles/task_profiles.json
@@ -46,7 +46,7 @@
       "File": "cpu.uclamp.latency_sensitive"
     },
     {
-      "Name": "Freezer",
+      "Name": "FreezerState",
       "Controller": "freezer",
       "File": "cgroup.freeze"
     }
@@ -70,11 +70,11 @@
       "Name": "Frozen",
       "Actions": [
         {
-          "Name": "SetAttribute",
+          "Name": "JoinCgroup",
           "Params":
           {
-            "Name": "Freezer",
-            "Value": "1"
+            "Controller": "freezer",
+            "Path": ""
           }
         }
       ]
@@ -83,11 +83,11 @@
       "Name": "Unfrozen",
       "Actions": [
         {
-          "Name": "SetAttribute",
+          "Name": "JoinCgroup",
           "Params":
           {
-            "Name": "Freezer",
-            "Value": "0"
+            "Controller": "freezer",
+            "Path": "../"
           }
         }
       ]
diff --git a/libsparse/Android.bp b/libsparse/Android.bp
index 860b9ae..5b6ce41 100644
--- a/libsparse/Android.bp
+++ b/libsparse/Android.bp
@@ -28,6 +28,10 @@
             enabled: true,
         },
     },
+    apex_available: [
+        "//apex_available:platform",
+        "com.android.virt",
+    ],
 }
 
 cc_binary {
diff --git a/rootdir/Android.mk b/rootdir/Android.mk
index 17d71f7..73d1101 100644
--- a/rootdir/Android.mk
+++ b/rootdir/Android.mk
@@ -69,7 +69,7 @@
 
 EXPORT_GLOBAL_CLANG_COVERAGE_OPTIONS :=
 ifeq ($(CLANG_COVERAGE),true)
-  EXPORT_GLOBAL_CLANG_COVERAGE_OPTIONS := export LLVM_PROFILE_FILE /data/misc/trace/clang-%p-%m.profraw
+  EXPORT_GLOBAL_CLANG_COVERAGE_OPTIONS := export LLVM_PROFILE_FILE /data/misc/trace/clang-%20m.profraw
 endif
 
 # Put it here instead of in init.rc module definition,
diff --git a/rootdir/avb/Android.bp b/rootdir/avb/Android.bp
index 85d2786..8c7caf3 100644
--- a/rootdir/avb/Android.bp
+++ b/rootdir/avb/Android.bp
@@ -18,3 +18,10 @@
         "s-gsi.avbpubkey",
     ],
 }
+
+filegroup {
+    name: "qcar-gsi_avbpubkey",
+    srcs: [
+        "qcar-gsi.avbpubkey",
+    ],
+}
diff --git a/rootdir/avb/Android.mk b/rootdir/avb/Android.mk
index c8fc1d6..f71f205 100644
--- a/rootdir/avb/Android.mk
+++ b/rootdir/avb/Android.mk
@@ -80,4 +80,15 @@
 
 include $(BUILD_PREBUILT)
 
+#######################################
+# qcar-gsi.avbpubkey
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := qcar-gsi.avbpubkey
+LOCAL_MODULE_CLASS := ETC
+LOCAL_SRC_FILES := $(LOCAL_MODULE)
+LOCAL_MODULE_PATH := $(my_gsi_avb_keys_path)
+
+include $(BUILD_PREBUILT)
+
 my_gsi_avb_keys_path :=
diff --git a/rootdir/avb/qcar-gsi.avbpubkey b/rootdir/avb/qcar-gsi.avbpubkey
new file mode 100644
index 0000000..ce56646
--- /dev/null
+++ b/rootdir/avb/qcar-gsi.avbpubkey
Binary files differ
diff --git a/rootdir/init.rc b/rootdir/init.rc
index d033afc..aa3aa1f 100644
--- a/rootdir/init.rc
+++ b/rootdir/init.rc
@@ -635,20 +635,21 @@
     mkdir /data/bootchart 0755 shell shell encryption=Require
     bootchart start
 
-    # Make sure that apexd is started in the default namespace
-    enter_default_mount_ns
-
     mkdir /data/vendor 0771 root root encryption=Require
     mkdir /data/vendor_ce 0771 root root encryption=None
     mkdir /data/vendor_de 0771 root root encryption=None
     mkdir /data/vendor/hardware 0771 root root
 
     # Start tombstoned early to be able to store tombstones.
+    mkdir /data/anr 0775 system system encryption=Require
     mkdir /data/tombstones 0771 system system encryption=Require
     mkdir /data/vendor/tombstones 0771 root root
     mkdir /data/vendor/tombstones/wifi 0771 wifi wifi
     start tombstoned
 
+    # Make sure that apexd is started in the default namespace
+    enter_default_mount_ns
+
     # /data/apex is now available. Start apexd to scan and activate APEXes.
     mkdir /data/apex 0755 root system encryption=None
     mkdir /data/apex/active 0755 root system
@@ -781,8 +782,6 @@
     # the following directory.
     mkdir /data/mediadrm 0770 mediadrm mediadrm encryption=Require
 
-    mkdir /data/anr 0775 system system encryption=Require
-
     # NFC: create data/nfc for nv storage
     mkdir /data/nfc 0770 nfc nfc encryption=Require
     mkdir /data/nfc/param 0770 nfc nfc
diff --git a/trusty/coverage/Android.bp b/trusty/coverage/Android.bp
index 3d2caa6..6038d44 100644
--- a/trusty/coverage/Android.bp
+++ b/trusty/coverage/Android.bp
@@ -14,6 +14,7 @@
 
 cc_library {
     name: "libtrusty_coverage",
+    vendor_available: true,
     srcs: [
         "coverage.cpp",
     ],
@@ -21,8 +22,9 @@
         "include",
     ],
     static_libs: [
-        "libtrusty_test",
+        "libtrusty",
     ],
+
     shared_libs: [
         "libbase",
         "liblog",
@@ -36,7 +38,7 @@
     ],
     static_libs: [
         "libtrusty_coverage",
-        "libtrusty_test",
+        "libtrusty",
     ],
     shared_libs: [
         "libbase",
diff --git a/trusty/fuzz/Android.bp b/trusty/fuzz/Android.bp
index 4df77af..ad13816 100644
--- a/trusty/fuzz/Android.bp
+++ b/trusty/fuzz/Android.bp
@@ -39,7 +39,7 @@
     export_include_dirs: ["include"],
     static_libs: [
         "libFuzzer",
-        "libtrusty_test",
+        "libtrusty",
     ],
     shared_libs: [
         "libtrusty_coverage",
diff --git a/trusty/libtrusty/Android.bp b/trusty/libtrusty/Android.bp
index 708fdbd..e0161a5 100644
--- a/trusty/libtrusty/Android.bp
+++ b/trusty/libtrusty/Android.bp
@@ -26,13 +26,8 @@
 
 cc_library {
     name: "libtrusty",
-    vendor: true,
-    defaults: ["libtrusty_defaults"],
-}
-
-// TODO(b/170753563): cc_fuzz can't deal with vendor components. Build libtrusty
-// for system.
-cc_test_library {
-    name: "libtrusty_test",
+    // TODO(b/170753563): cc_fuzz can't deal with vendor components. Build
+    // libtrusty for system and vendor.
+    vendor_available: true,
     defaults: ["libtrusty_defaults"],
 }