blob: 363a43326cbaf13f98d5067a7764470b9ac17c44 [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);
301 return false;
302 }
303 if (DeviceMapper::Instance().GetState(device_name) !=
Yifan Hong537802d2018-08-15 13:15:42 -0700304 DmDeviceState::INVALID) {
Yifan Hong420db9b2019-07-23 20:50:33 -0700305 // Partitions at target slot on non-Virtual A/B devices are mapped as
306 // dm-linear. Also, on Virtual A/B devices, system_other may be mapped for
307 // preopt apps as dm-linear.
308 // Call DestroyLogicalPartition to handle these cases.
Kelvin Zhang08bbbd42024-08-27 13:25:07 -0700309 bool success = DestroyLogicalPartition(device_name);
Yifan Hong420db9b2019-07-23 20:50:33 -0700310
311 // On a Virtual A/B device, |target_partition_name| may be a leftover from
312 // a paused update. Clean up any underlying devices.
Kelvin Zhang08bbbd42024-08-27 13:25:07 -0700313 if (ExpectMetadataMounted() &&
314 !device_name.ends_with(kRWSourcePartitionSuffix)) {
315 success &= snapshot_->UnmapUpdateSnapshot(device_name);
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700316 } else {
Kelvin Zhang08bbbd42024-08-27 13:25:07 -0700317 LOG(INFO) << "Skip UnmapUpdateSnapshot(" << device_name << ")";
Yifan Hong420db9b2019-07-23 20:50:33 -0700318 }
319
320 if (!success) {
Kelvin Zhang08bbbd42024-08-27 13:25:07 -0700321 LOG(ERROR) << "Cannot unmap " << device_name << " from device mapper.";
Yifan Hong537802d2018-08-15 13:15:42 -0700322 return false;
323 }
Kelvin Zhang08bbbd42024-08-27 13:25:07 -0700324 LOG(INFO) << "Successfully unmapped " << device_name
Yifan Hong537802d2018-08-15 13:15:42 -0700325 << " from device mapper.";
326 }
Kelvin Zhang08bbbd42024-08-27 13:25:07 -0700327 mapped_devices_.erase(device_name);
Yifan Hong537802d2018-08-15 13:15:42 -0700328 return true;
329}
330
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -0400331bool DynamicPartitionControlAndroid::UnmapAllPartitions() {
Kelvin Zhangf7ef12a2021-03-22 12:59:06 -0400332 snapshot_->UnmapAllSnapshots();
Tao Bao8c4d0082019-08-08 08:56:16 -0700333 if (mapped_devices_.empty()) {
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -0400334 return false;
Tao Bao8c4d0082019-08-08 08:56:16 -0700335 }
Yifan Hong537802d2018-08-15 13:15:42 -0700336 // UnmapPartitionOnDeviceMapper removes objects from mapped_devices_, hence
337 // a copy is needed for the loop.
Kelvin Zhang08bbbd42024-08-27 13:25:07 -0700338 std::set<std::string> mapped;
339 std::copy_if(mapped_devices_.begin(),
340 mapped_devices_.end(),
341 std::inserter(mapped, mapped.end()),
342 [](auto&& device_name) {
343 return !std::string_view(device_name)
344 .ends_with(kRWSourcePartitionSuffix);
345 });
Yifan Hong537802d2018-08-15 13:15:42 -0700346 LOG(INFO) << "Destroying [" << Join(mapped, ", ") << "] from device mapper";
Kelvin Zhang08bbbd42024-08-27 13:25:07 -0700347 for (const auto& device_name : mapped) {
348 ignore_result(UnmapPartitionOnDeviceMapper(device_name));
Yifan Hong537802d2018-08-15 13:15:42 -0700349 }
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -0400350 return true;
Yifan Hong537802d2018-08-15 13:15:42 -0700351}
352
353void DynamicPartitionControlAndroid::Cleanup() {
Kelvin Zhang08bbbd42024-08-27 13:25:07 -0700354 std::set<std::string> mapped = mapped_devices_;
355 LOG(INFO) << "Destroying [" << Join(mapped, ", ") << "] from device mapper";
356 for (const auto& device_name : mapped) {
357 ignore_result(UnmapPartitionOnDeviceMapper(device_name));
358 }
Kelvin Zhang6bec1ed2024-07-11 09:49:59 -0700359 LOG(INFO) << "UnmapAllPartitions done";
Yifan Hongbae27842019-10-24 16:56:12 -0700360 metadata_device_.reset();
Kelvin Zhangc675fc02022-06-22 10:18:54 -0700361 if (GetVirtualAbFeatureFlag().IsEnabled()) {
362 snapshot_ = SnapshotManager::New();
363 } else {
364 snapshot_ = SnapshotManagerStub::New();
365 }
366 CHECK(snapshot_ != nullptr) << "Cannot initialize SnapshotManager.";
Kelvin Zhang6bec1ed2024-07-11 09:49:59 -0700367 LOG(INFO) << "SnapshotManager initialized.";
Yifan Hong537802d2018-08-15 13:15:42 -0700368}
369
370bool DynamicPartitionControlAndroid::DeviceExists(const std::string& path) {
371 return base::PathExists(base::FilePath(path));
372}
373
374android::dm::DmDeviceState DynamicPartitionControlAndroid::GetState(
375 const std::string& name) {
376 return DeviceMapper::Instance().GetState(name);
377}
378
379bool DynamicPartitionControlAndroid::GetDmDevicePathByName(
380 const std::string& name, std::string* path) {
381 return DeviceMapper::Instance().GetDmDevicePathByName(name, path);
382}
383
384std::unique_ptr<MetadataBuilder>
385DynamicPartitionControlAndroid::LoadMetadataBuilder(
Tianjie24f96092020-06-30 12:26:25 -0700386 const std::string& super_device, uint32_t slot) {
387 auto builder = MetadataBuilder::New(PartitionOpener(), super_device, slot);
388 if (builder == nullptr) {
389 LOG(WARNING) << "No metadata slot " << BootControlInterface::SlotName(slot)
390 << " in " << super_device;
391 return nullptr;
392 }
393 LOG(INFO) << "Loaded metadata from slot "
394 << BootControlInterface::SlotName(slot) << " in " << super_device;
395 return builder;
Yifan Hong012508e2019-07-22 18:30:40 -0700396}
397
398std::unique_ptr<MetadataBuilder>
399DynamicPartitionControlAndroid::LoadMetadataBuilder(
Yifan Hong6e706b12018-11-09 16:50:51 -0800400 const std::string& super_device,
401 uint32_t source_slot,
402 uint32_t target_slot) {
Tianjie24f96092020-06-30 12:26:25 -0700403 bool always_keep_source_slot = !target_supports_snapshot_;
404 auto builder = MetadataBuilder::NewForUpdate(PartitionOpener(),
405 super_device,
406 source_slot,
407 target_slot,
408 always_keep_source_slot);
Yifan Hong537802d2018-08-15 13:15:42 -0700409 if (builder == nullptr) {
410 LOG(WARNING) << "No metadata slot "
411 << BootControlInterface::SlotName(source_slot) << " in "
412 << super_device;
Yifan Hongf48a0052018-10-29 16:30:43 -0700413 return nullptr;
Yifan Hong537802d2018-08-15 13:15:42 -0700414 }
Tianjie24f96092020-06-30 12:26:25 -0700415 LOG(INFO) << "Created metadata for new update from slot "
Yifan Hong537802d2018-08-15 13:15:42 -0700416 << BootControlInterface::SlotName(source_slot) << " in "
417 << super_device;
418 return builder;
419}
420
421bool DynamicPartitionControlAndroid::StoreMetadata(
422 const std::string& super_device,
423 MetadataBuilder* builder,
424 uint32_t target_slot) {
425 auto metadata = builder->Export();
426 if (metadata == nullptr) {
427 LOG(ERROR) << "Cannot export metadata to slot "
428 << BootControlInterface::SlotName(target_slot) << " in "
429 << super_device;
430 return false;
431 }
432
Yifan Hong186bb682019-07-23 14:04:39 -0700433 if (GetDynamicPartitionsFeatureFlag().IsRetrofit()) {
Yifan Hong6e706b12018-11-09 16:50:51 -0800434 if (!FlashPartitionTable(super_device, *metadata)) {
435 LOG(ERROR) << "Cannot write metadata to " << super_device;
436 return false;
437 }
438 LOG(INFO) << "Written metadata to " << super_device;
439 } else {
440 if (!UpdatePartitionTable(super_device, *metadata, target_slot)) {
441 LOG(ERROR) << "Cannot write metadata to slot "
442 << BootControlInterface::SlotName(target_slot) << " in "
443 << super_device;
444 return false;
445 }
446 LOG(INFO) << "Copied metadata to slot "
447 << BootControlInterface::SlotName(target_slot) << " in "
448 << super_device;
Yifan Hong537802d2018-08-15 13:15:42 -0700449 }
450
Yifan Hong537802d2018-08-15 13:15:42 -0700451 return true;
452}
453
454bool DynamicPartitionControlAndroid::GetDeviceDir(std::string* out) {
455 // We can't use fs_mgr to look up |partition_name| because fstab
456 // doesn't list every slot partition (it uses the slotselect option
457 // to mask the suffix).
458 //
459 // We can however assume that there's an entry for the /misc mount
460 // point and use that to get the device file for the misc
461 // partition. This helps us locate the disk that |partition_name|
462 // resides on. From there we'll assume that a by-name scheme is used
463 // so we can just replace the trailing "misc" by the given
464 // |partition_name| and suffix corresponding to |slot|, e.g.
465 //
466 // /dev/block/platform/soc.0/7824900.sdhci/by-name/misc ->
467 // /dev/block/platform/soc.0/7824900.sdhci/by-name/boot_a
468 //
469 // If needed, it's possible to relax the by-name assumption in the
470 // future by trawling /sys/block looking for the appropriate sibling
471 // of misc and then finding an entry in /dev matching the sysfs
472 // entry.
473
474 std::string err, misc_device = get_bootloader_message_blk_device(&err);
475 if (misc_device.empty()) {
476 LOG(ERROR) << "Unable to get misc block device: " << err;
477 return false;
478 }
479
480 if (!utils::IsSymlink(misc_device.c_str())) {
481 LOG(ERROR) << "Device file " << misc_device << " for /misc "
482 << "is not a symlink.";
483 return false;
484 }
485 *out = base::FilePath(misc_device).DirName().value();
486 return true;
487}
Yifan Hong012508e2019-07-22 18:30:40 -0700488
489bool DynamicPartitionControlAndroid::PreparePartitionsForUpdate(
490 uint32_t source_slot,
491 uint32_t target_slot,
Yifan Hongf0f4a912019-09-26 17:51:33 -0700492 const DeltaArchiveManifest& manifest,
Yifan Hongf033ecb2020-01-07 18:13:56 -0800493 bool update,
Daniel Zhengeede4c82023-06-13 11:21:06 -0700494 uint64_t* required_size,
495 ErrorCode* error) {
Yifan Hong6eec9952019-12-04 13:12:01 -0800496 source_slot_ = source_slot;
497 target_slot_ = target_slot;
Yifan Hongf033ecb2020-01-07 18:13:56 -0800498 if (required_size != nullptr) {
499 *required_size = 0;
500 }
Yifan Hong6eec9952019-12-04 13:12:01 -0800501
Yifan Hong3a1a5612019-11-05 16:34:32 -0800502 if (fs_mgr_overlayfs_is_setup()) {
503 // Non DAP devices can use overlayfs as well.
Daniel Zhengeede4c82023-06-13 11:21:06 -0700504 LOG(ERROR)
Yifan Hong3a1a5612019-11-05 16:34:32 -0800505 << "overlayfs overrides are active and can interfere with our "
506 "resources.\n"
507 << "run adb enable-verity to deactivate if required and try again.";
Daniel Zhengeede4c82023-06-13 11:21:06 -0700508 if (error) {
509 *error = ErrorCode::kOverlayfsenabledError;
510 return false;
511 }
Yifan Hong3a1a5612019-11-05 16:34:32 -0800512 }
513
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700514 // If metadata is erased but not formatted, it is possible to not mount
515 // it in recovery. It is acceptable to skip mounting and choose fallback path
516 // (PrepareDynamicPartitionsForUpdate) when sideloading full OTAs.
517 TEST_AND_RETURN_FALSE(EnsureMetadataMounted() || IsRecovery());
Yifan Hong29692902020-03-26 12:47:05 -0700518
519 if (update) {
520 TEST_AND_RETURN_FALSE(EraseSystemOtherAvbFooter(source_slot, target_slot));
521 }
522
Yifan Hong3a1a5612019-11-05 16:34:32 -0800523 if (!GetDynamicPartitionsFeatureFlag().IsEnabled()) {
524 return true;
525 }
526
527 if (target_slot == source_slot) {
528 LOG(ERROR) << "Cannot call PreparePartitionsForUpdate on current slot.";
529 return false;
530 }
531
Yifan Hongf6f75c22020-07-31 15:20:25 -0700532 if (!SetTargetBuildVars(manifest)) {
533 return false;
534 }
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700535 for (auto& list : dynamic_partition_list_) {
536 list.clear();
537 }
Yifan Hongf6f75c22020-07-31 15:20:25 -0700538
Yifan Hong3a1a5612019-11-05 16:34:32 -0800539 // Although the current build supports dynamic partitions, the given payload
540 // doesn't use it for target partitions. This could happen when applying a
541 // retrofit update. Skip updating the partition metadata for the target slot.
Yifan Hong3a1a5612019-11-05 16:34:32 -0800542 if (!is_target_dynamic_) {
543 return true;
544 }
545
Yifan Hongf0f4a912019-09-26 17:51:33 -0700546 if (!update)
547 return true;
548
Yifan Hongbae27842019-10-24 16:56:12 -0700549 bool delete_source = false;
550
Yifan Hong6d888562019-10-01 13:00:31 -0700551 if (GetVirtualAbFeatureFlag().IsEnabled()) {
552 // On Virtual A/B device, either CancelUpdate() or BeginUpdate() must be
553 // called before calling UnmapUpdateSnapshot.
554 // - If target_supports_snapshot_, PrepareSnapshotPartitionsForUpdate()
555 // calls BeginUpdate() which resets update state
Yifan Hongbae27842019-10-24 16:56:12 -0700556 // - If !target_supports_snapshot_ or PrepareSnapshotPartitionsForUpdate
557 // failed in recovery, explicitly CancelUpdate().
Yifan Hong6d888562019-10-01 13:00:31 -0700558 if (target_supports_snapshot_) {
Yifan Hongbae27842019-10-24 16:56:12 -0700559 if (PrepareSnapshotPartitionsForUpdate(
560 source_slot, target_slot, manifest, required_size)) {
561 return true;
562 }
563
564 // Virtual A/B device doing Virtual A/B update in Android mode must use
565 // snapshots.
566 if (!IsRecovery()) {
567 LOG(ERROR) << "PrepareSnapshotPartitionsForUpdate failed in Android "
568 << "mode";
569 return false;
570 }
571
572 delete_source = true;
573 LOG(INFO) << "PrepareSnapshotPartitionsForUpdate failed in recovery. "
574 << "Attempt to overwrite existing partitions if possible";
575 } else {
576 // Downgrading to an non-Virtual A/B build or is secondary OTA.
577 LOG(INFO) << "Using regular A/B on Virtual A/B because package disabled "
578 << "snapshots.";
Yifan Hong6d888562019-10-01 13:00:31 -0700579 }
Yifan Hongbae27842019-10-24 16:56:12 -0700580
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700581 // In recovery, if /metadata is not mounted, it is likely that metadata
582 // partition is erased and not formatted yet. After sideloading, when
583 // rebooting into the new version, init will erase metadata partition,
584 // hence the failure of CancelUpdate() can be ignored here.
585 // However, if metadata is mounted and CancelUpdate fails, sideloading
586 // should not proceed because during next boot, snapshots will overlay on
587 // the devices incorrectly.
588 if (ExpectMetadataMounted()) {
589 TEST_AND_RETURN_FALSE(snapshot_->CancelUpdate());
590 } else {
591 LOG(INFO) << "Skip canceling previous update because metadata is not "
592 << "mounted";
Yifan Hong6d888562019-10-01 13:00:31 -0700593 }
Yifan Hong420db9b2019-07-23 20:50:33 -0700594 }
Yifan Hongbae27842019-10-24 16:56:12 -0700595
Tianjie24f96092020-06-30 12:26:25 -0700596 // TODO(xunchang) support partial update on non VAB enabled devices.
Yifan Hong5c5743f2020-04-16 12:59:07 -0700597 TEST_AND_RETURN_FALSE(PrepareDynamicPartitionsForUpdate(
598 source_slot, target_slot, manifest, delete_source));
599
600 if (required_size != nullptr) {
601 *required_size = 0;
602 }
603 return true;
Yifan Hong420db9b2019-07-23 20:50:33 -0700604}
605
Yifan Hongf6f75c22020-07-31 15:20:25 -0700606bool DynamicPartitionControlAndroid::SetTargetBuildVars(
607 const DeltaArchiveManifest& manifest) {
608 // Precondition: current build supports dynamic partition.
609 CHECK(GetDynamicPartitionsFeatureFlag().IsEnabled());
610
611 bool is_target_dynamic =
612 !manifest.dynamic_partition_metadata().groups().empty();
613 bool target_supports_snapshot =
614 manifest.dynamic_partition_metadata().snapshot_enabled();
615
616 if (manifest.partial_update()) {
617 // Partial updates requires DAP. On partial updates that does not involve
618 // dynamic partitions, groups() can be empty, so also assume
619 // is_target_dynamic in this case. This assumption should be safe because we
620 // also check target_supports_snapshot below, which presumably also implies
621 // target build supports dynamic partition.
622 if (!is_target_dynamic) {
623 LOG(INFO) << "Assuming target build supports dynamic partitions for "
624 "partial updates.";
625 is_target_dynamic = true;
626 }
627
628 // Partial updates requires Virtual A/B. Double check that both current
629 // build and target build supports Virtual A/B.
630 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
631 LOG(ERROR) << "Partial update cannot be applied on a device that does "
632 "not support snapshots.";
633 return false;
634 }
635 if (!target_supports_snapshot) {
636 LOG(ERROR) << "Cannot apply partial update to a build that does not "
637 "support snapshots.";
638 return false;
639 }
640 }
641
642 // Store the flags.
643 is_target_dynamic_ = is_target_dynamic;
644 // If !is_target_dynamic_, leave target_supports_snapshot_ unset because
645 // snapshots would not work without dynamic partition.
646 if (is_target_dynamic_) {
647 target_supports_snapshot_ = target_supports_snapshot;
648 }
649 return true;
650}
651
Yifan Hong29692902020-03-26 12:47:05 -0700652namespace {
653// Try our best to erase AVB footer.
654class AvbFooterEraser {
655 public:
656 explicit AvbFooterEraser(const std::string& path) : path_(path) {}
657 bool Erase() {
658 // Try to mark the block device read-only. Ignore any
659 // failure since this won't work when passing regular files.
660 ignore_result(utils::SetBlockDeviceReadOnly(path_, false /* readonly */));
661
662 fd_.reset(new EintrSafeFileDescriptor());
663 int flags = O_WRONLY | O_TRUNC | O_CLOEXEC | O_SYNC;
664 TEST_AND_RETURN_FALSE(fd_->Open(path_.c_str(), flags));
665
666 // Need to write end-AVB_FOOTER_SIZE to end.
667 static_assert(AVB_FOOTER_SIZE > 0);
668 off64_t offset = fd_->Seek(-AVB_FOOTER_SIZE, SEEK_END);
669 TEST_AND_RETURN_FALSE_ERRNO(offset >= 0);
670 uint64_t write_size = AVB_FOOTER_SIZE;
671 LOG(INFO) << "Zeroing " << path_ << " @ [" << offset << ", "
672 << (offset + write_size) << "] (" << write_size << " bytes)";
673 brillo::Blob zeros(write_size);
674 TEST_AND_RETURN_FALSE(utils::WriteAll(fd_, zeros.data(), zeros.size()));
675 return true;
676 }
677 ~AvbFooterEraser() {
678 TEST_AND_RETURN(fd_ != nullptr && fd_->IsOpen());
679 if (!fd_->Close()) {
680 LOG(WARNING) << "Failed to close fd for " << path_;
681 }
682 }
683
684 private:
685 std::string path_;
686 FileDescriptorPtr fd_;
687};
688
689} // namespace
690
691std::optional<bool>
692DynamicPartitionControlAndroid::IsAvbEnabledOnSystemOther() {
693 auto prefix = GetProperty(kPostinstallFstabPrefix, "");
694 if (prefix.empty()) {
695 LOG(WARNING) << "Cannot get " << kPostinstallFstabPrefix;
696 return std::nullopt;
697 }
698 auto path = base::FilePath(prefix).Append("etc/fstab.postinstall").value();
699 return IsAvbEnabledInFstab(path);
700}
701
702std::optional<bool> DynamicPartitionControlAndroid::IsAvbEnabledInFstab(
703 const std::string& path) {
704 Fstab fstab;
705 if (!ReadFstabFromFile(path, &fstab)) {
Yifan Hong93cde302020-04-27 12:59:29 -0700706 PLOG(WARNING) << "Cannot read fstab from " << path;
707 if (errno == ENOENT) {
708 return false;
709 }
Yifan Hong29692902020-03-26 12:47:05 -0700710 return std::nullopt;
711 }
712 for (const auto& entry : fstab) {
713 if (!entry.avb_keys.empty()) {
714 return true;
715 }
716 }
717 return false;
718}
719
720bool DynamicPartitionControlAndroid::GetSystemOtherPath(
721 uint32_t source_slot,
722 uint32_t target_slot,
723 const std::string& partition_name_suffix,
724 std::string* path,
725 bool* should_unmap) {
726 path->clear();
727 *should_unmap = false;
728
P.Adarsh Reddy13e4195d2020-06-08 23:17:36 +0530729 // Check that AVB is enabled on system_other before erasing.
730 auto has_avb = IsAvbEnabledOnSystemOther();
731 TEST_AND_RETURN_FALSE(has_avb.has_value());
732 if (!has_avb.value()) {
733 LOG(INFO) << "AVB is not enabled on system_other. Skip erasing.";
734 return true;
735 }
Yifan Hong29692902020-03-26 12:47:05 -0700736
P.Adarsh Reddy13e4195d2020-06-08 23:17:36 +0530737 if (!IsRecovery()) {
Yifan Hong29692902020-03-26 12:47:05 -0700738 // Found unexpected avb_keys for system_other on devices retrofitting
739 // dynamic partitions. Previous crash in update_engine may leave logical
740 // partitions mapped on physical system_other partition. It is difficult to
741 // handle these cases. Just fail.
742 if (GetDynamicPartitionsFeatureFlag().IsRetrofit()) {
743 LOG(ERROR) << "Cannot erase AVB footer on system_other on devices with "
744 << "retrofit dynamic partitions. They should not have AVB "
745 << "enabled on system_other.";
746 return false;
747 }
748 }
749
750 std::string device_dir_str;
751 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
752 base::FilePath device_dir(device_dir_str);
753
754 // On devices without dynamic partition, search for static partitions.
755 if (!GetDynamicPartitionsFeatureFlag().IsEnabled()) {
756 *path = device_dir.Append(partition_name_suffix).value();
757 TEST_AND_RETURN_FALSE(DeviceExists(*path));
758 return true;
759 }
760
761 auto source_super_device =
762 device_dir.Append(GetSuperPartitionName(source_slot)).value();
763
764 auto builder = LoadMetadataBuilder(source_super_device, source_slot);
765 if (builder == nullptr) {
766 if (IsRecovery()) {
767 // It might be corrupted for some reason. It should still be able to
768 // sideload.
769 LOG(WARNING) << "Super partition metadata cannot be read from the source "
770 << "slot, skip erasing.";
771 return true;
772 } else {
773 // Device has booted into Android mode, indicating that the super
774 // partition metadata should be there.
775 LOG(ERROR) << "Super partition metadata cannot be read from the source "
776 << "slot. This is unexpected on devices with dynamic "
777 << "partitions enabled.";
778 return false;
779 }
780 }
781 auto p = builder->FindPartition(partition_name_suffix);
782 if (p == nullptr) {
783 // If the source slot is flashed without system_other, it does not exist
784 // in super partition metadata at source slot. It is safe to skip it.
785 LOG(INFO) << "Can't find " << partition_name_suffix
786 << " in metadata source slot, skip erasing.";
787 return true;
788 }
789 // System_other created by flashing tools should be erased.
790 // If partition is created by update_engine (via NewForUpdate), it is a
791 // left-over partition from the previous update and does not contain
792 // system_other, hence there is no need to erase.
793 // Note the reverse is not necessary true. If the flag is not set, we don't
794 // know if the partition is created by update_engine or by flashing tools
795 // because older versions of super partition metadata does not contain this
796 // flag. It is okay to erase the AVB footer anyways.
797 if (p->attributes() & LP_PARTITION_ATTR_UPDATED) {
798 LOG(INFO) << partition_name_suffix
799 << " does not contain system_other, skip erasing.";
800 return true;
801 }
802
Yifan Hong64331b32020-05-13 16:50:40 -0700803 if (p->size() < AVB_FOOTER_SIZE) {
804 LOG(INFO) << partition_name_suffix << " has length " << p->size()
805 << "( < AVB_FOOTER_SIZE " << AVB_FOOTER_SIZE
806 << "), skip erasing.";
807 return true;
808 }
809
Yifan Hong29692902020-03-26 12:47:05 -0700810 // Delete any pre-existing device with name |partition_name_suffix| and
811 // also remove it from |mapped_devices_|.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700812 // In recovery, metadata might not be mounted, and
813 // UnmapPartitionOnDeviceMapper might fail. However,
814 // it is unusual that system_other has already been mapped. Hence, just skip.
Kelvin Zhang08bbbd42024-08-27 13:25:07 -0700815 LOG(INFO) << "Destroying `" << partition_name_suffix
816 << "` from device mapper";
Yifan Hong29692902020-03-26 12:47:05 -0700817 TEST_AND_RETURN_FALSE(UnmapPartitionOnDeviceMapper(partition_name_suffix));
818 // Use CreateLogicalPartition directly to avoid mapping with existing
819 // snapshots.
820 CreateLogicalPartitionParams params = {
821 .block_device = source_super_device,
822 .metadata_slot = source_slot,
823 .partition_name = partition_name_suffix,
824 .force_writable = true,
825 .timeout_ms = kMapTimeout,
826 };
827 TEST_AND_RETURN_FALSE(CreateLogicalPartition(params, path));
828 *should_unmap = true;
829 return true;
830}
831
832bool DynamicPartitionControlAndroid::EraseSystemOtherAvbFooter(
833 uint32_t source_slot, uint32_t target_slot) {
834 LOG(INFO) << "Erasing AVB footer of system_other partition before update.";
835
836 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
837 const std::string partition_name_suffix = "system" + target_suffix;
838
839 std::string path;
840 bool should_unmap = false;
841
842 TEST_AND_RETURN_FALSE(GetSystemOtherPath(
843 source_slot, target_slot, partition_name_suffix, &path, &should_unmap));
844
845 if (path.empty()) {
846 return true;
847 }
848
849 bool ret = AvbFooterEraser(path).Erase();
850
851 // Delete |partition_name_suffix| from device mapper and from
852 // |mapped_devices_| again so that it does not interfere with update process.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700853 // In recovery, metadata might not be mounted, and
854 // UnmapPartitionOnDeviceMapper might fail. However, DestroyLogicalPartition
855 // should be called. If DestroyLogicalPartition does fail, it is still okay
856 // to skip the error here and let Prepare*() fail later.
Yifan Hong29692902020-03-26 12:47:05 -0700857 if (should_unmap) {
Kelvin Zhang08bbbd42024-08-27 13:25:07 -0700858 LOG(INFO) << "Destroying `" << partition_name_suffix
859 << "` from device mapper";
Yifan Hong29692902020-03-26 12:47:05 -0700860 TEST_AND_RETURN_FALSE(UnmapPartitionOnDeviceMapper(partition_name_suffix));
861 }
862
863 return ret;
864}
865
Yifan Hong420db9b2019-07-23 20:50:33 -0700866bool DynamicPartitionControlAndroid::PrepareDynamicPartitionsForUpdate(
867 uint32_t source_slot,
868 uint32_t target_slot,
Yifan Hongbae27842019-10-24 16:56:12 -0700869 const DeltaArchiveManifest& manifest,
870 bool delete_source) {
Yifan Hong012508e2019-07-22 18:30:40 -0700871 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
872
873 // Unmap all the target dynamic partitions because they would become
874 // inconsistent with the new metadata.
Yifan Hong13d41cb2019-09-16 13:18:22 -0700875 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
876 for (const auto& partition_name : group.partition_names()) {
877 if (!UnmapPartitionOnDeviceMapper(partition_name + target_suffix)) {
Yifan Hong012508e2019-07-22 18:30:40 -0700878 return false;
879 }
880 }
881 }
882
883 std::string device_dir_str;
Tianjie9f4dc7f2021-03-15 16:00:50 -0700884 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
Yifan Hong012508e2019-07-22 18:30:40 -0700885 base::FilePath device_dir(device_dir_str);
886 auto source_device =
Yifan Hong700d7c12019-07-23 20:49:16 -0700887 device_dir.Append(GetSuperPartitionName(source_slot)).value();
Yifan Hong012508e2019-07-22 18:30:40 -0700888
889 auto builder = LoadMetadataBuilder(source_device, source_slot, target_slot);
890 if (builder == nullptr) {
891 LOG(ERROR) << "No metadata at "
892 << BootControlInterface::SlotName(source_slot);
893 return false;
894 }
895
Yifan Hongbae27842019-10-24 16:56:12 -0700896 if (delete_source) {
897 TEST_AND_RETURN_FALSE(
898 DeleteSourcePartitions(builder.get(), source_slot, manifest));
899 }
900
Tianjie9f4dc7f2021-03-15 16:00:50 -0700901 TEST_AND_RETURN_FALSE(
902 UpdatePartitionMetadata(builder.get(), target_slot, manifest));
Yifan Hong012508e2019-07-22 18:30:40 -0700903
904 auto target_device =
Yifan Hong700d7c12019-07-23 20:49:16 -0700905 device_dir.Append(GetSuperPartitionName(target_slot)).value();
Daniel Zhengeede4c82023-06-13 11:21:06 -0700906
Yifan Hong012508e2019-07-22 18:30:40 -0700907 return StoreMetadata(target_device, builder.get(), target_slot);
908}
909
Yifan Hong3a1293a2021-04-16 13:21:20 -0700910DynamicPartitionControlAndroid::SpaceLimit
911DynamicPartitionControlAndroid::GetSpaceLimit(bool use_snapshot) {
912 // On device retrofitting dynamic partitions, allocatable_space = "super",
913 // where "super" is the sum of all block devices for that slot. Since block
914 // devices are dedicated for the corresponding slot, there's no need to halve
915 // the allocatable space.
916 if (GetDynamicPartitionsFeatureFlag().IsRetrofit())
917 return SpaceLimit::ERROR_IF_EXCEEDED_SUPER;
918
919 // On device launching dynamic partitions w/o VAB, regardless of recovery
920 // sideload, super partition must be big enough to hold both A and B slots of
921 // groups. Hence,
922 // allocatable_space = super / 2
923 if (!GetVirtualAbFeatureFlag().IsEnabled())
924 return SpaceLimit::ERROR_IF_EXCEEDED_HALF_OF_SUPER;
925
926 // Source build supports VAB. Super partition must be big enough to hold
927 // one slot of groups (ERROR_IF_EXCEEDED_SUPER). However, there are cases
928 // where additional warning messages needs to be written.
929
930 // If using snapshot updates, implying that target build also uses VAB,
931 // allocatable_space = super
932 if (use_snapshot)
933 return SpaceLimit::ERROR_IF_EXCEEDED_SUPER;
934
935 // Source build supports VAB but not using snapshot updates. There are
936 // several cases, as listed below.
937 // Sideloading: allocatable_space = super.
938 if (IsRecovery())
939 return SpaceLimit::ERROR_IF_EXCEEDED_SUPER;
940
941 // On launch VAB device, this implies secondary payload.
942 // Technically, we don't have to check anything, but sum(groups) < super
943 // still applies.
944 if (!GetVirtualAbFeatureFlag().IsRetrofit())
945 return SpaceLimit::ERROR_IF_EXCEEDED_SUPER;
946
947 // On retrofit VAB device, either of the following:
948 // - downgrading: allocatable_space = super / 2
949 // - secondary payload: don't check anything
950 // These two cases are indistinguishable,
951 // hence emit warning if sum(groups) > super / 2
952 return SpaceLimit::WARN_IF_EXCEEDED_HALF_OF_SUPER;
953}
954
Tianjie9f4dc7f2021-03-15 16:00:50 -0700955bool DynamicPartitionControlAndroid::CheckSuperPartitionAllocatableSpace(
956 android::fs_mgr::MetadataBuilder* builder,
957 const DeltaArchiveManifest& manifest,
958 bool use_snapshot) {
Yifan Hong3a1293a2021-04-16 13:21:20 -0700959 uint64_t sum_groups = 0;
Tianjie9f4dc7f2021-03-15 16:00:50 -0700960 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
Yifan Hong3a1293a2021-04-16 13:21:20 -0700961 sum_groups += group.size();
Tianjie9f4dc7f2021-03-15 16:00:50 -0700962 }
963
Yifan Hong3a1293a2021-04-16 13:21:20 -0700964 uint64_t full_space = builder->AllocatableSpace();
965 uint64_t half_space = full_space / 2;
966 constexpr const char* fmt =
967 "The maximum size of all groups for the target slot (%" PRIu64
968 ") has exceeded %sallocatable space for dynamic partitions %" PRIu64 ".";
969 switch (GetSpaceLimit(use_snapshot)) {
970 case SpaceLimit::ERROR_IF_EXCEEDED_HALF_OF_SUPER: {
971 if (sum_groups > half_space) {
972 LOG(ERROR) << StringPrintf(fmt, sum_groups, "HALF OF ", half_space);
973 return false;
974 }
975 // If test passes, it implies that the following two conditions also pass.
976 break;
977 }
978 case SpaceLimit::WARN_IF_EXCEEDED_HALF_OF_SUPER: {
979 if (sum_groups > half_space) {
980 LOG(WARNING) << StringPrintf(fmt, sum_groups, "HALF OF ", half_space)
981 << " This is allowed for downgrade or secondary OTA on "
982 "retrofit VAB device.";
983 }
984 // still check sum(groups) < super
985 [[fallthrough]];
986 }
987 case SpaceLimit::ERROR_IF_EXCEEDED_SUPER: {
988 if (sum_groups > full_space) {
Kelvin Zhangb9a9aa22024-10-15 10:38:35 -0700989 LOG(ERROR) << android::base::StringPrintf(
990 fmt, sum_groups, "", full_space);
Yifan Hong3a1293a2021-04-16 13:21:20 -0700991 return false;
992 }
993 break;
994 }
Tianjie9f4dc7f2021-03-15 16:00:50 -0700995 }
996
997 return true;
998}
999
Yifan Hong420db9b2019-07-23 20:50:33 -07001000bool DynamicPartitionControlAndroid::PrepareSnapshotPartitionsForUpdate(
1001 uint32_t source_slot,
1002 uint32_t target_slot,
Yifan Hongf033ecb2020-01-07 18:13:56 -08001003 const DeltaArchiveManifest& manifest,
1004 uint64_t* required_size) {
Yifan Hong4d7c5eb2020-04-03 11:31:50 -07001005 TEST_AND_RETURN_FALSE(ExpectMetadataMounted());
Tianjie9f4dc7f2021-03-15 16:00:50 -07001006
1007 std::string device_dir_str;
1008 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
1009 base::FilePath device_dir(device_dir_str);
1010 auto super_device =
1011 device_dir.Append(GetSuperPartitionName(source_slot)).value();
1012 auto builder = LoadMetadataBuilder(super_device, source_slot);
1013 if (builder == nullptr) {
1014 LOG(ERROR) << "No metadata at "
1015 << BootControlInterface::SlotName(source_slot);
1016 return false;
1017 }
1018
1019 TEST_AND_RETURN_FALSE(
1020 CheckSuperPartitionAllocatableSpace(builder.get(), manifest, true));
1021
Yifan Hong420db9b2019-07-23 20:50:33 -07001022 if (!snapshot_->BeginUpdate()) {
1023 LOG(ERROR) << "Cannot begin new update.";
1024 return false;
1025 }
Yifan Hongf033ecb2020-01-07 18:13:56 -08001026 auto ret = snapshot_->CreateUpdateSnapshots(manifest);
1027 if (!ret) {
1028 LOG(ERROR) << "Cannot create update snapshots: " << ret.string();
1029 if (required_size != nullptr &&
Yifan Hong0850bca2020-01-16 15:14:07 -08001030 ret.error_code() == Return::ErrorCode::NO_SPACE) {
Yifan Hongf033ecb2020-01-07 18:13:56 -08001031 *required_size = ret.required_size();
1032 }
Yifan Hong420db9b2019-07-23 20:50:33 -07001033 return false;
1034 }
1035 return true;
1036}
1037
Yifan Hong700d7c12019-07-23 20:49:16 -07001038std::string DynamicPartitionControlAndroid::GetSuperPartitionName(
1039 uint32_t slot) {
1040 return fs_mgr_get_super_partition_name(slot);
1041}
1042
Yifan Hong012508e2019-07-22 18:30:40 -07001043bool DynamicPartitionControlAndroid::UpdatePartitionMetadata(
1044 MetadataBuilder* builder,
1045 uint32_t target_slot,
Yifan Hong13d41cb2019-09-16 13:18:22 -07001046 const DeltaArchiveManifest& manifest) {
Yifan Hong8d6df9a2020-08-13 13:59:54 -07001047 // Check preconditions.
Yifan Hong265a8e32021-04-16 13:30:02 -07001048 if (GetVirtualAbFeatureFlag().IsEnabled()) {
1049 CHECK(!target_supports_snapshot_ || IsRecovery())
1050 << "Must use snapshot on VAB device when target build supports VAB and "
1051 "not sideloading.";
1052 LOG_IF(INFO, !target_supports_snapshot_)
1053 << "Not using snapshot on VAB device because target build does not "
1054 "support snapshot. Secondary or downgrade OTA?";
1055 LOG_IF(INFO, IsRecovery())
1056 << "Not using snapshot on VAB device because sideloading.";
1057 }
Yifan Hong8d6df9a2020-08-13 13:59:54 -07001058
Yifan Honga4e7da32019-09-30 18:25:03 -07001059 // If applying downgrade from Virtual A/B to non-Virtual A/B, the left-over
1060 // COW group needs to be deleted to ensure there are enough space to create
1061 // target partitions.
1062 builder->RemoveGroupAndPartitions(android::snapshot::kCowGroupName);
1063
Yifan Hong012508e2019-07-22 18:30:40 -07001064 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
1065 DeleteGroupsWithSuffix(builder, target_suffix);
1066
Tianjie9f4dc7f2021-03-15 16:00:50 -07001067 TEST_AND_RETURN_FALSE(
1068 CheckSuperPartitionAllocatableSpace(builder, manifest, false));
Yifan Hong012508e2019-07-22 18:30:40 -07001069
Yifan Hong13d41cb2019-09-16 13:18:22 -07001070 // name of partition(e.g. "system") -> size in bytes
1071 std::map<std::string, uint64_t> partition_sizes;
1072 for (const auto& partition : manifest.partitions()) {
1073 partition_sizes.emplace(partition.partition_name(),
1074 partition.new_partition_info().size());
1075 }
1076
1077 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
1078 auto group_name_suffix = group.name() + target_suffix;
1079 if (!builder->AddGroup(group_name_suffix, group.size())) {
Yifan Hong012508e2019-07-22 18:30:40 -07001080 LOG(ERROR) << "Cannot add group " << group_name_suffix << " with size "
Yifan Hong13d41cb2019-09-16 13:18:22 -07001081 << group.size();
Yifan Hong012508e2019-07-22 18:30:40 -07001082 return false;
1083 }
1084 LOG(INFO) << "Added group " << group_name_suffix << " with size "
Yifan Hong13d41cb2019-09-16 13:18:22 -07001085 << group.size();
Yifan Hong012508e2019-07-22 18:30:40 -07001086
Yifan Hong13d41cb2019-09-16 13:18:22 -07001087 for (const auto& partition_name : group.partition_names()) {
1088 auto partition_sizes_it = partition_sizes.find(partition_name);
1089 if (partition_sizes_it == partition_sizes.end()) {
1090 // TODO(tbao): Support auto-filling partition info for framework-only
1091 // OTA.
1092 LOG(ERROR) << "dynamic_partition_metadata contains partition "
1093 << partition_name << " but it is not part of the manifest. "
1094 << "This is not supported.";
1095 return false;
1096 }
1097 uint64_t partition_size = partition_sizes_it->second;
1098
1099 auto partition_name_suffix = partition_name + target_suffix;
Yifan Hong012508e2019-07-22 18:30:40 -07001100 Partition* p = builder->AddPartition(
1101 partition_name_suffix, group_name_suffix, LP_PARTITION_ATTR_READONLY);
1102 if (!p) {
1103 LOG(ERROR) << "Cannot add partition " << partition_name_suffix
1104 << " to group " << group_name_suffix;
1105 return false;
1106 }
Yifan Hong13d41cb2019-09-16 13:18:22 -07001107 if (!builder->ResizePartition(p, partition_size)) {
Yifan Hong012508e2019-07-22 18:30:40 -07001108 LOG(ERROR) << "Cannot resize partition " << partition_name_suffix
Yifan Hong13d41cb2019-09-16 13:18:22 -07001109 << " to size " << partition_size << ". Not enough space?";
Yifan Hong012508e2019-07-22 18:30:40 -07001110 return false;
1111 }
David Anderson0e1c7fd2021-03-08 19:01:59 -08001112 if (p->size() < partition_size) {
1113 LOG(ERROR) << "Partition " << partition_name_suffix
1114 << " was expected to have size " << partition_size
1115 << ", but instead has size " << p->size();
1116 return false;
1117 }
Yifan Hong012508e2019-07-22 18:30:40 -07001118 LOG(INFO) << "Added partition " << partition_name_suffix << " to group "
Yifan Hong13d41cb2019-09-16 13:18:22 -07001119 << group_name_suffix << " with size " << partition_size;
Yifan Hong012508e2019-07-22 18:30:40 -07001120 }
1121 }
1122
1123 return true;
1124}
1125
Yifan Hong7b3910a2020-03-24 17:47:32 -07001126bool DynamicPartitionControlAndroid::FinishUpdate(bool powerwash_required) {
Yifan Hong4d7c5eb2020-04-03 11:31:50 -07001127 if (ExpectMetadataMounted()) {
1128 if (snapshot_->GetUpdateState() == UpdateState::Initiated) {
1129 LOG(INFO) << "Snapshot writes are done.";
1130 return snapshot_->FinishedSnapshotWrites(powerwash_required);
1131 }
1132 } else {
1133 LOG(INFO) << "Skip FinishedSnapshotWrites() because /metadata is not "
1134 << "mounted";
Yifan Hongf0f4a912019-09-26 17:51:33 -07001135 }
1136 return true;
Yifan Honga33bca42019-09-03 20:29:45 -07001137}
1138
Yifan Hong3a1a5612019-11-05 16:34:32 -08001139bool DynamicPartitionControlAndroid::GetPartitionDevice(
1140 const std::string& partition_name,
1141 uint32_t slot,
1142 uint32_t current_slot,
Tianjie51a5a392020-06-03 14:39:32 -07001143 bool not_in_payload,
1144 std::string* device,
1145 bool* is_dynamic) {
Kelvin Zhang66a9ebb2021-01-25 13:35:10 -05001146 auto partition_dev =
1147 GetPartitionDevice(partition_name, slot, current_slot, not_in_payload);
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001148 if (!partition_dev.has_value()) {
Yifan Hong3a1a5612019-11-05 16:34:32 -08001149 return false;
1150 }
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001151 if (device) {
1152 *device = std::move(partition_dev->rw_device_path);
1153 }
1154 if (is_dynamic) {
1155 *is_dynamic = partition_dev->is_dynamic;
1156 }
Yifan Hong3a1a5612019-11-05 16:34:32 -08001157 return true;
1158}
1159
Tianjie51a5a392020-06-03 14:39:32 -07001160bool DynamicPartitionControlAndroid::GetPartitionDevice(
1161 const std::string& partition_name,
1162 uint32_t slot,
1163 uint32_t current_slot,
1164 std::string* device) {
1165 return GetPartitionDevice(
1166 partition_name, slot, current_slot, false, device, nullptr);
1167}
1168
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001169static std::string GetStaticDevicePath(
1170 const base::FilePath& device_dir,
1171 const std::string& partition_name_suffixed) {
1172 base::FilePath path = device_dir.Append(partition_name_suffixed);
1173 return path.value();
1174}
1175
1176std::optional<PartitionDevice>
1177DynamicPartitionControlAndroid::GetPartitionDevice(
1178 const std::string& partition_name,
1179 uint32_t slot,
1180 uint32_t current_slot,
1181 bool not_in_payload) {
1182 std::string device_dir_str;
1183 if (!GetDeviceDir(&device_dir_str)) {
1184 LOG(ERROR) << "Failed to GetDeviceDir()";
1185 return {};
1186 }
1187 const base::FilePath device_dir(device_dir_str);
1188 // When VABC is enabled, we can't get device path for dynamic partitions in
1189 // target slot.
1190 const auto& partition_name_suffix =
1191 partition_name + SlotSuffixForSlotNumber(slot);
Kelvin Zhangebd115e2021-03-08 16:10:25 -05001192 if (UpdateUsesSnapshotCompression() && slot != current_slot &&
1193 IsDynamicPartition(partition_name, slot)) {
Kelvin Zhang91ad6622021-03-01 13:46:17 -05001194 return {
Kelvin Zhanga9b5d8c2021-05-05 09:17:46 -04001195 {.readonly_device_path = base::FilePath{std::string{VABC_DEVICE_DIR}}
1196 .Append(partition_name_suffix)
1197 .value(),
Kelvin Zhang91ad6622021-03-01 13:46:17 -05001198 .is_dynamic = true}};
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001199 }
1200
1201 // When looking up target partition devices, treat them as static if the
1202 // current payload doesn't encode them as dynamic partitions. This may happen
1203 // when applying a retrofit update on top of a dynamic-partitions-enabled
1204 // build.
1205 std::string device;
1206 if (GetDynamicPartitionsFeatureFlag().IsEnabled() &&
1207 (slot == current_slot || is_target_dynamic_)) {
Kelvin Zhang08bbbd42024-08-27 13:25:07 -07001208 auto status = GetDynamicPartitionDevice(device_dir,
1209 partition_name_suffix,
1210 slot,
1211 current_slot,
1212 not_in_payload,
1213 &device);
1214 switch (status) {
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001215 case DynamicPartitionDeviceStatus::SUCCESS:
1216 return {{.rw_device_path = device,
Kelvin Zhanga9b5d8c2021-05-05 09:17:46 -04001217 .readonly_device_path = device,
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001218 .is_dynamic = true}};
1219
1220 case DynamicPartitionDeviceStatus::TRY_STATIC:
1221 break;
1222 case DynamicPartitionDeviceStatus::ERROR: // fallthrough
1223 default:
Kelvin Zhang08bbbd42024-08-27 13:25:07 -07001224 LOG(ERROR) << "Unhandled dynamic partition status " << (int)status;
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001225 return {};
1226 }
1227 }
1228 // Try static partitions.
1229 auto static_path = GetStaticDevicePath(device_dir, partition_name_suffix);
1230 if (!DeviceExists(static_path)) {
1231 LOG(ERROR) << "Device file " << static_path << " does not exist.";
1232 return {};
1233 }
1234
1235 return {{.rw_device_path = static_path,
Kelvin Zhanga9b5d8c2021-05-05 09:17:46 -04001236 .readonly_device_path = static_path,
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001237 .is_dynamic = false}};
1238}
1239
Yifan Hong3a1a5612019-11-05 16:34:32 -08001240bool DynamicPartitionControlAndroid::IsSuperBlockDevice(
1241 const base::FilePath& device_dir,
1242 uint32_t current_slot,
1243 const std::string& partition_name_suffix) {
1244 std::string source_device =
1245 device_dir.Append(GetSuperPartitionName(current_slot)).value();
1246 auto source_metadata = LoadMetadataBuilder(source_device, current_slot);
1247 return source_metadata->HasBlockDevice(partition_name_suffix);
1248}
1249
1250DynamicPartitionControlAndroid::DynamicPartitionDeviceStatus
1251DynamicPartitionControlAndroid::GetDynamicPartitionDevice(
1252 const base::FilePath& device_dir,
1253 const std::string& partition_name_suffix,
1254 uint32_t slot,
1255 uint32_t current_slot,
Tianjie51a5a392020-06-03 14:39:32 -07001256 bool not_in_payload,
Yifan Hong3a1a5612019-11-05 16:34:32 -08001257 std::string* device) {
1258 std::string super_device =
1259 device_dir.Append(GetSuperPartitionName(slot)).value();
Kelvin Zhang08bbbd42024-08-27 13:25:07 -07001260 auto device_name = GetDeviceName(partition_name_suffix, slot);
Yifan Hong3a1a5612019-11-05 16:34:32 -08001261
1262 auto builder = LoadMetadataBuilder(super_device, slot);
1263 if (builder == nullptr) {
1264 LOG(ERROR) << "No metadata in slot "
1265 << BootControlInterface::SlotName(slot);
1266 return DynamicPartitionDeviceStatus::ERROR;
1267 }
1268 if (builder->FindPartition(partition_name_suffix) == nullptr) {
1269 LOG(INFO) << partition_name_suffix
1270 << " is not in super partition metadata.";
1271
1272 if (IsSuperBlockDevice(device_dir, current_slot, partition_name_suffix)) {
1273 LOG(ERROR) << "The static partition " << partition_name_suffix
1274 << " is a block device for current metadata."
1275 << "It cannot be used as a logical partition.";
1276 return DynamicPartitionDeviceStatus::ERROR;
1277 }
1278
1279 return DynamicPartitionDeviceStatus::TRY_STATIC;
1280 }
1281
1282 if (slot == current_slot) {
Kelvin Zhang08bbbd42024-08-27 13:25:07 -07001283 if (GetState(device_name) != DmDeviceState::ACTIVE) {
1284 LOG(WARNING) << device_name << " is at current slot but it is "
Yifan Hong3a1a5612019-11-05 16:34:32 -08001285 << "not mapped. Now try to map it.";
1286 } else {
Kelvin Zhang08bbbd42024-08-27 13:25:07 -07001287 if (GetDmDevicePathByName(device_name, device)) {
1288 LOG(INFO) << device_name << " is mapped on device mapper: " << *device;
Yifan Hong3a1a5612019-11-05 16:34:32 -08001289 return DynamicPartitionDeviceStatus::SUCCESS;
1290 }
1291 LOG(ERROR) << partition_name_suffix << "is mapped but path is unknown.";
1292 return DynamicPartitionDeviceStatus::ERROR;
1293 }
1294 }
1295
Kelvin Zhang8b07db52024-07-24 09:13:25 -07001296 const bool force_writable = !not_in_payload;
Yifan Hong3a1a5612019-11-05 16:34:32 -08001297 if (MapPartitionOnDeviceMapper(
1298 super_device, partition_name_suffix, slot, force_writable, device)) {
1299 return DynamicPartitionDeviceStatus::SUCCESS;
1300 }
1301 return DynamicPartitionDeviceStatus::ERROR;
1302}
1303
Yifan Hong6eec9952019-12-04 13:12:01 -08001304void DynamicPartitionControlAndroid::set_fake_mapped_devices(
1305 const std::set<std::string>& fake) {
1306 mapped_devices_ = fake;
1307}
1308
Yifan Hongbae27842019-10-24 16:56:12 -07001309bool DynamicPartitionControlAndroid::IsRecovery() {
Kelvin Zhanga22ef552020-10-12 19:03:52 -04001310 return constants::kIsRecovery;
Yifan Hongbae27842019-10-24 16:56:12 -07001311}
1312
1313static bool IsIncrementalUpdate(const DeltaArchiveManifest& manifest) {
1314 const auto& partitions = manifest.partitions();
1315 return std::any_of(partitions.begin(), partitions.end(), [](const auto& p) {
1316 return p.has_old_partition_info();
1317 });
1318}
1319
1320bool DynamicPartitionControlAndroid::DeleteSourcePartitions(
1321 MetadataBuilder* builder,
1322 uint32_t source_slot,
1323 const DeltaArchiveManifest& manifest) {
1324 TEST_AND_RETURN_FALSE(IsRecovery());
1325
1326 if (IsIncrementalUpdate(manifest)) {
1327 LOG(ERROR) << "Cannot sideload incremental OTA because snapshots cannot "
1328 << "be created.";
1329 if (GetVirtualAbFeatureFlag().IsLaunch()) {
1330 LOG(ERROR) << "Sideloading incremental updates on devices launches "
1331 << " Virtual A/B is not supported.";
1332 }
1333 return false;
1334 }
1335
1336 LOG(INFO) << "Will overwrite existing partitions. Slot "
1337 << BootControlInterface::SlotName(source_slot)
Tianjie9f4dc7f2021-03-15 16:00:50 -07001338 << " may be unbootable until update finishes!";
Yifan Hongbae27842019-10-24 16:56:12 -07001339 const std::string source_suffix = SlotSuffixForSlotNumber(source_slot);
1340 DeleteGroupsWithSuffix(builder, source_suffix);
1341
1342 return true;
1343}
1344
Yifan Hong90965502020-02-19 15:22:47 -08001345std::unique_ptr<AbstractAction>
1346DynamicPartitionControlAndroid::GetCleanupPreviousUpdateAction(
1347 BootControlInterface* boot_control,
1348 PrefsInterface* prefs,
1349 CleanupPreviousUpdateActionDelegateInterface* delegate) {
1350 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1351 return std::make_unique<NoOpAction>();
1352 }
1353 return std::make_unique<CleanupPreviousUpdateAction>(
1354 prefs, boot_control, snapshot_.get(), delegate);
1355}
1356
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001357bool DynamicPartitionControlAndroid::ResetUpdate(PrefsInterface* prefs) {
1358 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1359 return true;
1360 }
Kelvin Zhangff5380b2022-03-16 13:35:04 -07001361 for (auto& list : dynamic_partition_list_) {
1362 list.clear();
1363 }
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001364
1365 LOG(INFO) << __func__ << " resetting update state and deleting snapshots.";
1366 TEST_AND_RETURN_FALSE(prefs != nullptr);
1367
1368 // If the device has already booted into the target slot,
1369 // ResetUpdateProgress may pass but CancelUpdate fails.
1370 // This is expected. A scheduled CleanupPreviousUpdateAction should free
1371 // space when it is done.
Daniel Zhengf9784802023-06-08 08:39:48 -07001372 TEST_AND_RETURN_FALSE(DeltaPerformer::ResetUpdateProgress(
1373 prefs, false /* quick */, false /* skip dynamic partitions metadata */));
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001374
Yifan Hong4d7c5eb2020-04-03 11:31:50 -07001375 if (ExpectMetadataMounted()) {
1376 TEST_AND_RETURN_FALSE(snapshot_->CancelUpdate());
1377 } else {
1378 LOG(INFO) << "Skip cancelling update in ResetUpdate because /metadata is "
1379 << "not mounted";
1380 }
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001381
1382 return true;
1383}
1384
Tianjie99d570d2020-06-04 14:57:19 -07001385bool DynamicPartitionControlAndroid::ListDynamicPartitionsForSlot(
Tianjie3a55fc22021-02-13 16:02:22 -08001386 uint32_t slot,
1387 uint32_t current_slot,
1388 std::vector<std::string>* partitions) {
Kelvin Zhangebd115e2021-03-08 16:10:25 -05001389 CHECK(slot == source_slot_ || target_slot_ != UINT32_MAX)
1390 << " source slot: " << source_slot_ << " target slot: " << target_slot_
1391 << " slot: " << slot
1392 << " attempting to query dynamic partition metadata for target slot "
1393 "before PreparePartitionForUpdate() is called. The "
1394 "metadata in target slot isn't valid until "
1395 "PreparePartitionForUpdate() is called, contining execution would "
1396 "likely cause problems.";
Tianjie3a55fc22021-02-13 16:02:22 -08001397 bool slot_enables_dynamic_partitions =
1398 GetDynamicPartitionsFeatureFlag().IsEnabled();
1399 // Check if the target slot has dynamic partitions, this may happen when
1400 // applying a retrofit package.
1401 if (slot != current_slot) {
1402 slot_enables_dynamic_partitions =
1403 slot_enables_dynamic_partitions && is_target_dynamic_;
1404 }
1405
1406 if (!slot_enables_dynamic_partitions) {
1407 LOG(INFO) << "Dynamic partition is not enabled for slot " << slot;
1408 return true;
Tianjie99d570d2020-06-04 14:57:19 -07001409 }
1410
1411 std::string device_dir_str;
1412 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
1413 base::FilePath device_dir(device_dir_str);
Tianjie3a55fc22021-02-13 16:02:22 -08001414 auto super_device = device_dir.Append(GetSuperPartitionName(slot)).value();
1415 auto builder = LoadMetadataBuilder(super_device, slot);
Tianjie99d570d2020-06-04 14:57:19 -07001416 TEST_AND_RETURN_FALSE(builder != nullptr);
1417
1418 std::vector<std::string> result;
Tianjie3a55fc22021-02-13 16:02:22 -08001419 auto suffix = SlotSuffixForSlotNumber(slot);
Tianjie99d570d2020-06-04 14:57:19 -07001420 for (const auto& group : builder->ListGroups()) {
1421 for (const auto& partition : builder->ListPartitionsInGroup(group)) {
1422 std::string_view partition_name = partition->name();
1423 if (!android::base::ConsumeSuffix(&partition_name, suffix)) {
1424 continue;
1425 }
1426 result.emplace_back(partition_name);
1427 }
1428 }
1429 *partitions = std::move(result);
1430 return true;
1431}
1432
Tianjie24f96092020-06-30 12:26:25 -07001433bool DynamicPartitionControlAndroid::VerifyExtentsForUntouchedPartitions(
1434 uint32_t source_slot,
1435 uint32_t target_slot,
1436 const std::vector<std::string>& partitions) {
1437 std::string device_dir_str;
1438 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
1439 base::FilePath device_dir(device_dir_str);
1440
1441 auto source_super_device =
1442 device_dir.Append(GetSuperPartitionName(source_slot)).value();
1443 auto source_builder = LoadMetadataBuilder(source_super_device, source_slot);
1444 TEST_AND_RETURN_FALSE(source_builder != nullptr);
1445
1446 auto target_super_device =
1447 device_dir.Append(GetSuperPartitionName(target_slot)).value();
1448 auto target_builder = LoadMetadataBuilder(target_super_device, target_slot);
1449 TEST_AND_RETURN_FALSE(target_builder != nullptr);
1450
1451 return MetadataBuilder::VerifyExtentsAgainstSourceMetadata(
1452 *source_builder, source_slot, *target_builder, target_slot, partitions);
1453}
1454
Yifan Hong4d7c5eb2020-04-03 11:31:50 -07001455bool DynamicPartitionControlAndroid::ExpectMetadataMounted() {
1456 // No need to mount metadata for non-Virtual A/B devices.
1457 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1458 return false;
1459 }
1460 // Intentionally not checking |metadata_device_| in Android mode.
1461 // /metadata should always be mounted in Android mode. If it isn't, let caller
1462 // fails when calling into SnapshotManager.
1463 if (!IsRecovery()) {
1464 return true;
1465 }
1466 // In recovery mode, explicitly check |metadata_device_|.
1467 return metadata_device_ != nullptr;
1468}
1469
1470bool DynamicPartitionControlAndroid::EnsureMetadataMounted() {
1471 // No need to mount metadata for non-Virtual A/B devices.
1472 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1473 return true;
1474 }
1475
1476 if (metadata_device_ == nullptr) {
1477 metadata_device_ = snapshot_->EnsureMetadataMounted();
1478 }
1479 return metadata_device_ != nullptr;
1480}
1481
David Andersona4b7ba62023-05-10 21:41:37 -07001482std::unique_ptr<android::snapshot::ICowWriter>
Kelvin Zhang34618522020-09-28 09:21:02 -04001483DynamicPartitionControlAndroid::OpenCowWriter(
1484 const std::string& partition_name,
1485 const std::optional<std::string>& source_path,
David Andersona4b7ba62023-05-10 21:41:37 -07001486 std::optional<uint64_t> label) {
Kelvin Zhang34618522020-09-28 09:21:02 -04001487 auto suffix = SlotSuffixForSlotNumber(target_slot_);
1488
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -04001489 auto super_device = GetSuperDevice();
1490 if (!super_device.has_value()) {
Kelvin Zhang34618522020-09-28 09:21:02 -04001491 return nullptr;
1492 }
Kelvin Zhang34618522020-09-28 09:21:02 -04001493 CreateLogicalPartitionParams params = {
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -04001494 .block_device = super_device->value(),
Kelvin Zhang34618522020-09-28 09:21:02 -04001495 .metadata_slot = target_slot_,
1496 .partition_name = partition_name + suffix,
1497 .force_writable = true,
Kelvin Zhang877ddbe2020-11-09 13:37:56 -05001498 .timeout_ms = kMapSnapshotTimeout};
Kelvin Zhang34618522020-09-28 09:21:02 -04001499 // TODO(zhangkelvin) Open an APPEND mode CowWriter once there's an API to do
1500 // it.
David Andersona4b7ba62023-05-10 21:41:37 -07001501 return snapshot_->OpenSnapshotWriter(params, label);
Kelvin Zhang877ddbe2020-11-09 13:37:56 -05001502} // namespace chromeos_update_engine
Kelvin Zhang34618522020-09-28 09:21:02 -04001503
Kelvin Zhang1a0ed712022-01-26 16:09:05 -08001504std::unique_ptr<FileDescriptor> DynamicPartitionControlAndroid::OpenCowFd(
Kelvin Zhangc82511c2020-11-06 16:01:24 -05001505 const std::string& unsuffixed_partition_name,
1506 const std::optional<std::string>& source_path,
1507 bool is_append) {
David Andersona4b7ba62023-05-10 21:41:37 -07001508 auto cow_writer = OpenCowWriter(
1509 unsuffixed_partition_name, source_path, {kEndOfInstallLabel});
Kelvin Zhangc82511c2020-11-06 16:01:24 -05001510 if (cow_writer == nullptr) {
David Andersona4b7ba62023-05-10 21:41:37 -07001511 LOG(ERROR) << "OpenCowWriter failed";
Kelvin Zhangc82511c2020-11-06 16:01:24 -05001512 return nullptr;
1513 }
David Andersona4b7ba62023-05-10 21:41:37 -07001514 auto fd = cow_writer->OpenFileDescriptor(source_path);
1515 if (fd == nullptr) {
1516 LOG(ERROR) << "ICowReader::OpenFileDescriptor failed";
Kelvin Zhang21a49912021-03-12 14:28:33 -05001517 return nullptr;
1518 }
David Andersona4b7ba62023-05-10 21:41:37 -07001519 return std::make_unique<CowWriterFileDescriptor>(
1520 std::move(cow_writer), std::move(fd), source_path);
Kelvin Zhangc82511c2020-11-06 16:01:24 -05001521}
1522
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -04001523std::optional<base::FilePath> DynamicPartitionControlAndroid::GetSuperDevice() {
1524 std::string device_dir_str;
1525 if (!GetDeviceDir(&device_dir_str)) {
1526 LOG(ERROR) << "Failed to get device dir!";
1527 return {};
1528 }
1529 base::FilePath device_dir(device_dir_str);
1530 auto super_device = device_dir.Append(GetSuperPartitionName(target_slot_));
1531 return super_device;
1532}
1533
1534bool DynamicPartitionControlAndroid::MapAllPartitions() {
Kelvin Zhang877ddbe2020-11-09 13:37:56 -05001535 return snapshot_->MapAllSnapshots(kMapSnapshotTimeout);
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -04001536}
1537
Kelvin Zhangeb9de162020-11-16 15:47:28 -05001538bool DynamicPartitionControlAndroid::IsDynamicPartition(
Kelvin Zhangebd115e2021-03-08 16:10:25 -05001539 const std::string& partition_name, uint32_t slot) {
1540 if (slot >= dynamic_partition_list_.size()) {
1541 LOG(ERROR) << "Seeing unexpected slot # " << slot << " currently assuming "
1542 << dynamic_partition_list_.size() << " slots";
1543 return false;
1544 }
1545 auto& dynamic_partition_list = dynamic_partition_list_[slot];
1546 if (dynamic_partition_list.empty() &&
Kelvin Zhangeb9de162020-11-16 15:47:28 -05001547 GetDynamicPartitionsFeatureFlag().IsEnabled()) {
Tianjie3a55fc22021-02-13 16:02:22 -08001548 // Use the DAP config of the target slot.
1549 CHECK(ListDynamicPartitionsForSlot(
Kelvin Zhangebd115e2021-03-08 16:10:25 -05001550 slot, source_slot_, &dynamic_partition_list));
Kelvin Zhangeb9de162020-11-16 15:47:28 -05001551 }
Kelvin Zhangebd115e2021-03-08 16:10:25 -05001552 return std::find(dynamic_partition_list.begin(),
1553 dynamic_partition_list.end(),
1554 partition_name) != dynamic_partition_list.end();
Kelvin Zhangeb9de162020-11-16 15:47:28 -05001555}
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001556
Yifan Hongb0cbd392021-02-04 11:11:45 -08001557bool DynamicPartitionControlAndroid::UpdateUsesSnapshotCompression() {
Kelvin Zhang741c2d42021-04-13 12:40:38 -04001558 return GetVirtualAbFeatureFlag().IsEnabled() &&
1559 snapshot_->UpdateUsesCompression();
Yifan Hongb0cbd392021-02-04 11:11:45 -08001560}
1561
David Andersone35b4382022-03-08 23:18:29 -08001562FeatureFlag
1563DynamicPartitionControlAndroid::GetVirtualAbUserspaceSnapshotsFeatureFlag() {
1564 return virtual_ab_userspace_snapshots_;
1565}
1566
Yifan Hong537802d2018-08-15 13:15:42 -07001567} // namespace chromeos_update_engine