blob: 822b05e6b49edd3ebdd083aa9bfdb62fe479295f [file] [log] [blame]
Yifan Hong537802d2018-08-15 13:15:42 -07001//
2// Copyright (C) 2018 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
16
Amin Hassaniec7bc112020-10-29 16:47:58 -070017#include "update_engine/aosp/dynamic_partition_control_android.h"
Yifan Hong537802d2018-08-15 13:15:42 -070018
Kelvin Zhang91d95fa2020-11-05 13:52:00 -050019#include <algorithm>
Yifan Hong420db9b2019-07-23 20:50:33 -070020#include <chrono> // NOLINT(build/c++11) - using libsnapshot / liblp API
Kelvin Zhang34618522020-09-28 09:21:02 -040021#include <cstdint>
Yifan Hong13d41cb2019-09-16 13:18:22 -070022#include <map>
Yifan Hong537802d2018-08-15 13:15:42 -070023#include <memory>
24#include <set>
25#include <string>
Tianjie99d570d2020-06-04 14:57:19 -070026#include <string_view>
27#include <utility>
Yifan Hong012508e2019-07-22 18:30:40 -070028#include <vector>
Yifan Hong537802d2018-08-15 13:15:42 -070029
30#include <android-base/properties.h>
31#include <android-base/strings.h>
32#include <base/files/file_util.h>
33#include <base/logging.h>
Yifan Hong012508e2019-07-22 18:30:40 -070034#include <base/strings/string_util.h>
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 Zhangc675fc02022-06-22 10:18:54 -0700104 UnmapAllPartitions();
105 metadata_device_.reset();
Yifan Hong537802d2018-08-15 13:15:42 -0700106}
107
Yifan Hong186bb682019-07-23 14:04:39 -0700108static FeatureFlag GetFeatureFlag(const char* enable_prop,
109 const char* retrofit_prop) {
Kelvin Zhangda1b3142020-09-24 17:09:02 -0400110 // Default retrofit to false if retrofit_prop is empty.
111 bool retrofit = retrofit_prop && retrofit_prop[0] != '\0' &&
112 GetBoolProperty(retrofit_prop, false);
Yifan Hong186bb682019-07-23 14:04:39 -0700113 bool enabled = GetBoolProperty(enable_prop, false);
114 if (retrofit && !enabled) {
115 LOG(ERROR) << retrofit_prop << " is true but " << enable_prop
116 << " is not. These sysprops are inconsistent. Assume that "
117 << enable_prop << " is true from now on.";
118 }
119 if (retrofit) {
120 return FeatureFlag(FeatureFlag::Value::RETROFIT);
121 }
122 if (enabled) {
123 return FeatureFlag(FeatureFlag::Value::LAUNCH);
124 }
125 return FeatureFlag(FeatureFlag::Value::NONE);
Yifan Hong537802d2018-08-15 13:15:42 -0700126}
127
Kelvin Zhangebd115e2021-03-08 16:10:25 -0500128DynamicPartitionControlAndroid::DynamicPartitionControlAndroid(
129 uint32_t source_slot)
Yifan Hongb38e1af2019-10-17 14:59:22 -0700130 : dynamic_partitions_(
131 GetFeatureFlag(kUseDynamicPartitions, kRetrfoitDynamicPartitions)),
Kelvin Zhangda1b3142020-09-24 17:09:02 -0400132 virtual_ab_(GetFeatureFlag(kVirtualAbEnabled, kVirtualAbRetrofit)),
133 virtual_ab_compression_(GetFeatureFlag(kVirtualAbCompressionEnabled,
Kelvin Zhangebd115e2021-03-08 16:10:25 -0500134 kVirtualAbCompressionRetrofit)),
Kelvin Zhang1c4b9812022-04-06 17:29:00 -0700135 virtual_ab_compression_xor_(
136 GetFeatureFlag(kVirtualAbCompressionXorEnabled, "")),
David Andersone35b4382022-03-08 23:18:29 -0800137 virtual_ab_userspace_snapshots_(
138 GetFeatureFlag(kVirtualAbUserspaceSnapshotsEnabled, nullptr)),
Kelvin Zhangebd115e2021-03-08 16:10:25 -0500139 source_slot_(source_slot) {
Yifan Hongb38e1af2019-10-17 14:59:22 -0700140 if (GetVirtualAbFeatureFlag().IsEnabled()) {
Yifan Hongf033ecb2020-01-07 18:13:56 -0800141 snapshot_ = SnapshotManager::New();
Yifan Hongf9cb4492020-04-15 13:00:20 -0700142 } else {
143 snapshot_ = SnapshotManagerStub::New();
Yifan Hongb38e1af2019-10-17 14:59:22 -0700144 }
Yifan Hongf9cb4492020-04-15 13:00:20 -0700145 CHECK(snapshot_ != nullptr) << "Cannot initialize SnapshotManager.";
Yifan Hongb38e1af2019-10-17 14:59:22 -0700146}
147
Yifan Hong186bb682019-07-23 14:04:39 -0700148FeatureFlag DynamicPartitionControlAndroid::GetDynamicPartitionsFeatureFlag() {
Yifan Hongb38e1af2019-10-17 14:59:22 -0700149 return dynamic_partitions_;
Yifan Hong6e706b12018-11-09 16:50:51 -0800150}
151
Yifan Hong413d5722019-07-23 14:21:09 -0700152FeatureFlag DynamicPartitionControlAndroid::GetVirtualAbFeatureFlag() {
Yifan Hongb38e1af2019-10-17 14:59:22 -0700153 return virtual_ab_;
Yifan Hong413d5722019-07-23 14:21:09 -0700154}
155
Kelvin Zhangda1b3142020-09-24 17:09:02 -0400156FeatureFlag
157DynamicPartitionControlAndroid::GetVirtualAbCompressionFeatureFlag() {
Kelvin Zhangb9a5f612021-01-22 14:34:05 -0500158 if constexpr (constants::kIsRecovery) {
159 // Don't attempt VABC in recovery
160 return FeatureFlag(FeatureFlag::Value::NONE);
161 }
Kelvin Zhangda1b3142020-09-24 17:09:02 -0400162 return virtual_ab_compression_;
163}
164
Kelvin Zhang1c4b9812022-04-06 17:29:00 -0700165FeatureFlag
166DynamicPartitionControlAndroid::GetVirtualAbCompressionXorFeatureFlag() {
167 return virtual_ab_compression_xor_;
168}
169
Yifan Hongf5261562020-03-10 10:28:10 -0700170bool DynamicPartitionControlAndroid::OptimizeOperation(
171 const std::string& partition_name,
172 const InstallOperation& operation,
173 InstallOperation* optimized) {
Alessio Balsini2a3b4a22019-11-25 16:46:51 +0000174 switch (operation.type()) {
175 case InstallOperation::SOURCE_COPY:
176 return target_supports_snapshot_ &&
177 GetVirtualAbFeatureFlag().IsEnabled() &&
Yifan Hong6eec9952019-12-04 13:12:01 -0800178 mapped_devices_.count(partition_name +
179 SlotSuffixForSlotNumber(target_slot_)) > 0 &&
Yifan Hongf5261562020-03-10 10:28:10 -0700180 OptimizeSourceCopyOperation(operation, optimized);
Alessio Balsini2a3b4a22019-11-25 16:46:51 +0000181 break;
182 default:
183 break;
184 }
Alessio Balsini14980e22019-11-26 11:46:06 +0000185 return false;
186}
187
Yifan Hong8546a712019-03-28 14:42:53 -0700188bool DynamicPartitionControlAndroid::MapPartitionInternal(
Yifan Hong537802d2018-08-15 13:15:42 -0700189 const std::string& super_device,
190 const std::string& target_partition_name,
191 uint32_t slot,
Yifan Hongaf65ef12018-10-29 11:09:06 -0700192 bool force_writable,
Yifan Hong537802d2018-08-15 13:15:42 -0700193 std::string* path) {
David Andersonbb90dfb2019-08-13 14:14:56 -0700194 CreateLogicalPartitionParams params = {
195 .block_device = super_device,
196 .metadata_slot = slot,
197 .partition_name = target_partition_name,
198 .force_writable = force_writable,
David Andersonbb90dfb2019-08-13 14:14:56 -0700199 };
Yifan Hong420db9b2019-07-23 20:50:33 -0700200 bool success = false;
Yifan Hongf0f4a912019-09-26 17:51:33 -0700201 if (GetVirtualAbFeatureFlag().IsEnabled() && target_supports_snapshot_ &&
Kelvin Zhang8b07db52024-07-24 09:13:25 -0700202 slot != source_slot_ && force_writable && ExpectMetadataMounted()) {
Yifan Hong420db9b2019-07-23 20:50:33 -0700203 // Only target partitions are mapped with force_writable. On Virtual
204 // A/B devices, target partitions may overlap with source partitions, so
205 // they must be mapped with snapshot.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700206 // One exception is when /metadata is not mounted. Fallback to
207 // CreateLogicalPartition as snapshots are not created in the first place.
Yifan Hong420db9b2019-07-23 20:50:33 -0700208 params.timeout_ms = kMapSnapshotTimeout;
209 success = snapshot_->MapUpdateSnapshot(params, path);
210 } else {
211 params.timeout_ms = kMapTimeout;
212 success = CreateLogicalPartition(params, path);
213 }
David Andersonbb90dfb2019-08-13 14:14:56 -0700214
Yifan Hong420db9b2019-07-23 20:50:33 -0700215 if (!success) {
Yifan Hong537802d2018-08-15 13:15:42 -0700216 LOG(ERROR) << "Cannot map " << target_partition_name << " in "
217 << super_device << " on device mapper.";
218 return false;
219 }
220 LOG(INFO) << "Succesfully mapped " << target_partition_name
Yifan Hongaf65ef12018-10-29 11:09:06 -0700221 << " to device mapper (force_writable = " << force_writable
222 << "); device path at " << *path;
Yifan Hong537802d2018-08-15 13:15:42 -0700223 mapped_devices_.insert(target_partition_name);
224 return true;
225}
226
Yifan Hong8546a712019-03-28 14:42:53 -0700227bool DynamicPartitionControlAndroid::MapPartitionOnDeviceMapper(
228 const std::string& super_device,
229 const std::string& target_partition_name,
230 uint32_t slot,
231 bool force_writable,
232 std::string* path) {
233 DmDeviceState state = GetState(target_partition_name);
234 if (state == DmDeviceState::ACTIVE) {
235 if (mapped_devices_.find(target_partition_name) != mapped_devices_.end()) {
236 if (GetDmDevicePathByName(target_partition_name, path)) {
237 LOG(INFO) << target_partition_name
238 << " is mapped on device mapper: " << *path;
239 return true;
240 }
241 LOG(ERROR) << target_partition_name << " is mapped but path is unknown.";
242 return false;
243 }
244 // If target_partition_name is not in mapped_devices_ but state is ACTIVE,
245 // the device might be mapped incorrectly before. Attempt to unmap it.
246 // Note that for source partitions, if GetState() == ACTIVE, callers (e.g.
247 // BootControlAndroid) should not call MapPartitionOnDeviceMapper, but
248 // should directly call GetDmDevicePathByName.
David Anderson4c891c92019-06-21 17:45:23 -0700249 if (!UnmapPartitionOnDeviceMapper(target_partition_name)) {
Yifan Hong8546a712019-03-28 14:42:53 -0700250 LOG(ERROR) << target_partition_name
251 << " is mapped before the update, and it cannot be unmapped.";
252 return false;
253 }
254 state = GetState(target_partition_name);
255 if (state != DmDeviceState::INVALID) {
256 LOG(ERROR) << target_partition_name << " is unmapped but state is "
257 << static_cast<std::underlying_type_t<DmDeviceState>>(state);
258 return false;
259 }
260 }
261 if (state == DmDeviceState::INVALID) {
262 return MapPartitionInternal(
263 super_device, target_partition_name, slot, force_writable, path);
264 }
265
266 LOG(ERROR) << target_partition_name
267 << " is mapped on device mapper but state is unknown: "
268 << static_cast<std::underlying_type_t<DmDeviceState>>(state);
269 return false;
270}
271
Yifan Hong537802d2018-08-15 13:15:42 -0700272bool DynamicPartitionControlAndroid::UnmapPartitionOnDeviceMapper(
David Anderson4c891c92019-06-21 17:45:23 -0700273 const std::string& target_partition_name) {
Yifan Hong537802d2018-08-15 13:15:42 -0700274 if (DeviceMapper::Instance().GetState(target_partition_name) !=
275 DmDeviceState::INVALID) {
Yifan Hong420db9b2019-07-23 20:50:33 -0700276 // Partitions at target slot on non-Virtual A/B devices are mapped as
277 // dm-linear. Also, on Virtual A/B devices, system_other may be mapped for
278 // preopt apps as dm-linear.
279 // Call DestroyLogicalPartition to handle these cases.
280 bool success = DestroyLogicalPartition(target_partition_name);
281
282 // On a Virtual A/B device, |target_partition_name| may be a leftover from
283 // a paused update. Clean up any underlying devices.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700284 if (ExpectMetadataMounted()) {
Yifan Hong420db9b2019-07-23 20:50:33 -0700285 success &= snapshot_->UnmapUpdateSnapshot(target_partition_name);
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700286 } else {
287 LOG(INFO) << "Skip UnmapUpdateSnapshot(" << target_partition_name
288 << ") because metadata is not mounted";
Yifan Hong420db9b2019-07-23 20:50:33 -0700289 }
290
291 if (!success) {
Yifan Hong537802d2018-08-15 13:15:42 -0700292 LOG(ERROR) << "Cannot unmap " << target_partition_name
293 << " from device mapper.";
294 return false;
295 }
296 LOG(INFO) << "Successfully unmapped " << target_partition_name
297 << " from device mapper.";
298 }
299 mapped_devices_.erase(target_partition_name);
300 return true;
301}
302
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -0400303bool DynamicPartitionControlAndroid::UnmapAllPartitions() {
Kelvin Zhangf7ef12a2021-03-22 12:59:06 -0400304 snapshot_->UnmapAllSnapshots();
Tao Bao8c4d0082019-08-08 08:56:16 -0700305 if (mapped_devices_.empty()) {
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -0400306 return false;
Tao Bao8c4d0082019-08-08 08:56:16 -0700307 }
Yifan Hong537802d2018-08-15 13:15:42 -0700308 // UnmapPartitionOnDeviceMapper removes objects from mapped_devices_, hence
309 // a copy is needed for the loop.
310 std::set<std::string> mapped = mapped_devices_;
311 LOG(INFO) << "Destroying [" << Join(mapped, ", ") << "] from device mapper";
312 for (const auto& partition_name : mapped) {
David Anderson4c891c92019-06-21 17:45:23 -0700313 ignore_result(UnmapPartitionOnDeviceMapper(partition_name));
Yifan Hong537802d2018-08-15 13:15:42 -0700314 }
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -0400315 return true;
Yifan Hong537802d2018-08-15 13:15:42 -0700316}
317
318void DynamicPartitionControlAndroid::Cleanup() {
Yifan Hongbae27842019-10-24 16:56:12 -0700319 UnmapAllPartitions();
Kelvin Zhang6bec1ed2024-07-11 09:49:59 -0700320 LOG(INFO) << "UnmapAllPartitions done";
Yifan Hongbae27842019-10-24 16:56:12 -0700321 metadata_device_.reset();
Kelvin Zhangc675fc02022-06-22 10:18:54 -0700322 if (GetVirtualAbFeatureFlag().IsEnabled()) {
323 snapshot_ = SnapshotManager::New();
324 } else {
325 snapshot_ = SnapshotManagerStub::New();
326 }
327 CHECK(snapshot_ != nullptr) << "Cannot initialize SnapshotManager.";
Kelvin Zhang6bec1ed2024-07-11 09:49:59 -0700328 LOG(INFO) << "SnapshotManager initialized.";
Yifan Hong537802d2018-08-15 13:15:42 -0700329}
330
331bool DynamicPartitionControlAndroid::DeviceExists(const std::string& path) {
332 return base::PathExists(base::FilePath(path));
333}
334
335android::dm::DmDeviceState DynamicPartitionControlAndroid::GetState(
336 const std::string& name) {
337 return DeviceMapper::Instance().GetState(name);
338}
339
340bool DynamicPartitionControlAndroid::GetDmDevicePathByName(
341 const std::string& name, std::string* path) {
342 return DeviceMapper::Instance().GetDmDevicePathByName(name, path);
343}
344
345std::unique_ptr<MetadataBuilder>
346DynamicPartitionControlAndroid::LoadMetadataBuilder(
Tianjie24f96092020-06-30 12:26:25 -0700347 const std::string& super_device, uint32_t slot) {
348 auto builder = MetadataBuilder::New(PartitionOpener(), super_device, slot);
349 if (builder == nullptr) {
350 LOG(WARNING) << "No metadata slot " << BootControlInterface::SlotName(slot)
351 << " in " << super_device;
352 return nullptr;
353 }
354 LOG(INFO) << "Loaded metadata from slot "
355 << BootControlInterface::SlotName(slot) << " in " << super_device;
356 return builder;
Yifan Hong012508e2019-07-22 18:30:40 -0700357}
358
359std::unique_ptr<MetadataBuilder>
360DynamicPartitionControlAndroid::LoadMetadataBuilder(
Yifan Hong6e706b12018-11-09 16:50:51 -0800361 const std::string& super_device,
362 uint32_t source_slot,
363 uint32_t target_slot) {
Tianjie24f96092020-06-30 12:26:25 -0700364 bool always_keep_source_slot = !target_supports_snapshot_;
365 auto builder = MetadataBuilder::NewForUpdate(PartitionOpener(),
366 super_device,
367 source_slot,
368 target_slot,
369 always_keep_source_slot);
Yifan Hong537802d2018-08-15 13:15:42 -0700370 if (builder == nullptr) {
371 LOG(WARNING) << "No metadata slot "
372 << BootControlInterface::SlotName(source_slot) << " in "
373 << super_device;
Yifan Hongf48a0052018-10-29 16:30:43 -0700374 return nullptr;
Yifan Hong537802d2018-08-15 13:15:42 -0700375 }
Tianjie24f96092020-06-30 12:26:25 -0700376 LOG(INFO) << "Created metadata for new update from slot "
Yifan Hong537802d2018-08-15 13:15:42 -0700377 << BootControlInterface::SlotName(source_slot) << " in "
378 << super_device;
379 return builder;
380}
381
382bool DynamicPartitionControlAndroid::StoreMetadata(
383 const std::string& super_device,
384 MetadataBuilder* builder,
385 uint32_t target_slot) {
386 auto metadata = builder->Export();
387 if (metadata == nullptr) {
388 LOG(ERROR) << "Cannot export metadata to slot "
389 << BootControlInterface::SlotName(target_slot) << " in "
390 << super_device;
391 return false;
392 }
393
Yifan Hong186bb682019-07-23 14:04:39 -0700394 if (GetDynamicPartitionsFeatureFlag().IsRetrofit()) {
Yifan Hong6e706b12018-11-09 16:50:51 -0800395 if (!FlashPartitionTable(super_device, *metadata)) {
396 LOG(ERROR) << "Cannot write metadata to " << super_device;
397 return false;
398 }
399 LOG(INFO) << "Written metadata to " << super_device;
400 } else {
401 if (!UpdatePartitionTable(super_device, *metadata, target_slot)) {
402 LOG(ERROR) << "Cannot write metadata to slot "
403 << BootControlInterface::SlotName(target_slot) << " in "
404 << super_device;
405 return false;
406 }
407 LOG(INFO) << "Copied metadata to slot "
408 << BootControlInterface::SlotName(target_slot) << " in "
409 << super_device;
Yifan Hong537802d2018-08-15 13:15:42 -0700410 }
411
Yifan Hong537802d2018-08-15 13:15:42 -0700412 return true;
413}
414
415bool DynamicPartitionControlAndroid::GetDeviceDir(std::string* out) {
416 // We can't use fs_mgr to look up |partition_name| because fstab
417 // doesn't list every slot partition (it uses the slotselect option
418 // to mask the suffix).
419 //
420 // We can however assume that there's an entry for the /misc mount
421 // point and use that to get the device file for the misc
422 // partition. This helps us locate the disk that |partition_name|
423 // resides on. From there we'll assume that a by-name scheme is used
424 // so we can just replace the trailing "misc" by the given
425 // |partition_name| and suffix corresponding to |slot|, e.g.
426 //
427 // /dev/block/platform/soc.0/7824900.sdhci/by-name/misc ->
428 // /dev/block/platform/soc.0/7824900.sdhci/by-name/boot_a
429 //
430 // If needed, it's possible to relax the by-name assumption in the
431 // future by trawling /sys/block looking for the appropriate sibling
432 // of misc and then finding an entry in /dev matching the sysfs
433 // entry.
434
435 std::string err, misc_device = get_bootloader_message_blk_device(&err);
436 if (misc_device.empty()) {
437 LOG(ERROR) << "Unable to get misc block device: " << err;
438 return false;
439 }
440
441 if (!utils::IsSymlink(misc_device.c_str())) {
442 LOG(ERROR) << "Device file " << misc_device << " for /misc "
443 << "is not a symlink.";
444 return false;
445 }
446 *out = base::FilePath(misc_device).DirName().value();
447 return true;
448}
Yifan Hong012508e2019-07-22 18:30:40 -0700449
450bool DynamicPartitionControlAndroid::PreparePartitionsForUpdate(
451 uint32_t source_slot,
452 uint32_t target_slot,
Yifan Hongf0f4a912019-09-26 17:51:33 -0700453 const DeltaArchiveManifest& manifest,
Yifan Hongf033ecb2020-01-07 18:13:56 -0800454 bool update,
Daniel Zhengeede4c82023-06-13 11:21:06 -0700455 uint64_t* required_size,
456 ErrorCode* error) {
Yifan Hong6eec9952019-12-04 13:12:01 -0800457 source_slot_ = source_slot;
458 target_slot_ = target_slot;
Yifan Hongf033ecb2020-01-07 18:13:56 -0800459 if (required_size != nullptr) {
460 *required_size = 0;
461 }
Yifan Hong6eec9952019-12-04 13:12:01 -0800462
Yifan Hong3a1a5612019-11-05 16:34:32 -0800463 if (fs_mgr_overlayfs_is_setup()) {
464 // Non DAP devices can use overlayfs as well.
Daniel Zhengeede4c82023-06-13 11:21:06 -0700465 LOG(ERROR)
Yifan Hong3a1a5612019-11-05 16:34:32 -0800466 << "overlayfs overrides are active and can interfere with our "
467 "resources.\n"
468 << "run adb enable-verity to deactivate if required and try again.";
Daniel Zhengeede4c82023-06-13 11:21:06 -0700469 if (error) {
470 *error = ErrorCode::kOverlayfsenabledError;
471 return false;
472 }
Yifan Hong3a1a5612019-11-05 16:34:32 -0800473 }
474
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700475 // If metadata is erased but not formatted, it is possible to not mount
476 // it in recovery. It is acceptable to skip mounting and choose fallback path
477 // (PrepareDynamicPartitionsForUpdate) when sideloading full OTAs.
478 TEST_AND_RETURN_FALSE(EnsureMetadataMounted() || IsRecovery());
Yifan Hong29692902020-03-26 12:47:05 -0700479
480 if (update) {
481 TEST_AND_RETURN_FALSE(EraseSystemOtherAvbFooter(source_slot, target_slot));
482 }
483
Yifan Hong3a1a5612019-11-05 16:34:32 -0800484 if (!GetDynamicPartitionsFeatureFlag().IsEnabled()) {
485 return true;
486 }
487
488 if (target_slot == source_slot) {
489 LOG(ERROR) << "Cannot call PreparePartitionsForUpdate on current slot.";
490 return false;
491 }
492
Yifan Hongf6f75c22020-07-31 15:20:25 -0700493 if (!SetTargetBuildVars(manifest)) {
494 return false;
495 }
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700496 for (auto& list : dynamic_partition_list_) {
497 list.clear();
498 }
Yifan Hongf6f75c22020-07-31 15:20:25 -0700499
Yifan Hong3a1a5612019-11-05 16:34:32 -0800500 // Although the current build supports dynamic partitions, the given payload
501 // doesn't use it for target partitions. This could happen when applying a
502 // retrofit update. Skip updating the partition metadata for the target slot.
Yifan Hong3a1a5612019-11-05 16:34:32 -0800503 if (!is_target_dynamic_) {
504 return true;
505 }
506
Yifan Hongf0f4a912019-09-26 17:51:33 -0700507 if (!update)
508 return true;
509
Yifan Hongbae27842019-10-24 16:56:12 -0700510 bool delete_source = false;
511
Yifan Hong6d888562019-10-01 13:00:31 -0700512 if (GetVirtualAbFeatureFlag().IsEnabled()) {
513 // On Virtual A/B device, either CancelUpdate() or BeginUpdate() must be
514 // called before calling UnmapUpdateSnapshot.
515 // - If target_supports_snapshot_, PrepareSnapshotPartitionsForUpdate()
516 // calls BeginUpdate() which resets update state
Yifan Hongbae27842019-10-24 16:56:12 -0700517 // - If !target_supports_snapshot_ or PrepareSnapshotPartitionsForUpdate
518 // failed in recovery, explicitly CancelUpdate().
Yifan Hong6d888562019-10-01 13:00:31 -0700519 if (target_supports_snapshot_) {
Yifan Hongbae27842019-10-24 16:56:12 -0700520 if (PrepareSnapshotPartitionsForUpdate(
521 source_slot, target_slot, manifest, required_size)) {
522 return true;
523 }
524
525 // Virtual A/B device doing Virtual A/B update in Android mode must use
526 // snapshots.
527 if (!IsRecovery()) {
528 LOG(ERROR) << "PrepareSnapshotPartitionsForUpdate failed in Android "
529 << "mode";
530 return false;
531 }
532
533 delete_source = true;
534 LOG(INFO) << "PrepareSnapshotPartitionsForUpdate failed in recovery. "
535 << "Attempt to overwrite existing partitions if possible";
536 } else {
537 // Downgrading to an non-Virtual A/B build or is secondary OTA.
538 LOG(INFO) << "Using regular A/B on Virtual A/B because package disabled "
539 << "snapshots.";
Yifan Hong6d888562019-10-01 13:00:31 -0700540 }
Yifan Hongbae27842019-10-24 16:56:12 -0700541
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700542 // In recovery, if /metadata is not mounted, it is likely that metadata
543 // partition is erased and not formatted yet. After sideloading, when
544 // rebooting into the new version, init will erase metadata partition,
545 // hence the failure of CancelUpdate() can be ignored here.
546 // However, if metadata is mounted and CancelUpdate fails, sideloading
547 // should not proceed because during next boot, snapshots will overlay on
548 // the devices incorrectly.
549 if (ExpectMetadataMounted()) {
550 TEST_AND_RETURN_FALSE(snapshot_->CancelUpdate());
551 } else {
552 LOG(INFO) << "Skip canceling previous update because metadata is not "
553 << "mounted";
Yifan Hong6d888562019-10-01 13:00:31 -0700554 }
Yifan Hong420db9b2019-07-23 20:50:33 -0700555 }
Yifan Hongbae27842019-10-24 16:56:12 -0700556
Tianjie24f96092020-06-30 12:26:25 -0700557 // TODO(xunchang) support partial update on non VAB enabled devices.
Yifan Hong5c5743f2020-04-16 12:59:07 -0700558 TEST_AND_RETURN_FALSE(PrepareDynamicPartitionsForUpdate(
559 source_slot, target_slot, manifest, delete_source));
560
561 if (required_size != nullptr) {
562 *required_size = 0;
563 }
564 return true;
Yifan Hong420db9b2019-07-23 20:50:33 -0700565}
566
Yifan Hongf6f75c22020-07-31 15:20:25 -0700567bool DynamicPartitionControlAndroid::SetTargetBuildVars(
568 const DeltaArchiveManifest& manifest) {
569 // Precondition: current build supports dynamic partition.
570 CHECK(GetDynamicPartitionsFeatureFlag().IsEnabled());
571
572 bool is_target_dynamic =
573 !manifest.dynamic_partition_metadata().groups().empty();
574 bool target_supports_snapshot =
575 manifest.dynamic_partition_metadata().snapshot_enabled();
576
577 if (manifest.partial_update()) {
578 // Partial updates requires DAP. On partial updates that does not involve
579 // dynamic partitions, groups() can be empty, so also assume
580 // is_target_dynamic in this case. This assumption should be safe because we
581 // also check target_supports_snapshot below, which presumably also implies
582 // target build supports dynamic partition.
583 if (!is_target_dynamic) {
584 LOG(INFO) << "Assuming target build supports dynamic partitions for "
585 "partial updates.";
586 is_target_dynamic = true;
587 }
588
589 // Partial updates requires Virtual A/B. Double check that both current
590 // build and target build supports Virtual A/B.
591 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
592 LOG(ERROR) << "Partial update cannot be applied on a device that does "
593 "not support snapshots.";
594 return false;
595 }
596 if (!target_supports_snapshot) {
597 LOG(ERROR) << "Cannot apply partial update to a build that does not "
598 "support snapshots.";
599 return false;
600 }
601 }
602
603 // Store the flags.
604 is_target_dynamic_ = is_target_dynamic;
605 // If !is_target_dynamic_, leave target_supports_snapshot_ unset because
606 // snapshots would not work without dynamic partition.
607 if (is_target_dynamic_) {
608 target_supports_snapshot_ = target_supports_snapshot;
609 }
610 return true;
611}
612
Yifan Hong29692902020-03-26 12:47:05 -0700613namespace {
614// Try our best to erase AVB footer.
615class AvbFooterEraser {
616 public:
617 explicit AvbFooterEraser(const std::string& path) : path_(path) {}
618 bool Erase() {
619 // Try to mark the block device read-only. Ignore any
620 // failure since this won't work when passing regular files.
621 ignore_result(utils::SetBlockDeviceReadOnly(path_, false /* readonly */));
622
623 fd_.reset(new EintrSafeFileDescriptor());
624 int flags = O_WRONLY | O_TRUNC | O_CLOEXEC | O_SYNC;
625 TEST_AND_RETURN_FALSE(fd_->Open(path_.c_str(), flags));
626
627 // Need to write end-AVB_FOOTER_SIZE to end.
628 static_assert(AVB_FOOTER_SIZE > 0);
629 off64_t offset = fd_->Seek(-AVB_FOOTER_SIZE, SEEK_END);
630 TEST_AND_RETURN_FALSE_ERRNO(offset >= 0);
631 uint64_t write_size = AVB_FOOTER_SIZE;
632 LOG(INFO) << "Zeroing " << path_ << " @ [" << offset << ", "
633 << (offset + write_size) << "] (" << write_size << " bytes)";
634 brillo::Blob zeros(write_size);
635 TEST_AND_RETURN_FALSE(utils::WriteAll(fd_, zeros.data(), zeros.size()));
636 return true;
637 }
638 ~AvbFooterEraser() {
639 TEST_AND_RETURN(fd_ != nullptr && fd_->IsOpen());
640 if (!fd_->Close()) {
641 LOG(WARNING) << "Failed to close fd for " << path_;
642 }
643 }
644
645 private:
646 std::string path_;
647 FileDescriptorPtr fd_;
648};
649
650} // namespace
651
652std::optional<bool>
653DynamicPartitionControlAndroid::IsAvbEnabledOnSystemOther() {
654 auto prefix = GetProperty(kPostinstallFstabPrefix, "");
655 if (prefix.empty()) {
656 LOG(WARNING) << "Cannot get " << kPostinstallFstabPrefix;
657 return std::nullopt;
658 }
659 auto path = base::FilePath(prefix).Append("etc/fstab.postinstall").value();
660 return IsAvbEnabledInFstab(path);
661}
662
663std::optional<bool> DynamicPartitionControlAndroid::IsAvbEnabledInFstab(
664 const std::string& path) {
665 Fstab fstab;
666 if (!ReadFstabFromFile(path, &fstab)) {
Yifan Hong93cde302020-04-27 12:59:29 -0700667 PLOG(WARNING) << "Cannot read fstab from " << path;
668 if (errno == ENOENT) {
669 return false;
670 }
Yifan Hong29692902020-03-26 12:47:05 -0700671 return std::nullopt;
672 }
673 for (const auto& entry : fstab) {
674 if (!entry.avb_keys.empty()) {
675 return true;
676 }
677 }
678 return false;
679}
680
681bool DynamicPartitionControlAndroid::GetSystemOtherPath(
682 uint32_t source_slot,
683 uint32_t target_slot,
684 const std::string& partition_name_suffix,
685 std::string* path,
686 bool* should_unmap) {
687 path->clear();
688 *should_unmap = false;
689
P.Adarsh Reddy13e4195d2020-06-08 23:17:36 +0530690 // Check that AVB is enabled on system_other before erasing.
691 auto has_avb = IsAvbEnabledOnSystemOther();
692 TEST_AND_RETURN_FALSE(has_avb.has_value());
693 if (!has_avb.value()) {
694 LOG(INFO) << "AVB is not enabled on system_other. Skip erasing.";
695 return true;
696 }
Yifan Hong29692902020-03-26 12:47:05 -0700697
P.Adarsh Reddy13e4195d2020-06-08 23:17:36 +0530698 if (!IsRecovery()) {
Yifan Hong29692902020-03-26 12:47:05 -0700699 // Found unexpected avb_keys for system_other on devices retrofitting
700 // dynamic partitions. Previous crash in update_engine may leave logical
701 // partitions mapped on physical system_other partition. It is difficult to
702 // handle these cases. Just fail.
703 if (GetDynamicPartitionsFeatureFlag().IsRetrofit()) {
704 LOG(ERROR) << "Cannot erase AVB footer on system_other on devices with "
705 << "retrofit dynamic partitions. They should not have AVB "
706 << "enabled on system_other.";
707 return false;
708 }
709 }
710
711 std::string device_dir_str;
712 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
713 base::FilePath device_dir(device_dir_str);
714
715 // On devices without dynamic partition, search for static partitions.
716 if (!GetDynamicPartitionsFeatureFlag().IsEnabled()) {
717 *path = device_dir.Append(partition_name_suffix).value();
718 TEST_AND_RETURN_FALSE(DeviceExists(*path));
719 return true;
720 }
721
722 auto source_super_device =
723 device_dir.Append(GetSuperPartitionName(source_slot)).value();
724
725 auto builder = LoadMetadataBuilder(source_super_device, source_slot);
726 if (builder == nullptr) {
727 if (IsRecovery()) {
728 // It might be corrupted for some reason. It should still be able to
729 // sideload.
730 LOG(WARNING) << "Super partition metadata cannot be read from the source "
731 << "slot, skip erasing.";
732 return true;
733 } else {
734 // Device has booted into Android mode, indicating that the super
735 // partition metadata should be there.
736 LOG(ERROR) << "Super partition metadata cannot be read from the source "
737 << "slot. This is unexpected on devices with dynamic "
738 << "partitions enabled.";
739 return false;
740 }
741 }
742 auto p = builder->FindPartition(partition_name_suffix);
743 if (p == nullptr) {
744 // If the source slot is flashed without system_other, it does not exist
745 // in super partition metadata at source slot. It is safe to skip it.
746 LOG(INFO) << "Can't find " << partition_name_suffix
747 << " in metadata source slot, skip erasing.";
748 return true;
749 }
750 // System_other created by flashing tools should be erased.
751 // If partition is created by update_engine (via NewForUpdate), it is a
752 // left-over partition from the previous update and does not contain
753 // system_other, hence there is no need to erase.
754 // Note the reverse is not necessary true. If the flag is not set, we don't
755 // know if the partition is created by update_engine or by flashing tools
756 // because older versions of super partition metadata does not contain this
757 // flag. It is okay to erase the AVB footer anyways.
758 if (p->attributes() & LP_PARTITION_ATTR_UPDATED) {
759 LOG(INFO) << partition_name_suffix
760 << " does not contain system_other, skip erasing.";
761 return true;
762 }
763
Yifan Hong64331b32020-05-13 16:50:40 -0700764 if (p->size() < AVB_FOOTER_SIZE) {
765 LOG(INFO) << partition_name_suffix << " has length " << p->size()
766 << "( < AVB_FOOTER_SIZE " << AVB_FOOTER_SIZE
767 << "), skip erasing.";
768 return true;
769 }
770
Yifan Hong29692902020-03-26 12:47:05 -0700771 // Delete any pre-existing device with name |partition_name_suffix| and
772 // also remove it from |mapped_devices_|.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700773 // In recovery, metadata might not be mounted, and
774 // UnmapPartitionOnDeviceMapper might fail. However,
775 // it is unusual that system_other has already been mapped. Hence, just skip.
Yifan Hong29692902020-03-26 12:47:05 -0700776 TEST_AND_RETURN_FALSE(UnmapPartitionOnDeviceMapper(partition_name_suffix));
777 // Use CreateLogicalPartition directly to avoid mapping with existing
778 // snapshots.
779 CreateLogicalPartitionParams params = {
780 .block_device = source_super_device,
781 .metadata_slot = source_slot,
782 .partition_name = partition_name_suffix,
783 .force_writable = true,
784 .timeout_ms = kMapTimeout,
785 };
786 TEST_AND_RETURN_FALSE(CreateLogicalPartition(params, path));
787 *should_unmap = true;
788 return true;
789}
790
791bool DynamicPartitionControlAndroid::EraseSystemOtherAvbFooter(
792 uint32_t source_slot, uint32_t target_slot) {
793 LOG(INFO) << "Erasing AVB footer of system_other partition before update.";
794
795 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
796 const std::string partition_name_suffix = "system" + target_suffix;
797
798 std::string path;
799 bool should_unmap = false;
800
801 TEST_AND_RETURN_FALSE(GetSystemOtherPath(
802 source_slot, target_slot, partition_name_suffix, &path, &should_unmap));
803
804 if (path.empty()) {
805 return true;
806 }
807
808 bool ret = AvbFooterEraser(path).Erase();
809
810 // Delete |partition_name_suffix| from device mapper and from
811 // |mapped_devices_| again so that it does not interfere with update process.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700812 // In recovery, metadata might not be mounted, and
813 // UnmapPartitionOnDeviceMapper might fail. However, DestroyLogicalPartition
814 // should be called. If DestroyLogicalPartition does fail, it is still okay
815 // to skip the error here and let Prepare*() fail later.
Yifan Hong29692902020-03-26 12:47:05 -0700816 if (should_unmap) {
817 TEST_AND_RETURN_FALSE(UnmapPartitionOnDeviceMapper(partition_name_suffix));
818 }
819
820 return ret;
821}
822
Yifan Hong420db9b2019-07-23 20:50:33 -0700823bool DynamicPartitionControlAndroid::PrepareDynamicPartitionsForUpdate(
824 uint32_t source_slot,
825 uint32_t target_slot,
Yifan Hongbae27842019-10-24 16:56:12 -0700826 const DeltaArchiveManifest& manifest,
827 bool delete_source) {
Yifan Hong012508e2019-07-22 18:30:40 -0700828 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
829
830 // Unmap all the target dynamic partitions because they would become
831 // inconsistent with the new metadata.
Yifan Hong13d41cb2019-09-16 13:18:22 -0700832 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
833 for (const auto& partition_name : group.partition_names()) {
834 if (!UnmapPartitionOnDeviceMapper(partition_name + target_suffix)) {
Yifan Hong012508e2019-07-22 18:30:40 -0700835 return false;
836 }
837 }
838 }
839
840 std::string device_dir_str;
Tianjie9f4dc7f2021-03-15 16:00:50 -0700841 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
Yifan Hong012508e2019-07-22 18:30:40 -0700842 base::FilePath device_dir(device_dir_str);
843 auto source_device =
Yifan Hong700d7c12019-07-23 20:49:16 -0700844 device_dir.Append(GetSuperPartitionName(source_slot)).value();
Yifan Hong012508e2019-07-22 18:30:40 -0700845
846 auto builder = LoadMetadataBuilder(source_device, source_slot, target_slot);
847 if (builder == nullptr) {
848 LOG(ERROR) << "No metadata at "
849 << BootControlInterface::SlotName(source_slot);
850 return false;
851 }
852
Yifan Hongbae27842019-10-24 16:56:12 -0700853 if (delete_source) {
854 TEST_AND_RETURN_FALSE(
855 DeleteSourcePartitions(builder.get(), source_slot, manifest));
856 }
857
Tianjie9f4dc7f2021-03-15 16:00:50 -0700858 TEST_AND_RETURN_FALSE(
859 UpdatePartitionMetadata(builder.get(), target_slot, manifest));
Yifan Hong012508e2019-07-22 18:30:40 -0700860
861 auto target_device =
Yifan Hong700d7c12019-07-23 20:49:16 -0700862 device_dir.Append(GetSuperPartitionName(target_slot)).value();
Daniel Zhengeede4c82023-06-13 11:21:06 -0700863
Yifan Hong012508e2019-07-22 18:30:40 -0700864 return StoreMetadata(target_device, builder.get(), target_slot);
865}
866
Yifan Hong3a1293a2021-04-16 13:21:20 -0700867DynamicPartitionControlAndroid::SpaceLimit
868DynamicPartitionControlAndroid::GetSpaceLimit(bool use_snapshot) {
869 // On device retrofitting dynamic partitions, allocatable_space = "super",
870 // where "super" is the sum of all block devices for that slot. Since block
871 // devices are dedicated for the corresponding slot, there's no need to halve
872 // the allocatable space.
873 if (GetDynamicPartitionsFeatureFlag().IsRetrofit())
874 return SpaceLimit::ERROR_IF_EXCEEDED_SUPER;
875
876 // On device launching dynamic partitions w/o VAB, regardless of recovery
877 // sideload, super partition must be big enough to hold both A and B slots of
878 // groups. Hence,
879 // allocatable_space = super / 2
880 if (!GetVirtualAbFeatureFlag().IsEnabled())
881 return SpaceLimit::ERROR_IF_EXCEEDED_HALF_OF_SUPER;
882
883 // Source build supports VAB. Super partition must be big enough to hold
884 // one slot of groups (ERROR_IF_EXCEEDED_SUPER). However, there are cases
885 // where additional warning messages needs to be written.
886
887 // If using snapshot updates, implying that target build also uses VAB,
888 // allocatable_space = super
889 if (use_snapshot)
890 return SpaceLimit::ERROR_IF_EXCEEDED_SUPER;
891
892 // Source build supports VAB but not using snapshot updates. There are
893 // several cases, as listed below.
894 // Sideloading: allocatable_space = super.
895 if (IsRecovery())
896 return SpaceLimit::ERROR_IF_EXCEEDED_SUPER;
897
898 // On launch VAB device, this implies secondary payload.
899 // Technically, we don't have to check anything, but sum(groups) < super
900 // still applies.
901 if (!GetVirtualAbFeatureFlag().IsRetrofit())
902 return SpaceLimit::ERROR_IF_EXCEEDED_SUPER;
903
904 // On retrofit VAB device, either of the following:
905 // - downgrading: allocatable_space = super / 2
906 // - secondary payload: don't check anything
907 // These two cases are indistinguishable,
908 // hence emit warning if sum(groups) > super / 2
909 return SpaceLimit::WARN_IF_EXCEEDED_HALF_OF_SUPER;
910}
911
Tianjie9f4dc7f2021-03-15 16:00:50 -0700912bool DynamicPartitionControlAndroid::CheckSuperPartitionAllocatableSpace(
913 android::fs_mgr::MetadataBuilder* builder,
914 const DeltaArchiveManifest& manifest,
915 bool use_snapshot) {
Yifan Hong3a1293a2021-04-16 13:21:20 -0700916 uint64_t sum_groups = 0;
Tianjie9f4dc7f2021-03-15 16:00:50 -0700917 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
Yifan Hong3a1293a2021-04-16 13:21:20 -0700918 sum_groups += group.size();
Tianjie9f4dc7f2021-03-15 16:00:50 -0700919 }
920
Yifan Hong3a1293a2021-04-16 13:21:20 -0700921 uint64_t full_space = builder->AllocatableSpace();
922 uint64_t half_space = full_space / 2;
923 constexpr const char* fmt =
924 "The maximum size of all groups for the target slot (%" PRIu64
925 ") has exceeded %sallocatable space for dynamic partitions %" PRIu64 ".";
926 switch (GetSpaceLimit(use_snapshot)) {
927 case SpaceLimit::ERROR_IF_EXCEEDED_HALF_OF_SUPER: {
928 if (sum_groups > half_space) {
929 LOG(ERROR) << StringPrintf(fmt, sum_groups, "HALF OF ", half_space);
930 return false;
931 }
932 // If test passes, it implies that the following two conditions also pass.
933 break;
934 }
935 case SpaceLimit::WARN_IF_EXCEEDED_HALF_OF_SUPER: {
936 if (sum_groups > half_space) {
937 LOG(WARNING) << StringPrintf(fmt, sum_groups, "HALF OF ", half_space)
938 << " This is allowed for downgrade or secondary OTA on "
939 "retrofit VAB device.";
940 }
941 // still check sum(groups) < super
942 [[fallthrough]];
943 }
944 case SpaceLimit::ERROR_IF_EXCEEDED_SUPER: {
945 if (sum_groups > full_space) {
Kelvin Zhangb9a9aa22024-10-15 10:38:35 -0700946 LOG(ERROR) << android::base::StringPrintf(
947 fmt, sum_groups, "", full_space);
Yifan Hong3a1293a2021-04-16 13:21:20 -0700948 return false;
949 }
950 break;
951 }
Tianjie9f4dc7f2021-03-15 16:00:50 -0700952 }
953
954 return true;
955}
956
Yifan Hong420db9b2019-07-23 20:50:33 -0700957bool DynamicPartitionControlAndroid::PrepareSnapshotPartitionsForUpdate(
958 uint32_t source_slot,
959 uint32_t target_slot,
Yifan Hongf033ecb2020-01-07 18:13:56 -0800960 const DeltaArchiveManifest& manifest,
961 uint64_t* required_size) {
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700962 TEST_AND_RETURN_FALSE(ExpectMetadataMounted());
Tianjie9f4dc7f2021-03-15 16:00:50 -0700963
964 std::string device_dir_str;
965 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
966 base::FilePath device_dir(device_dir_str);
967 auto super_device =
968 device_dir.Append(GetSuperPartitionName(source_slot)).value();
969 auto builder = LoadMetadataBuilder(super_device, source_slot);
970 if (builder == nullptr) {
971 LOG(ERROR) << "No metadata at "
972 << BootControlInterface::SlotName(source_slot);
973 return false;
974 }
975
976 TEST_AND_RETURN_FALSE(
977 CheckSuperPartitionAllocatableSpace(builder.get(), manifest, true));
978
Yifan Hong420db9b2019-07-23 20:50:33 -0700979 if (!snapshot_->BeginUpdate()) {
980 LOG(ERROR) << "Cannot begin new update.";
981 return false;
982 }
Yifan Hongf033ecb2020-01-07 18:13:56 -0800983 auto ret = snapshot_->CreateUpdateSnapshots(manifest);
984 if (!ret) {
985 LOG(ERROR) << "Cannot create update snapshots: " << ret.string();
986 if (required_size != nullptr &&
Yifan Hong0850bca2020-01-16 15:14:07 -0800987 ret.error_code() == Return::ErrorCode::NO_SPACE) {
Yifan Hongf033ecb2020-01-07 18:13:56 -0800988 *required_size = ret.required_size();
989 }
Yifan Hong420db9b2019-07-23 20:50:33 -0700990 return false;
991 }
992 return true;
993}
994
Yifan Hong700d7c12019-07-23 20:49:16 -0700995std::string DynamicPartitionControlAndroid::GetSuperPartitionName(
996 uint32_t slot) {
997 return fs_mgr_get_super_partition_name(slot);
998}
999
Yifan Hong012508e2019-07-22 18:30:40 -07001000bool DynamicPartitionControlAndroid::UpdatePartitionMetadata(
1001 MetadataBuilder* builder,
1002 uint32_t target_slot,
Yifan Hong13d41cb2019-09-16 13:18:22 -07001003 const DeltaArchiveManifest& manifest) {
Yifan Hong8d6df9a2020-08-13 13:59:54 -07001004 // Check preconditions.
Yifan Hong265a8e32021-04-16 13:30:02 -07001005 if (GetVirtualAbFeatureFlag().IsEnabled()) {
1006 CHECK(!target_supports_snapshot_ || IsRecovery())
1007 << "Must use snapshot on VAB device when target build supports VAB and "
1008 "not sideloading.";
1009 LOG_IF(INFO, !target_supports_snapshot_)
1010 << "Not using snapshot on VAB device because target build does not "
1011 "support snapshot. Secondary or downgrade OTA?";
1012 LOG_IF(INFO, IsRecovery())
1013 << "Not using snapshot on VAB device because sideloading.";
1014 }
Yifan Hong8d6df9a2020-08-13 13:59:54 -07001015
Yifan Honga4e7da32019-09-30 18:25:03 -07001016 // If applying downgrade from Virtual A/B to non-Virtual A/B, the left-over
1017 // COW group needs to be deleted to ensure there are enough space to create
1018 // target partitions.
1019 builder->RemoveGroupAndPartitions(android::snapshot::kCowGroupName);
1020
Yifan Hong012508e2019-07-22 18:30:40 -07001021 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
1022 DeleteGroupsWithSuffix(builder, target_suffix);
1023
Tianjie9f4dc7f2021-03-15 16:00:50 -07001024 TEST_AND_RETURN_FALSE(
1025 CheckSuperPartitionAllocatableSpace(builder, manifest, false));
Yifan Hong012508e2019-07-22 18:30:40 -07001026
Yifan Hong13d41cb2019-09-16 13:18:22 -07001027 // name of partition(e.g. "system") -> size in bytes
1028 std::map<std::string, uint64_t> partition_sizes;
1029 for (const auto& partition : manifest.partitions()) {
1030 partition_sizes.emplace(partition.partition_name(),
1031 partition.new_partition_info().size());
1032 }
1033
1034 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
1035 auto group_name_suffix = group.name() + target_suffix;
1036 if (!builder->AddGroup(group_name_suffix, group.size())) {
Yifan Hong012508e2019-07-22 18:30:40 -07001037 LOG(ERROR) << "Cannot add group " << group_name_suffix << " with size "
Yifan Hong13d41cb2019-09-16 13:18:22 -07001038 << group.size();
Yifan Hong012508e2019-07-22 18:30:40 -07001039 return false;
1040 }
1041 LOG(INFO) << "Added group " << group_name_suffix << " with size "
Yifan Hong13d41cb2019-09-16 13:18:22 -07001042 << group.size();
Yifan Hong012508e2019-07-22 18:30:40 -07001043
Yifan Hong13d41cb2019-09-16 13:18:22 -07001044 for (const auto& partition_name : group.partition_names()) {
1045 auto partition_sizes_it = partition_sizes.find(partition_name);
1046 if (partition_sizes_it == partition_sizes.end()) {
1047 // TODO(tbao): Support auto-filling partition info for framework-only
1048 // OTA.
1049 LOG(ERROR) << "dynamic_partition_metadata contains partition "
1050 << partition_name << " but it is not part of the manifest. "
1051 << "This is not supported.";
1052 return false;
1053 }
1054 uint64_t partition_size = partition_sizes_it->second;
1055
1056 auto partition_name_suffix = partition_name + target_suffix;
Yifan Hong012508e2019-07-22 18:30:40 -07001057 Partition* p = builder->AddPartition(
1058 partition_name_suffix, group_name_suffix, LP_PARTITION_ATTR_READONLY);
1059 if (!p) {
1060 LOG(ERROR) << "Cannot add partition " << partition_name_suffix
1061 << " to group " << group_name_suffix;
1062 return false;
1063 }
Yifan Hong13d41cb2019-09-16 13:18:22 -07001064 if (!builder->ResizePartition(p, partition_size)) {
Yifan Hong012508e2019-07-22 18:30:40 -07001065 LOG(ERROR) << "Cannot resize partition " << partition_name_suffix
Yifan Hong13d41cb2019-09-16 13:18:22 -07001066 << " to size " << partition_size << ". Not enough space?";
Yifan Hong012508e2019-07-22 18:30:40 -07001067 return false;
1068 }
David Anderson0e1c7fd2021-03-08 19:01:59 -08001069 if (p->size() < partition_size) {
1070 LOG(ERROR) << "Partition " << partition_name_suffix
1071 << " was expected to have size " << partition_size
1072 << ", but instead has size " << p->size();
1073 return false;
1074 }
Yifan Hong012508e2019-07-22 18:30:40 -07001075 LOG(INFO) << "Added partition " << partition_name_suffix << " to group "
Yifan Hong13d41cb2019-09-16 13:18:22 -07001076 << group_name_suffix << " with size " << partition_size;
Yifan Hong012508e2019-07-22 18:30:40 -07001077 }
1078 }
1079
1080 return true;
1081}
1082
Yifan Hong7b3910a2020-03-24 17:47:32 -07001083bool DynamicPartitionControlAndroid::FinishUpdate(bool powerwash_required) {
Yifan Hong4d7c5eb2020-04-03 11:31:50 -07001084 if (ExpectMetadataMounted()) {
1085 if (snapshot_->GetUpdateState() == UpdateState::Initiated) {
1086 LOG(INFO) << "Snapshot writes are done.";
1087 return snapshot_->FinishedSnapshotWrites(powerwash_required);
1088 }
1089 } else {
1090 LOG(INFO) << "Skip FinishedSnapshotWrites() because /metadata is not "
1091 << "mounted";
Yifan Hongf0f4a912019-09-26 17:51:33 -07001092 }
1093 return true;
Yifan Honga33bca42019-09-03 20:29:45 -07001094}
1095
Yifan Hong3a1a5612019-11-05 16:34:32 -08001096bool DynamicPartitionControlAndroid::GetPartitionDevice(
1097 const std::string& partition_name,
1098 uint32_t slot,
1099 uint32_t current_slot,
Tianjie51a5a392020-06-03 14:39:32 -07001100 bool not_in_payload,
1101 std::string* device,
1102 bool* is_dynamic) {
Kelvin Zhang66a9ebb2021-01-25 13:35:10 -05001103 auto partition_dev =
1104 GetPartitionDevice(partition_name, slot, current_slot, not_in_payload);
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001105 if (!partition_dev.has_value()) {
Yifan Hong3a1a5612019-11-05 16:34:32 -08001106 return false;
1107 }
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001108 if (device) {
1109 *device = std::move(partition_dev->rw_device_path);
1110 }
1111 if (is_dynamic) {
1112 *is_dynamic = partition_dev->is_dynamic;
1113 }
Yifan Hong3a1a5612019-11-05 16:34:32 -08001114 return true;
1115}
1116
Tianjie51a5a392020-06-03 14:39:32 -07001117bool DynamicPartitionControlAndroid::GetPartitionDevice(
1118 const std::string& partition_name,
1119 uint32_t slot,
1120 uint32_t current_slot,
1121 std::string* device) {
1122 return GetPartitionDevice(
1123 partition_name, slot, current_slot, false, device, nullptr);
1124}
1125
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001126static std::string GetStaticDevicePath(
1127 const base::FilePath& device_dir,
1128 const std::string& partition_name_suffixed) {
1129 base::FilePath path = device_dir.Append(partition_name_suffixed);
1130 return path.value();
1131}
1132
1133std::optional<PartitionDevice>
1134DynamicPartitionControlAndroid::GetPartitionDevice(
1135 const std::string& partition_name,
1136 uint32_t slot,
1137 uint32_t current_slot,
1138 bool not_in_payload) {
1139 std::string device_dir_str;
1140 if (!GetDeviceDir(&device_dir_str)) {
1141 LOG(ERROR) << "Failed to GetDeviceDir()";
1142 return {};
1143 }
1144 const base::FilePath device_dir(device_dir_str);
1145 // When VABC is enabled, we can't get device path for dynamic partitions in
1146 // target slot.
1147 const auto& partition_name_suffix =
1148 partition_name + SlotSuffixForSlotNumber(slot);
Kelvin Zhangebd115e2021-03-08 16:10:25 -05001149 if (UpdateUsesSnapshotCompression() && slot != current_slot &&
1150 IsDynamicPartition(partition_name, slot)) {
Kelvin Zhang91ad6622021-03-01 13:46:17 -05001151 return {
Kelvin Zhanga9b5d8c2021-05-05 09:17:46 -04001152 {.readonly_device_path = base::FilePath{std::string{VABC_DEVICE_DIR}}
1153 .Append(partition_name_suffix)
1154 .value(),
Kelvin Zhang91ad6622021-03-01 13:46:17 -05001155 .is_dynamic = true}};
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001156 }
1157
1158 // When looking up target partition devices, treat them as static if the
1159 // current payload doesn't encode them as dynamic partitions. This may happen
1160 // when applying a retrofit update on top of a dynamic-partitions-enabled
1161 // build.
1162 std::string device;
1163 if (GetDynamicPartitionsFeatureFlag().IsEnabled() &&
1164 (slot == current_slot || is_target_dynamic_)) {
1165 switch (GetDynamicPartitionDevice(device_dir,
1166 partition_name_suffix,
1167 slot,
1168 current_slot,
1169 not_in_payload,
1170 &device)) {
1171 case DynamicPartitionDeviceStatus::SUCCESS:
1172 return {{.rw_device_path = device,
Kelvin Zhanga9b5d8c2021-05-05 09:17:46 -04001173 .readonly_device_path = device,
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001174 .is_dynamic = true}};
1175
1176 case DynamicPartitionDeviceStatus::TRY_STATIC:
1177 break;
1178 case DynamicPartitionDeviceStatus::ERROR: // fallthrough
1179 default:
1180 return {};
1181 }
1182 }
1183 // Try static partitions.
1184 auto static_path = GetStaticDevicePath(device_dir, partition_name_suffix);
1185 if (!DeviceExists(static_path)) {
1186 LOG(ERROR) << "Device file " << static_path << " does not exist.";
1187 return {};
1188 }
1189
1190 return {{.rw_device_path = static_path,
Kelvin Zhanga9b5d8c2021-05-05 09:17:46 -04001191 .readonly_device_path = static_path,
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001192 .is_dynamic = false}};
1193}
1194
Yifan Hong3a1a5612019-11-05 16:34:32 -08001195bool DynamicPartitionControlAndroid::IsSuperBlockDevice(
1196 const base::FilePath& device_dir,
1197 uint32_t current_slot,
1198 const std::string& partition_name_suffix) {
1199 std::string source_device =
1200 device_dir.Append(GetSuperPartitionName(current_slot)).value();
1201 auto source_metadata = LoadMetadataBuilder(source_device, current_slot);
1202 return source_metadata->HasBlockDevice(partition_name_suffix);
1203}
1204
1205DynamicPartitionControlAndroid::DynamicPartitionDeviceStatus
1206DynamicPartitionControlAndroid::GetDynamicPartitionDevice(
1207 const base::FilePath& device_dir,
1208 const std::string& partition_name_suffix,
1209 uint32_t slot,
1210 uint32_t current_slot,
Tianjie51a5a392020-06-03 14:39:32 -07001211 bool not_in_payload,
Yifan Hong3a1a5612019-11-05 16:34:32 -08001212 std::string* device) {
1213 std::string super_device =
1214 device_dir.Append(GetSuperPartitionName(slot)).value();
1215
1216 auto builder = LoadMetadataBuilder(super_device, slot);
1217 if (builder == nullptr) {
1218 LOG(ERROR) << "No metadata in slot "
1219 << BootControlInterface::SlotName(slot);
1220 return DynamicPartitionDeviceStatus::ERROR;
1221 }
1222 if (builder->FindPartition(partition_name_suffix) == nullptr) {
1223 LOG(INFO) << partition_name_suffix
1224 << " is not in super partition metadata.";
1225
1226 if (IsSuperBlockDevice(device_dir, current_slot, partition_name_suffix)) {
1227 LOG(ERROR) << "The static partition " << partition_name_suffix
1228 << " is a block device for current metadata."
1229 << "It cannot be used as a logical partition.";
1230 return DynamicPartitionDeviceStatus::ERROR;
1231 }
1232
1233 return DynamicPartitionDeviceStatus::TRY_STATIC;
1234 }
1235
1236 if (slot == current_slot) {
1237 if (GetState(partition_name_suffix) != DmDeviceState::ACTIVE) {
1238 LOG(WARNING) << partition_name_suffix << " is at current slot but it is "
1239 << "not mapped. Now try to map it.";
1240 } else {
1241 if (GetDmDevicePathByName(partition_name_suffix, device)) {
1242 LOG(INFO) << partition_name_suffix
1243 << " is mapped on device mapper: " << *device;
1244 return DynamicPartitionDeviceStatus::SUCCESS;
1245 }
1246 LOG(ERROR) << partition_name_suffix << "is mapped but path is unknown.";
1247 return DynamicPartitionDeviceStatus::ERROR;
1248 }
1249 }
1250
Kelvin Zhang8b07db52024-07-24 09:13:25 -07001251 const bool force_writable = !not_in_payload;
Yifan Hong3a1a5612019-11-05 16:34:32 -08001252 if (MapPartitionOnDeviceMapper(
1253 super_device, partition_name_suffix, slot, force_writable, device)) {
1254 return DynamicPartitionDeviceStatus::SUCCESS;
1255 }
1256 return DynamicPartitionDeviceStatus::ERROR;
1257}
1258
Yifan Hong6eec9952019-12-04 13:12:01 -08001259void DynamicPartitionControlAndroid::set_fake_mapped_devices(
1260 const std::set<std::string>& fake) {
1261 mapped_devices_ = fake;
1262}
1263
Yifan Hongbae27842019-10-24 16:56:12 -07001264bool DynamicPartitionControlAndroid::IsRecovery() {
Kelvin Zhanga22ef552020-10-12 19:03:52 -04001265 return constants::kIsRecovery;
Yifan Hongbae27842019-10-24 16:56:12 -07001266}
1267
1268static bool IsIncrementalUpdate(const DeltaArchiveManifest& manifest) {
1269 const auto& partitions = manifest.partitions();
1270 return std::any_of(partitions.begin(), partitions.end(), [](const auto& p) {
1271 return p.has_old_partition_info();
1272 });
1273}
1274
1275bool DynamicPartitionControlAndroid::DeleteSourcePartitions(
1276 MetadataBuilder* builder,
1277 uint32_t source_slot,
1278 const DeltaArchiveManifest& manifest) {
1279 TEST_AND_RETURN_FALSE(IsRecovery());
1280
1281 if (IsIncrementalUpdate(manifest)) {
1282 LOG(ERROR) << "Cannot sideload incremental OTA because snapshots cannot "
1283 << "be created.";
1284 if (GetVirtualAbFeatureFlag().IsLaunch()) {
1285 LOG(ERROR) << "Sideloading incremental updates on devices launches "
1286 << " Virtual A/B is not supported.";
1287 }
1288 return false;
1289 }
1290
1291 LOG(INFO) << "Will overwrite existing partitions. Slot "
1292 << BootControlInterface::SlotName(source_slot)
Tianjie9f4dc7f2021-03-15 16:00:50 -07001293 << " may be unbootable until update finishes!";
Yifan Hongbae27842019-10-24 16:56:12 -07001294 const std::string source_suffix = SlotSuffixForSlotNumber(source_slot);
1295 DeleteGroupsWithSuffix(builder, source_suffix);
1296
1297 return true;
1298}
1299
Yifan Hong90965502020-02-19 15:22:47 -08001300std::unique_ptr<AbstractAction>
1301DynamicPartitionControlAndroid::GetCleanupPreviousUpdateAction(
1302 BootControlInterface* boot_control,
1303 PrefsInterface* prefs,
1304 CleanupPreviousUpdateActionDelegateInterface* delegate) {
1305 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1306 return std::make_unique<NoOpAction>();
1307 }
1308 return std::make_unique<CleanupPreviousUpdateAction>(
1309 prefs, boot_control, snapshot_.get(), delegate);
1310}
1311
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001312bool DynamicPartitionControlAndroid::ResetUpdate(PrefsInterface* prefs) {
1313 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1314 return true;
1315 }
Kelvin Zhangff5380b2022-03-16 13:35:04 -07001316 for (auto& list : dynamic_partition_list_) {
1317 list.clear();
1318 }
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001319
1320 LOG(INFO) << __func__ << " resetting update state and deleting snapshots.";
1321 TEST_AND_RETURN_FALSE(prefs != nullptr);
1322
1323 // If the device has already booted into the target slot,
1324 // ResetUpdateProgress may pass but CancelUpdate fails.
1325 // This is expected. A scheduled CleanupPreviousUpdateAction should free
1326 // space when it is done.
Daniel Zhengf9784802023-06-08 08:39:48 -07001327 TEST_AND_RETURN_FALSE(DeltaPerformer::ResetUpdateProgress(
1328 prefs, false /* quick */, false /* skip dynamic partitions metadata */));
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001329
Yifan Hong4d7c5eb2020-04-03 11:31:50 -07001330 if (ExpectMetadataMounted()) {
1331 TEST_AND_RETURN_FALSE(snapshot_->CancelUpdate());
1332 } else {
1333 LOG(INFO) << "Skip cancelling update in ResetUpdate because /metadata is "
1334 << "not mounted";
1335 }
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001336
1337 return true;
1338}
1339
Tianjie99d570d2020-06-04 14:57:19 -07001340bool DynamicPartitionControlAndroid::ListDynamicPartitionsForSlot(
Tianjie3a55fc22021-02-13 16:02:22 -08001341 uint32_t slot,
1342 uint32_t current_slot,
1343 std::vector<std::string>* partitions) {
Kelvin Zhangebd115e2021-03-08 16:10:25 -05001344 CHECK(slot == source_slot_ || target_slot_ != UINT32_MAX)
1345 << " source slot: " << source_slot_ << " target slot: " << target_slot_
1346 << " slot: " << slot
1347 << " attempting to query dynamic partition metadata for target slot "
1348 "before PreparePartitionForUpdate() is called. The "
1349 "metadata in target slot isn't valid until "
1350 "PreparePartitionForUpdate() is called, contining execution would "
1351 "likely cause problems.";
Tianjie3a55fc22021-02-13 16:02:22 -08001352 bool slot_enables_dynamic_partitions =
1353 GetDynamicPartitionsFeatureFlag().IsEnabled();
1354 // Check if the target slot has dynamic partitions, this may happen when
1355 // applying a retrofit package.
1356 if (slot != current_slot) {
1357 slot_enables_dynamic_partitions =
1358 slot_enables_dynamic_partitions && is_target_dynamic_;
1359 }
1360
1361 if (!slot_enables_dynamic_partitions) {
1362 LOG(INFO) << "Dynamic partition is not enabled for slot " << slot;
1363 return true;
Tianjie99d570d2020-06-04 14:57:19 -07001364 }
1365
1366 std::string device_dir_str;
1367 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
1368 base::FilePath device_dir(device_dir_str);
Tianjie3a55fc22021-02-13 16:02:22 -08001369 auto super_device = device_dir.Append(GetSuperPartitionName(slot)).value();
1370 auto builder = LoadMetadataBuilder(super_device, slot);
Tianjie99d570d2020-06-04 14:57:19 -07001371 TEST_AND_RETURN_FALSE(builder != nullptr);
1372
1373 std::vector<std::string> result;
Tianjie3a55fc22021-02-13 16:02:22 -08001374 auto suffix = SlotSuffixForSlotNumber(slot);
Tianjie99d570d2020-06-04 14:57:19 -07001375 for (const auto& group : builder->ListGroups()) {
1376 for (const auto& partition : builder->ListPartitionsInGroup(group)) {
1377 std::string_view partition_name = partition->name();
1378 if (!android::base::ConsumeSuffix(&partition_name, suffix)) {
1379 continue;
1380 }
1381 result.emplace_back(partition_name);
1382 }
1383 }
1384 *partitions = std::move(result);
1385 return true;
1386}
1387
Tianjie24f96092020-06-30 12:26:25 -07001388bool DynamicPartitionControlAndroid::VerifyExtentsForUntouchedPartitions(
1389 uint32_t source_slot,
1390 uint32_t target_slot,
1391 const std::vector<std::string>& partitions) {
1392 std::string device_dir_str;
1393 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
1394 base::FilePath device_dir(device_dir_str);
1395
1396 auto source_super_device =
1397 device_dir.Append(GetSuperPartitionName(source_slot)).value();
1398 auto source_builder = LoadMetadataBuilder(source_super_device, source_slot);
1399 TEST_AND_RETURN_FALSE(source_builder != nullptr);
1400
1401 auto target_super_device =
1402 device_dir.Append(GetSuperPartitionName(target_slot)).value();
1403 auto target_builder = LoadMetadataBuilder(target_super_device, target_slot);
1404 TEST_AND_RETURN_FALSE(target_builder != nullptr);
1405
1406 return MetadataBuilder::VerifyExtentsAgainstSourceMetadata(
1407 *source_builder, source_slot, *target_builder, target_slot, partitions);
1408}
1409
Yifan Hong4d7c5eb2020-04-03 11:31:50 -07001410bool DynamicPartitionControlAndroid::ExpectMetadataMounted() {
1411 // No need to mount metadata for non-Virtual A/B devices.
1412 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1413 return false;
1414 }
1415 // Intentionally not checking |metadata_device_| in Android mode.
1416 // /metadata should always be mounted in Android mode. If it isn't, let caller
1417 // fails when calling into SnapshotManager.
1418 if (!IsRecovery()) {
1419 return true;
1420 }
1421 // In recovery mode, explicitly check |metadata_device_|.
1422 return metadata_device_ != nullptr;
1423}
1424
1425bool DynamicPartitionControlAndroid::EnsureMetadataMounted() {
1426 // No need to mount metadata for non-Virtual A/B devices.
1427 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1428 return true;
1429 }
1430
1431 if (metadata_device_ == nullptr) {
1432 metadata_device_ = snapshot_->EnsureMetadataMounted();
1433 }
1434 return metadata_device_ != nullptr;
1435}
1436
David Andersona4b7ba62023-05-10 21:41:37 -07001437std::unique_ptr<android::snapshot::ICowWriter>
Kelvin Zhang34618522020-09-28 09:21:02 -04001438DynamicPartitionControlAndroid::OpenCowWriter(
1439 const std::string& partition_name,
1440 const std::optional<std::string>& source_path,
David Andersona4b7ba62023-05-10 21:41:37 -07001441 std::optional<uint64_t> label) {
Kelvin Zhang34618522020-09-28 09:21:02 -04001442 auto suffix = SlotSuffixForSlotNumber(target_slot_);
1443
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -04001444 auto super_device = GetSuperDevice();
1445 if (!super_device.has_value()) {
Kelvin Zhang34618522020-09-28 09:21:02 -04001446 return nullptr;
1447 }
Kelvin Zhang34618522020-09-28 09:21:02 -04001448 CreateLogicalPartitionParams params = {
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -04001449 .block_device = super_device->value(),
Kelvin Zhang34618522020-09-28 09:21:02 -04001450 .metadata_slot = target_slot_,
1451 .partition_name = partition_name + suffix,
1452 .force_writable = true,
Kelvin Zhang877ddbe2020-11-09 13:37:56 -05001453 .timeout_ms = kMapSnapshotTimeout};
Kelvin Zhang34618522020-09-28 09:21:02 -04001454 // TODO(zhangkelvin) Open an APPEND mode CowWriter once there's an API to do
1455 // it.
David Andersona4b7ba62023-05-10 21:41:37 -07001456 return snapshot_->OpenSnapshotWriter(params, label);
Kelvin Zhang877ddbe2020-11-09 13:37:56 -05001457} // namespace chromeos_update_engine
Kelvin Zhang34618522020-09-28 09:21:02 -04001458
Kelvin Zhang1a0ed712022-01-26 16:09:05 -08001459std::unique_ptr<FileDescriptor> DynamicPartitionControlAndroid::OpenCowFd(
Kelvin Zhangc82511c2020-11-06 16:01:24 -05001460 const std::string& unsuffixed_partition_name,
1461 const std::optional<std::string>& source_path,
1462 bool is_append) {
David Andersona4b7ba62023-05-10 21:41:37 -07001463 auto cow_writer = OpenCowWriter(
1464 unsuffixed_partition_name, source_path, {kEndOfInstallLabel});
Kelvin Zhangc82511c2020-11-06 16:01:24 -05001465 if (cow_writer == nullptr) {
David Andersona4b7ba62023-05-10 21:41:37 -07001466 LOG(ERROR) << "OpenCowWriter failed";
Kelvin Zhangc82511c2020-11-06 16:01:24 -05001467 return nullptr;
1468 }
David Andersona4b7ba62023-05-10 21:41:37 -07001469 auto fd = cow_writer->OpenFileDescriptor(source_path);
1470 if (fd == nullptr) {
1471 LOG(ERROR) << "ICowReader::OpenFileDescriptor failed";
Kelvin Zhang21a49912021-03-12 14:28:33 -05001472 return nullptr;
1473 }
David Andersona4b7ba62023-05-10 21:41:37 -07001474 return std::make_unique<CowWriterFileDescriptor>(
1475 std::move(cow_writer), std::move(fd), source_path);
Kelvin Zhangc82511c2020-11-06 16:01:24 -05001476}
1477
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -04001478std::optional<base::FilePath> DynamicPartitionControlAndroid::GetSuperDevice() {
1479 std::string device_dir_str;
1480 if (!GetDeviceDir(&device_dir_str)) {
1481 LOG(ERROR) << "Failed to get device dir!";
1482 return {};
1483 }
1484 base::FilePath device_dir(device_dir_str);
1485 auto super_device = device_dir.Append(GetSuperPartitionName(target_slot_));
1486 return super_device;
1487}
1488
1489bool DynamicPartitionControlAndroid::MapAllPartitions() {
Kelvin Zhang877ddbe2020-11-09 13:37:56 -05001490 return snapshot_->MapAllSnapshots(kMapSnapshotTimeout);
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -04001491}
1492
Kelvin Zhangeb9de162020-11-16 15:47:28 -05001493bool DynamicPartitionControlAndroid::IsDynamicPartition(
Kelvin Zhangebd115e2021-03-08 16:10:25 -05001494 const std::string& partition_name, uint32_t slot) {
1495 if (slot >= dynamic_partition_list_.size()) {
1496 LOG(ERROR) << "Seeing unexpected slot # " << slot << " currently assuming "
1497 << dynamic_partition_list_.size() << " slots";
1498 return false;
1499 }
1500 auto& dynamic_partition_list = dynamic_partition_list_[slot];
1501 if (dynamic_partition_list.empty() &&
Kelvin Zhangeb9de162020-11-16 15:47:28 -05001502 GetDynamicPartitionsFeatureFlag().IsEnabled()) {
Tianjie3a55fc22021-02-13 16:02:22 -08001503 // Use the DAP config of the target slot.
1504 CHECK(ListDynamicPartitionsForSlot(
Kelvin Zhangebd115e2021-03-08 16:10:25 -05001505 slot, source_slot_, &dynamic_partition_list));
Kelvin Zhangeb9de162020-11-16 15:47:28 -05001506 }
Kelvin Zhangebd115e2021-03-08 16:10:25 -05001507 return std::find(dynamic_partition_list.begin(),
1508 dynamic_partition_list.end(),
1509 partition_name) != dynamic_partition_list.end();
Kelvin Zhangeb9de162020-11-16 15:47:28 -05001510}
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001511
Yifan Hongb0cbd392021-02-04 11:11:45 -08001512bool DynamicPartitionControlAndroid::UpdateUsesSnapshotCompression() {
Kelvin Zhang741c2d42021-04-13 12:40:38 -04001513 return GetVirtualAbFeatureFlag().IsEnabled() &&
1514 snapshot_->UpdateUsesCompression();
Yifan Hongb0cbd392021-02-04 11:11:45 -08001515}
1516
David Andersone35b4382022-03-08 23:18:29 -08001517FeatureFlag
1518DynamicPartitionControlAndroid::GetVirtualAbUserspaceSnapshotsFeatureFlag() {
1519 return virtual_ab_userspace_snapshots_;
1520}
1521
Yifan Hong537802d2018-08-15 13:15:42 -07001522} // namespace chromeos_update_engine