blob: b2954420ee26655f1f0395513d23f8e219e601c6 [file] [log] [blame]
Yifan Hong537802d2018-08-15 13:15:42 -07001//
2// Copyright (C) 2018 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
16
Amin Hassaniec7bc112020-10-29 16:47:58 -070017#include "update_engine/aosp/dynamic_partition_control_android.h"
Yifan Hong537802d2018-08-15 13:15:42 -070018
Kelvin Zhang91d95fa2020-11-05 13:52:00 -050019#include <algorithm>
Yifan Hong420db9b2019-07-23 20:50:33 -070020#include <chrono> // NOLINT(build/c++11) - using libsnapshot / liblp API
Kelvin Zhang34618522020-09-28 09:21:02 -040021#include <cstdint>
Yifan Hong13d41cb2019-09-16 13:18:22 -070022#include <map>
Yifan Hong537802d2018-08-15 13:15:42 -070023#include <memory>
24#include <set>
25#include <string>
Tianjie99d570d2020-06-04 14:57:19 -070026#include <string_view>
27#include <utility>
Yifan Hong012508e2019-07-22 18:30:40 -070028#include <vector>
Yifan Hong537802d2018-08-15 13:15:42 -070029
30#include <android-base/properties.h>
31#include <android-base/strings.h>
32#include <base/files/file_util.h>
33#include <base/logging.h>
Yifan Hong012508e2019-07-22 18:30:40 -070034#include <base/strings/string_util.h>
Yifan Hong3a1293a2021-04-16 13:21:20 -070035#include <base/strings/stringprintf.h>
Yifan Hong537802d2018-08-15 13:15:42 -070036#include <bootloader_message/bootloader_message.h>
Yifan Hong012508e2019-07-22 18:30:40 -070037#include <fs_mgr.h>
Yifan Hong537802d2018-08-15 13:15:42 -070038#include <fs_mgr_dm_linear.h>
Yifan Hong3a1a5612019-11-05 16:34:32 -080039#include <fs_mgr_overlayfs.h>
Yifan Hong29692902020-03-26 12:47:05 -070040#include <libavb/libavb.h>
Yifan Hong3a1a5612019-11-05 16:34:32 -080041#include <libdm/dm.h>
Kelvin Zhang34618522020-09-28 09:21:02 -040042#include <liblp/liblp.h>
43#include <libsnapshot/cow_writer.h>
Yifan Hong420db9b2019-07-23 20:50:33 -070044#include <libsnapshot/snapshot.h>
Yifan Hongf9cb4492020-04-15 13:00:20 -070045#include <libsnapshot/snapshot_stub.h>
Yifan Hong537802d2018-08-15 13:15:42 -070046
Amin Hassaniec7bc112020-10-29 16:47:58 -070047#include "update_engine/aosp/cleanup_previous_update_action.h"
48#include "update_engine/aosp/dynamic_partition_utils.h"
Yifan Hong537802d2018-08-15 13:15:42 -070049#include "update_engine/common/boot_control_interface.h"
Kelvin Zhangb9a5f612021-01-22 14:34:05 -050050#include "update_engine/common/dynamic_partition_control_interface.h"
51#include "update_engine/common/platform_constants.h"
Yifan Hong537802d2018-08-15 13:15:42 -070052#include "update_engine/common/utils.h"
Kelvin Zhang21a49912021-03-12 14:28:33 -050053#include "update_engine/payload_consumer/cow_writer_file_descriptor.h"
Yifan Hong6a6d0f12020-03-11 13:20:52 -070054#include "update_engine/payload_consumer/delta_performer.h"
Yifan Hong537802d2018-08-15 13:15:42 -070055
56using android::base::GetBoolProperty;
Yifan Hong29692902020-03-26 12:47:05 -070057using android::base::GetProperty;
Yifan Hong537802d2018-08-15 13:15:42 -070058using android::base::Join;
59using android::dm::DeviceMapper;
60using android::dm::DmDeviceState;
61using android::fs_mgr::CreateLogicalPartition;
David Andersonbb90dfb2019-08-13 14:14:56 -070062using android::fs_mgr::CreateLogicalPartitionParams;
Yifan Hong537802d2018-08-15 13:15:42 -070063using android::fs_mgr::DestroyLogicalPartition;
Yifan Hong29692902020-03-26 12:47:05 -070064using android::fs_mgr::Fstab;
Yifan Hong537802d2018-08-15 13:15:42 -070065using android::fs_mgr::MetadataBuilder;
Yifan Hong012508e2019-07-22 18:30:40 -070066using android::fs_mgr::Partition;
Yifan Hong6e706b12018-11-09 16:50:51 -080067using android::fs_mgr::PartitionOpener;
Yifan Hong012508e2019-07-22 18:30:40 -070068using android::fs_mgr::SlotSuffixForSlotNumber;
Yifan Hongf5261562020-03-10 10:28:10 -070069using android::snapshot::OptimizeSourceCopyOperation;
Yifan Hong0850bca2020-01-16 15:14:07 -080070using android::snapshot::Return;
Yifan Hongf033ecb2020-01-07 18:13:56 -080071using android::snapshot::SnapshotManager;
Yifan Hongf9cb4492020-04-15 13:00:20 -070072using android::snapshot::SnapshotManagerStub;
Yifan Hong2257ee12020-01-13 18:33:00 -080073using android::snapshot::UpdateState;
Yifan Hong3a1293a2021-04-16 13:21:20 -070074using base::StringPrintf;
Yifan Hong537802d2018-08-15 13:15:42 -070075
76namespace chromeos_update_engine {
77
Yifan Hong6e706b12018-11-09 16:50:51 -080078constexpr char kUseDynamicPartitions[] = "ro.boot.dynamic_partitions";
79constexpr char kRetrfoitDynamicPartitions[] =
80 "ro.boot.dynamic_partitions_retrofit";
Yifan Hong413d5722019-07-23 14:21:09 -070081constexpr char kVirtualAbEnabled[] = "ro.virtual_ab.enabled";
82constexpr char kVirtualAbRetrofit[] = "ro.virtual_ab.retrofit";
Kelvin Zhangda1b3142020-09-24 17:09:02 -040083constexpr char kVirtualAbCompressionEnabled[] =
84 "ro.virtual_ab.compression.enabled";
Kelvin Zhang1c4b9812022-04-06 17:29:00 -070085constexpr auto&& kVirtualAbCompressionXorEnabled =
86 "ro.virtual_ab.compression.xor.enabled";
David Andersone35b4382022-03-08 23:18:29 -080087constexpr char kVirtualAbUserspaceSnapshotsEnabled[] =
88 "ro.virtual_ab.userspace.snapshots.enabled";
Kelvin Zhangda1b3142020-09-24 17:09:02 -040089
90// Currently, android doesn't have a retrofit prop for VAB Compression. However,
91// struct FeatureFlag forces us to determine if a feature is 'retrofit'. So this
92// is here just to simplify code. Replace it with real retrofit prop name once
93// there is one.
94constexpr char kVirtualAbCompressionRetrofit[] = "";
Yifan Hong29692902020-03-26 12:47:05 -070095constexpr char kPostinstallFstabPrefix[] = "ro.postinstall.fstab.prefix";
Yifan Hong420db9b2019-07-23 20:50:33 -070096// Map timeout for dynamic partitions.
97constexpr std::chrono::milliseconds kMapTimeout{1000};
98// Map timeout for dynamic partitions with snapshots. Since several devices
99// needs to be mapped, this timeout is longer than |kMapTimeout|.
Kelvin Zhangcf3280b2021-09-01 19:36:01 -0700100constexpr std::chrono::milliseconds kMapSnapshotTimeout{10000};
Yifan Hong420db9b2019-07-23 20:50:33 -0700101
Yifan Hong537802d2018-08-15 13:15:42 -0700102DynamicPartitionControlAndroid::~DynamicPartitionControlAndroid() {
Yifan Hongbae27842019-10-24 16:56:12 -0700103 Cleanup();
Yifan Hong537802d2018-08-15 13:15:42 -0700104}
105
Yifan Hong186bb682019-07-23 14:04:39 -0700106static FeatureFlag GetFeatureFlag(const char* enable_prop,
107 const char* retrofit_prop) {
Kelvin Zhangda1b3142020-09-24 17:09:02 -0400108 // Default retrofit to false if retrofit_prop is empty.
109 bool retrofit = retrofit_prop && retrofit_prop[0] != '\0' &&
110 GetBoolProperty(retrofit_prop, false);
Yifan Hong186bb682019-07-23 14:04:39 -0700111 bool enabled = GetBoolProperty(enable_prop, false);
112 if (retrofit && !enabled) {
113 LOG(ERROR) << retrofit_prop << " is true but " << enable_prop
114 << " is not. These sysprops are inconsistent. Assume that "
115 << enable_prop << " is true from now on.";
116 }
117 if (retrofit) {
118 return FeatureFlag(FeatureFlag::Value::RETROFIT);
119 }
120 if (enabled) {
121 return FeatureFlag(FeatureFlag::Value::LAUNCH);
122 }
123 return FeatureFlag(FeatureFlag::Value::NONE);
Yifan Hong537802d2018-08-15 13:15:42 -0700124}
125
Kelvin Zhangebd115e2021-03-08 16:10:25 -0500126DynamicPartitionControlAndroid::DynamicPartitionControlAndroid(
127 uint32_t source_slot)
Yifan Hongb38e1af2019-10-17 14:59:22 -0700128 : dynamic_partitions_(
129 GetFeatureFlag(kUseDynamicPartitions, kRetrfoitDynamicPartitions)),
Kelvin Zhangda1b3142020-09-24 17:09:02 -0400130 virtual_ab_(GetFeatureFlag(kVirtualAbEnabled, kVirtualAbRetrofit)),
131 virtual_ab_compression_(GetFeatureFlag(kVirtualAbCompressionEnabled,
Kelvin Zhangebd115e2021-03-08 16:10:25 -0500132 kVirtualAbCompressionRetrofit)),
Kelvin Zhang1c4b9812022-04-06 17:29:00 -0700133 virtual_ab_compression_xor_(
134 GetFeatureFlag(kVirtualAbCompressionXorEnabled, "")),
David Andersone35b4382022-03-08 23:18:29 -0800135 virtual_ab_userspace_snapshots_(
136 GetFeatureFlag(kVirtualAbUserspaceSnapshotsEnabled, nullptr)),
Kelvin Zhangebd115e2021-03-08 16:10:25 -0500137 source_slot_(source_slot) {
Yifan Hongb38e1af2019-10-17 14:59:22 -0700138 if (GetVirtualAbFeatureFlag().IsEnabled()) {
Yifan Hongf033ecb2020-01-07 18:13:56 -0800139 snapshot_ = SnapshotManager::New();
Yifan Hongf9cb4492020-04-15 13:00:20 -0700140 } else {
141 snapshot_ = SnapshotManagerStub::New();
Yifan Hongb38e1af2019-10-17 14:59:22 -0700142 }
Yifan Hongf9cb4492020-04-15 13:00:20 -0700143 CHECK(snapshot_ != nullptr) << "Cannot initialize SnapshotManager.";
Yifan Hongb38e1af2019-10-17 14:59:22 -0700144}
145
Yifan Hong186bb682019-07-23 14:04:39 -0700146FeatureFlag DynamicPartitionControlAndroid::GetDynamicPartitionsFeatureFlag() {
Yifan Hongb38e1af2019-10-17 14:59:22 -0700147 return dynamic_partitions_;
Yifan Hong6e706b12018-11-09 16:50:51 -0800148}
149
Yifan Hong413d5722019-07-23 14:21:09 -0700150FeatureFlag DynamicPartitionControlAndroid::GetVirtualAbFeatureFlag() {
Yifan Hongb38e1af2019-10-17 14:59:22 -0700151 return virtual_ab_;
Yifan Hong413d5722019-07-23 14:21:09 -0700152}
153
Kelvin Zhangda1b3142020-09-24 17:09:02 -0400154FeatureFlag
155DynamicPartitionControlAndroid::GetVirtualAbCompressionFeatureFlag() {
Kelvin Zhangb9a5f612021-01-22 14:34:05 -0500156 if constexpr (constants::kIsRecovery) {
157 // Don't attempt VABC in recovery
158 return FeatureFlag(FeatureFlag::Value::NONE);
159 }
Kelvin Zhangda1b3142020-09-24 17:09:02 -0400160 return virtual_ab_compression_;
161}
162
Kelvin Zhang1c4b9812022-04-06 17:29:00 -0700163FeatureFlag
164DynamicPartitionControlAndroid::GetVirtualAbCompressionXorFeatureFlag() {
165 return virtual_ab_compression_xor_;
166}
167
Yifan Hongf5261562020-03-10 10:28:10 -0700168bool DynamicPartitionControlAndroid::OptimizeOperation(
169 const std::string& partition_name,
170 const InstallOperation& operation,
171 InstallOperation* optimized) {
Alessio Balsini2a3b4a22019-11-25 16:46:51 +0000172 switch (operation.type()) {
173 case InstallOperation::SOURCE_COPY:
174 return target_supports_snapshot_ &&
175 GetVirtualAbFeatureFlag().IsEnabled() &&
Yifan Hong6eec9952019-12-04 13:12:01 -0800176 mapped_devices_.count(partition_name +
177 SlotSuffixForSlotNumber(target_slot_)) > 0 &&
Yifan Hongf5261562020-03-10 10:28:10 -0700178 OptimizeSourceCopyOperation(operation, optimized);
Alessio Balsini2a3b4a22019-11-25 16:46:51 +0000179 break;
180 default:
181 break;
182 }
Alessio Balsini14980e22019-11-26 11:46:06 +0000183 return false;
184}
185
Yifan Hong8546a712019-03-28 14:42:53 -0700186bool DynamicPartitionControlAndroid::MapPartitionInternal(
Yifan Hong537802d2018-08-15 13:15:42 -0700187 const std::string& super_device,
188 const std::string& target_partition_name,
189 uint32_t slot,
Yifan Hongaf65ef12018-10-29 11:09:06 -0700190 bool force_writable,
Yifan Hong537802d2018-08-15 13:15:42 -0700191 std::string* path) {
David Andersonbb90dfb2019-08-13 14:14:56 -0700192 CreateLogicalPartitionParams params = {
193 .block_device = super_device,
194 .metadata_slot = slot,
195 .partition_name = target_partition_name,
196 .force_writable = force_writable,
David Andersonbb90dfb2019-08-13 14:14:56 -0700197 };
Yifan Hong420db9b2019-07-23 20:50:33 -0700198 bool success = false;
Yifan Hongf0f4a912019-09-26 17:51:33 -0700199 if (GetVirtualAbFeatureFlag().IsEnabled() && target_supports_snapshot_ &&
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700200 force_writable && ExpectMetadataMounted()) {
Yifan Hong420db9b2019-07-23 20:50:33 -0700201 // Only target partitions are mapped with force_writable. On Virtual
202 // A/B devices, target partitions may overlap with source partitions, so
203 // they must be mapped with snapshot.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700204 // One exception is when /metadata is not mounted. Fallback to
205 // CreateLogicalPartition as snapshots are not created in the first place.
Yifan Hong420db9b2019-07-23 20:50:33 -0700206 params.timeout_ms = kMapSnapshotTimeout;
207 success = snapshot_->MapUpdateSnapshot(params, path);
208 } else {
209 params.timeout_ms = kMapTimeout;
210 success = CreateLogicalPartition(params, path);
211 }
David Andersonbb90dfb2019-08-13 14:14:56 -0700212
Yifan Hong420db9b2019-07-23 20:50:33 -0700213 if (!success) {
Yifan Hong537802d2018-08-15 13:15:42 -0700214 LOG(ERROR) << "Cannot map " << target_partition_name << " in "
215 << super_device << " on device mapper.";
216 return false;
217 }
218 LOG(INFO) << "Succesfully mapped " << target_partition_name
Yifan Hongaf65ef12018-10-29 11:09:06 -0700219 << " to device mapper (force_writable = " << force_writable
220 << "); device path at " << *path;
Yifan Hong537802d2018-08-15 13:15:42 -0700221 mapped_devices_.insert(target_partition_name);
222 return true;
223}
224
Yifan Hong8546a712019-03-28 14:42:53 -0700225bool DynamicPartitionControlAndroid::MapPartitionOnDeviceMapper(
226 const std::string& super_device,
227 const std::string& target_partition_name,
228 uint32_t slot,
229 bool force_writable,
230 std::string* path) {
231 DmDeviceState state = GetState(target_partition_name);
232 if (state == DmDeviceState::ACTIVE) {
233 if (mapped_devices_.find(target_partition_name) != mapped_devices_.end()) {
234 if (GetDmDevicePathByName(target_partition_name, path)) {
235 LOG(INFO) << target_partition_name
236 << " is mapped on device mapper: " << *path;
237 return true;
238 }
239 LOG(ERROR) << target_partition_name << " is mapped but path is unknown.";
240 return false;
241 }
242 // If target_partition_name is not in mapped_devices_ but state is ACTIVE,
243 // the device might be mapped incorrectly before. Attempt to unmap it.
244 // Note that for source partitions, if GetState() == ACTIVE, callers (e.g.
245 // BootControlAndroid) should not call MapPartitionOnDeviceMapper, but
246 // should directly call GetDmDevicePathByName.
David Anderson4c891c92019-06-21 17:45:23 -0700247 if (!UnmapPartitionOnDeviceMapper(target_partition_name)) {
Yifan Hong8546a712019-03-28 14:42:53 -0700248 LOG(ERROR) << target_partition_name
249 << " is mapped before the update, and it cannot be unmapped.";
250 return false;
251 }
252 state = GetState(target_partition_name);
253 if (state != DmDeviceState::INVALID) {
254 LOG(ERROR) << target_partition_name << " is unmapped but state is "
255 << static_cast<std::underlying_type_t<DmDeviceState>>(state);
256 return false;
257 }
258 }
259 if (state == DmDeviceState::INVALID) {
260 return MapPartitionInternal(
261 super_device, target_partition_name, slot, force_writable, path);
262 }
263
264 LOG(ERROR) << target_partition_name
265 << " is mapped on device mapper but state is unknown: "
266 << static_cast<std::underlying_type_t<DmDeviceState>>(state);
267 return false;
268}
269
Yifan Hong537802d2018-08-15 13:15:42 -0700270bool DynamicPartitionControlAndroid::UnmapPartitionOnDeviceMapper(
David Anderson4c891c92019-06-21 17:45:23 -0700271 const std::string& target_partition_name) {
Yifan Hong537802d2018-08-15 13:15:42 -0700272 if (DeviceMapper::Instance().GetState(target_partition_name) !=
273 DmDeviceState::INVALID) {
Yifan Hong420db9b2019-07-23 20:50:33 -0700274 // Partitions at target slot on non-Virtual A/B devices are mapped as
275 // dm-linear. Also, on Virtual A/B devices, system_other may be mapped for
276 // preopt apps as dm-linear.
277 // Call DestroyLogicalPartition to handle these cases.
278 bool success = DestroyLogicalPartition(target_partition_name);
279
280 // On a Virtual A/B device, |target_partition_name| may be a leftover from
281 // a paused update. Clean up any underlying devices.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700282 if (ExpectMetadataMounted()) {
Yifan Hong420db9b2019-07-23 20:50:33 -0700283 success &= snapshot_->UnmapUpdateSnapshot(target_partition_name);
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700284 } else {
285 LOG(INFO) << "Skip UnmapUpdateSnapshot(" << target_partition_name
286 << ") because metadata is not mounted";
Yifan Hong420db9b2019-07-23 20:50:33 -0700287 }
288
289 if (!success) {
Yifan Hong537802d2018-08-15 13:15:42 -0700290 LOG(ERROR) << "Cannot unmap " << target_partition_name
291 << " from device mapper.";
292 return false;
293 }
294 LOG(INFO) << "Successfully unmapped " << target_partition_name
295 << " from device mapper.";
296 }
297 mapped_devices_.erase(target_partition_name);
298 return true;
299}
300
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -0400301bool DynamicPartitionControlAndroid::UnmapAllPartitions() {
Kelvin Zhangf7ef12a2021-03-22 12:59:06 -0400302 snapshot_->UnmapAllSnapshots();
Tao Bao8c4d0082019-08-08 08:56:16 -0700303 if (mapped_devices_.empty()) {
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -0400304 return false;
Tao Bao8c4d0082019-08-08 08:56:16 -0700305 }
Yifan Hong537802d2018-08-15 13:15:42 -0700306 // UnmapPartitionOnDeviceMapper removes objects from mapped_devices_, hence
307 // a copy is needed for the loop.
308 std::set<std::string> mapped = mapped_devices_;
309 LOG(INFO) << "Destroying [" << Join(mapped, ", ") << "] from device mapper";
310 for (const auto& partition_name : mapped) {
David Anderson4c891c92019-06-21 17:45:23 -0700311 ignore_result(UnmapPartitionOnDeviceMapper(partition_name));
Yifan Hong537802d2018-08-15 13:15:42 -0700312 }
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -0400313 return true;
Yifan Hong537802d2018-08-15 13:15:42 -0700314}
315
316void DynamicPartitionControlAndroid::Cleanup() {
Yifan Hongbae27842019-10-24 16:56:12 -0700317 UnmapAllPartitions();
318 metadata_device_.reset();
Yifan Hong537802d2018-08-15 13:15:42 -0700319}
320
321bool DynamicPartitionControlAndroid::DeviceExists(const std::string& path) {
322 return base::PathExists(base::FilePath(path));
323}
324
325android::dm::DmDeviceState DynamicPartitionControlAndroid::GetState(
326 const std::string& name) {
327 return DeviceMapper::Instance().GetState(name);
328}
329
330bool DynamicPartitionControlAndroid::GetDmDevicePathByName(
331 const std::string& name, std::string* path) {
332 return DeviceMapper::Instance().GetDmDevicePathByName(name, path);
333}
334
335std::unique_ptr<MetadataBuilder>
336DynamicPartitionControlAndroid::LoadMetadataBuilder(
Tianjie24f96092020-06-30 12:26:25 -0700337 const std::string& super_device, uint32_t slot) {
338 auto builder = MetadataBuilder::New(PartitionOpener(), super_device, slot);
339 if (builder == nullptr) {
340 LOG(WARNING) << "No metadata slot " << BootControlInterface::SlotName(slot)
341 << " in " << super_device;
342 return nullptr;
343 }
344 LOG(INFO) << "Loaded metadata from slot "
345 << BootControlInterface::SlotName(slot) << " in " << super_device;
346 return builder;
Yifan Hong012508e2019-07-22 18:30:40 -0700347}
348
349std::unique_ptr<MetadataBuilder>
350DynamicPartitionControlAndroid::LoadMetadataBuilder(
Yifan Hong6e706b12018-11-09 16:50:51 -0800351 const std::string& super_device,
352 uint32_t source_slot,
353 uint32_t target_slot) {
Tianjie24f96092020-06-30 12:26:25 -0700354 bool always_keep_source_slot = !target_supports_snapshot_;
355 auto builder = MetadataBuilder::NewForUpdate(PartitionOpener(),
356 super_device,
357 source_slot,
358 target_slot,
359 always_keep_source_slot);
Yifan Hong537802d2018-08-15 13:15:42 -0700360 if (builder == nullptr) {
361 LOG(WARNING) << "No metadata slot "
362 << BootControlInterface::SlotName(source_slot) << " in "
363 << super_device;
Yifan Hongf48a0052018-10-29 16:30:43 -0700364 return nullptr;
Yifan Hong537802d2018-08-15 13:15:42 -0700365 }
Tianjie24f96092020-06-30 12:26:25 -0700366 LOG(INFO) << "Created metadata for new update from slot "
Yifan Hong537802d2018-08-15 13:15:42 -0700367 << BootControlInterface::SlotName(source_slot) << " in "
368 << super_device;
369 return builder;
370}
371
372bool DynamicPartitionControlAndroid::StoreMetadata(
373 const std::string& super_device,
374 MetadataBuilder* builder,
375 uint32_t target_slot) {
376 auto metadata = builder->Export();
377 if (metadata == nullptr) {
378 LOG(ERROR) << "Cannot export metadata to slot "
379 << BootControlInterface::SlotName(target_slot) << " in "
380 << super_device;
381 return false;
382 }
383
Yifan Hong186bb682019-07-23 14:04:39 -0700384 if (GetDynamicPartitionsFeatureFlag().IsRetrofit()) {
Yifan Hong6e706b12018-11-09 16:50:51 -0800385 if (!FlashPartitionTable(super_device, *metadata)) {
386 LOG(ERROR) << "Cannot write metadata to " << super_device;
387 return false;
388 }
389 LOG(INFO) << "Written metadata to " << super_device;
390 } else {
391 if (!UpdatePartitionTable(super_device, *metadata, target_slot)) {
392 LOG(ERROR) << "Cannot write metadata to slot "
393 << BootControlInterface::SlotName(target_slot) << " in "
394 << super_device;
395 return false;
396 }
397 LOG(INFO) << "Copied metadata to slot "
398 << BootControlInterface::SlotName(target_slot) << " in "
399 << super_device;
Yifan Hong537802d2018-08-15 13:15:42 -0700400 }
401
Yifan Hong537802d2018-08-15 13:15:42 -0700402 return true;
403}
404
405bool DynamicPartitionControlAndroid::GetDeviceDir(std::string* out) {
406 // We can't use fs_mgr to look up |partition_name| because fstab
407 // doesn't list every slot partition (it uses the slotselect option
408 // to mask the suffix).
409 //
410 // We can however assume that there's an entry for the /misc mount
411 // point and use that to get the device file for the misc
412 // partition. This helps us locate the disk that |partition_name|
413 // resides on. From there we'll assume that a by-name scheme is used
414 // so we can just replace the trailing "misc" by the given
415 // |partition_name| and suffix corresponding to |slot|, e.g.
416 //
417 // /dev/block/platform/soc.0/7824900.sdhci/by-name/misc ->
418 // /dev/block/platform/soc.0/7824900.sdhci/by-name/boot_a
419 //
420 // If needed, it's possible to relax the by-name assumption in the
421 // future by trawling /sys/block looking for the appropriate sibling
422 // of misc and then finding an entry in /dev matching the sysfs
423 // entry.
424
425 std::string err, misc_device = get_bootloader_message_blk_device(&err);
426 if (misc_device.empty()) {
427 LOG(ERROR) << "Unable to get misc block device: " << err;
428 return false;
429 }
430
431 if (!utils::IsSymlink(misc_device.c_str())) {
432 LOG(ERROR) << "Device file " << misc_device << " for /misc "
433 << "is not a symlink.";
434 return false;
435 }
436 *out = base::FilePath(misc_device).DirName().value();
437 return true;
438}
Yifan Hong012508e2019-07-22 18:30:40 -0700439
440bool DynamicPartitionControlAndroid::PreparePartitionsForUpdate(
441 uint32_t source_slot,
442 uint32_t target_slot,
Yifan Hongf0f4a912019-09-26 17:51:33 -0700443 const DeltaArchiveManifest& manifest,
Yifan Hongf033ecb2020-01-07 18:13:56 -0800444 bool update,
445 uint64_t* required_size) {
Yifan Hong6eec9952019-12-04 13:12:01 -0800446 source_slot_ = source_slot;
447 target_slot_ = target_slot;
Yifan Hongf033ecb2020-01-07 18:13:56 -0800448 if (required_size != nullptr) {
449 *required_size = 0;
450 }
Yifan Hong6eec9952019-12-04 13:12:01 -0800451
Yifan Hong3a1a5612019-11-05 16:34:32 -0800452 if (fs_mgr_overlayfs_is_setup()) {
453 // Non DAP devices can use overlayfs as well.
454 LOG(WARNING)
455 << "overlayfs overrides are active and can interfere with our "
456 "resources.\n"
457 << "run adb enable-verity to deactivate if required and try again.";
458 }
459
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700460 // If metadata is erased but not formatted, it is possible to not mount
461 // it in recovery. It is acceptable to skip mounting and choose fallback path
462 // (PrepareDynamicPartitionsForUpdate) when sideloading full OTAs.
463 TEST_AND_RETURN_FALSE(EnsureMetadataMounted() || IsRecovery());
Yifan Hong29692902020-03-26 12:47:05 -0700464
465 if (update) {
466 TEST_AND_RETURN_FALSE(EraseSystemOtherAvbFooter(source_slot, target_slot));
467 }
468
Yifan Hong3a1a5612019-11-05 16:34:32 -0800469 if (!GetDynamicPartitionsFeatureFlag().IsEnabled()) {
470 return true;
471 }
472
473 if (target_slot == source_slot) {
474 LOG(ERROR) << "Cannot call PreparePartitionsForUpdate on current slot.";
475 return false;
476 }
477
Yifan Hongf6f75c22020-07-31 15:20:25 -0700478 if (!SetTargetBuildVars(manifest)) {
479 return false;
480 }
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700481 for (auto& list : dynamic_partition_list_) {
482 list.clear();
483 }
Yifan Hongf6f75c22020-07-31 15:20:25 -0700484
Yifan Hong3a1a5612019-11-05 16:34:32 -0800485 // Although the current build supports dynamic partitions, the given payload
486 // doesn't use it for target partitions. This could happen when applying a
487 // retrofit update. Skip updating the partition metadata for the target slot.
Yifan Hong3a1a5612019-11-05 16:34:32 -0800488 if (!is_target_dynamic_) {
489 return true;
490 }
491
Yifan Hongf0f4a912019-09-26 17:51:33 -0700492 if (!update)
493 return true;
494
Yifan Hongbae27842019-10-24 16:56:12 -0700495 bool delete_source = false;
496
Yifan Hong6d888562019-10-01 13:00:31 -0700497 if (GetVirtualAbFeatureFlag().IsEnabled()) {
498 // On Virtual A/B device, either CancelUpdate() or BeginUpdate() must be
499 // called before calling UnmapUpdateSnapshot.
500 // - If target_supports_snapshot_, PrepareSnapshotPartitionsForUpdate()
501 // calls BeginUpdate() which resets update state
Yifan Hongbae27842019-10-24 16:56:12 -0700502 // - If !target_supports_snapshot_ or PrepareSnapshotPartitionsForUpdate
503 // failed in recovery, explicitly CancelUpdate().
Yifan Hong6d888562019-10-01 13:00:31 -0700504 if (target_supports_snapshot_) {
Yifan Hongbae27842019-10-24 16:56:12 -0700505 if (PrepareSnapshotPartitionsForUpdate(
506 source_slot, target_slot, manifest, required_size)) {
507 return true;
508 }
509
510 // Virtual A/B device doing Virtual A/B update in Android mode must use
511 // snapshots.
512 if (!IsRecovery()) {
513 LOG(ERROR) << "PrepareSnapshotPartitionsForUpdate failed in Android "
514 << "mode";
515 return false;
516 }
517
518 delete_source = true;
519 LOG(INFO) << "PrepareSnapshotPartitionsForUpdate failed in recovery. "
520 << "Attempt to overwrite existing partitions if possible";
521 } else {
522 // Downgrading to an non-Virtual A/B build or is secondary OTA.
523 LOG(INFO) << "Using regular A/B on Virtual A/B because package disabled "
524 << "snapshots.";
Yifan Hong6d888562019-10-01 13:00:31 -0700525 }
Yifan Hongbae27842019-10-24 16:56:12 -0700526
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700527 // In recovery, if /metadata is not mounted, it is likely that metadata
528 // partition is erased and not formatted yet. After sideloading, when
529 // rebooting into the new version, init will erase metadata partition,
530 // hence the failure of CancelUpdate() can be ignored here.
531 // However, if metadata is mounted and CancelUpdate fails, sideloading
532 // should not proceed because during next boot, snapshots will overlay on
533 // the devices incorrectly.
534 if (ExpectMetadataMounted()) {
535 TEST_AND_RETURN_FALSE(snapshot_->CancelUpdate());
536 } else {
537 LOG(INFO) << "Skip canceling previous update because metadata is not "
538 << "mounted";
Yifan Hong6d888562019-10-01 13:00:31 -0700539 }
Yifan Hong420db9b2019-07-23 20:50:33 -0700540 }
Yifan Hongbae27842019-10-24 16:56:12 -0700541
Tianjie24f96092020-06-30 12:26:25 -0700542 // TODO(xunchang) support partial update on non VAB enabled devices.
Yifan Hong5c5743f2020-04-16 12:59:07 -0700543 TEST_AND_RETURN_FALSE(PrepareDynamicPartitionsForUpdate(
544 source_slot, target_slot, manifest, delete_source));
545
546 if (required_size != nullptr) {
547 *required_size = 0;
548 }
549 return true;
Yifan Hong420db9b2019-07-23 20:50:33 -0700550}
551
Yifan Hongf6f75c22020-07-31 15:20:25 -0700552bool DynamicPartitionControlAndroid::SetTargetBuildVars(
553 const DeltaArchiveManifest& manifest) {
554 // Precondition: current build supports dynamic partition.
555 CHECK(GetDynamicPartitionsFeatureFlag().IsEnabled());
556
557 bool is_target_dynamic =
558 !manifest.dynamic_partition_metadata().groups().empty();
559 bool target_supports_snapshot =
560 manifest.dynamic_partition_metadata().snapshot_enabled();
561
562 if (manifest.partial_update()) {
563 // Partial updates requires DAP. On partial updates that does not involve
564 // dynamic partitions, groups() can be empty, so also assume
565 // is_target_dynamic in this case. This assumption should be safe because we
566 // also check target_supports_snapshot below, which presumably also implies
567 // target build supports dynamic partition.
568 if (!is_target_dynamic) {
569 LOG(INFO) << "Assuming target build supports dynamic partitions for "
570 "partial updates.";
571 is_target_dynamic = true;
572 }
573
574 // Partial updates requires Virtual A/B. Double check that both current
575 // build and target build supports Virtual A/B.
576 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
577 LOG(ERROR) << "Partial update cannot be applied on a device that does "
578 "not support snapshots.";
579 return false;
580 }
581 if (!target_supports_snapshot) {
582 LOG(ERROR) << "Cannot apply partial update to a build that does not "
583 "support snapshots.";
584 return false;
585 }
586 }
587
588 // Store the flags.
589 is_target_dynamic_ = is_target_dynamic;
590 // If !is_target_dynamic_, leave target_supports_snapshot_ unset because
591 // snapshots would not work without dynamic partition.
592 if (is_target_dynamic_) {
593 target_supports_snapshot_ = target_supports_snapshot;
594 }
595 return true;
596}
597
Yifan Hong29692902020-03-26 12:47:05 -0700598namespace {
599// Try our best to erase AVB footer.
600class AvbFooterEraser {
601 public:
602 explicit AvbFooterEraser(const std::string& path) : path_(path) {}
603 bool Erase() {
604 // Try to mark the block device read-only. Ignore any
605 // failure since this won't work when passing regular files.
606 ignore_result(utils::SetBlockDeviceReadOnly(path_, false /* readonly */));
607
608 fd_.reset(new EintrSafeFileDescriptor());
609 int flags = O_WRONLY | O_TRUNC | O_CLOEXEC | O_SYNC;
610 TEST_AND_RETURN_FALSE(fd_->Open(path_.c_str(), flags));
611
612 // Need to write end-AVB_FOOTER_SIZE to end.
613 static_assert(AVB_FOOTER_SIZE > 0);
614 off64_t offset = fd_->Seek(-AVB_FOOTER_SIZE, SEEK_END);
615 TEST_AND_RETURN_FALSE_ERRNO(offset >= 0);
616 uint64_t write_size = AVB_FOOTER_SIZE;
617 LOG(INFO) << "Zeroing " << path_ << " @ [" << offset << ", "
618 << (offset + write_size) << "] (" << write_size << " bytes)";
619 brillo::Blob zeros(write_size);
620 TEST_AND_RETURN_FALSE(utils::WriteAll(fd_, zeros.data(), zeros.size()));
621 return true;
622 }
623 ~AvbFooterEraser() {
624 TEST_AND_RETURN(fd_ != nullptr && fd_->IsOpen());
625 if (!fd_->Close()) {
626 LOG(WARNING) << "Failed to close fd for " << path_;
627 }
628 }
629
630 private:
631 std::string path_;
632 FileDescriptorPtr fd_;
633};
634
635} // namespace
636
637std::optional<bool>
638DynamicPartitionControlAndroid::IsAvbEnabledOnSystemOther() {
639 auto prefix = GetProperty(kPostinstallFstabPrefix, "");
640 if (prefix.empty()) {
641 LOG(WARNING) << "Cannot get " << kPostinstallFstabPrefix;
642 return std::nullopt;
643 }
644 auto path = base::FilePath(prefix).Append("etc/fstab.postinstall").value();
645 return IsAvbEnabledInFstab(path);
646}
647
648std::optional<bool> DynamicPartitionControlAndroid::IsAvbEnabledInFstab(
649 const std::string& path) {
650 Fstab fstab;
651 if (!ReadFstabFromFile(path, &fstab)) {
Yifan Hong93cde302020-04-27 12:59:29 -0700652 PLOG(WARNING) << "Cannot read fstab from " << path;
653 if (errno == ENOENT) {
654 return false;
655 }
Yifan Hong29692902020-03-26 12:47:05 -0700656 return std::nullopt;
657 }
658 for (const auto& entry : fstab) {
659 if (!entry.avb_keys.empty()) {
660 return true;
661 }
662 }
663 return false;
664}
665
666bool DynamicPartitionControlAndroid::GetSystemOtherPath(
667 uint32_t source_slot,
668 uint32_t target_slot,
669 const std::string& partition_name_suffix,
670 std::string* path,
671 bool* should_unmap) {
672 path->clear();
673 *should_unmap = false;
674
P.Adarsh Reddy13e4195d2020-06-08 23:17:36 +0530675 // Check that AVB is enabled on system_other before erasing.
676 auto has_avb = IsAvbEnabledOnSystemOther();
677 TEST_AND_RETURN_FALSE(has_avb.has_value());
678 if (!has_avb.value()) {
679 LOG(INFO) << "AVB is not enabled on system_other. Skip erasing.";
680 return true;
681 }
Yifan Hong29692902020-03-26 12:47:05 -0700682
P.Adarsh Reddy13e4195d2020-06-08 23:17:36 +0530683 if (!IsRecovery()) {
Yifan Hong29692902020-03-26 12:47:05 -0700684 // Found unexpected avb_keys for system_other on devices retrofitting
685 // dynamic partitions. Previous crash in update_engine may leave logical
686 // partitions mapped on physical system_other partition. It is difficult to
687 // handle these cases. Just fail.
688 if (GetDynamicPartitionsFeatureFlag().IsRetrofit()) {
689 LOG(ERROR) << "Cannot erase AVB footer on system_other on devices with "
690 << "retrofit dynamic partitions. They should not have AVB "
691 << "enabled on system_other.";
692 return false;
693 }
694 }
695
696 std::string device_dir_str;
697 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
698 base::FilePath device_dir(device_dir_str);
699
700 // On devices without dynamic partition, search for static partitions.
701 if (!GetDynamicPartitionsFeatureFlag().IsEnabled()) {
702 *path = device_dir.Append(partition_name_suffix).value();
703 TEST_AND_RETURN_FALSE(DeviceExists(*path));
704 return true;
705 }
706
707 auto source_super_device =
708 device_dir.Append(GetSuperPartitionName(source_slot)).value();
709
710 auto builder = LoadMetadataBuilder(source_super_device, source_slot);
711 if (builder == nullptr) {
712 if (IsRecovery()) {
713 // It might be corrupted for some reason. It should still be able to
714 // sideload.
715 LOG(WARNING) << "Super partition metadata cannot be read from the source "
716 << "slot, skip erasing.";
717 return true;
718 } else {
719 // Device has booted into Android mode, indicating that the super
720 // partition metadata should be there.
721 LOG(ERROR) << "Super partition metadata cannot be read from the source "
722 << "slot. This is unexpected on devices with dynamic "
723 << "partitions enabled.";
724 return false;
725 }
726 }
727 auto p = builder->FindPartition(partition_name_suffix);
728 if (p == nullptr) {
729 // If the source slot is flashed without system_other, it does not exist
730 // in super partition metadata at source slot. It is safe to skip it.
731 LOG(INFO) << "Can't find " << partition_name_suffix
732 << " in metadata source slot, skip erasing.";
733 return true;
734 }
735 // System_other created by flashing tools should be erased.
736 // If partition is created by update_engine (via NewForUpdate), it is a
737 // left-over partition from the previous update and does not contain
738 // system_other, hence there is no need to erase.
739 // Note the reverse is not necessary true. If the flag is not set, we don't
740 // know if the partition is created by update_engine or by flashing tools
741 // because older versions of super partition metadata does not contain this
742 // flag. It is okay to erase the AVB footer anyways.
743 if (p->attributes() & LP_PARTITION_ATTR_UPDATED) {
744 LOG(INFO) << partition_name_suffix
745 << " does not contain system_other, skip erasing.";
746 return true;
747 }
748
Yifan Hong64331b32020-05-13 16:50:40 -0700749 if (p->size() < AVB_FOOTER_SIZE) {
750 LOG(INFO) << partition_name_suffix << " has length " << p->size()
751 << "( < AVB_FOOTER_SIZE " << AVB_FOOTER_SIZE
752 << "), skip erasing.";
753 return true;
754 }
755
Yifan Hong29692902020-03-26 12:47:05 -0700756 // Delete any pre-existing device with name |partition_name_suffix| and
757 // also remove it from |mapped_devices_|.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700758 // In recovery, metadata might not be mounted, and
759 // UnmapPartitionOnDeviceMapper might fail. However,
760 // it is unusual that system_other has already been mapped. Hence, just skip.
Yifan Hong29692902020-03-26 12:47:05 -0700761 TEST_AND_RETURN_FALSE(UnmapPartitionOnDeviceMapper(partition_name_suffix));
762 // Use CreateLogicalPartition directly to avoid mapping with existing
763 // snapshots.
764 CreateLogicalPartitionParams params = {
765 .block_device = source_super_device,
766 .metadata_slot = source_slot,
767 .partition_name = partition_name_suffix,
768 .force_writable = true,
769 .timeout_ms = kMapTimeout,
770 };
771 TEST_AND_RETURN_FALSE(CreateLogicalPartition(params, path));
772 *should_unmap = true;
773 return true;
774}
775
776bool DynamicPartitionControlAndroid::EraseSystemOtherAvbFooter(
777 uint32_t source_slot, uint32_t target_slot) {
778 LOG(INFO) << "Erasing AVB footer of system_other partition before update.";
779
780 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
781 const std::string partition_name_suffix = "system" + target_suffix;
782
783 std::string path;
784 bool should_unmap = false;
785
786 TEST_AND_RETURN_FALSE(GetSystemOtherPath(
787 source_slot, target_slot, partition_name_suffix, &path, &should_unmap));
788
789 if (path.empty()) {
790 return true;
791 }
792
793 bool ret = AvbFooterEraser(path).Erase();
794
795 // Delete |partition_name_suffix| from device mapper and from
796 // |mapped_devices_| again so that it does not interfere with update process.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700797 // In recovery, metadata might not be mounted, and
798 // UnmapPartitionOnDeviceMapper might fail. However, DestroyLogicalPartition
799 // should be called. If DestroyLogicalPartition does fail, it is still okay
800 // to skip the error here and let Prepare*() fail later.
Yifan Hong29692902020-03-26 12:47:05 -0700801 if (should_unmap) {
802 TEST_AND_RETURN_FALSE(UnmapPartitionOnDeviceMapper(partition_name_suffix));
803 }
804
805 return ret;
806}
807
Yifan Hong420db9b2019-07-23 20:50:33 -0700808bool DynamicPartitionControlAndroid::PrepareDynamicPartitionsForUpdate(
809 uint32_t source_slot,
810 uint32_t target_slot,
Yifan Hongbae27842019-10-24 16:56:12 -0700811 const DeltaArchiveManifest& manifest,
812 bool delete_source) {
Yifan Hong012508e2019-07-22 18:30:40 -0700813 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
814
815 // Unmap all the target dynamic partitions because they would become
816 // inconsistent with the new metadata.
Yifan Hong13d41cb2019-09-16 13:18:22 -0700817 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
818 for (const auto& partition_name : group.partition_names()) {
819 if (!UnmapPartitionOnDeviceMapper(partition_name + target_suffix)) {
Yifan Hong012508e2019-07-22 18:30:40 -0700820 return false;
821 }
822 }
823 }
824
825 std::string device_dir_str;
Tianjie9f4dc7f2021-03-15 16:00:50 -0700826 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
Yifan Hong012508e2019-07-22 18:30:40 -0700827 base::FilePath device_dir(device_dir_str);
828 auto source_device =
Yifan Hong700d7c12019-07-23 20:49:16 -0700829 device_dir.Append(GetSuperPartitionName(source_slot)).value();
Yifan Hong012508e2019-07-22 18:30:40 -0700830
831 auto builder = LoadMetadataBuilder(source_device, source_slot, target_slot);
832 if (builder == nullptr) {
833 LOG(ERROR) << "No metadata at "
834 << BootControlInterface::SlotName(source_slot);
835 return false;
836 }
837
Yifan Hongbae27842019-10-24 16:56:12 -0700838 if (delete_source) {
839 TEST_AND_RETURN_FALSE(
840 DeleteSourcePartitions(builder.get(), source_slot, manifest));
841 }
842
Tianjie9f4dc7f2021-03-15 16:00:50 -0700843 TEST_AND_RETURN_FALSE(
844 UpdatePartitionMetadata(builder.get(), target_slot, manifest));
Yifan Hong012508e2019-07-22 18:30:40 -0700845
846 auto target_device =
Yifan Hong700d7c12019-07-23 20:49:16 -0700847 device_dir.Append(GetSuperPartitionName(target_slot)).value();
Yifan Hong012508e2019-07-22 18:30:40 -0700848 return StoreMetadata(target_device, builder.get(), target_slot);
849}
850
Yifan Hong3a1293a2021-04-16 13:21:20 -0700851DynamicPartitionControlAndroid::SpaceLimit
852DynamicPartitionControlAndroid::GetSpaceLimit(bool use_snapshot) {
853 // On device retrofitting dynamic partitions, allocatable_space = "super",
854 // where "super" is the sum of all block devices for that slot. Since block
855 // devices are dedicated for the corresponding slot, there's no need to halve
856 // the allocatable space.
857 if (GetDynamicPartitionsFeatureFlag().IsRetrofit())
858 return SpaceLimit::ERROR_IF_EXCEEDED_SUPER;
859
860 // On device launching dynamic partitions w/o VAB, regardless of recovery
861 // sideload, super partition must be big enough to hold both A and B slots of
862 // groups. Hence,
863 // allocatable_space = super / 2
864 if (!GetVirtualAbFeatureFlag().IsEnabled())
865 return SpaceLimit::ERROR_IF_EXCEEDED_HALF_OF_SUPER;
866
867 // Source build supports VAB. Super partition must be big enough to hold
868 // one slot of groups (ERROR_IF_EXCEEDED_SUPER). However, there are cases
869 // where additional warning messages needs to be written.
870
871 // If using snapshot updates, implying that target build also uses VAB,
872 // allocatable_space = super
873 if (use_snapshot)
874 return SpaceLimit::ERROR_IF_EXCEEDED_SUPER;
875
876 // Source build supports VAB but not using snapshot updates. There are
877 // several cases, as listed below.
878 // Sideloading: allocatable_space = super.
879 if (IsRecovery())
880 return SpaceLimit::ERROR_IF_EXCEEDED_SUPER;
881
882 // On launch VAB device, this implies secondary payload.
883 // Technically, we don't have to check anything, but sum(groups) < super
884 // still applies.
885 if (!GetVirtualAbFeatureFlag().IsRetrofit())
886 return SpaceLimit::ERROR_IF_EXCEEDED_SUPER;
887
888 // On retrofit VAB device, either of the following:
889 // - downgrading: allocatable_space = super / 2
890 // - secondary payload: don't check anything
891 // These two cases are indistinguishable,
892 // hence emit warning if sum(groups) > super / 2
893 return SpaceLimit::WARN_IF_EXCEEDED_HALF_OF_SUPER;
894}
895
Tianjie9f4dc7f2021-03-15 16:00:50 -0700896bool DynamicPartitionControlAndroid::CheckSuperPartitionAllocatableSpace(
897 android::fs_mgr::MetadataBuilder* builder,
898 const DeltaArchiveManifest& manifest,
899 bool use_snapshot) {
Yifan Hong3a1293a2021-04-16 13:21:20 -0700900 uint64_t sum_groups = 0;
Tianjie9f4dc7f2021-03-15 16:00:50 -0700901 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
Yifan Hong3a1293a2021-04-16 13:21:20 -0700902 sum_groups += group.size();
Tianjie9f4dc7f2021-03-15 16:00:50 -0700903 }
904
Yifan Hong3a1293a2021-04-16 13:21:20 -0700905 uint64_t full_space = builder->AllocatableSpace();
906 uint64_t half_space = full_space / 2;
907 constexpr const char* fmt =
908 "The maximum size of all groups for the target slot (%" PRIu64
909 ") has exceeded %sallocatable space for dynamic partitions %" PRIu64 ".";
910 switch (GetSpaceLimit(use_snapshot)) {
911 case SpaceLimit::ERROR_IF_EXCEEDED_HALF_OF_SUPER: {
912 if (sum_groups > half_space) {
913 LOG(ERROR) << StringPrintf(fmt, sum_groups, "HALF OF ", half_space);
914 return false;
915 }
916 // If test passes, it implies that the following two conditions also pass.
917 break;
918 }
919 case SpaceLimit::WARN_IF_EXCEEDED_HALF_OF_SUPER: {
920 if (sum_groups > half_space) {
921 LOG(WARNING) << StringPrintf(fmt, sum_groups, "HALF OF ", half_space)
922 << " This is allowed for downgrade or secondary OTA on "
923 "retrofit VAB device.";
924 }
925 // still check sum(groups) < super
926 [[fallthrough]];
927 }
928 case SpaceLimit::ERROR_IF_EXCEEDED_SUPER: {
929 if (sum_groups > full_space) {
930 LOG(ERROR) << base::StringPrintf(fmt, sum_groups, "", full_space);
931 return false;
932 }
933 break;
934 }
Tianjie9f4dc7f2021-03-15 16:00:50 -0700935 }
936
937 return true;
938}
939
Yifan Hong420db9b2019-07-23 20:50:33 -0700940bool DynamicPartitionControlAndroid::PrepareSnapshotPartitionsForUpdate(
941 uint32_t source_slot,
942 uint32_t target_slot,
Yifan Hongf033ecb2020-01-07 18:13:56 -0800943 const DeltaArchiveManifest& manifest,
944 uint64_t* required_size) {
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700945 TEST_AND_RETURN_FALSE(ExpectMetadataMounted());
Tianjie9f4dc7f2021-03-15 16:00:50 -0700946
947 std::string device_dir_str;
948 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
949 base::FilePath device_dir(device_dir_str);
950 auto super_device =
951 device_dir.Append(GetSuperPartitionName(source_slot)).value();
952 auto builder = LoadMetadataBuilder(super_device, source_slot);
953 if (builder == nullptr) {
954 LOG(ERROR) << "No metadata at "
955 << BootControlInterface::SlotName(source_slot);
956 return false;
957 }
958
959 TEST_AND_RETURN_FALSE(
960 CheckSuperPartitionAllocatableSpace(builder.get(), manifest, true));
961
Yifan Hong420db9b2019-07-23 20:50:33 -0700962 if (!snapshot_->BeginUpdate()) {
963 LOG(ERROR) << "Cannot begin new update.";
964 return false;
965 }
Yifan Hongf033ecb2020-01-07 18:13:56 -0800966 auto ret = snapshot_->CreateUpdateSnapshots(manifest);
967 if (!ret) {
968 LOG(ERROR) << "Cannot create update snapshots: " << ret.string();
969 if (required_size != nullptr &&
Yifan Hong0850bca2020-01-16 15:14:07 -0800970 ret.error_code() == Return::ErrorCode::NO_SPACE) {
Yifan Hongf033ecb2020-01-07 18:13:56 -0800971 *required_size = ret.required_size();
972 }
Yifan Hong420db9b2019-07-23 20:50:33 -0700973 return false;
974 }
975 return true;
976}
977
Yifan Hong700d7c12019-07-23 20:49:16 -0700978std::string DynamicPartitionControlAndroid::GetSuperPartitionName(
979 uint32_t slot) {
980 return fs_mgr_get_super_partition_name(slot);
981}
982
Yifan Hong012508e2019-07-22 18:30:40 -0700983bool DynamicPartitionControlAndroid::UpdatePartitionMetadata(
984 MetadataBuilder* builder,
985 uint32_t target_slot,
Yifan Hong13d41cb2019-09-16 13:18:22 -0700986 const DeltaArchiveManifest& manifest) {
Yifan Hong8d6df9a2020-08-13 13:59:54 -0700987 // Check preconditions.
Yifan Hong265a8e32021-04-16 13:30:02 -0700988 if (GetVirtualAbFeatureFlag().IsEnabled()) {
989 CHECK(!target_supports_snapshot_ || IsRecovery())
990 << "Must use snapshot on VAB device when target build supports VAB and "
991 "not sideloading.";
992 LOG_IF(INFO, !target_supports_snapshot_)
993 << "Not using snapshot on VAB device because target build does not "
994 "support snapshot. Secondary or downgrade OTA?";
995 LOG_IF(INFO, IsRecovery())
996 << "Not using snapshot on VAB device because sideloading.";
997 }
Yifan Hong8d6df9a2020-08-13 13:59:54 -0700998
Yifan Honga4e7da32019-09-30 18:25:03 -0700999 // If applying downgrade from Virtual A/B to non-Virtual A/B, the left-over
1000 // COW group needs to be deleted to ensure there are enough space to create
1001 // target partitions.
1002 builder->RemoveGroupAndPartitions(android::snapshot::kCowGroupName);
1003
Yifan Hong012508e2019-07-22 18:30:40 -07001004 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
1005 DeleteGroupsWithSuffix(builder, target_suffix);
1006
Tianjie9f4dc7f2021-03-15 16:00:50 -07001007 TEST_AND_RETURN_FALSE(
1008 CheckSuperPartitionAllocatableSpace(builder, manifest, false));
Yifan Hong012508e2019-07-22 18:30:40 -07001009
Yifan Hong13d41cb2019-09-16 13:18:22 -07001010 // name of partition(e.g. "system") -> size in bytes
1011 std::map<std::string, uint64_t> partition_sizes;
1012 for (const auto& partition : manifest.partitions()) {
1013 partition_sizes.emplace(partition.partition_name(),
1014 partition.new_partition_info().size());
1015 }
1016
1017 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
1018 auto group_name_suffix = group.name() + target_suffix;
1019 if (!builder->AddGroup(group_name_suffix, group.size())) {
Yifan Hong012508e2019-07-22 18:30:40 -07001020 LOG(ERROR) << "Cannot add group " << group_name_suffix << " with size "
Yifan Hong13d41cb2019-09-16 13:18:22 -07001021 << group.size();
Yifan Hong012508e2019-07-22 18:30:40 -07001022 return false;
1023 }
1024 LOG(INFO) << "Added group " << group_name_suffix << " with size "
Yifan Hong13d41cb2019-09-16 13:18:22 -07001025 << group.size();
Yifan Hong012508e2019-07-22 18:30:40 -07001026
Yifan Hong13d41cb2019-09-16 13:18:22 -07001027 for (const auto& partition_name : group.partition_names()) {
1028 auto partition_sizes_it = partition_sizes.find(partition_name);
1029 if (partition_sizes_it == partition_sizes.end()) {
1030 // TODO(tbao): Support auto-filling partition info for framework-only
1031 // OTA.
1032 LOG(ERROR) << "dynamic_partition_metadata contains partition "
1033 << partition_name << " but it is not part of the manifest. "
1034 << "This is not supported.";
1035 return false;
1036 }
1037 uint64_t partition_size = partition_sizes_it->second;
1038
1039 auto partition_name_suffix = partition_name + target_suffix;
Yifan Hong012508e2019-07-22 18:30:40 -07001040 Partition* p = builder->AddPartition(
1041 partition_name_suffix, group_name_suffix, LP_PARTITION_ATTR_READONLY);
1042 if (!p) {
1043 LOG(ERROR) << "Cannot add partition " << partition_name_suffix
1044 << " to group " << group_name_suffix;
1045 return false;
1046 }
Yifan Hong13d41cb2019-09-16 13:18:22 -07001047 if (!builder->ResizePartition(p, partition_size)) {
Yifan Hong012508e2019-07-22 18:30:40 -07001048 LOG(ERROR) << "Cannot resize partition " << partition_name_suffix
Yifan Hong13d41cb2019-09-16 13:18:22 -07001049 << " to size " << partition_size << ". Not enough space?";
Yifan Hong012508e2019-07-22 18:30:40 -07001050 return false;
1051 }
David Anderson0e1c7fd2021-03-08 19:01:59 -08001052 if (p->size() < partition_size) {
1053 LOG(ERROR) << "Partition " << partition_name_suffix
1054 << " was expected to have size " << partition_size
1055 << ", but instead has size " << p->size();
1056 return false;
1057 }
Yifan Hong012508e2019-07-22 18:30:40 -07001058 LOG(INFO) << "Added partition " << partition_name_suffix << " to group "
Yifan Hong13d41cb2019-09-16 13:18:22 -07001059 << group_name_suffix << " with size " << partition_size;
Yifan Hong012508e2019-07-22 18:30:40 -07001060 }
1061 }
1062
1063 return true;
1064}
1065
Yifan Hong7b3910a2020-03-24 17:47:32 -07001066bool DynamicPartitionControlAndroid::FinishUpdate(bool powerwash_required) {
Yifan Hong4d7c5eb2020-04-03 11:31:50 -07001067 if (ExpectMetadataMounted()) {
1068 if (snapshot_->GetUpdateState() == UpdateState::Initiated) {
1069 LOG(INFO) << "Snapshot writes are done.";
1070 return snapshot_->FinishedSnapshotWrites(powerwash_required);
1071 }
1072 } else {
1073 LOG(INFO) << "Skip FinishedSnapshotWrites() because /metadata is not "
1074 << "mounted";
Yifan Hongf0f4a912019-09-26 17:51:33 -07001075 }
1076 return true;
Yifan Honga33bca42019-09-03 20:29:45 -07001077}
1078
Yifan Hong3a1a5612019-11-05 16:34:32 -08001079bool DynamicPartitionControlAndroid::GetPartitionDevice(
1080 const std::string& partition_name,
1081 uint32_t slot,
1082 uint32_t current_slot,
Tianjie51a5a392020-06-03 14:39:32 -07001083 bool not_in_payload,
1084 std::string* device,
1085 bool* is_dynamic) {
Kelvin Zhang66a9ebb2021-01-25 13:35:10 -05001086 auto partition_dev =
1087 GetPartitionDevice(partition_name, slot, current_slot, not_in_payload);
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001088 if (!partition_dev.has_value()) {
Yifan Hong3a1a5612019-11-05 16:34:32 -08001089 return false;
1090 }
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001091 if (device) {
1092 *device = std::move(partition_dev->rw_device_path);
1093 }
1094 if (is_dynamic) {
1095 *is_dynamic = partition_dev->is_dynamic;
1096 }
Yifan Hong3a1a5612019-11-05 16:34:32 -08001097 return true;
1098}
1099
Tianjie51a5a392020-06-03 14:39:32 -07001100bool DynamicPartitionControlAndroid::GetPartitionDevice(
1101 const std::string& partition_name,
1102 uint32_t slot,
1103 uint32_t current_slot,
1104 std::string* device) {
1105 return GetPartitionDevice(
1106 partition_name, slot, current_slot, false, device, nullptr);
1107}
1108
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001109static std::string GetStaticDevicePath(
1110 const base::FilePath& device_dir,
1111 const std::string& partition_name_suffixed) {
1112 base::FilePath path = device_dir.Append(partition_name_suffixed);
1113 return path.value();
1114}
1115
1116std::optional<PartitionDevice>
1117DynamicPartitionControlAndroid::GetPartitionDevice(
1118 const std::string& partition_name,
1119 uint32_t slot,
1120 uint32_t current_slot,
1121 bool not_in_payload) {
1122 std::string device_dir_str;
1123 if (!GetDeviceDir(&device_dir_str)) {
1124 LOG(ERROR) << "Failed to GetDeviceDir()";
1125 return {};
1126 }
1127 const base::FilePath device_dir(device_dir_str);
1128 // When VABC is enabled, we can't get device path for dynamic partitions in
1129 // target slot.
1130 const auto& partition_name_suffix =
1131 partition_name + SlotSuffixForSlotNumber(slot);
Kelvin Zhangebd115e2021-03-08 16:10:25 -05001132 if (UpdateUsesSnapshotCompression() && slot != current_slot &&
1133 IsDynamicPartition(partition_name, slot)) {
Kelvin Zhang91ad6622021-03-01 13:46:17 -05001134 return {
Kelvin Zhanga9b5d8c2021-05-05 09:17:46 -04001135 {.readonly_device_path = base::FilePath{std::string{VABC_DEVICE_DIR}}
1136 .Append(partition_name_suffix)
1137 .value(),
Kelvin Zhang91ad6622021-03-01 13:46:17 -05001138 .is_dynamic = true}};
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001139 }
1140
1141 // When looking up target partition devices, treat them as static if the
1142 // current payload doesn't encode them as dynamic partitions. This may happen
1143 // when applying a retrofit update on top of a dynamic-partitions-enabled
1144 // build.
1145 std::string device;
1146 if (GetDynamicPartitionsFeatureFlag().IsEnabled() &&
1147 (slot == current_slot || is_target_dynamic_)) {
1148 switch (GetDynamicPartitionDevice(device_dir,
1149 partition_name_suffix,
1150 slot,
1151 current_slot,
1152 not_in_payload,
1153 &device)) {
1154 case DynamicPartitionDeviceStatus::SUCCESS:
1155 return {{.rw_device_path = device,
Kelvin Zhanga9b5d8c2021-05-05 09:17:46 -04001156 .readonly_device_path = device,
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001157 .is_dynamic = true}};
1158
1159 case DynamicPartitionDeviceStatus::TRY_STATIC:
1160 break;
1161 case DynamicPartitionDeviceStatus::ERROR: // fallthrough
1162 default:
1163 return {};
1164 }
1165 }
1166 // Try static partitions.
1167 auto static_path = GetStaticDevicePath(device_dir, partition_name_suffix);
1168 if (!DeviceExists(static_path)) {
1169 LOG(ERROR) << "Device file " << static_path << " does not exist.";
1170 return {};
1171 }
1172
1173 return {{.rw_device_path = static_path,
Kelvin Zhanga9b5d8c2021-05-05 09:17:46 -04001174 .readonly_device_path = static_path,
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001175 .is_dynamic = false}};
1176}
1177
Yifan Hong3a1a5612019-11-05 16:34:32 -08001178bool DynamicPartitionControlAndroid::IsSuperBlockDevice(
1179 const base::FilePath& device_dir,
1180 uint32_t current_slot,
1181 const std::string& partition_name_suffix) {
1182 std::string source_device =
1183 device_dir.Append(GetSuperPartitionName(current_slot)).value();
1184 auto source_metadata = LoadMetadataBuilder(source_device, current_slot);
1185 return source_metadata->HasBlockDevice(partition_name_suffix);
1186}
1187
1188DynamicPartitionControlAndroid::DynamicPartitionDeviceStatus
1189DynamicPartitionControlAndroid::GetDynamicPartitionDevice(
1190 const base::FilePath& device_dir,
1191 const std::string& partition_name_suffix,
1192 uint32_t slot,
1193 uint32_t current_slot,
Tianjie51a5a392020-06-03 14:39:32 -07001194 bool not_in_payload,
Yifan Hong3a1a5612019-11-05 16:34:32 -08001195 std::string* device) {
1196 std::string super_device =
1197 device_dir.Append(GetSuperPartitionName(slot)).value();
1198
1199 auto builder = LoadMetadataBuilder(super_device, slot);
1200 if (builder == nullptr) {
1201 LOG(ERROR) << "No metadata in slot "
1202 << BootControlInterface::SlotName(slot);
1203 return DynamicPartitionDeviceStatus::ERROR;
1204 }
1205 if (builder->FindPartition(partition_name_suffix) == nullptr) {
1206 LOG(INFO) << partition_name_suffix
1207 << " is not in super partition metadata.";
1208
1209 if (IsSuperBlockDevice(device_dir, current_slot, partition_name_suffix)) {
1210 LOG(ERROR) << "The static partition " << partition_name_suffix
1211 << " is a block device for current metadata."
1212 << "It cannot be used as a logical partition.";
1213 return DynamicPartitionDeviceStatus::ERROR;
1214 }
1215
1216 return DynamicPartitionDeviceStatus::TRY_STATIC;
1217 }
1218
1219 if (slot == current_slot) {
1220 if (GetState(partition_name_suffix) != DmDeviceState::ACTIVE) {
1221 LOG(WARNING) << partition_name_suffix << " is at current slot but it is "
1222 << "not mapped. Now try to map it.";
1223 } else {
1224 if (GetDmDevicePathByName(partition_name_suffix, device)) {
1225 LOG(INFO) << partition_name_suffix
1226 << " is mapped on device mapper: " << *device;
1227 return DynamicPartitionDeviceStatus::SUCCESS;
1228 }
1229 LOG(ERROR) << partition_name_suffix << "is mapped but path is unknown.";
1230 return DynamicPartitionDeviceStatus::ERROR;
1231 }
1232 }
1233
Tianjie51a5a392020-06-03 14:39:32 -07001234 bool force_writable = (slot != current_slot) && !not_in_payload;
Yifan Hong3a1a5612019-11-05 16:34:32 -08001235 if (MapPartitionOnDeviceMapper(
1236 super_device, partition_name_suffix, slot, force_writable, device)) {
1237 return DynamicPartitionDeviceStatus::SUCCESS;
1238 }
1239 return DynamicPartitionDeviceStatus::ERROR;
1240}
1241
Yifan Hong6eec9952019-12-04 13:12:01 -08001242void DynamicPartitionControlAndroid::set_fake_mapped_devices(
1243 const std::set<std::string>& fake) {
1244 mapped_devices_ = fake;
1245}
1246
Yifan Hongbae27842019-10-24 16:56:12 -07001247bool DynamicPartitionControlAndroid::IsRecovery() {
Kelvin Zhanga22ef552020-10-12 19:03:52 -04001248 return constants::kIsRecovery;
Yifan Hongbae27842019-10-24 16:56:12 -07001249}
1250
1251static bool IsIncrementalUpdate(const DeltaArchiveManifest& manifest) {
1252 const auto& partitions = manifest.partitions();
1253 return std::any_of(partitions.begin(), partitions.end(), [](const auto& p) {
1254 return p.has_old_partition_info();
1255 });
1256}
1257
1258bool DynamicPartitionControlAndroid::DeleteSourcePartitions(
1259 MetadataBuilder* builder,
1260 uint32_t source_slot,
1261 const DeltaArchiveManifest& manifest) {
1262 TEST_AND_RETURN_FALSE(IsRecovery());
1263
1264 if (IsIncrementalUpdate(manifest)) {
1265 LOG(ERROR) << "Cannot sideload incremental OTA because snapshots cannot "
1266 << "be created.";
1267 if (GetVirtualAbFeatureFlag().IsLaunch()) {
1268 LOG(ERROR) << "Sideloading incremental updates on devices launches "
1269 << " Virtual A/B is not supported.";
1270 }
1271 return false;
1272 }
1273
1274 LOG(INFO) << "Will overwrite existing partitions. Slot "
1275 << BootControlInterface::SlotName(source_slot)
Tianjie9f4dc7f2021-03-15 16:00:50 -07001276 << " may be unbootable until update finishes!";
Yifan Hongbae27842019-10-24 16:56:12 -07001277 const std::string source_suffix = SlotSuffixForSlotNumber(source_slot);
1278 DeleteGroupsWithSuffix(builder, source_suffix);
1279
1280 return true;
1281}
1282
Yifan Hong90965502020-02-19 15:22:47 -08001283std::unique_ptr<AbstractAction>
1284DynamicPartitionControlAndroid::GetCleanupPreviousUpdateAction(
1285 BootControlInterface* boot_control,
1286 PrefsInterface* prefs,
1287 CleanupPreviousUpdateActionDelegateInterface* delegate) {
1288 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1289 return std::make_unique<NoOpAction>();
1290 }
1291 return std::make_unique<CleanupPreviousUpdateAction>(
1292 prefs, boot_control, snapshot_.get(), delegate);
1293}
1294
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001295bool DynamicPartitionControlAndroid::ResetUpdate(PrefsInterface* prefs) {
1296 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1297 return true;
1298 }
Kelvin Zhangff5380b2022-03-16 13:35:04 -07001299 for (auto& list : dynamic_partition_list_) {
1300 list.clear();
1301 }
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001302
1303 LOG(INFO) << __func__ << " resetting update state and deleting snapshots.";
1304 TEST_AND_RETURN_FALSE(prefs != nullptr);
1305
1306 // If the device has already booted into the target slot,
1307 // ResetUpdateProgress may pass but CancelUpdate fails.
1308 // This is expected. A scheduled CleanupPreviousUpdateAction should free
1309 // space when it is done.
1310 TEST_AND_RETURN_FALSE(DeltaPerformer::ResetUpdateProgress(
1311 prefs, false /* quick */, false /* skip dynamic partitions metadata */));
1312
Yifan Hong4d7c5eb2020-04-03 11:31:50 -07001313 if (ExpectMetadataMounted()) {
1314 TEST_AND_RETURN_FALSE(snapshot_->CancelUpdate());
1315 } else {
1316 LOG(INFO) << "Skip cancelling update in ResetUpdate because /metadata is "
1317 << "not mounted";
1318 }
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001319
1320 return true;
1321}
1322
Tianjie99d570d2020-06-04 14:57:19 -07001323bool DynamicPartitionControlAndroid::ListDynamicPartitionsForSlot(
Tianjie3a55fc22021-02-13 16:02:22 -08001324 uint32_t slot,
1325 uint32_t current_slot,
1326 std::vector<std::string>* partitions) {
Kelvin Zhangebd115e2021-03-08 16:10:25 -05001327 CHECK(slot == source_slot_ || target_slot_ != UINT32_MAX)
1328 << " source slot: " << source_slot_ << " target slot: " << target_slot_
1329 << " slot: " << slot
1330 << " attempting to query dynamic partition metadata for target slot "
1331 "before PreparePartitionForUpdate() is called. The "
1332 "metadata in target slot isn't valid until "
1333 "PreparePartitionForUpdate() is called, contining execution would "
1334 "likely cause problems.";
Tianjie3a55fc22021-02-13 16:02:22 -08001335 bool slot_enables_dynamic_partitions =
1336 GetDynamicPartitionsFeatureFlag().IsEnabled();
1337 // Check if the target slot has dynamic partitions, this may happen when
1338 // applying a retrofit package.
1339 if (slot != current_slot) {
1340 slot_enables_dynamic_partitions =
1341 slot_enables_dynamic_partitions && is_target_dynamic_;
1342 }
1343
1344 if (!slot_enables_dynamic_partitions) {
1345 LOG(INFO) << "Dynamic partition is not enabled for slot " << slot;
1346 return true;
Tianjie99d570d2020-06-04 14:57:19 -07001347 }
1348
1349 std::string device_dir_str;
1350 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
1351 base::FilePath device_dir(device_dir_str);
Tianjie3a55fc22021-02-13 16:02:22 -08001352 auto super_device = device_dir.Append(GetSuperPartitionName(slot)).value();
1353 auto builder = LoadMetadataBuilder(super_device, slot);
Tianjie99d570d2020-06-04 14:57:19 -07001354 TEST_AND_RETURN_FALSE(builder != nullptr);
1355
1356 std::vector<std::string> result;
Tianjie3a55fc22021-02-13 16:02:22 -08001357 auto suffix = SlotSuffixForSlotNumber(slot);
Tianjie99d570d2020-06-04 14:57:19 -07001358 for (const auto& group : builder->ListGroups()) {
1359 for (const auto& partition : builder->ListPartitionsInGroup(group)) {
1360 std::string_view partition_name = partition->name();
1361 if (!android::base::ConsumeSuffix(&partition_name, suffix)) {
1362 continue;
1363 }
1364 result.emplace_back(partition_name);
1365 }
1366 }
1367 *partitions = std::move(result);
1368 return true;
1369}
1370
Tianjie24f96092020-06-30 12:26:25 -07001371bool DynamicPartitionControlAndroid::VerifyExtentsForUntouchedPartitions(
1372 uint32_t source_slot,
1373 uint32_t target_slot,
1374 const std::vector<std::string>& partitions) {
1375 std::string device_dir_str;
1376 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
1377 base::FilePath device_dir(device_dir_str);
1378
1379 auto source_super_device =
1380 device_dir.Append(GetSuperPartitionName(source_slot)).value();
1381 auto source_builder = LoadMetadataBuilder(source_super_device, source_slot);
1382 TEST_AND_RETURN_FALSE(source_builder != nullptr);
1383
1384 auto target_super_device =
1385 device_dir.Append(GetSuperPartitionName(target_slot)).value();
1386 auto target_builder = LoadMetadataBuilder(target_super_device, target_slot);
1387 TEST_AND_RETURN_FALSE(target_builder != nullptr);
1388
1389 return MetadataBuilder::VerifyExtentsAgainstSourceMetadata(
1390 *source_builder, source_slot, *target_builder, target_slot, partitions);
1391}
1392
Yifan Hong4d7c5eb2020-04-03 11:31:50 -07001393bool DynamicPartitionControlAndroid::ExpectMetadataMounted() {
1394 // No need to mount metadata for non-Virtual A/B devices.
1395 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1396 return false;
1397 }
1398 // Intentionally not checking |metadata_device_| in Android mode.
1399 // /metadata should always be mounted in Android mode. If it isn't, let caller
1400 // fails when calling into SnapshotManager.
1401 if (!IsRecovery()) {
1402 return true;
1403 }
1404 // In recovery mode, explicitly check |metadata_device_|.
1405 return metadata_device_ != nullptr;
1406}
1407
1408bool DynamicPartitionControlAndroid::EnsureMetadataMounted() {
1409 // No need to mount metadata for non-Virtual A/B devices.
1410 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1411 return true;
1412 }
1413
1414 if (metadata_device_ == nullptr) {
1415 metadata_device_ = snapshot_->EnsureMetadataMounted();
1416 }
1417 return metadata_device_ != nullptr;
1418}
1419
Kelvin Zhang34618522020-09-28 09:21:02 -04001420std::unique_ptr<android::snapshot::ISnapshotWriter>
1421DynamicPartitionControlAndroid::OpenCowWriter(
1422 const std::string& partition_name,
1423 const std::optional<std::string>& source_path,
1424 bool is_append) {
1425 auto suffix = SlotSuffixForSlotNumber(target_slot_);
1426
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -04001427 auto super_device = GetSuperDevice();
1428 if (!super_device.has_value()) {
Kelvin Zhang34618522020-09-28 09:21:02 -04001429 return nullptr;
1430 }
Kelvin Zhang34618522020-09-28 09:21:02 -04001431 CreateLogicalPartitionParams params = {
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -04001432 .block_device = super_device->value(),
Kelvin Zhang34618522020-09-28 09:21:02 -04001433 .metadata_slot = target_slot_,
1434 .partition_name = partition_name + suffix,
1435 .force_writable = true,
Kelvin Zhang877ddbe2020-11-09 13:37:56 -05001436 .timeout_ms = kMapSnapshotTimeout};
Kelvin Zhang34618522020-09-28 09:21:02 -04001437 // TODO(zhangkelvin) Open an APPEND mode CowWriter once there's an API to do
1438 // it.
1439 return snapshot_->OpenSnapshotWriter(params, std::move(source_path));
Kelvin Zhang877ddbe2020-11-09 13:37:56 -05001440} // namespace chromeos_update_engine
Kelvin Zhang34618522020-09-28 09:21:02 -04001441
Kelvin Zhang1a0ed712022-01-26 16:09:05 -08001442std::unique_ptr<FileDescriptor> DynamicPartitionControlAndroid::OpenCowFd(
Kelvin Zhangc82511c2020-11-06 16:01:24 -05001443 const std::string& unsuffixed_partition_name,
1444 const std::optional<std::string>& source_path,
1445 bool is_append) {
1446 auto cow_writer =
1447 OpenCowWriter(unsuffixed_partition_name, source_path, is_append);
1448 if (cow_writer == nullptr) {
1449 return nullptr;
1450 }
Kelvin Zhang21a49912021-03-12 14:28:33 -05001451 if (!cow_writer->InitializeAppend(kEndOfInstallLabel)) {
Kelvin Zhang77804b42021-12-30 09:04:54 -08001452 LOG(ERROR) << "Failed to InitializeAppend(" << kEndOfInstallLabel << ")";
Kelvin Zhang21a49912021-03-12 14:28:33 -05001453 return nullptr;
1454 }
Kelvin Zhang77804b42021-12-30 09:04:54 -08001455 auto reader = cow_writer->OpenReader();
1456 if (reader == nullptr) {
1457 LOG(ERROR) << "ICowWriter::OpenReader() failed.";
1458 return nullptr;
1459 }
Kelvin Zhang1a0ed712022-01-26 16:09:05 -08001460 return std::make_unique<CowWriterFileDescriptor>(std::move(cow_writer),
Kelvin Zhang77804b42021-12-30 09:04:54 -08001461 std::move(reader));
Kelvin Zhangc82511c2020-11-06 16:01:24 -05001462}
1463
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -04001464std::optional<base::FilePath> DynamicPartitionControlAndroid::GetSuperDevice() {
1465 std::string device_dir_str;
1466 if (!GetDeviceDir(&device_dir_str)) {
1467 LOG(ERROR) << "Failed to get device dir!";
1468 return {};
1469 }
1470 base::FilePath device_dir(device_dir_str);
1471 auto super_device = device_dir.Append(GetSuperPartitionName(target_slot_));
1472 return super_device;
1473}
1474
1475bool DynamicPartitionControlAndroid::MapAllPartitions() {
Kelvin Zhang877ddbe2020-11-09 13:37:56 -05001476 return snapshot_->MapAllSnapshots(kMapSnapshotTimeout);
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -04001477}
1478
Kelvin Zhangeb9de162020-11-16 15:47:28 -05001479bool DynamicPartitionControlAndroid::IsDynamicPartition(
Kelvin Zhangebd115e2021-03-08 16:10:25 -05001480 const std::string& partition_name, uint32_t slot) {
1481 if (slot >= dynamic_partition_list_.size()) {
1482 LOG(ERROR) << "Seeing unexpected slot # " << slot << " currently assuming "
1483 << dynamic_partition_list_.size() << " slots";
1484 return false;
1485 }
1486 auto& dynamic_partition_list = dynamic_partition_list_[slot];
1487 if (dynamic_partition_list.empty() &&
Kelvin Zhangeb9de162020-11-16 15:47:28 -05001488 GetDynamicPartitionsFeatureFlag().IsEnabled()) {
Tianjie3a55fc22021-02-13 16:02:22 -08001489 // Use the DAP config of the target slot.
1490 CHECK(ListDynamicPartitionsForSlot(
Kelvin Zhangebd115e2021-03-08 16:10:25 -05001491 slot, source_slot_, &dynamic_partition_list));
Kelvin Zhangeb9de162020-11-16 15:47:28 -05001492 }
Kelvin Zhangebd115e2021-03-08 16:10:25 -05001493 return std::find(dynamic_partition_list.begin(),
1494 dynamic_partition_list.end(),
1495 partition_name) != dynamic_partition_list.end();
Kelvin Zhangeb9de162020-11-16 15:47:28 -05001496}
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001497
Yifan Hongb0cbd392021-02-04 11:11:45 -08001498bool DynamicPartitionControlAndroid::UpdateUsesSnapshotCompression() {
Kelvin Zhang741c2d42021-04-13 12:40:38 -04001499 return GetVirtualAbFeatureFlag().IsEnabled() &&
1500 snapshot_->UpdateUsesCompression();
Yifan Hongb0cbd392021-02-04 11:11:45 -08001501}
1502
David Andersone35b4382022-03-08 23:18:29 -08001503FeatureFlag
1504DynamicPartitionControlAndroid::GetVirtualAbUserspaceSnapshotsFeatureFlag() {
1505 return virtual_ab_userspace_snapshots_;
1506}
1507
Yifan Hong537802d2018-08-15 13:15:42 -07001508} // namespace chromeos_update_engine