blob: d1c3bf26392fad41c5cee5d35421a1c232928b8b [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>
Kelvin Zhang08bbbd42024-08-27 13:25:07 -070022#include <iterator>
Yifan Hong13d41cb2019-09-16 13:18:22 -070023#include <map>
Yifan Hong537802d2018-08-15 13:15:42 -070024#include <memory>
25#include <set>
26#include <string>
Tianjie99d570d2020-06-04 14:57:19 -070027#include <string_view>
28#include <utility>
Yifan Hong012508e2019-07-22 18:30:40 -070029#include <vector>
Yifan Hong537802d2018-08-15 13:15:42 -070030
31#include <android-base/properties.h>
32#include <android-base/strings.h>
33#include <base/files/file_util.h>
34#include <base/logging.h>
Kelvin Zhangb9a9aa22024-10-15 10:38:35 -070035#include <android-base/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"
Daniel Zhengeede4c82023-06-13 11:21:06 -070051#include "update_engine/common/error_code.h"
Kelvin Zhangb9a5f612021-01-22 14:34:05 -050052#include "update_engine/common/platform_constants.h"
Yifan Hong537802d2018-08-15 13:15:42 -070053#include "update_engine/common/utils.h"
Kelvin Zhang21a49912021-03-12 14:28:33 -050054#include "update_engine/payload_consumer/cow_writer_file_descriptor.h"
Yifan Hong6a6d0f12020-03-11 13:20:52 -070055#include "update_engine/payload_consumer/delta_performer.h"
Yifan Hong537802d2018-08-15 13:15:42 -070056
57using android::base::GetBoolProperty;
Yifan Hong29692902020-03-26 12:47:05 -070058using android::base::GetProperty;
Yifan Hong537802d2018-08-15 13:15:42 -070059using android::base::Join;
Kelvin Zhangb9a9aa22024-10-15 10:38:35 -070060using android::base::StringPrintf;
Yifan Hong537802d2018-08-15 13:15:42 -070061using android::dm::DeviceMapper;
62using android::dm::DmDeviceState;
63using android::fs_mgr::CreateLogicalPartition;
David Andersonbb90dfb2019-08-13 14:14:56 -070064using android::fs_mgr::CreateLogicalPartitionParams;
Yifan Hong537802d2018-08-15 13:15:42 -070065using android::fs_mgr::DestroyLogicalPartition;
Yifan Hong29692902020-03-26 12:47:05 -070066using android::fs_mgr::Fstab;
Yifan Hong537802d2018-08-15 13:15:42 -070067using android::fs_mgr::MetadataBuilder;
Yifan Hong012508e2019-07-22 18:30:40 -070068using android::fs_mgr::Partition;
Yifan Hong6e706b12018-11-09 16:50:51 -080069using android::fs_mgr::PartitionOpener;
Yifan Hong012508e2019-07-22 18:30:40 -070070using android::fs_mgr::SlotSuffixForSlotNumber;
Yifan Hongf5261562020-03-10 10:28:10 -070071using android::snapshot::OptimizeSourceCopyOperation;
Yifan Hong0850bca2020-01-16 15:14:07 -080072using android::snapshot::Return;
Yifan Hongf033ecb2020-01-07 18:13:56 -080073using android::snapshot::SnapshotManager;
Yifan Hongf9cb4492020-04-15 13:00:20 -070074using android::snapshot::SnapshotManagerStub;
Yifan Hong2257ee12020-01-13 18:33:00 -080075using android::snapshot::UpdateState;
Yifan Hong537802d2018-08-15 13:15:42 -070076
77namespace chromeos_update_engine {
78
Yifan Hong6e706b12018-11-09 16:50:51 -080079constexpr char kUseDynamicPartitions[] = "ro.boot.dynamic_partitions";
80constexpr char kRetrfoitDynamicPartitions[] =
81 "ro.boot.dynamic_partitions_retrofit";
Yifan Hong413d5722019-07-23 14:21:09 -070082constexpr char kVirtualAbEnabled[] = "ro.virtual_ab.enabled";
83constexpr char kVirtualAbRetrofit[] = "ro.virtual_ab.retrofit";
Kelvin Zhangda1b3142020-09-24 17:09:02 -040084constexpr char kVirtualAbCompressionEnabled[] =
85 "ro.virtual_ab.compression.enabled";
Kelvin Zhang1c4b9812022-04-06 17:29:00 -070086constexpr auto&& kVirtualAbCompressionXorEnabled =
87 "ro.virtual_ab.compression.xor.enabled";
David Andersone35b4382022-03-08 23:18:29 -080088constexpr char kVirtualAbUserspaceSnapshotsEnabled[] =
89 "ro.virtual_ab.userspace.snapshots.enabled";
Kelvin Zhangda1b3142020-09-24 17:09:02 -040090
91// Currently, android doesn't have a retrofit prop for VAB Compression. However,
92// struct FeatureFlag forces us to determine if a feature is 'retrofit'. So this
93// is here just to simplify code. Replace it with real retrofit prop name once
94// there is one.
95constexpr char kVirtualAbCompressionRetrofit[] = "";
Yifan Hong29692902020-03-26 12:47:05 -070096constexpr char kPostinstallFstabPrefix[] = "ro.postinstall.fstab.prefix";
Yifan Hong420db9b2019-07-23 20:50:33 -070097// Map timeout for dynamic partitions.
98constexpr std::chrono::milliseconds kMapTimeout{1000};
99// Map timeout for dynamic partitions with snapshots. Since several devices
100// needs to be mapped, this timeout is longer than |kMapTimeout|.
Kelvin Zhangcf3280b2021-09-01 19:36:01 -0700101constexpr std::chrono::milliseconds kMapSnapshotTimeout{10000};
Yifan Hong420db9b2019-07-23 20:50:33 -0700102
Yifan Hong537802d2018-08-15 13:15:42 -0700103DynamicPartitionControlAndroid::~DynamicPartitionControlAndroid() {
Kelvin Zhang08bbbd42024-08-27 13:25:07 -0700104 std::set<std::string> mapped = mapped_devices_;
105 LOG(INFO) << "Destroying [" << Join(mapped, ", ") << "] from device mapper";
106 for (const auto& device_name : mapped) {
107 ignore_result(UnmapPartitionOnDeviceMapper(device_name));
108 }
Kelvin Zhangc675fc02022-06-22 10:18:54 -0700109 metadata_device_.reset();
Yifan Hong537802d2018-08-15 13:15:42 -0700110}
111
Yifan Hong186bb682019-07-23 14:04:39 -0700112static FeatureFlag GetFeatureFlag(const char* enable_prop,
113 const char* retrofit_prop) {
Kelvin Zhangda1b3142020-09-24 17:09:02 -0400114 // Default retrofit to false if retrofit_prop is empty.
115 bool retrofit = retrofit_prop && retrofit_prop[0] != '\0' &&
116 GetBoolProperty(retrofit_prop, false);
Yifan Hong186bb682019-07-23 14:04:39 -0700117 bool enabled = GetBoolProperty(enable_prop, false);
118 if (retrofit && !enabled) {
119 LOG(ERROR) << retrofit_prop << " is true but " << enable_prop
120 << " is not. These sysprops are inconsistent. Assume that "
121 << enable_prop << " is true from now on.";
122 }
123 if (retrofit) {
124 return FeatureFlag(FeatureFlag::Value::RETROFIT);
125 }
126 if (enabled) {
127 return FeatureFlag(FeatureFlag::Value::LAUNCH);
128 }
129 return FeatureFlag(FeatureFlag::Value::NONE);
Yifan Hong537802d2018-08-15 13:15:42 -0700130}
131
Kelvin Zhangebd115e2021-03-08 16:10:25 -0500132DynamicPartitionControlAndroid::DynamicPartitionControlAndroid(
133 uint32_t source_slot)
Yifan Hongb38e1af2019-10-17 14:59:22 -0700134 : dynamic_partitions_(
135 GetFeatureFlag(kUseDynamicPartitions, kRetrfoitDynamicPartitions)),
Kelvin Zhangda1b3142020-09-24 17:09:02 -0400136 virtual_ab_(GetFeatureFlag(kVirtualAbEnabled, kVirtualAbRetrofit)),
137 virtual_ab_compression_(GetFeatureFlag(kVirtualAbCompressionEnabled,
Kelvin Zhangebd115e2021-03-08 16:10:25 -0500138 kVirtualAbCompressionRetrofit)),
Kelvin Zhang1c4b9812022-04-06 17:29:00 -0700139 virtual_ab_compression_xor_(
140 GetFeatureFlag(kVirtualAbCompressionXorEnabled, "")),
David Andersone35b4382022-03-08 23:18:29 -0800141 virtual_ab_userspace_snapshots_(
142 GetFeatureFlag(kVirtualAbUserspaceSnapshotsEnabled, nullptr)),
Kelvin Zhangebd115e2021-03-08 16:10:25 -0500143 source_slot_(source_slot) {
Yifan Hongb38e1af2019-10-17 14:59:22 -0700144 if (GetVirtualAbFeatureFlag().IsEnabled()) {
Yifan Hongf033ecb2020-01-07 18:13:56 -0800145 snapshot_ = SnapshotManager::New();
Yifan Hongf9cb4492020-04-15 13:00:20 -0700146 } else {
147 snapshot_ = SnapshotManagerStub::New();
Yifan Hongb38e1af2019-10-17 14:59:22 -0700148 }
Yifan Hongf9cb4492020-04-15 13:00:20 -0700149 CHECK(snapshot_ != nullptr) << "Cannot initialize SnapshotManager.";
Yifan Hongb38e1af2019-10-17 14:59:22 -0700150}
151
Yifan Hong186bb682019-07-23 14:04:39 -0700152FeatureFlag DynamicPartitionControlAndroid::GetDynamicPartitionsFeatureFlag() {
Yifan Hongb38e1af2019-10-17 14:59:22 -0700153 return dynamic_partitions_;
Yifan Hong6e706b12018-11-09 16:50:51 -0800154}
155
Yifan Hong413d5722019-07-23 14:21:09 -0700156FeatureFlag DynamicPartitionControlAndroid::GetVirtualAbFeatureFlag() {
Yifan Hongb38e1af2019-10-17 14:59:22 -0700157 return virtual_ab_;
Yifan Hong413d5722019-07-23 14:21:09 -0700158}
159
Kelvin Zhangda1b3142020-09-24 17:09:02 -0400160FeatureFlag
161DynamicPartitionControlAndroid::GetVirtualAbCompressionFeatureFlag() {
Kelvin Zhangb9a5f612021-01-22 14:34:05 -0500162 if constexpr (constants::kIsRecovery) {
163 // Don't attempt VABC in recovery
164 return FeatureFlag(FeatureFlag::Value::NONE);
165 }
Kelvin Zhangda1b3142020-09-24 17:09:02 -0400166 return virtual_ab_compression_;
167}
168
Kelvin Zhang1c4b9812022-04-06 17:29:00 -0700169FeatureFlag
170DynamicPartitionControlAndroid::GetVirtualAbCompressionXorFeatureFlag() {
171 return virtual_ab_compression_xor_;
172}
173
Yifan Hongf5261562020-03-10 10:28:10 -0700174bool DynamicPartitionControlAndroid::OptimizeOperation(
175 const std::string& partition_name,
176 const InstallOperation& operation,
177 InstallOperation* optimized) {
Alessio Balsini2a3b4a22019-11-25 16:46:51 +0000178 switch (operation.type()) {
179 case InstallOperation::SOURCE_COPY:
180 return target_supports_snapshot_ &&
181 GetVirtualAbFeatureFlag().IsEnabled() &&
Yifan Hong6eec9952019-12-04 13:12:01 -0800182 mapped_devices_.count(partition_name +
183 SlotSuffixForSlotNumber(target_slot_)) > 0 &&
Yifan Hongf5261562020-03-10 10:28:10 -0700184 OptimizeSourceCopyOperation(operation, optimized);
Alessio Balsini2a3b4a22019-11-25 16:46:51 +0000185 break;
186 default:
187 break;
188 }
Alessio Balsini14980e22019-11-26 11:46:06 +0000189 return false;
190}
191
Kelvin Zhang08bbbd42024-08-27 13:25:07 -0700192constexpr auto&& kRWSourcePartitionSuffix = "_ota";
193std::string DynamicPartitionControlAndroid::GetDeviceName(
194 std::string partition_name, uint32_t slot) const {
195 if (partition_name.ends_with(kRWSourcePartitionSuffix)) {
196 return partition_name;
197 }
198 if (!partition_name.ends_with("_a") && !partition_name.ends_with("_b")) {
199 partition_name += slot ? "_b" : "_a";
200 }
201 if (slot == source_slot_) {
202 return partition_name + kRWSourcePartitionSuffix;
203 }
204 return partition_name;
205}
206
Yifan Hong8546a712019-03-28 14:42:53 -0700207bool DynamicPartitionControlAndroid::MapPartitionInternal(
Yifan Hong537802d2018-08-15 13:15:42 -0700208 const std::string& super_device,
209 const std::string& target_partition_name,
210 uint32_t slot,
Yifan Hongaf65ef12018-10-29 11:09:06 -0700211 bool force_writable,
Yifan Hong537802d2018-08-15 13:15:42 -0700212 std::string* path) {
Kelvin Zhang08bbbd42024-08-27 13:25:07 -0700213 auto device_name = GetDeviceName(target_partition_name, slot);
David Andersonbb90dfb2019-08-13 14:14:56 -0700214 CreateLogicalPartitionParams params = {
215 .block_device = super_device,
216 .metadata_slot = slot,
217 .partition_name = target_partition_name,
218 .force_writable = force_writable,
Kelvin Zhang08bbbd42024-08-27 13:25:07 -0700219 .device_name = device_name};
Yifan Hong420db9b2019-07-23 20:50:33 -0700220 bool success = false;
Yifan Hongf0f4a912019-09-26 17:51:33 -0700221 if (GetVirtualAbFeatureFlag().IsEnabled() && target_supports_snapshot_ &&
Kelvin Zhang8b07db52024-07-24 09:13:25 -0700222 slot != source_slot_ && force_writable && ExpectMetadataMounted()) {
Yifan Hong420db9b2019-07-23 20:50:33 -0700223 // Only target partitions are mapped with force_writable. On Virtual
224 // A/B devices, target partitions may overlap with source partitions, so
225 // they must be mapped with snapshot.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700226 // One exception is when /metadata is not mounted. Fallback to
227 // CreateLogicalPartition as snapshots are not created in the first place.
Yifan Hong420db9b2019-07-23 20:50:33 -0700228 params.timeout_ms = kMapSnapshotTimeout;
229 success = snapshot_->MapUpdateSnapshot(params, path);
230 } else {
231 params.timeout_ms = kMapTimeout;
232 success = CreateLogicalPartition(params, path);
233 }
David Andersonbb90dfb2019-08-13 14:14:56 -0700234
Yifan Hong420db9b2019-07-23 20:50:33 -0700235 if (!success) {
Yifan Hong537802d2018-08-15 13:15:42 -0700236 LOG(ERROR) << "Cannot map " << target_partition_name << " in "
237 << super_device << " on device mapper.";
238 return false;
239 }
240 LOG(INFO) << "Succesfully mapped " << target_partition_name
Yifan Hongaf65ef12018-10-29 11:09:06 -0700241 << " to device mapper (force_writable = " << force_writable
242 << "); device path at " << *path;
Kelvin Zhang08bbbd42024-08-27 13:25:07 -0700243 mapped_devices_.insert(params.device_name);
Yifan Hong537802d2018-08-15 13:15:42 -0700244 return true;
245}
246
Yifan Hong8546a712019-03-28 14:42:53 -0700247bool DynamicPartitionControlAndroid::MapPartitionOnDeviceMapper(
248 const std::string& super_device,
249 const std::string& target_partition_name,
250 uint32_t slot,
251 bool force_writable,
252 std::string* path) {
Kelvin Zhang08bbbd42024-08-27 13:25:07 -0700253 auto device_name = GetDeviceName(target_partition_name, slot);
254 DmDeviceState state = GetState(device_name);
Yifan Hong8546a712019-03-28 14:42:53 -0700255 if (state == DmDeviceState::ACTIVE) {
Kelvin Zhang08bbbd42024-08-27 13:25:07 -0700256 if (mapped_devices_.find(device_name) != mapped_devices_.end()) {
Yifan Hong8546a712019-03-28 14:42:53 -0700257 if (GetDmDevicePathByName(target_partition_name, path)) {
258 LOG(INFO) << target_partition_name
259 << " is mapped on device mapper: " << *path;
260 return true;
261 }
262 LOG(ERROR) << target_partition_name << " is mapped but path is unknown.";
263 return false;
264 }
265 // If target_partition_name is not in mapped_devices_ but state is ACTIVE,
266 // the device might be mapped incorrectly before. Attempt to unmap it.
267 // Note that for source partitions, if GetState() == ACTIVE, callers (e.g.
268 // BootControlAndroid) should not call MapPartitionOnDeviceMapper, but
269 // should directly call GetDmDevicePathByName.
Kelvin Zhang08bbbd42024-08-27 13:25:07 -0700270 LOG(INFO) << "Destroying `" << device_name << "` from device mapper";
271 if (!UnmapPartitionOnDeviceMapper(device_name)) {
Yifan Hong8546a712019-03-28 14:42:53 -0700272 LOG(ERROR) << target_partition_name
273 << " is mapped before the update, and it cannot be unmapped.";
274 return false;
275 }
Kelvin Zhang08bbbd42024-08-27 13:25:07 -0700276 state = GetState(device_name);
Yifan Hong8546a712019-03-28 14:42:53 -0700277 if (state != DmDeviceState::INVALID) {
278 LOG(ERROR) << target_partition_name << " is unmapped but state is "
279 << static_cast<std::underlying_type_t<DmDeviceState>>(state);
280 return false;
281 }
282 }
283 if (state == DmDeviceState::INVALID) {
284 return MapPartitionInternal(
285 super_device, target_partition_name, slot, force_writable, path);
286 }
287
288 LOG(ERROR) << target_partition_name
289 << " is mapped on device mapper but state is unknown: "
290 << static_cast<std::underlying_type_t<DmDeviceState>>(state);
291 return false;
292}
293
Yifan Hong537802d2018-08-15 13:15:42 -0700294bool DynamicPartitionControlAndroid::UnmapPartitionOnDeviceMapper(
David Anderson4c891c92019-06-21 17:45:23 -0700295 const std::string& target_partition_name) {
Kelvin Zhang08bbbd42024-08-27 13:25:07 -0700296 auto device_name = target_partition_name;
297 if (target_partition_name.ends_with("_a") ||
298 target_partition_name.ends_with("_b")) {
299 auto slot = target_partition_name.ends_with("_a") ? 0 : 1;
300 device_name = GetDeviceName(target_partition_name, slot);
Kelvin Zhang08bbbd42024-08-27 13:25:07 -0700301 }
302 if (DeviceMapper::Instance().GetState(device_name) !=
Yifan Hong537802d2018-08-15 13:15:42 -0700303 DmDeviceState::INVALID) {
Yifan Hong420db9b2019-07-23 20:50:33 -0700304 // Partitions at target slot on non-Virtual A/B devices are mapped as
305 // dm-linear. Also, on Virtual A/B devices, system_other may be mapped for
306 // preopt apps as dm-linear.
307 // Call DestroyLogicalPartition to handle these cases.
Kelvin Zhang08bbbd42024-08-27 13:25:07 -0700308 bool success = DestroyLogicalPartition(device_name);
Yifan Hong420db9b2019-07-23 20:50:33 -0700309
310 // On a Virtual A/B device, |target_partition_name| may be a leftover from
311 // a paused update. Clean up any underlying devices.
Kelvin Zhang08bbbd42024-08-27 13:25:07 -0700312 if (ExpectMetadataMounted() &&
313 !device_name.ends_with(kRWSourcePartitionSuffix)) {
314 success &= snapshot_->UnmapUpdateSnapshot(device_name);
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700315 } else {
Kelvin Zhang08bbbd42024-08-27 13:25:07 -0700316 LOG(INFO) << "Skip UnmapUpdateSnapshot(" << device_name << ")";
Yifan Hong420db9b2019-07-23 20:50:33 -0700317 }
318
319 if (!success) {
Kelvin Zhang08bbbd42024-08-27 13:25:07 -0700320 LOG(ERROR) << "Cannot unmap " << device_name << " from device mapper.";
Yifan Hong537802d2018-08-15 13:15:42 -0700321 return false;
322 }
Kelvin Zhang08bbbd42024-08-27 13:25:07 -0700323 LOG(INFO) << "Successfully unmapped " << device_name
Yifan Hong537802d2018-08-15 13:15:42 -0700324 << " from device mapper.";
325 }
Kelvin Zhang08bbbd42024-08-27 13:25:07 -0700326 mapped_devices_.erase(device_name);
Yifan Hong537802d2018-08-15 13:15:42 -0700327 return true;
328}
329
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -0400330bool DynamicPartitionControlAndroid::UnmapAllPartitions() {
Kelvin Zhangf7ef12a2021-03-22 12:59:06 -0400331 snapshot_->UnmapAllSnapshots();
Tao Bao8c4d0082019-08-08 08:56:16 -0700332 if (mapped_devices_.empty()) {
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -0400333 return false;
Tao Bao8c4d0082019-08-08 08:56:16 -0700334 }
Yifan Hong537802d2018-08-15 13:15:42 -0700335 // UnmapPartitionOnDeviceMapper removes objects from mapped_devices_, hence
336 // a copy is needed for the loop.
Kelvin Zhang08bbbd42024-08-27 13:25:07 -0700337 std::set<std::string> mapped;
338 std::copy_if(mapped_devices_.begin(),
339 mapped_devices_.end(),
340 std::inserter(mapped, mapped.end()),
341 [](auto&& device_name) {
342 return !std::string_view(device_name)
343 .ends_with(kRWSourcePartitionSuffix);
344 });
Yifan Hong537802d2018-08-15 13:15:42 -0700345 LOG(INFO) << "Destroying [" << Join(mapped, ", ") << "] from device mapper";
Kelvin Zhang08bbbd42024-08-27 13:25:07 -0700346 for (const auto& device_name : mapped) {
347 ignore_result(UnmapPartitionOnDeviceMapper(device_name));
Yifan Hong537802d2018-08-15 13:15:42 -0700348 }
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -0400349 return true;
Yifan Hong537802d2018-08-15 13:15:42 -0700350}
351
352void DynamicPartitionControlAndroid::Cleanup() {
Kelvin Zhang08bbbd42024-08-27 13:25:07 -0700353 std::set<std::string> mapped = mapped_devices_;
354 LOG(INFO) << "Destroying [" << Join(mapped, ", ") << "] from device mapper";
355 for (const auto& device_name : mapped) {
356 ignore_result(UnmapPartitionOnDeviceMapper(device_name));
357 }
Kelvin Zhang6bec1ed2024-07-11 09:49:59 -0700358 LOG(INFO) << "UnmapAllPartitions done";
Yifan Hongbae27842019-10-24 16:56:12 -0700359 metadata_device_.reset();
Kelvin Zhangc675fc02022-06-22 10:18:54 -0700360 if (GetVirtualAbFeatureFlag().IsEnabled()) {
361 snapshot_ = SnapshotManager::New();
362 } else {
363 snapshot_ = SnapshotManagerStub::New();
364 }
365 CHECK(snapshot_ != nullptr) << "Cannot initialize SnapshotManager.";
Kelvin Zhang6bec1ed2024-07-11 09:49:59 -0700366 LOG(INFO) << "SnapshotManager initialized.";
Yifan Hong537802d2018-08-15 13:15:42 -0700367}
368
369bool DynamicPartitionControlAndroid::DeviceExists(const std::string& path) {
370 return base::PathExists(base::FilePath(path));
371}
372
373android::dm::DmDeviceState DynamicPartitionControlAndroid::GetState(
374 const std::string& name) {
375 return DeviceMapper::Instance().GetState(name);
376}
377
378bool DynamicPartitionControlAndroid::GetDmDevicePathByName(
379 const std::string& name, std::string* path) {
380 return DeviceMapper::Instance().GetDmDevicePathByName(name, path);
381}
382
383std::unique_ptr<MetadataBuilder>
384DynamicPartitionControlAndroid::LoadMetadataBuilder(
Tianjie24f96092020-06-30 12:26:25 -0700385 const std::string& super_device, uint32_t slot) {
386 auto builder = MetadataBuilder::New(PartitionOpener(), super_device, slot);
387 if (builder == nullptr) {
388 LOG(WARNING) << "No metadata slot " << BootControlInterface::SlotName(slot)
389 << " in " << super_device;
390 return nullptr;
391 }
392 LOG(INFO) << "Loaded metadata from slot "
393 << BootControlInterface::SlotName(slot) << " in " << super_device;
394 return builder;
Yifan Hong012508e2019-07-22 18:30:40 -0700395}
396
397std::unique_ptr<MetadataBuilder>
398DynamicPartitionControlAndroid::LoadMetadataBuilder(
Yifan Hong6e706b12018-11-09 16:50:51 -0800399 const std::string& super_device,
400 uint32_t source_slot,
401 uint32_t target_slot) {
Tianjie24f96092020-06-30 12:26:25 -0700402 bool always_keep_source_slot = !target_supports_snapshot_;
403 auto builder = MetadataBuilder::NewForUpdate(PartitionOpener(),
404 super_device,
405 source_slot,
406 target_slot,
407 always_keep_source_slot);
Yifan Hong537802d2018-08-15 13:15:42 -0700408 if (builder == nullptr) {
409 LOG(WARNING) << "No metadata slot "
410 << BootControlInterface::SlotName(source_slot) << " in "
411 << super_device;
Yifan Hongf48a0052018-10-29 16:30:43 -0700412 return nullptr;
Yifan Hong537802d2018-08-15 13:15:42 -0700413 }
Tianjie24f96092020-06-30 12:26:25 -0700414 LOG(INFO) << "Created metadata for new update from slot "
Yifan Hong537802d2018-08-15 13:15:42 -0700415 << BootControlInterface::SlotName(source_slot) << " in "
416 << super_device;
417 return builder;
418}
419
420bool DynamicPartitionControlAndroid::StoreMetadata(
421 const std::string& super_device,
422 MetadataBuilder* builder,
423 uint32_t target_slot) {
424 auto metadata = builder->Export();
425 if (metadata == nullptr) {
426 LOG(ERROR) << "Cannot export metadata to slot "
427 << BootControlInterface::SlotName(target_slot) << " in "
428 << super_device;
429 return false;
430 }
431
Yifan Hong186bb682019-07-23 14:04:39 -0700432 if (GetDynamicPartitionsFeatureFlag().IsRetrofit()) {
Yifan Hong6e706b12018-11-09 16:50:51 -0800433 if (!FlashPartitionTable(super_device, *metadata)) {
434 LOG(ERROR) << "Cannot write metadata to " << super_device;
435 return false;
436 }
437 LOG(INFO) << "Written metadata to " << super_device;
438 } else {
439 if (!UpdatePartitionTable(super_device, *metadata, target_slot)) {
440 LOG(ERROR) << "Cannot write metadata to slot "
441 << BootControlInterface::SlotName(target_slot) << " in "
442 << super_device;
443 return false;
444 }
445 LOG(INFO) << "Copied metadata to slot "
446 << BootControlInterface::SlotName(target_slot) << " in "
447 << super_device;
Yifan Hong537802d2018-08-15 13:15:42 -0700448 }
449
Yifan Hong537802d2018-08-15 13:15:42 -0700450 return true;
451}
452
453bool DynamicPartitionControlAndroid::GetDeviceDir(std::string* out) {
454 // We can't use fs_mgr to look up |partition_name| because fstab
455 // doesn't list every slot partition (it uses the slotselect option
456 // to mask the suffix).
457 //
458 // We can however assume that there's an entry for the /misc mount
459 // point and use that to get the device file for the misc
460 // partition. This helps us locate the disk that |partition_name|
461 // resides on. From there we'll assume that a by-name scheme is used
462 // so we can just replace the trailing "misc" by the given
463 // |partition_name| and suffix corresponding to |slot|, e.g.
464 //
465 // /dev/block/platform/soc.0/7824900.sdhci/by-name/misc ->
466 // /dev/block/platform/soc.0/7824900.sdhci/by-name/boot_a
467 //
468 // If needed, it's possible to relax the by-name assumption in the
469 // future by trawling /sys/block looking for the appropriate sibling
470 // of misc and then finding an entry in /dev matching the sysfs
471 // entry.
472
473 std::string err, misc_device = get_bootloader_message_blk_device(&err);
474 if (misc_device.empty()) {
475 LOG(ERROR) << "Unable to get misc block device: " << err;
476 return false;
477 }
478
479 if (!utils::IsSymlink(misc_device.c_str())) {
480 LOG(ERROR) << "Device file " << misc_device << " for /misc "
481 << "is not a symlink.";
482 return false;
483 }
484 *out = base::FilePath(misc_device).DirName().value();
485 return true;
486}
Yifan Hong012508e2019-07-22 18:30:40 -0700487
488bool DynamicPartitionControlAndroid::PreparePartitionsForUpdate(
489 uint32_t source_slot,
490 uint32_t target_slot,
Yifan Hongf0f4a912019-09-26 17:51:33 -0700491 const DeltaArchiveManifest& manifest,
Yifan Hongf033ecb2020-01-07 18:13:56 -0800492 bool update,
Daniel Zhengeede4c82023-06-13 11:21:06 -0700493 uint64_t* required_size,
494 ErrorCode* error) {
Yifan Hong6eec9952019-12-04 13:12:01 -0800495 source_slot_ = source_slot;
496 target_slot_ = target_slot;
Yifan Hongf033ecb2020-01-07 18:13:56 -0800497 if (required_size != nullptr) {
498 *required_size = 0;
499 }
Yifan Hong6eec9952019-12-04 13:12:01 -0800500
Yifan Hong3a1a5612019-11-05 16:34:32 -0800501 if (fs_mgr_overlayfs_is_setup()) {
502 // Non DAP devices can use overlayfs as well.
Daniel Zhengeede4c82023-06-13 11:21:06 -0700503 LOG(ERROR)
Yifan Hong3a1a5612019-11-05 16:34:32 -0800504 << "overlayfs overrides are active and can interfere with our "
505 "resources.\n"
506 << "run adb enable-verity to deactivate if required and try again.";
Daniel Zhengeede4c82023-06-13 11:21:06 -0700507 if (error) {
508 *error = ErrorCode::kOverlayfsenabledError;
509 return false;
510 }
Yifan Hong3a1a5612019-11-05 16:34:32 -0800511 }
512
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700513 // If metadata is erased but not formatted, it is possible to not mount
514 // it in recovery. It is acceptable to skip mounting and choose fallback path
515 // (PrepareDynamicPartitionsForUpdate) when sideloading full OTAs.
516 TEST_AND_RETURN_FALSE(EnsureMetadataMounted() || IsRecovery());
Yifan Hong29692902020-03-26 12:47:05 -0700517
518 if (update) {
519 TEST_AND_RETURN_FALSE(EraseSystemOtherAvbFooter(source_slot, target_slot));
520 }
521
Yifan Hong3a1a5612019-11-05 16:34:32 -0800522 if (!GetDynamicPartitionsFeatureFlag().IsEnabled()) {
523 return true;
524 }
525
526 if (target_slot == source_slot) {
527 LOG(ERROR) << "Cannot call PreparePartitionsForUpdate on current slot.";
528 return false;
529 }
530
Yifan Hongf6f75c22020-07-31 15:20:25 -0700531 if (!SetTargetBuildVars(manifest)) {
532 return false;
533 }
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700534 for (auto& list : dynamic_partition_list_) {
535 list.clear();
536 }
Yifan Hongf6f75c22020-07-31 15:20:25 -0700537
Yifan Hong3a1a5612019-11-05 16:34:32 -0800538 // Although the current build supports dynamic partitions, the given payload
539 // doesn't use it for target partitions. This could happen when applying a
540 // retrofit update. Skip updating the partition metadata for the target slot.
Yifan Hong3a1a5612019-11-05 16:34:32 -0800541 if (!is_target_dynamic_) {
542 return true;
543 }
544
Yifan Hongf0f4a912019-09-26 17:51:33 -0700545 if (!update)
546 return true;
547
Yifan Hongbae27842019-10-24 16:56:12 -0700548 bool delete_source = false;
549
Yifan Hong6d888562019-10-01 13:00:31 -0700550 if (GetVirtualAbFeatureFlag().IsEnabled()) {
551 // On Virtual A/B device, either CancelUpdate() or BeginUpdate() must be
552 // called before calling UnmapUpdateSnapshot.
553 // - If target_supports_snapshot_, PrepareSnapshotPartitionsForUpdate()
554 // calls BeginUpdate() which resets update state
Yifan Hongbae27842019-10-24 16:56:12 -0700555 // - If !target_supports_snapshot_ or PrepareSnapshotPartitionsForUpdate
556 // failed in recovery, explicitly CancelUpdate().
Yifan Hong6d888562019-10-01 13:00:31 -0700557 if (target_supports_snapshot_) {
Yifan Hongbae27842019-10-24 16:56:12 -0700558 if (PrepareSnapshotPartitionsForUpdate(
559 source_slot, target_slot, manifest, required_size)) {
560 return true;
561 }
562
563 // Virtual A/B device doing Virtual A/B update in Android mode must use
564 // snapshots.
565 if (!IsRecovery()) {
566 LOG(ERROR) << "PrepareSnapshotPartitionsForUpdate failed in Android "
567 << "mode";
568 return false;
569 }
570
571 delete_source = true;
572 LOG(INFO) << "PrepareSnapshotPartitionsForUpdate failed in recovery. "
573 << "Attempt to overwrite existing partitions if possible";
574 } else {
575 // Downgrading to an non-Virtual A/B build or is secondary OTA.
576 LOG(INFO) << "Using regular A/B on Virtual A/B because package disabled "
577 << "snapshots.";
Yifan Hong6d888562019-10-01 13:00:31 -0700578 }
Yifan Hongbae27842019-10-24 16:56:12 -0700579
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700580 // In recovery, if /metadata is not mounted, it is likely that metadata
581 // partition is erased and not formatted yet. After sideloading, when
582 // rebooting into the new version, init will erase metadata partition,
583 // hence the failure of CancelUpdate() can be ignored here.
584 // However, if metadata is mounted and CancelUpdate fails, sideloading
585 // should not proceed because during next boot, snapshots will overlay on
586 // the devices incorrectly.
587 if (ExpectMetadataMounted()) {
588 TEST_AND_RETURN_FALSE(snapshot_->CancelUpdate());
589 } else {
590 LOG(INFO) << "Skip canceling previous update because metadata is not "
591 << "mounted";
Yifan Hong6d888562019-10-01 13:00:31 -0700592 }
Yifan Hong420db9b2019-07-23 20:50:33 -0700593 }
Yifan Hongbae27842019-10-24 16:56:12 -0700594
Tianjie24f96092020-06-30 12:26:25 -0700595 // TODO(xunchang) support partial update on non VAB enabled devices.
Yifan Hong5c5743f2020-04-16 12:59:07 -0700596 TEST_AND_RETURN_FALSE(PrepareDynamicPartitionsForUpdate(
597 source_slot, target_slot, manifest, delete_source));
598
599 if (required_size != nullptr) {
600 *required_size = 0;
601 }
602 return true;
Yifan Hong420db9b2019-07-23 20:50:33 -0700603}
604
Yifan Hongf6f75c22020-07-31 15:20:25 -0700605bool DynamicPartitionControlAndroid::SetTargetBuildVars(
606 const DeltaArchiveManifest& manifest) {
607 // Precondition: current build supports dynamic partition.
608 CHECK(GetDynamicPartitionsFeatureFlag().IsEnabled());
609
610 bool is_target_dynamic =
611 !manifest.dynamic_partition_metadata().groups().empty();
612 bool target_supports_snapshot =
613 manifest.dynamic_partition_metadata().snapshot_enabled();
614
615 if (manifest.partial_update()) {
616 // Partial updates requires DAP. On partial updates that does not involve
617 // dynamic partitions, groups() can be empty, so also assume
618 // is_target_dynamic in this case. This assumption should be safe because we
619 // also check target_supports_snapshot below, which presumably also implies
620 // target build supports dynamic partition.
621 if (!is_target_dynamic) {
622 LOG(INFO) << "Assuming target build supports dynamic partitions for "
623 "partial updates.";
624 is_target_dynamic = true;
625 }
626
627 // Partial updates requires Virtual A/B. Double check that both current
628 // build and target build supports Virtual A/B.
629 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
630 LOG(ERROR) << "Partial update cannot be applied on a device that does "
631 "not support snapshots.";
632 return false;
633 }
634 if (!target_supports_snapshot) {
635 LOG(ERROR) << "Cannot apply partial update to a build that does not "
636 "support snapshots.";
637 return false;
638 }
639 }
640
641 // Store the flags.
642 is_target_dynamic_ = is_target_dynamic;
643 // If !is_target_dynamic_, leave target_supports_snapshot_ unset because
644 // snapshots would not work without dynamic partition.
645 if (is_target_dynamic_) {
646 target_supports_snapshot_ = target_supports_snapshot;
647 }
648 return true;
649}
650
Yifan Hong29692902020-03-26 12:47:05 -0700651namespace {
652// Try our best to erase AVB footer.
653class AvbFooterEraser {
654 public:
655 explicit AvbFooterEraser(const std::string& path) : path_(path) {}
656 bool Erase() {
657 // Try to mark the block device read-only. Ignore any
658 // failure since this won't work when passing regular files.
659 ignore_result(utils::SetBlockDeviceReadOnly(path_, false /* readonly */));
660
661 fd_.reset(new EintrSafeFileDescriptor());
662 int flags = O_WRONLY | O_TRUNC | O_CLOEXEC | O_SYNC;
663 TEST_AND_RETURN_FALSE(fd_->Open(path_.c_str(), flags));
664
665 // Need to write end-AVB_FOOTER_SIZE to end.
666 static_assert(AVB_FOOTER_SIZE > 0);
667 off64_t offset = fd_->Seek(-AVB_FOOTER_SIZE, SEEK_END);
668 TEST_AND_RETURN_FALSE_ERRNO(offset >= 0);
669 uint64_t write_size = AVB_FOOTER_SIZE;
670 LOG(INFO) << "Zeroing " << path_ << " @ [" << offset << ", "
671 << (offset + write_size) << "] (" << write_size << " bytes)";
672 brillo::Blob zeros(write_size);
673 TEST_AND_RETURN_FALSE(utils::WriteAll(fd_, zeros.data(), zeros.size()));
674 return true;
675 }
676 ~AvbFooterEraser() {
677 TEST_AND_RETURN(fd_ != nullptr && fd_->IsOpen());
678 if (!fd_->Close()) {
679 LOG(WARNING) << "Failed to close fd for " << path_;
680 }
681 }
682
683 private:
684 std::string path_;
685 FileDescriptorPtr fd_;
686};
687
688} // namespace
689
690std::optional<bool>
691DynamicPartitionControlAndroid::IsAvbEnabledOnSystemOther() {
692 auto prefix = GetProperty(kPostinstallFstabPrefix, "");
693 if (prefix.empty()) {
694 LOG(WARNING) << "Cannot get " << kPostinstallFstabPrefix;
695 return std::nullopt;
696 }
697 auto path = base::FilePath(prefix).Append("etc/fstab.postinstall").value();
698 return IsAvbEnabledInFstab(path);
699}
700
701std::optional<bool> DynamicPartitionControlAndroid::IsAvbEnabledInFstab(
702 const std::string& path) {
703 Fstab fstab;
704 if (!ReadFstabFromFile(path, &fstab)) {
Yifan Hong93cde302020-04-27 12:59:29 -0700705 PLOG(WARNING) << "Cannot read fstab from " << path;
706 if (errno == ENOENT) {
707 return false;
708 }
Yifan Hong29692902020-03-26 12:47:05 -0700709 return std::nullopt;
710 }
711 for (const auto& entry : fstab) {
712 if (!entry.avb_keys.empty()) {
713 return true;
714 }
715 }
716 return false;
717}
718
719bool DynamicPartitionControlAndroid::GetSystemOtherPath(
720 uint32_t source_slot,
721 uint32_t target_slot,
722 const std::string& partition_name_suffix,
723 std::string* path,
724 bool* should_unmap) {
725 path->clear();
726 *should_unmap = false;
727
P.Adarsh Reddy13e4195d2020-06-08 23:17:36 +0530728 // Check that AVB is enabled on system_other before erasing.
729 auto has_avb = IsAvbEnabledOnSystemOther();
730 TEST_AND_RETURN_FALSE(has_avb.has_value());
731 if (!has_avb.value()) {
732 LOG(INFO) << "AVB is not enabled on system_other. Skip erasing.";
733 return true;
734 }
Yifan Hong29692902020-03-26 12:47:05 -0700735
P.Adarsh Reddy13e4195d2020-06-08 23:17:36 +0530736 if (!IsRecovery()) {
Yifan Hong29692902020-03-26 12:47:05 -0700737 // Found unexpected avb_keys for system_other on devices retrofitting
738 // dynamic partitions. Previous crash in update_engine may leave logical
739 // partitions mapped on physical system_other partition. It is difficult to
740 // handle these cases. Just fail.
741 if (GetDynamicPartitionsFeatureFlag().IsRetrofit()) {
742 LOG(ERROR) << "Cannot erase AVB footer on system_other on devices with "
743 << "retrofit dynamic partitions. They should not have AVB "
744 << "enabled on system_other.";
745 return false;
746 }
747 }
748
749 std::string device_dir_str;
750 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
751 base::FilePath device_dir(device_dir_str);
752
753 // On devices without dynamic partition, search for static partitions.
754 if (!GetDynamicPartitionsFeatureFlag().IsEnabled()) {
755 *path = device_dir.Append(partition_name_suffix).value();
756 TEST_AND_RETURN_FALSE(DeviceExists(*path));
757 return true;
758 }
759
760 auto source_super_device =
761 device_dir.Append(GetSuperPartitionName(source_slot)).value();
762
763 auto builder = LoadMetadataBuilder(source_super_device, source_slot);
764 if (builder == nullptr) {
765 if (IsRecovery()) {
766 // It might be corrupted for some reason. It should still be able to
767 // sideload.
768 LOG(WARNING) << "Super partition metadata cannot be read from the source "
769 << "slot, skip erasing.";
770 return true;
771 } else {
772 // Device has booted into Android mode, indicating that the super
773 // partition metadata should be there.
774 LOG(ERROR) << "Super partition metadata cannot be read from the source "
775 << "slot. This is unexpected on devices with dynamic "
776 << "partitions enabled.";
777 return false;
778 }
779 }
780 auto p = builder->FindPartition(partition_name_suffix);
781 if (p == nullptr) {
782 // If the source slot is flashed without system_other, it does not exist
783 // in super partition metadata at source slot. It is safe to skip it.
784 LOG(INFO) << "Can't find " << partition_name_suffix
785 << " in metadata source slot, skip erasing.";
786 return true;
787 }
788 // System_other created by flashing tools should be erased.
789 // If partition is created by update_engine (via NewForUpdate), it is a
790 // left-over partition from the previous update and does not contain
791 // system_other, hence there is no need to erase.
792 // Note the reverse is not necessary true. If the flag is not set, we don't
793 // know if the partition is created by update_engine or by flashing tools
794 // because older versions of super partition metadata does not contain this
795 // flag. It is okay to erase the AVB footer anyways.
796 if (p->attributes() & LP_PARTITION_ATTR_UPDATED) {
797 LOG(INFO) << partition_name_suffix
798 << " does not contain system_other, skip erasing.";
799 return true;
800 }
801
Yifan Hong64331b32020-05-13 16:50:40 -0700802 if (p->size() < AVB_FOOTER_SIZE) {
803 LOG(INFO) << partition_name_suffix << " has length " << p->size()
804 << "( < AVB_FOOTER_SIZE " << AVB_FOOTER_SIZE
805 << "), skip erasing.";
806 return true;
807 }
808
Yifan Hong29692902020-03-26 12:47:05 -0700809 // Delete any pre-existing device with name |partition_name_suffix| and
810 // also remove it from |mapped_devices_|.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700811 // In recovery, metadata might not be mounted, and
812 // UnmapPartitionOnDeviceMapper might fail. However,
813 // it is unusual that system_other has already been mapped. Hence, just skip.
Kelvin Zhang08bbbd42024-08-27 13:25:07 -0700814 LOG(INFO) << "Destroying `" << partition_name_suffix
815 << "` from device mapper";
Yifan Hong29692902020-03-26 12:47:05 -0700816 TEST_AND_RETURN_FALSE(UnmapPartitionOnDeviceMapper(partition_name_suffix));
817 // Use CreateLogicalPartition directly to avoid mapping with existing
818 // snapshots.
819 CreateLogicalPartitionParams params = {
820 .block_device = source_super_device,
821 .metadata_slot = source_slot,
822 .partition_name = partition_name_suffix,
823 .force_writable = true,
824 .timeout_ms = kMapTimeout,
825 };
826 TEST_AND_RETURN_FALSE(CreateLogicalPartition(params, path));
827 *should_unmap = true;
828 return true;
829}
830
831bool DynamicPartitionControlAndroid::EraseSystemOtherAvbFooter(
832 uint32_t source_slot, uint32_t target_slot) {
833 LOG(INFO) << "Erasing AVB footer of system_other partition before update.";
834
835 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
836 const std::string partition_name_suffix = "system" + target_suffix;
837
838 std::string path;
839 bool should_unmap = false;
840
841 TEST_AND_RETURN_FALSE(GetSystemOtherPath(
842 source_slot, target_slot, partition_name_suffix, &path, &should_unmap));
843
844 if (path.empty()) {
845 return true;
846 }
847
848 bool ret = AvbFooterEraser(path).Erase();
849
850 // Delete |partition_name_suffix| from device mapper and from
851 // |mapped_devices_| again so that it does not interfere with update process.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700852 // In recovery, metadata might not be mounted, and
853 // UnmapPartitionOnDeviceMapper might fail. However, DestroyLogicalPartition
854 // should be called. If DestroyLogicalPartition does fail, it is still okay
855 // to skip the error here and let Prepare*() fail later.
Yifan Hong29692902020-03-26 12:47:05 -0700856 if (should_unmap) {
Kelvin Zhang08bbbd42024-08-27 13:25:07 -0700857 LOG(INFO) << "Destroying `" << partition_name_suffix
858 << "` from device mapper";
Yifan Hong29692902020-03-26 12:47:05 -0700859 TEST_AND_RETURN_FALSE(UnmapPartitionOnDeviceMapper(partition_name_suffix));
860 }
861
862 return ret;
863}
864
Yifan Hong420db9b2019-07-23 20:50:33 -0700865bool DynamicPartitionControlAndroid::PrepareDynamicPartitionsForUpdate(
866 uint32_t source_slot,
867 uint32_t target_slot,
Yifan Hongbae27842019-10-24 16:56:12 -0700868 const DeltaArchiveManifest& manifest,
869 bool delete_source) {
Yifan Hong012508e2019-07-22 18:30:40 -0700870 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
871
872 // Unmap all the target dynamic partitions because they would become
873 // inconsistent with the new metadata.
Yifan Hong13d41cb2019-09-16 13:18:22 -0700874 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
875 for (const auto& partition_name : group.partition_names()) {
876 if (!UnmapPartitionOnDeviceMapper(partition_name + target_suffix)) {
Yifan Hong012508e2019-07-22 18:30:40 -0700877 return false;
878 }
879 }
880 }
881
882 std::string device_dir_str;
Tianjie9f4dc7f2021-03-15 16:00:50 -0700883 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
Yifan Hong012508e2019-07-22 18:30:40 -0700884 base::FilePath device_dir(device_dir_str);
885 auto source_device =
Yifan Hong700d7c12019-07-23 20:49:16 -0700886 device_dir.Append(GetSuperPartitionName(source_slot)).value();
Yifan Hong012508e2019-07-22 18:30:40 -0700887
888 auto builder = LoadMetadataBuilder(source_device, source_slot, target_slot);
889 if (builder == nullptr) {
890 LOG(ERROR) << "No metadata at "
891 << BootControlInterface::SlotName(source_slot);
892 return false;
893 }
894
Yifan Hongbae27842019-10-24 16:56:12 -0700895 if (delete_source) {
896 TEST_AND_RETURN_FALSE(
897 DeleteSourcePartitions(builder.get(), source_slot, manifest));
898 }
899
Tianjie9f4dc7f2021-03-15 16:00:50 -0700900 TEST_AND_RETURN_FALSE(
901 UpdatePartitionMetadata(builder.get(), target_slot, manifest));
Yifan Hong012508e2019-07-22 18:30:40 -0700902
903 auto target_device =
Yifan Hong700d7c12019-07-23 20:49:16 -0700904 device_dir.Append(GetSuperPartitionName(target_slot)).value();
Daniel Zhengeede4c82023-06-13 11:21:06 -0700905
Yifan Hong012508e2019-07-22 18:30:40 -0700906 return StoreMetadata(target_device, builder.get(), target_slot);
907}
908
Yifan Hong3a1293a2021-04-16 13:21:20 -0700909DynamicPartitionControlAndroid::SpaceLimit
910DynamicPartitionControlAndroid::GetSpaceLimit(bool use_snapshot) {
911 // On device retrofitting dynamic partitions, allocatable_space = "super",
912 // where "super" is the sum of all block devices for that slot. Since block
913 // devices are dedicated for the corresponding slot, there's no need to halve
914 // the allocatable space.
915 if (GetDynamicPartitionsFeatureFlag().IsRetrofit())
916 return SpaceLimit::ERROR_IF_EXCEEDED_SUPER;
917
918 // On device launching dynamic partitions w/o VAB, regardless of recovery
919 // sideload, super partition must be big enough to hold both A and B slots of
920 // groups. Hence,
921 // allocatable_space = super / 2
922 if (!GetVirtualAbFeatureFlag().IsEnabled())
923 return SpaceLimit::ERROR_IF_EXCEEDED_HALF_OF_SUPER;
924
925 // Source build supports VAB. Super partition must be big enough to hold
926 // one slot of groups (ERROR_IF_EXCEEDED_SUPER). However, there are cases
927 // where additional warning messages needs to be written.
928
929 // If using snapshot updates, implying that target build also uses VAB,
930 // allocatable_space = super
931 if (use_snapshot)
932 return SpaceLimit::ERROR_IF_EXCEEDED_SUPER;
933
934 // Source build supports VAB but not using snapshot updates. There are
935 // several cases, as listed below.
936 // Sideloading: allocatable_space = super.
937 if (IsRecovery())
938 return SpaceLimit::ERROR_IF_EXCEEDED_SUPER;
939
940 // On launch VAB device, this implies secondary payload.
941 // Technically, we don't have to check anything, but sum(groups) < super
942 // still applies.
943 if (!GetVirtualAbFeatureFlag().IsRetrofit())
944 return SpaceLimit::ERROR_IF_EXCEEDED_SUPER;
945
946 // On retrofit VAB device, either of the following:
947 // - downgrading: allocatable_space = super / 2
948 // - secondary payload: don't check anything
949 // These two cases are indistinguishable,
950 // hence emit warning if sum(groups) > super / 2
951 return SpaceLimit::WARN_IF_EXCEEDED_HALF_OF_SUPER;
952}
953
Tianjie9f4dc7f2021-03-15 16:00:50 -0700954bool DynamicPartitionControlAndroid::CheckSuperPartitionAllocatableSpace(
955 android::fs_mgr::MetadataBuilder* builder,
956 const DeltaArchiveManifest& manifest,
957 bool use_snapshot) {
Yifan Hong3a1293a2021-04-16 13:21:20 -0700958 uint64_t sum_groups = 0;
Tianjie9f4dc7f2021-03-15 16:00:50 -0700959 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
Yifan Hong3a1293a2021-04-16 13:21:20 -0700960 sum_groups += group.size();
Tianjie9f4dc7f2021-03-15 16:00:50 -0700961 }
962
Yifan Hong3a1293a2021-04-16 13:21:20 -0700963 uint64_t full_space = builder->AllocatableSpace();
964 uint64_t half_space = full_space / 2;
965 constexpr const char* fmt =
966 "The maximum size of all groups for the target slot (%" PRIu64
967 ") has exceeded %sallocatable space for dynamic partitions %" PRIu64 ".";
968 switch (GetSpaceLimit(use_snapshot)) {
969 case SpaceLimit::ERROR_IF_EXCEEDED_HALF_OF_SUPER: {
970 if (sum_groups > half_space) {
971 LOG(ERROR) << StringPrintf(fmt, sum_groups, "HALF OF ", half_space);
972 return false;
973 }
974 // If test passes, it implies that the following two conditions also pass.
975 break;
976 }
977 case SpaceLimit::WARN_IF_EXCEEDED_HALF_OF_SUPER: {
978 if (sum_groups > half_space) {
979 LOG(WARNING) << StringPrintf(fmt, sum_groups, "HALF OF ", half_space)
980 << " This is allowed for downgrade or secondary OTA on "
981 "retrofit VAB device.";
982 }
983 // still check sum(groups) < super
984 [[fallthrough]];
985 }
986 case SpaceLimit::ERROR_IF_EXCEEDED_SUPER: {
987 if (sum_groups > full_space) {
Kelvin Zhangb9a9aa22024-10-15 10:38:35 -0700988 LOG(ERROR) << android::base::StringPrintf(
989 fmt, sum_groups, "", full_space);
Yifan Hong3a1293a2021-04-16 13:21:20 -0700990 return false;
991 }
992 break;
993 }
Tianjie9f4dc7f2021-03-15 16:00:50 -0700994 }
995
996 return true;
997}
998
Yifan Hong420db9b2019-07-23 20:50:33 -0700999bool DynamicPartitionControlAndroid::PrepareSnapshotPartitionsForUpdate(
1000 uint32_t source_slot,
1001 uint32_t target_slot,
Yifan Hongf033ecb2020-01-07 18:13:56 -08001002 const DeltaArchiveManifest& manifest,
1003 uint64_t* required_size) {
Yifan Hong4d7c5eb2020-04-03 11:31:50 -07001004 TEST_AND_RETURN_FALSE(ExpectMetadataMounted());
Tianjie9f4dc7f2021-03-15 16:00:50 -07001005
1006 std::string device_dir_str;
1007 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
1008 base::FilePath device_dir(device_dir_str);
1009 auto super_device =
1010 device_dir.Append(GetSuperPartitionName(source_slot)).value();
1011 auto builder = LoadMetadataBuilder(super_device, source_slot);
1012 if (builder == nullptr) {
1013 LOG(ERROR) << "No metadata at "
1014 << BootControlInterface::SlotName(source_slot);
1015 return false;
1016 }
1017
1018 TEST_AND_RETURN_FALSE(
1019 CheckSuperPartitionAllocatableSpace(builder.get(), manifest, true));
1020
Yifan Hong420db9b2019-07-23 20:50:33 -07001021 if (!snapshot_->BeginUpdate()) {
1022 LOG(ERROR) << "Cannot begin new update.";
1023 return false;
1024 }
Yifan Hongf033ecb2020-01-07 18:13:56 -08001025 auto ret = snapshot_->CreateUpdateSnapshots(manifest);
1026 if (!ret) {
1027 LOG(ERROR) << "Cannot create update snapshots: " << ret.string();
1028 if (required_size != nullptr &&
Yifan Hong0850bca2020-01-16 15:14:07 -08001029 ret.error_code() == Return::ErrorCode::NO_SPACE) {
Yifan Hongf033ecb2020-01-07 18:13:56 -08001030 *required_size = ret.required_size();
1031 }
Yifan Hong420db9b2019-07-23 20:50:33 -07001032 return false;
1033 }
1034 return true;
1035}
1036
Yifan Hong700d7c12019-07-23 20:49:16 -07001037std::string DynamicPartitionControlAndroid::GetSuperPartitionName(
1038 uint32_t slot) {
1039 return fs_mgr_get_super_partition_name(slot);
1040}
1041
Yifan Hong012508e2019-07-22 18:30:40 -07001042bool DynamicPartitionControlAndroid::UpdatePartitionMetadata(
1043 MetadataBuilder* builder,
1044 uint32_t target_slot,
Yifan Hong13d41cb2019-09-16 13:18:22 -07001045 const DeltaArchiveManifest& manifest) {
Yifan Hong8d6df9a2020-08-13 13:59:54 -07001046 // Check preconditions.
Yifan Hong265a8e32021-04-16 13:30:02 -07001047 if (GetVirtualAbFeatureFlag().IsEnabled()) {
1048 CHECK(!target_supports_snapshot_ || IsRecovery())
1049 << "Must use snapshot on VAB device when target build supports VAB and "
1050 "not sideloading.";
1051 LOG_IF(INFO, !target_supports_snapshot_)
1052 << "Not using snapshot on VAB device because target build does not "
1053 "support snapshot. Secondary or downgrade OTA?";
1054 LOG_IF(INFO, IsRecovery())
1055 << "Not using snapshot on VAB device because sideloading.";
1056 }
Yifan Hong8d6df9a2020-08-13 13:59:54 -07001057
Yifan Honga4e7da32019-09-30 18:25:03 -07001058 // If applying downgrade from Virtual A/B to non-Virtual A/B, the left-over
1059 // COW group needs to be deleted to ensure there are enough space to create
1060 // target partitions.
1061 builder->RemoveGroupAndPartitions(android::snapshot::kCowGroupName);
1062
Yifan Hong012508e2019-07-22 18:30:40 -07001063 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
1064 DeleteGroupsWithSuffix(builder, target_suffix);
1065
Tianjie9f4dc7f2021-03-15 16:00:50 -07001066 TEST_AND_RETURN_FALSE(
1067 CheckSuperPartitionAllocatableSpace(builder, manifest, false));
Yifan Hong012508e2019-07-22 18:30:40 -07001068
Yifan Hong13d41cb2019-09-16 13:18:22 -07001069 // name of partition(e.g. "system") -> size in bytes
1070 std::map<std::string, uint64_t> partition_sizes;
1071 for (const auto& partition : manifest.partitions()) {
1072 partition_sizes.emplace(partition.partition_name(),
1073 partition.new_partition_info().size());
1074 }
1075
1076 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
1077 auto group_name_suffix = group.name() + target_suffix;
1078 if (!builder->AddGroup(group_name_suffix, group.size())) {
Yifan Hong012508e2019-07-22 18:30:40 -07001079 LOG(ERROR) << "Cannot add group " << group_name_suffix << " with size "
Yifan Hong13d41cb2019-09-16 13:18:22 -07001080 << group.size();
Yifan Hong012508e2019-07-22 18:30:40 -07001081 return false;
1082 }
1083 LOG(INFO) << "Added group " << group_name_suffix << " with size "
Yifan Hong13d41cb2019-09-16 13:18:22 -07001084 << group.size();
Yifan Hong012508e2019-07-22 18:30:40 -07001085
Yifan Hong13d41cb2019-09-16 13:18:22 -07001086 for (const auto& partition_name : group.partition_names()) {
1087 auto partition_sizes_it = partition_sizes.find(partition_name);
1088 if (partition_sizes_it == partition_sizes.end()) {
1089 // TODO(tbao): Support auto-filling partition info for framework-only
1090 // OTA.
1091 LOG(ERROR) << "dynamic_partition_metadata contains partition "
1092 << partition_name << " but it is not part of the manifest. "
1093 << "This is not supported.";
1094 return false;
1095 }
1096 uint64_t partition_size = partition_sizes_it->second;
1097
1098 auto partition_name_suffix = partition_name + target_suffix;
Yifan Hong012508e2019-07-22 18:30:40 -07001099 Partition* p = builder->AddPartition(
1100 partition_name_suffix, group_name_suffix, LP_PARTITION_ATTR_READONLY);
1101 if (!p) {
1102 LOG(ERROR) << "Cannot add partition " << partition_name_suffix
1103 << " to group " << group_name_suffix;
1104 return false;
1105 }
Yifan Hong13d41cb2019-09-16 13:18:22 -07001106 if (!builder->ResizePartition(p, partition_size)) {
Yifan Hong012508e2019-07-22 18:30:40 -07001107 LOG(ERROR) << "Cannot resize partition " << partition_name_suffix
Yifan Hong13d41cb2019-09-16 13:18:22 -07001108 << " to size " << partition_size << ". Not enough space?";
Yifan Hong012508e2019-07-22 18:30:40 -07001109 return false;
1110 }
David Anderson0e1c7fd2021-03-08 19:01:59 -08001111 if (p->size() < partition_size) {
1112 LOG(ERROR) << "Partition " << partition_name_suffix
1113 << " was expected to have size " << partition_size
1114 << ", but instead has size " << p->size();
1115 return false;
1116 }
Yifan Hong012508e2019-07-22 18:30:40 -07001117 LOG(INFO) << "Added partition " << partition_name_suffix << " to group "
Yifan Hong13d41cb2019-09-16 13:18:22 -07001118 << group_name_suffix << " with size " << partition_size;
Yifan Hong012508e2019-07-22 18:30:40 -07001119 }
1120 }
1121
1122 return true;
1123}
1124
Yifan Hong7b3910a2020-03-24 17:47:32 -07001125bool DynamicPartitionControlAndroid::FinishUpdate(bool powerwash_required) {
Yifan Hong4d7c5eb2020-04-03 11:31:50 -07001126 if (ExpectMetadataMounted()) {
1127 if (snapshot_->GetUpdateState() == UpdateState::Initiated) {
1128 LOG(INFO) << "Snapshot writes are done.";
1129 return snapshot_->FinishedSnapshotWrites(powerwash_required);
1130 }
1131 } else {
1132 LOG(INFO) << "Skip FinishedSnapshotWrites() because /metadata is not "
1133 << "mounted";
Yifan Hongf0f4a912019-09-26 17:51:33 -07001134 }
1135 return true;
Yifan Honga33bca42019-09-03 20:29:45 -07001136}
1137
Yifan Hong3a1a5612019-11-05 16:34:32 -08001138bool DynamicPartitionControlAndroid::GetPartitionDevice(
1139 const std::string& partition_name,
1140 uint32_t slot,
1141 uint32_t current_slot,
Tianjie51a5a392020-06-03 14:39:32 -07001142 bool not_in_payload,
1143 std::string* device,
1144 bool* is_dynamic) {
Kelvin Zhang66a9ebb2021-01-25 13:35:10 -05001145 auto partition_dev =
1146 GetPartitionDevice(partition_name, slot, current_slot, not_in_payload);
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001147 if (!partition_dev.has_value()) {
Yifan Hong3a1a5612019-11-05 16:34:32 -08001148 return false;
1149 }
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001150 if (device) {
1151 *device = std::move(partition_dev->rw_device_path);
1152 }
1153 if (is_dynamic) {
1154 *is_dynamic = partition_dev->is_dynamic;
1155 }
Yifan Hong3a1a5612019-11-05 16:34:32 -08001156 return true;
1157}
1158
Tianjie51a5a392020-06-03 14:39:32 -07001159bool DynamicPartitionControlAndroid::GetPartitionDevice(
1160 const std::string& partition_name,
1161 uint32_t slot,
1162 uint32_t current_slot,
1163 std::string* device) {
1164 return GetPartitionDevice(
1165 partition_name, slot, current_slot, false, device, nullptr);
1166}
1167
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001168static std::string GetStaticDevicePath(
1169 const base::FilePath& device_dir,
1170 const std::string& partition_name_suffixed) {
1171 base::FilePath path = device_dir.Append(partition_name_suffixed);
1172 return path.value();
1173}
1174
1175std::optional<PartitionDevice>
1176DynamicPartitionControlAndroid::GetPartitionDevice(
1177 const std::string& partition_name,
1178 uint32_t slot,
1179 uint32_t current_slot,
1180 bool not_in_payload) {
1181 std::string device_dir_str;
1182 if (!GetDeviceDir(&device_dir_str)) {
1183 LOG(ERROR) << "Failed to GetDeviceDir()";
1184 return {};
1185 }
1186 const base::FilePath device_dir(device_dir_str);
1187 // When VABC is enabled, we can't get device path for dynamic partitions in
1188 // target slot.
1189 const auto& partition_name_suffix =
1190 partition_name + SlotSuffixForSlotNumber(slot);
Kelvin Zhangebd115e2021-03-08 16:10:25 -05001191 if (UpdateUsesSnapshotCompression() && slot != current_slot &&
1192 IsDynamicPartition(partition_name, slot)) {
Kelvin Zhang91ad6622021-03-01 13:46:17 -05001193 return {
Kelvin Zhanga9b5d8c2021-05-05 09:17:46 -04001194 {.readonly_device_path = base::FilePath{std::string{VABC_DEVICE_DIR}}
1195 .Append(partition_name_suffix)
1196 .value(),
Kelvin Zhang91ad6622021-03-01 13:46:17 -05001197 .is_dynamic = true}};
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001198 }
1199
1200 // When looking up target partition devices, treat them as static if the
1201 // current payload doesn't encode them as dynamic partitions. This may happen
1202 // when applying a retrofit update on top of a dynamic-partitions-enabled
1203 // build.
1204 std::string device;
1205 if (GetDynamicPartitionsFeatureFlag().IsEnabled() &&
1206 (slot == current_slot || is_target_dynamic_)) {
Kelvin Zhang08bbbd42024-08-27 13:25:07 -07001207 auto status = GetDynamicPartitionDevice(device_dir,
1208 partition_name_suffix,
1209 slot,
1210 current_slot,
1211 not_in_payload,
1212 &device);
1213 switch (status) {
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001214 case DynamicPartitionDeviceStatus::SUCCESS:
1215 return {{.rw_device_path = device,
Kelvin Zhanga9b5d8c2021-05-05 09:17:46 -04001216 .readonly_device_path = device,
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001217 .is_dynamic = true}};
1218
1219 case DynamicPartitionDeviceStatus::TRY_STATIC:
1220 break;
1221 case DynamicPartitionDeviceStatus::ERROR: // fallthrough
1222 default:
Kelvin Zhang08bbbd42024-08-27 13:25:07 -07001223 LOG(ERROR) << "Unhandled dynamic partition status " << (int)status;
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001224 return {};
1225 }
1226 }
1227 // Try static partitions.
1228 auto static_path = GetStaticDevicePath(device_dir, partition_name_suffix);
1229 if (!DeviceExists(static_path)) {
1230 LOG(ERROR) << "Device file " << static_path << " does not exist.";
1231 return {};
1232 }
1233
1234 return {{.rw_device_path = static_path,
Kelvin Zhanga9b5d8c2021-05-05 09:17:46 -04001235 .readonly_device_path = static_path,
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001236 .is_dynamic = false}};
1237}
1238
Yifan Hong3a1a5612019-11-05 16:34:32 -08001239bool DynamicPartitionControlAndroid::IsSuperBlockDevice(
1240 const base::FilePath& device_dir,
1241 uint32_t current_slot,
1242 const std::string& partition_name_suffix) {
1243 std::string source_device =
1244 device_dir.Append(GetSuperPartitionName(current_slot)).value();
1245 auto source_metadata = LoadMetadataBuilder(source_device, current_slot);
1246 return source_metadata->HasBlockDevice(partition_name_suffix);
1247}
1248
1249DynamicPartitionControlAndroid::DynamicPartitionDeviceStatus
1250DynamicPartitionControlAndroid::GetDynamicPartitionDevice(
1251 const base::FilePath& device_dir,
1252 const std::string& partition_name_suffix,
1253 uint32_t slot,
1254 uint32_t current_slot,
Tianjie51a5a392020-06-03 14:39:32 -07001255 bool not_in_payload,
Yifan Hong3a1a5612019-11-05 16:34:32 -08001256 std::string* device) {
1257 std::string super_device =
1258 device_dir.Append(GetSuperPartitionName(slot)).value();
Kelvin Zhang08bbbd42024-08-27 13:25:07 -07001259 auto device_name = GetDeviceName(partition_name_suffix, slot);
Yifan Hong3a1a5612019-11-05 16:34:32 -08001260
1261 auto builder = LoadMetadataBuilder(super_device, slot);
1262 if (builder == nullptr) {
1263 LOG(ERROR) << "No metadata in slot "
1264 << BootControlInterface::SlotName(slot);
1265 return DynamicPartitionDeviceStatus::ERROR;
1266 }
1267 if (builder->FindPartition(partition_name_suffix) == nullptr) {
1268 LOG(INFO) << partition_name_suffix
1269 << " is not in super partition metadata.";
1270
1271 if (IsSuperBlockDevice(device_dir, current_slot, partition_name_suffix)) {
1272 LOG(ERROR) << "The static partition " << partition_name_suffix
1273 << " is a block device for current metadata."
1274 << "It cannot be used as a logical partition.";
1275 return DynamicPartitionDeviceStatus::ERROR;
1276 }
1277
1278 return DynamicPartitionDeviceStatus::TRY_STATIC;
1279 }
1280
1281 if (slot == current_slot) {
Kelvin Zhang08bbbd42024-08-27 13:25:07 -07001282 if (GetState(device_name) != DmDeviceState::ACTIVE) {
1283 LOG(WARNING) << device_name << " is at current slot but it is "
Yifan Hong3a1a5612019-11-05 16:34:32 -08001284 << "not mapped. Now try to map it.";
1285 } else {
Kelvin Zhang08bbbd42024-08-27 13:25:07 -07001286 if (GetDmDevicePathByName(device_name, device)) {
1287 LOG(INFO) << device_name << " is mapped on device mapper: " << *device;
Yifan Hong3a1a5612019-11-05 16:34:32 -08001288 return DynamicPartitionDeviceStatus::SUCCESS;
1289 }
1290 LOG(ERROR) << partition_name_suffix << "is mapped but path is unknown.";
1291 return DynamicPartitionDeviceStatus::ERROR;
1292 }
1293 }
1294
Kelvin Zhang8b07db52024-07-24 09:13:25 -07001295 const bool force_writable = !not_in_payload;
Yifan Hong3a1a5612019-11-05 16:34:32 -08001296 if (MapPartitionOnDeviceMapper(
1297 super_device, partition_name_suffix, slot, force_writable, device)) {
1298 return DynamicPartitionDeviceStatus::SUCCESS;
1299 }
1300 return DynamicPartitionDeviceStatus::ERROR;
1301}
1302
Yifan Hong6eec9952019-12-04 13:12:01 -08001303void DynamicPartitionControlAndroid::set_fake_mapped_devices(
1304 const std::set<std::string>& fake) {
1305 mapped_devices_ = fake;
1306}
1307
Yifan Hongbae27842019-10-24 16:56:12 -07001308bool DynamicPartitionControlAndroid::IsRecovery() {
Kelvin Zhanga22ef552020-10-12 19:03:52 -04001309 return constants::kIsRecovery;
Yifan Hongbae27842019-10-24 16:56:12 -07001310}
1311
1312static bool IsIncrementalUpdate(const DeltaArchiveManifest& manifest) {
1313 const auto& partitions = manifest.partitions();
1314 return std::any_of(partitions.begin(), partitions.end(), [](const auto& p) {
1315 return p.has_old_partition_info();
1316 });
1317}
1318
1319bool DynamicPartitionControlAndroid::DeleteSourcePartitions(
1320 MetadataBuilder* builder,
1321 uint32_t source_slot,
1322 const DeltaArchiveManifest& manifest) {
1323 TEST_AND_RETURN_FALSE(IsRecovery());
1324
1325 if (IsIncrementalUpdate(manifest)) {
1326 LOG(ERROR) << "Cannot sideload incremental OTA because snapshots cannot "
1327 << "be created.";
1328 if (GetVirtualAbFeatureFlag().IsLaunch()) {
1329 LOG(ERROR) << "Sideloading incremental updates on devices launches "
1330 << " Virtual A/B is not supported.";
1331 }
1332 return false;
1333 }
1334
1335 LOG(INFO) << "Will overwrite existing partitions. Slot "
1336 << BootControlInterface::SlotName(source_slot)
Tianjie9f4dc7f2021-03-15 16:00:50 -07001337 << " may be unbootable until update finishes!";
Yifan Hongbae27842019-10-24 16:56:12 -07001338 const std::string source_suffix = SlotSuffixForSlotNumber(source_slot);
1339 DeleteGroupsWithSuffix(builder, source_suffix);
1340
1341 return true;
1342}
1343
Yifan Hong90965502020-02-19 15:22:47 -08001344std::unique_ptr<AbstractAction>
1345DynamicPartitionControlAndroid::GetCleanupPreviousUpdateAction(
1346 BootControlInterface* boot_control,
1347 PrefsInterface* prefs,
1348 CleanupPreviousUpdateActionDelegateInterface* delegate) {
1349 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1350 return std::make_unique<NoOpAction>();
1351 }
1352 return std::make_unique<CleanupPreviousUpdateAction>(
1353 prefs, boot_control, snapshot_.get(), delegate);
1354}
1355
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001356bool DynamicPartitionControlAndroid::ResetUpdate(PrefsInterface* prefs) {
1357 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1358 return true;
1359 }
Kelvin Zhangff5380b2022-03-16 13:35:04 -07001360 for (auto& list : dynamic_partition_list_) {
1361 list.clear();
1362 }
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001363
1364 LOG(INFO) << __func__ << " resetting update state and deleting snapshots.";
1365 TEST_AND_RETURN_FALSE(prefs != nullptr);
1366
1367 // If the device has already booted into the target slot,
1368 // ResetUpdateProgress may pass but CancelUpdate fails.
1369 // This is expected. A scheduled CleanupPreviousUpdateAction should free
1370 // space when it is done.
Daniel Zhengf9784802023-06-08 08:39:48 -07001371 TEST_AND_RETURN_FALSE(DeltaPerformer::ResetUpdateProgress(
1372 prefs, false /* quick */, false /* skip dynamic partitions metadata */));
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001373
Yifan Hong4d7c5eb2020-04-03 11:31:50 -07001374 if (ExpectMetadataMounted()) {
1375 TEST_AND_RETURN_FALSE(snapshot_->CancelUpdate());
1376 } else {
1377 LOG(INFO) << "Skip cancelling update in ResetUpdate because /metadata is "
1378 << "not mounted";
1379 }
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001380
1381 return true;
1382}
1383
Tianjie99d570d2020-06-04 14:57:19 -07001384bool DynamicPartitionControlAndroid::ListDynamicPartitionsForSlot(
Tianjie3a55fc22021-02-13 16:02:22 -08001385 uint32_t slot,
1386 uint32_t current_slot,
1387 std::vector<std::string>* partitions) {
Kelvin Zhangebd115e2021-03-08 16:10:25 -05001388 CHECK(slot == source_slot_ || target_slot_ != UINT32_MAX)
1389 << " source slot: " << source_slot_ << " target slot: " << target_slot_
1390 << " slot: " << slot
1391 << " attempting to query dynamic partition metadata for target slot "
1392 "before PreparePartitionForUpdate() is called. The "
1393 "metadata in target slot isn't valid until "
1394 "PreparePartitionForUpdate() is called, contining execution would "
1395 "likely cause problems.";
Tianjie3a55fc22021-02-13 16:02:22 -08001396 bool slot_enables_dynamic_partitions =
1397 GetDynamicPartitionsFeatureFlag().IsEnabled();
1398 // Check if the target slot has dynamic partitions, this may happen when
1399 // applying a retrofit package.
1400 if (slot != current_slot) {
1401 slot_enables_dynamic_partitions =
1402 slot_enables_dynamic_partitions && is_target_dynamic_;
1403 }
1404
1405 if (!slot_enables_dynamic_partitions) {
1406 LOG(INFO) << "Dynamic partition is not enabled for slot " << slot;
1407 return true;
Tianjie99d570d2020-06-04 14:57:19 -07001408 }
1409
1410 std::string device_dir_str;
1411 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
1412 base::FilePath device_dir(device_dir_str);
Tianjie3a55fc22021-02-13 16:02:22 -08001413 auto super_device = device_dir.Append(GetSuperPartitionName(slot)).value();
1414 auto builder = LoadMetadataBuilder(super_device, slot);
Tianjie99d570d2020-06-04 14:57:19 -07001415 TEST_AND_RETURN_FALSE(builder != nullptr);
1416
1417 std::vector<std::string> result;
Tianjie3a55fc22021-02-13 16:02:22 -08001418 auto suffix = SlotSuffixForSlotNumber(slot);
Tianjie99d570d2020-06-04 14:57:19 -07001419 for (const auto& group : builder->ListGroups()) {
1420 for (const auto& partition : builder->ListPartitionsInGroup(group)) {
1421 std::string_view partition_name = partition->name();
1422 if (!android::base::ConsumeSuffix(&partition_name, suffix)) {
1423 continue;
1424 }
1425 result.emplace_back(partition_name);
1426 }
1427 }
1428 *partitions = std::move(result);
1429 return true;
1430}
1431
Tianjie24f96092020-06-30 12:26:25 -07001432bool DynamicPartitionControlAndroid::VerifyExtentsForUntouchedPartitions(
1433 uint32_t source_slot,
1434 uint32_t target_slot,
1435 const std::vector<std::string>& partitions) {
1436 std::string device_dir_str;
1437 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
1438 base::FilePath device_dir(device_dir_str);
1439
1440 auto source_super_device =
1441 device_dir.Append(GetSuperPartitionName(source_slot)).value();
1442 auto source_builder = LoadMetadataBuilder(source_super_device, source_slot);
1443 TEST_AND_RETURN_FALSE(source_builder != nullptr);
1444
1445 auto target_super_device =
1446 device_dir.Append(GetSuperPartitionName(target_slot)).value();
1447 auto target_builder = LoadMetadataBuilder(target_super_device, target_slot);
1448 TEST_AND_RETURN_FALSE(target_builder != nullptr);
1449
1450 return MetadataBuilder::VerifyExtentsAgainstSourceMetadata(
1451 *source_builder, source_slot, *target_builder, target_slot, partitions);
1452}
1453
Yifan Hong4d7c5eb2020-04-03 11:31:50 -07001454bool DynamicPartitionControlAndroid::ExpectMetadataMounted() {
1455 // No need to mount metadata for non-Virtual A/B devices.
1456 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1457 return false;
1458 }
1459 // Intentionally not checking |metadata_device_| in Android mode.
1460 // /metadata should always be mounted in Android mode. If it isn't, let caller
1461 // fails when calling into SnapshotManager.
1462 if (!IsRecovery()) {
1463 return true;
1464 }
1465 // In recovery mode, explicitly check |metadata_device_|.
1466 return metadata_device_ != nullptr;
1467}
1468
1469bool DynamicPartitionControlAndroid::EnsureMetadataMounted() {
1470 // No need to mount metadata for non-Virtual A/B devices.
1471 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1472 return true;
1473 }
1474
1475 if (metadata_device_ == nullptr) {
1476 metadata_device_ = snapshot_->EnsureMetadataMounted();
1477 }
1478 return metadata_device_ != nullptr;
1479}
1480
David Andersona4b7ba62023-05-10 21:41:37 -07001481std::unique_ptr<android::snapshot::ICowWriter>
Kelvin Zhang34618522020-09-28 09:21:02 -04001482DynamicPartitionControlAndroid::OpenCowWriter(
1483 const std::string& partition_name,
1484 const std::optional<std::string>& source_path,
David Andersona4b7ba62023-05-10 21:41:37 -07001485 std::optional<uint64_t> label) {
Kelvin Zhang34618522020-09-28 09:21:02 -04001486 auto suffix = SlotSuffixForSlotNumber(target_slot_);
1487
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -04001488 auto super_device = GetSuperDevice();
1489 if (!super_device.has_value()) {
Kelvin Zhang34618522020-09-28 09:21:02 -04001490 return nullptr;
1491 }
Kelvin Zhang34618522020-09-28 09:21:02 -04001492 CreateLogicalPartitionParams params = {
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -04001493 .block_device = super_device->value(),
Kelvin Zhang34618522020-09-28 09:21:02 -04001494 .metadata_slot = target_slot_,
1495 .partition_name = partition_name + suffix,
1496 .force_writable = true,
Kelvin Zhang877ddbe2020-11-09 13:37:56 -05001497 .timeout_ms = kMapSnapshotTimeout};
Kelvin Zhang34618522020-09-28 09:21:02 -04001498 // TODO(zhangkelvin) Open an APPEND mode CowWriter once there's an API to do
1499 // it.
David Andersona4b7ba62023-05-10 21:41:37 -07001500 return snapshot_->OpenSnapshotWriter(params, label);
Kelvin Zhang877ddbe2020-11-09 13:37:56 -05001501} // namespace chromeos_update_engine
Kelvin Zhang34618522020-09-28 09:21:02 -04001502
Kelvin Zhang1a0ed712022-01-26 16:09:05 -08001503std::unique_ptr<FileDescriptor> DynamicPartitionControlAndroid::OpenCowFd(
Kelvin Zhangc82511c2020-11-06 16:01:24 -05001504 const std::string& unsuffixed_partition_name,
1505 const std::optional<std::string>& source_path,
1506 bool is_append) {
David Andersona4b7ba62023-05-10 21:41:37 -07001507 auto cow_writer = OpenCowWriter(
1508 unsuffixed_partition_name, source_path, {kEndOfInstallLabel});
Kelvin Zhangc82511c2020-11-06 16:01:24 -05001509 if (cow_writer == nullptr) {
David Andersona4b7ba62023-05-10 21:41:37 -07001510 LOG(ERROR) << "OpenCowWriter failed";
Kelvin Zhangc82511c2020-11-06 16:01:24 -05001511 return nullptr;
1512 }
David Andersona4b7ba62023-05-10 21:41:37 -07001513 auto fd = cow_writer->OpenFileDescriptor(source_path);
1514 if (fd == nullptr) {
1515 LOG(ERROR) << "ICowReader::OpenFileDescriptor failed";
Kelvin Zhang21a49912021-03-12 14:28:33 -05001516 return nullptr;
1517 }
David Andersona4b7ba62023-05-10 21:41:37 -07001518 return std::make_unique<CowWriterFileDescriptor>(
1519 std::move(cow_writer), std::move(fd), source_path);
Kelvin Zhangc82511c2020-11-06 16:01:24 -05001520}
1521
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -04001522std::optional<base::FilePath> DynamicPartitionControlAndroid::GetSuperDevice() {
1523 std::string device_dir_str;
1524 if (!GetDeviceDir(&device_dir_str)) {
1525 LOG(ERROR) << "Failed to get device dir!";
1526 return {};
1527 }
1528 base::FilePath device_dir(device_dir_str);
1529 auto super_device = device_dir.Append(GetSuperPartitionName(target_slot_));
1530 return super_device;
1531}
1532
1533bool DynamicPartitionControlAndroid::MapAllPartitions() {
Kelvin Zhang877ddbe2020-11-09 13:37:56 -05001534 return snapshot_->MapAllSnapshots(kMapSnapshotTimeout);
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -04001535}
1536
Kelvin Zhangeb9de162020-11-16 15:47:28 -05001537bool DynamicPartitionControlAndroid::IsDynamicPartition(
Kelvin Zhangebd115e2021-03-08 16:10:25 -05001538 const std::string& partition_name, uint32_t slot) {
1539 if (slot >= dynamic_partition_list_.size()) {
1540 LOG(ERROR) << "Seeing unexpected slot # " << slot << " currently assuming "
1541 << dynamic_partition_list_.size() << " slots";
1542 return false;
1543 }
1544 auto& dynamic_partition_list = dynamic_partition_list_[slot];
1545 if (dynamic_partition_list.empty() &&
Kelvin Zhangeb9de162020-11-16 15:47:28 -05001546 GetDynamicPartitionsFeatureFlag().IsEnabled()) {
Tianjie3a55fc22021-02-13 16:02:22 -08001547 // Use the DAP config of the target slot.
1548 CHECK(ListDynamicPartitionsForSlot(
Kelvin Zhangebd115e2021-03-08 16:10:25 -05001549 slot, source_slot_, &dynamic_partition_list));
Kelvin Zhangeb9de162020-11-16 15:47:28 -05001550 }
Kelvin Zhangebd115e2021-03-08 16:10:25 -05001551 return std::find(dynamic_partition_list.begin(),
1552 dynamic_partition_list.end(),
1553 partition_name) != dynamic_partition_list.end();
Kelvin Zhangeb9de162020-11-16 15:47:28 -05001554}
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001555
Yifan Hongb0cbd392021-02-04 11:11:45 -08001556bool DynamicPartitionControlAndroid::UpdateUsesSnapshotCompression() {
Kelvin Zhang741c2d42021-04-13 12:40:38 -04001557 return GetVirtualAbFeatureFlag().IsEnabled() &&
1558 snapshot_->UpdateUsesCompression();
Yifan Hongb0cbd392021-02-04 11:11:45 -08001559}
1560
David Andersone35b4382022-03-08 23:18:29 -08001561FeatureFlag
1562DynamicPartitionControlAndroid::GetVirtualAbUserspaceSnapshotsFeatureFlag() {
1563 return virtual_ab_userspace_snapshots_;
1564}
1565
Yifan Hong537802d2018-08-15 13:15:42 -07001566} // namespace chromeos_update_engine