blob: d8df5206f8a878cfb0f8e6e3c05c942d4a3d6fce [file] [log] [blame]
Yifan Hong537802d2018-08-15 13:15:42 -07001//
2// Copyright (C) 2018 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
16
Amin Hassaniec7bc112020-10-29 16:47:58 -070017#include "update_engine/aosp/dynamic_partition_control_android.h"
Yifan Hong537802d2018-08-15 13:15:42 -070018
Kelvin Zhang91d95fa2020-11-05 13:52:00 -050019#include <algorithm>
Yifan Hong420db9b2019-07-23 20:50:33 -070020#include <chrono> // NOLINT(build/c++11) - using libsnapshot / liblp API
Kelvin Zhang34618522020-09-28 09:21:02 -040021#include <cstdint>
Yifan Hong13d41cb2019-09-16 13:18:22 -070022#include <map>
Yifan Hong537802d2018-08-15 13:15:42 -070023#include <memory>
24#include <set>
25#include <string>
Tianjie99d570d2020-06-04 14:57:19 -070026#include <string_view>
27#include <utility>
Yifan Hong012508e2019-07-22 18:30:40 -070028#include <vector>
Yifan Hong537802d2018-08-15 13:15:42 -070029
30#include <android-base/properties.h>
31#include <android-base/strings.h>
32#include <base/files/file_util.h>
33#include <base/logging.h>
Yifan Hong012508e2019-07-22 18:30:40 -070034#include <base/strings/string_util.h>
Yifan Hong3a1293a2021-04-16 13:21:20 -070035#include <base/strings/stringprintf.h>
Yifan Hong537802d2018-08-15 13:15:42 -070036#include <bootloader_message/bootloader_message.h>
Yifan Hong012508e2019-07-22 18:30:40 -070037#include <fs_mgr.h>
Yifan Hong537802d2018-08-15 13:15:42 -070038#include <fs_mgr_dm_linear.h>
Yifan Hong3a1a5612019-11-05 16:34:32 -080039#include <fs_mgr_overlayfs.h>
Yifan Hong29692902020-03-26 12:47:05 -070040#include <libavb/libavb.h>
Yifan Hong3a1a5612019-11-05 16:34:32 -080041#include <libdm/dm.h>
Kelvin Zhang34618522020-09-28 09:21:02 -040042#include <liblp/liblp.h>
43#include <libsnapshot/cow_writer.h>
Yifan Hong420db9b2019-07-23 20:50:33 -070044#include <libsnapshot/snapshot.h>
Yifan Hongf9cb4492020-04-15 13:00:20 -070045#include <libsnapshot/snapshot_stub.h>
Yifan Hong537802d2018-08-15 13:15:42 -070046
Amin Hassaniec7bc112020-10-29 16:47:58 -070047#include "update_engine/aosp/cleanup_previous_update_action.h"
48#include "update_engine/aosp/dynamic_partition_utils.h"
Yifan Hong537802d2018-08-15 13:15:42 -070049#include "update_engine/common/boot_control_interface.h"
Kelvin Zhangb9a5f612021-01-22 14:34:05 -050050#include "update_engine/common/dynamic_partition_control_interface.h"
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;
60using android::dm::DeviceMapper;
61using android::dm::DmDeviceState;
62using android::fs_mgr::CreateLogicalPartition;
David Andersonbb90dfb2019-08-13 14:14:56 -070063using android::fs_mgr::CreateLogicalPartitionParams;
Yifan Hong537802d2018-08-15 13:15:42 -070064using android::fs_mgr::DestroyLogicalPartition;
Yifan Hong29692902020-03-26 12:47:05 -070065using android::fs_mgr::Fstab;
Yifan Hong537802d2018-08-15 13:15:42 -070066using android::fs_mgr::MetadataBuilder;
Yifan Hong012508e2019-07-22 18:30:40 -070067using android::fs_mgr::Partition;
Yifan Hong6e706b12018-11-09 16:50:51 -080068using android::fs_mgr::PartitionOpener;
Yifan Hong012508e2019-07-22 18:30:40 -070069using android::fs_mgr::SlotSuffixForSlotNumber;
Yifan Hongf5261562020-03-10 10:28:10 -070070using android::snapshot::OptimizeSourceCopyOperation;
Yifan Hong0850bca2020-01-16 15:14:07 -080071using android::snapshot::Return;
Yifan Hongf033ecb2020-01-07 18:13:56 -080072using android::snapshot::SnapshotManager;
Yifan Hongf9cb4492020-04-15 13:00:20 -070073using android::snapshot::SnapshotManagerStub;
Yifan Hong2257ee12020-01-13 18:33:00 -080074using android::snapshot::UpdateState;
Yifan Hong3a1293a2021-04-16 13:21:20 -070075using base::StringPrintf;
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_ &&
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700202 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();
320 metadata_device_.reset();
Kelvin Zhangc675fc02022-06-22 10:18:54 -0700321 if (GetVirtualAbFeatureFlag().IsEnabled()) {
322 snapshot_ = SnapshotManager::New();
323 } else {
324 snapshot_ = SnapshotManagerStub::New();
325 }
326 CHECK(snapshot_ != nullptr) << "Cannot initialize SnapshotManager.";
Yifan Hong537802d2018-08-15 13:15:42 -0700327}
328
329bool DynamicPartitionControlAndroid::DeviceExists(const std::string& path) {
330 return base::PathExists(base::FilePath(path));
331}
332
333android::dm::DmDeviceState DynamicPartitionControlAndroid::GetState(
334 const std::string& name) {
335 return DeviceMapper::Instance().GetState(name);
336}
337
338bool DynamicPartitionControlAndroid::GetDmDevicePathByName(
339 const std::string& name, std::string* path) {
340 return DeviceMapper::Instance().GetDmDevicePathByName(name, path);
341}
342
343std::unique_ptr<MetadataBuilder>
344DynamicPartitionControlAndroid::LoadMetadataBuilder(
Tianjie24f96092020-06-30 12:26:25 -0700345 const std::string& super_device, uint32_t slot) {
346 auto builder = MetadataBuilder::New(PartitionOpener(), super_device, slot);
347 if (builder == nullptr) {
348 LOG(WARNING) << "No metadata slot " << BootControlInterface::SlotName(slot)
349 << " in " << super_device;
350 return nullptr;
351 }
352 LOG(INFO) << "Loaded metadata from slot "
353 << BootControlInterface::SlotName(slot) << " in " << super_device;
354 return builder;
Yifan Hong012508e2019-07-22 18:30:40 -0700355}
356
357std::unique_ptr<MetadataBuilder>
358DynamicPartitionControlAndroid::LoadMetadataBuilder(
Yifan Hong6e706b12018-11-09 16:50:51 -0800359 const std::string& super_device,
360 uint32_t source_slot,
361 uint32_t target_slot) {
Tianjie24f96092020-06-30 12:26:25 -0700362 bool always_keep_source_slot = !target_supports_snapshot_;
363 auto builder = MetadataBuilder::NewForUpdate(PartitionOpener(),
364 super_device,
365 source_slot,
366 target_slot,
367 always_keep_source_slot);
Yifan Hong537802d2018-08-15 13:15:42 -0700368 if (builder == nullptr) {
369 LOG(WARNING) << "No metadata slot "
370 << BootControlInterface::SlotName(source_slot) << " in "
371 << super_device;
Yifan Hongf48a0052018-10-29 16:30:43 -0700372 return nullptr;
Yifan Hong537802d2018-08-15 13:15:42 -0700373 }
Tianjie24f96092020-06-30 12:26:25 -0700374 LOG(INFO) << "Created metadata for new update from slot "
Yifan Hong537802d2018-08-15 13:15:42 -0700375 << BootControlInterface::SlotName(source_slot) << " in "
376 << super_device;
377 return builder;
378}
379
380bool DynamicPartitionControlAndroid::StoreMetadata(
381 const std::string& super_device,
382 MetadataBuilder* builder,
383 uint32_t target_slot) {
384 auto metadata = builder->Export();
385 if (metadata == nullptr) {
386 LOG(ERROR) << "Cannot export metadata to slot "
387 << BootControlInterface::SlotName(target_slot) << " in "
388 << super_device;
389 return false;
390 }
391
Yifan Hong186bb682019-07-23 14:04:39 -0700392 if (GetDynamicPartitionsFeatureFlag().IsRetrofit()) {
Yifan Hong6e706b12018-11-09 16:50:51 -0800393 if (!FlashPartitionTable(super_device, *metadata)) {
394 LOG(ERROR) << "Cannot write metadata to " << super_device;
395 return false;
396 }
397 LOG(INFO) << "Written metadata to " << super_device;
398 } else {
399 if (!UpdatePartitionTable(super_device, *metadata, target_slot)) {
400 LOG(ERROR) << "Cannot write metadata to slot "
401 << BootControlInterface::SlotName(target_slot) << " in "
402 << super_device;
403 return false;
404 }
405 LOG(INFO) << "Copied metadata to slot "
406 << BootControlInterface::SlotName(target_slot) << " in "
407 << super_device;
Yifan Hong537802d2018-08-15 13:15:42 -0700408 }
409
Yifan Hong537802d2018-08-15 13:15:42 -0700410 return true;
411}
412
413bool DynamicPartitionControlAndroid::GetDeviceDir(std::string* out) {
414 // We can't use fs_mgr to look up |partition_name| because fstab
415 // doesn't list every slot partition (it uses the slotselect option
416 // to mask the suffix).
417 //
418 // We can however assume that there's an entry for the /misc mount
419 // point and use that to get the device file for the misc
420 // partition. This helps us locate the disk that |partition_name|
421 // resides on. From there we'll assume that a by-name scheme is used
422 // so we can just replace the trailing "misc" by the given
423 // |partition_name| and suffix corresponding to |slot|, e.g.
424 //
425 // /dev/block/platform/soc.0/7824900.sdhci/by-name/misc ->
426 // /dev/block/platform/soc.0/7824900.sdhci/by-name/boot_a
427 //
428 // If needed, it's possible to relax the by-name assumption in the
429 // future by trawling /sys/block looking for the appropriate sibling
430 // of misc and then finding an entry in /dev matching the sysfs
431 // entry.
432
433 std::string err, misc_device = get_bootloader_message_blk_device(&err);
434 if (misc_device.empty()) {
435 LOG(ERROR) << "Unable to get misc block device: " << err;
436 return false;
437 }
438
439 if (!utils::IsSymlink(misc_device.c_str())) {
440 LOG(ERROR) << "Device file " << misc_device << " for /misc "
441 << "is not a symlink.";
442 return false;
443 }
444 *out = base::FilePath(misc_device).DirName().value();
445 return true;
446}
Yifan Hong012508e2019-07-22 18:30:40 -0700447
448bool DynamicPartitionControlAndroid::PreparePartitionsForUpdate(
449 uint32_t source_slot,
450 uint32_t target_slot,
Yifan Hongf0f4a912019-09-26 17:51:33 -0700451 const DeltaArchiveManifest& manifest,
Yifan Hongf033ecb2020-01-07 18:13:56 -0800452 bool update,
Daniel Zhengeede4c82023-06-13 11:21:06 -0700453 uint64_t* required_size,
454 ErrorCode* error) {
Yifan Hong6eec9952019-12-04 13:12:01 -0800455 source_slot_ = source_slot;
456 target_slot_ = target_slot;
Yifan Hongf033ecb2020-01-07 18:13:56 -0800457 if (required_size != nullptr) {
458 *required_size = 0;
459 }
Yifan Hong6eec9952019-12-04 13:12:01 -0800460
Yifan Hong3a1a5612019-11-05 16:34:32 -0800461 if (fs_mgr_overlayfs_is_setup()) {
462 // Non DAP devices can use overlayfs as well.
Daniel Zhengeede4c82023-06-13 11:21:06 -0700463 LOG(ERROR)
Yifan Hong3a1a5612019-11-05 16:34:32 -0800464 << "overlayfs overrides are active and can interfere with our "
465 "resources.\n"
466 << "run adb enable-verity to deactivate if required and try again.";
Daniel Zhengeede4c82023-06-13 11:21:06 -0700467 if (error) {
468 *error = ErrorCode::kOverlayfsenabledError;
469 return false;
470 }
Yifan Hong3a1a5612019-11-05 16:34:32 -0800471 }
472
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700473 // If metadata is erased but not formatted, it is possible to not mount
474 // it in recovery. It is acceptable to skip mounting and choose fallback path
475 // (PrepareDynamicPartitionsForUpdate) when sideloading full OTAs.
476 TEST_AND_RETURN_FALSE(EnsureMetadataMounted() || IsRecovery());
Yifan Hong29692902020-03-26 12:47:05 -0700477
478 if (update) {
479 TEST_AND_RETURN_FALSE(EraseSystemOtherAvbFooter(source_slot, target_slot));
480 }
481
Yifan Hong3a1a5612019-11-05 16:34:32 -0800482 if (!GetDynamicPartitionsFeatureFlag().IsEnabled()) {
483 return true;
484 }
485
486 if (target_slot == source_slot) {
487 LOG(ERROR) << "Cannot call PreparePartitionsForUpdate on current slot.";
488 return false;
489 }
490
Yifan Hongf6f75c22020-07-31 15:20:25 -0700491 if (!SetTargetBuildVars(manifest)) {
492 return false;
493 }
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700494 for (auto& list : dynamic_partition_list_) {
495 list.clear();
496 }
Yifan Hongf6f75c22020-07-31 15:20:25 -0700497
Yifan Hong3a1a5612019-11-05 16:34:32 -0800498 // Although the current build supports dynamic partitions, the given payload
499 // doesn't use it for target partitions. This could happen when applying a
500 // retrofit update. Skip updating the partition metadata for the target slot.
Yifan Hong3a1a5612019-11-05 16:34:32 -0800501 if (!is_target_dynamic_) {
502 return true;
503 }
504
Yifan Hongf0f4a912019-09-26 17:51:33 -0700505 if (!update)
506 return true;
507
Yifan Hongbae27842019-10-24 16:56:12 -0700508 bool delete_source = false;
509
Yifan Hong6d888562019-10-01 13:00:31 -0700510 if (GetVirtualAbFeatureFlag().IsEnabled()) {
511 // On Virtual A/B device, either CancelUpdate() or BeginUpdate() must be
512 // called before calling UnmapUpdateSnapshot.
513 // - If target_supports_snapshot_, PrepareSnapshotPartitionsForUpdate()
514 // calls BeginUpdate() which resets update state
Yifan Hongbae27842019-10-24 16:56:12 -0700515 // - If !target_supports_snapshot_ or PrepareSnapshotPartitionsForUpdate
516 // failed in recovery, explicitly CancelUpdate().
Yifan Hong6d888562019-10-01 13:00:31 -0700517 if (target_supports_snapshot_) {
Yifan Hongbae27842019-10-24 16:56:12 -0700518 if (PrepareSnapshotPartitionsForUpdate(
519 source_slot, target_slot, manifest, required_size)) {
520 return true;
521 }
522
523 // Virtual A/B device doing Virtual A/B update in Android mode must use
524 // snapshots.
525 if (!IsRecovery()) {
526 LOG(ERROR) << "PrepareSnapshotPartitionsForUpdate failed in Android "
527 << "mode";
528 return false;
529 }
530
531 delete_source = true;
532 LOG(INFO) << "PrepareSnapshotPartitionsForUpdate failed in recovery. "
533 << "Attempt to overwrite existing partitions if possible";
534 } else {
535 // Downgrading to an non-Virtual A/B build or is secondary OTA.
536 LOG(INFO) << "Using regular A/B on Virtual A/B because package disabled "
537 << "snapshots.";
Yifan Hong6d888562019-10-01 13:00:31 -0700538 }
Yifan Hongbae27842019-10-24 16:56:12 -0700539
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700540 // In recovery, if /metadata is not mounted, it is likely that metadata
541 // partition is erased and not formatted yet. After sideloading, when
542 // rebooting into the new version, init will erase metadata partition,
543 // hence the failure of CancelUpdate() can be ignored here.
544 // However, if metadata is mounted and CancelUpdate fails, sideloading
545 // should not proceed because during next boot, snapshots will overlay on
546 // the devices incorrectly.
547 if (ExpectMetadataMounted()) {
548 TEST_AND_RETURN_FALSE(snapshot_->CancelUpdate());
549 } else {
550 LOG(INFO) << "Skip canceling previous update because metadata is not "
551 << "mounted";
Yifan Hong6d888562019-10-01 13:00:31 -0700552 }
Yifan Hong420db9b2019-07-23 20:50:33 -0700553 }
Yifan Hongbae27842019-10-24 16:56:12 -0700554
Tianjie24f96092020-06-30 12:26:25 -0700555 // TODO(xunchang) support partial update on non VAB enabled devices.
Yifan Hong5c5743f2020-04-16 12:59:07 -0700556 TEST_AND_RETURN_FALSE(PrepareDynamicPartitionsForUpdate(
557 source_slot, target_slot, manifest, delete_source));
558
559 if (required_size != nullptr) {
560 *required_size = 0;
561 }
562 return true;
Yifan Hong420db9b2019-07-23 20:50:33 -0700563}
564
Yifan Hongf6f75c22020-07-31 15:20:25 -0700565bool DynamicPartitionControlAndroid::SetTargetBuildVars(
566 const DeltaArchiveManifest& manifest) {
567 // Precondition: current build supports dynamic partition.
568 CHECK(GetDynamicPartitionsFeatureFlag().IsEnabled());
569
570 bool is_target_dynamic =
571 !manifest.dynamic_partition_metadata().groups().empty();
572 bool target_supports_snapshot =
573 manifest.dynamic_partition_metadata().snapshot_enabled();
574
575 if (manifest.partial_update()) {
576 // Partial updates requires DAP. On partial updates that does not involve
577 // dynamic partitions, groups() can be empty, so also assume
578 // is_target_dynamic in this case. This assumption should be safe because we
579 // also check target_supports_snapshot below, which presumably also implies
580 // target build supports dynamic partition.
581 if (!is_target_dynamic) {
582 LOG(INFO) << "Assuming target build supports dynamic partitions for "
583 "partial updates.";
584 is_target_dynamic = true;
585 }
586
587 // Partial updates requires Virtual A/B. Double check that both current
588 // build and target build supports Virtual A/B.
589 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
590 LOG(ERROR) << "Partial update cannot be applied on a device that does "
591 "not support snapshots.";
592 return false;
593 }
594 if (!target_supports_snapshot) {
595 LOG(ERROR) << "Cannot apply partial update to a build that does not "
596 "support snapshots.";
597 return false;
598 }
599 }
600
601 // Store the flags.
602 is_target_dynamic_ = is_target_dynamic;
603 // If !is_target_dynamic_, leave target_supports_snapshot_ unset because
604 // snapshots would not work without dynamic partition.
605 if (is_target_dynamic_) {
606 target_supports_snapshot_ = target_supports_snapshot;
607 }
608 return true;
609}
610
Yifan Hong29692902020-03-26 12:47:05 -0700611namespace {
612// Try our best to erase AVB footer.
613class AvbFooterEraser {
614 public:
615 explicit AvbFooterEraser(const std::string& path) : path_(path) {}
616 bool Erase() {
617 // Try to mark the block device read-only. Ignore any
618 // failure since this won't work when passing regular files.
619 ignore_result(utils::SetBlockDeviceReadOnly(path_, false /* readonly */));
620
621 fd_.reset(new EintrSafeFileDescriptor());
622 int flags = O_WRONLY | O_TRUNC | O_CLOEXEC | O_SYNC;
623 TEST_AND_RETURN_FALSE(fd_->Open(path_.c_str(), flags));
624
625 // Need to write end-AVB_FOOTER_SIZE to end.
626 static_assert(AVB_FOOTER_SIZE > 0);
627 off64_t offset = fd_->Seek(-AVB_FOOTER_SIZE, SEEK_END);
628 TEST_AND_RETURN_FALSE_ERRNO(offset >= 0);
629 uint64_t write_size = AVB_FOOTER_SIZE;
630 LOG(INFO) << "Zeroing " << path_ << " @ [" << offset << ", "
631 << (offset + write_size) << "] (" << write_size << " bytes)";
632 brillo::Blob zeros(write_size);
633 TEST_AND_RETURN_FALSE(utils::WriteAll(fd_, zeros.data(), zeros.size()));
634 return true;
635 }
636 ~AvbFooterEraser() {
637 TEST_AND_RETURN(fd_ != nullptr && fd_->IsOpen());
638 if (!fd_->Close()) {
639 LOG(WARNING) << "Failed to close fd for " << path_;
640 }
641 }
642
643 private:
644 std::string path_;
645 FileDescriptorPtr fd_;
646};
647
648} // namespace
649
650std::optional<bool>
651DynamicPartitionControlAndroid::IsAvbEnabledOnSystemOther() {
652 auto prefix = GetProperty(kPostinstallFstabPrefix, "");
653 if (prefix.empty()) {
654 LOG(WARNING) << "Cannot get " << kPostinstallFstabPrefix;
655 return std::nullopt;
656 }
657 auto path = base::FilePath(prefix).Append("etc/fstab.postinstall").value();
658 return IsAvbEnabledInFstab(path);
659}
660
661std::optional<bool> DynamicPartitionControlAndroid::IsAvbEnabledInFstab(
662 const std::string& path) {
663 Fstab fstab;
664 if (!ReadFstabFromFile(path, &fstab)) {
Yifan Hong93cde302020-04-27 12:59:29 -0700665 PLOG(WARNING) << "Cannot read fstab from " << path;
666 if (errno == ENOENT) {
667 return false;
668 }
Yifan Hong29692902020-03-26 12:47:05 -0700669 return std::nullopt;
670 }
671 for (const auto& entry : fstab) {
672 if (!entry.avb_keys.empty()) {
673 return true;
674 }
675 }
676 return false;
677}
678
679bool DynamicPartitionControlAndroid::GetSystemOtherPath(
680 uint32_t source_slot,
681 uint32_t target_slot,
682 const std::string& partition_name_suffix,
683 std::string* path,
684 bool* should_unmap) {
685 path->clear();
686 *should_unmap = false;
687
P.Adarsh Reddy13e4195d2020-06-08 23:17:36 +0530688 // Check that AVB is enabled on system_other before erasing.
689 auto has_avb = IsAvbEnabledOnSystemOther();
690 TEST_AND_RETURN_FALSE(has_avb.has_value());
691 if (!has_avb.value()) {
692 LOG(INFO) << "AVB is not enabled on system_other. Skip erasing.";
693 return true;
694 }
Yifan Hong29692902020-03-26 12:47:05 -0700695
P.Adarsh Reddy13e4195d2020-06-08 23:17:36 +0530696 if (!IsRecovery()) {
Yifan Hong29692902020-03-26 12:47:05 -0700697 // Found unexpected avb_keys for system_other on devices retrofitting
698 // dynamic partitions. Previous crash in update_engine may leave logical
699 // partitions mapped on physical system_other partition. It is difficult to
700 // handle these cases. Just fail.
701 if (GetDynamicPartitionsFeatureFlag().IsRetrofit()) {
702 LOG(ERROR) << "Cannot erase AVB footer on system_other on devices with "
703 << "retrofit dynamic partitions. They should not have AVB "
704 << "enabled on system_other.";
705 return false;
706 }
707 }
708
709 std::string device_dir_str;
710 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
711 base::FilePath device_dir(device_dir_str);
712
713 // On devices without dynamic partition, search for static partitions.
714 if (!GetDynamicPartitionsFeatureFlag().IsEnabled()) {
715 *path = device_dir.Append(partition_name_suffix).value();
716 TEST_AND_RETURN_FALSE(DeviceExists(*path));
717 return true;
718 }
719
720 auto source_super_device =
721 device_dir.Append(GetSuperPartitionName(source_slot)).value();
722
723 auto builder = LoadMetadataBuilder(source_super_device, source_slot);
724 if (builder == nullptr) {
725 if (IsRecovery()) {
726 // It might be corrupted for some reason. It should still be able to
727 // sideload.
728 LOG(WARNING) << "Super partition metadata cannot be read from the source "
729 << "slot, skip erasing.";
730 return true;
731 } else {
732 // Device has booted into Android mode, indicating that the super
733 // partition metadata should be there.
734 LOG(ERROR) << "Super partition metadata cannot be read from the source "
735 << "slot. This is unexpected on devices with dynamic "
736 << "partitions enabled.";
737 return false;
738 }
739 }
740 auto p = builder->FindPartition(partition_name_suffix);
741 if (p == nullptr) {
742 // If the source slot is flashed without system_other, it does not exist
743 // in super partition metadata at source slot. It is safe to skip it.
744 LOG(INFO) << "Can't find " << partition_name_suffix
745 << " in metadata source slot, skip erasing.";
746 return true;
747 }
748 // System_other created by flashing tools should be erased.
749 // If partition is created by update_engine (via NewForUpdate), it is a
750 // left-over partition from the previous update and does not contain
751 // system_other, hence there is no need to erase.
752 // Note the reverse is not necessary true. If the flag is not set, we don't
753 // know if the partition is created by update_engine or by flashing tools
754 // because older versions of super partition metadata does not contain this
755 // flag. It is okay to erase the AVB footer anyways.
756 if (p->attributes() & LP_PARTITION_ATTR_UPDATED) {
757 LOG(INFO) << partition_name_suffix
758 << " does not contain system_other, skip erasing.";
759 return true;
760 }
761
Yifan Hong64331b32020-05-13 16:50:40 -0700762 if (p->size() < AVB_FOOTER_SIZE) {
763 LOG(INFO) << partition_name_suffix << " has length " << p->size()
764 << "( < AVB_FOOTER_SIZE " << AVB_FOOTER_SIZE
765 << "), skip erasing.";
766 return true;
767 }
768
Yifan Hong29692902020-03-26 12:47:05 -0700769 // Delete any pre-existing device with name |partition_name_suffix| and
770 // also remove it from |mapped_devices_|.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700771 // In recovery, metadata might not be mounted, and
772 // UnmapPartitionOnDeviceMapper might fail. However,
773 // it is unusual that system_other has already been mapped. Hence, just skip.
Yifan Hong29692902020-03-26 12:47:05 -0700774 TEST_AND_RETURN_FALSE(UnmapPartitionOnDeviceMapper(partition_name_suffix));
775 // Use CreateLogicalPartition directly to avoid mapping with existing
776 // snapshots.
777 CreateLogicalPartitionParams params = {
778 .block_device = source_super_device,
779 .metadata_slot = source_slot,
780 .partition_name = partition_name_suffix,
781 .force_writable = true,
782 .timeout_ms = kMapTimeout,
783 };
784 TEST_AND_RETURN_FALSE(CreateLogicalPartition(params, path));
785 *should_unmap = true;
786 return true;
787}
788
789bool DynamicPartitionControlAndroid::EraseSystemOtherAvbFooter(
790 uint32_t source_slot, uint32_t target_slot) {
791 LOG(INFO) << "Erasing AVB footer of system_other partition before update.";
792
793 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
794 const std::string partition_name_suffix = "system" + target_suffix;
795
796 std::string path;
797 bool should_unmap = false;
798
799 TEST_AND_RETURN_FALSE(GetSystemOtherPath(
800 source_slot, target_slot, partition_name_suffix, &path, &should_unmap));
801
802 if (path.empty()) {
803 return true;
804 }
805
806 bool ret = AvbFooterEraser(path).Erase();
807
808 // Delete |partition_name_suffix| from device mapper and from
809 // |mapped_devices_| again so that it does not interfere with update process.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700810 // In recovery, metadata might not be mounted, and
811 // UnmapPartitionOnDeviceMapper might fail. However, DestroyLogicalPartition
812 // should be called. If DestroyLogicalPartition does fail, it is still okay
813 // to skip the error here and let Prepare*() fail later.
Yifan Hong29692902020-03-26 12:47:05 -0700814 if (should_unmap) {
815 TEST_AND_RETURN_FALSE(UnmapPartitionOnDeviceMapper(partition_name_suffix));
816 }
817
818 return ret;
819}
820
Yifan Hong420db9b2019-07-23 20:50:33 -0700821bool DynamicPartitionControlAndroid::PrepareDynamicPartitionsForUpdate(
822 uint32_t source_slot,
823 uint32_t target_slot,
Yifan Hongbae27842019-10-24 16:56:12 -0700824 const DeltaArchiveManifest& manifest,
825 bool delete_source) {
Yifan Hong012508e2019-07-22 18:30:40 -0700826 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
827
828 // Unmap all the target dynamic partitions because they would become
829 // inconsistent with the new metadata.
Yifan Hong13d41cb2019-09-16 13:18:22 -0700830 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
831 for (const auto& partition_name : group.partition_names()) {
832 if (!UnmapPartitionOnDeviceMapper(partition_name + target_suffix)) {
Yifan Hong012508e2019-07-22 18:30:40 -0700833 return false;
834 }
835 }
836 }
837
838 std::string device_dir_str;
Tianjie9f4dc7f2021-03-15 16:00:50 -0700839 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
Yifan Hong012508e2019-07-22 18:30:40 -0700840 base::FilePath device_dir(device_dir_str);
841 auto source_device =
Yifan Hong700d7c12019-07-23 20:49:16 -0700842 device_dir.Append(GetSuperPartitionName(source_slot)).value();
Yifan Hong012508e2019-07-22 18:30:40 -0700843
844 auto builder = LoadMetadataBuilder(source_device, source_slot, target_slot);
845 if (builder == nullptr) {
846 LOG(ERROR) << "No metadata at "
847 << BootControlInterface::SlotName(source_slot);
848 return false;
849 }
850
Yifan Hongbae27842019-10-24 16:56:12 -0700851 if (delete_source) {
852 TEST_AND_RETURN_FALSE(
853 DeleteSourcePartitions(builder.get(), source_slot, manifest));
854 }
855
Tianjie9f4dc7f2021-03-15 16:00:50 -0700856 TEST_AND_RETURN_FALSE(
857 UpdatePartitionMetadata(builder.get(), target_slot, manifest));
Yifan Hong012508e2019-07-22 18:30:40 -0700858
859 auto target_device =
Yifan Hong700d7c12019-07-23 20:49:16 -0700860 device_dir.Append(GetSuperPartitionName(target_slot)).value();
Daniel Zhengeede4c82023-06-13 11:21:06 -0700861
Yifan Hong012508e2019-07-22 18:30:40 -0700862 return StoreMetadata(target_device, builder.get(), target_slot);
863}
864
Yifan Hong3a1293a2021-04-16 13:21:20 -0700865DynamicPartitionControlAndroid::SpaceLimit
866DynamicPartitionControlAndroid::GetSpaceLimit(bool use_snapshot) {
867 // On device retrofitting dynamic partitions, allocatable_space = "super",
868 // where "super" is the sum of all block devices for that slot. Since block
869 // devices are dedicated for the corresponding slot, there's no need to halve
870 // the allocatable space.
871 if (GetDynamicPartitionsFeatureFlag().IsRetrofit())
872 return SpaceLimit::ERROR_IF_EXCEEDED_SUPER;
873
874 // On device launching dynamic partitions w/o VAB, regardless of recovery
875 // sideload, super partition must be big enough to hold both A and B slots of
876 // groups. Hence,
877 // allocatable_space = super / 2
878 if (!GetVirtualAbFeatureFlag().IsEnabled())
879 return SpaceLimit::ERROR_IF_EXCEEDED_HALF_OF_SUPER;
880
881 // Source build supports VAB. Super partition must be big enough to hold
882 // one slot of groups (ERROR_IF_EXCEEDED_SUPER). However, there are cases
883 // where additional warning messages needs to be written.
884
885 // If using snapshot updates, implying that target build also uses VAB,
886 // allocatable_space = super
887 if (use_snapshot)
888 return SpaceLimit::ERROR_IF_EXCEEDED_SUPER;
889
890 // Source build supports VAB but not using snapshot updates. There are
891 // several cases, as listed below.
892 // Sideloading: allocatable_space = super.
893 if (IsRecovery())
894 return SpaceLimit::ERROR_IF_EXCEEDED_SUPER;
895
896 // On launch VAB device, this implies secondary payload.
897 // Technically, we don't have to check anything, but sum(groups) < super
898 // still applies.
899 if (!GetVirtualAbFeatureFlag().IsRetrofit())
900 return SpaceLimit::ERROR_IF_EXCEEDED_SUPER;
901
902 // On retrofit VAB device, either of the following:
903 // - downgrading: allocatable_space = super / 2
904 // - secondary payload: don't check anything
905 // These two cases are indistinguishable,
906 // hence emit warning if sum(groups) > super / 2
907 return SpaceLimit::WARN_IF_EXCEEDED_HALF_OF_SUPER;
908}
909
Tianjie9f4dc7f2021-03-15 16:00:50 -0700910bool DynamicPartitionControlAndroid::CheckSuperPartitionAllocatableSpace(
911 android::fs_mgr::MetadataBuilder* builder,
912 const DeltaArchiveManifest& manifest,
913 bool use_snapshot) {
Yifan Hong3a1293a2021-04-16 13:21:20 -0700914 uint64_t sum_groups = 0;
Tianjie9f4dc7f2021-03-15 16:00:50 -0700915 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
Yifan Hong3a1293a2021-04-16 13:21:20 -0700916 sum_groups += group.size();
Tianjie9f4dc7f2021-03-15 16:00:50 -0700917 }
918
Yifan Hong3a1293a2021-04-16 13:21:20 -0700919 uint64_t full_space = builder->AllocatableSpace();
920 uint64_t half_space = full_space / 2;
921 constexpr const char* fmt =
922 "The maximum size of all groups for the target slot (%" PRIu64
923 ") has exceeded %sallocatable space for dynamic partitions %" PRIu64 ".";
924 switch (GetSpaceLimit(use_snapshot)) {
925 case SpaceLimit::ERROR_IF_EXCEEDED_HALF_OF_SUPER: {
926 if (sum_groups > half_space) {
927 LOG(ERROR) << StringPrintf(fmt, sum_groups, "HALF OF ", half_space);
928 return false;
929 }
930 // If test passes, it implies that the following two conditions also pass.
931 break;
932 }
933 case SpaceLimit::WARN_IF_EXCEEDED_HALF_OF_SUPER: {
934 if (sum_groups > half_space) {
935 LOG(WARNING) << StringPrintf(fmt, sum_groups, "HALF OF ", half_space)
936 << " This is allowed for downgrade or secondary OTA on "
937 "retrofit VAB device.";
938 }
939 // still check sum(groups) < super
940 [[fallthrough]];
941 }
942 case SpaceLimit::ERROR_IF_EXCEEDED_SUPER: {
943 if (sum_groups > full_space) {
944 LOG(ERROR) << base::StringPrintf(fmt, sum_groups, "", full_space);
945 return false;
946 }
947 break;
948 }
Tianjie9f4dc7f2021-03-15 16:00:50 -0700949 }
950
951 return true;
952}
953
Yifan Hong420db9b2019-07-23 20:50:33 -0700954bool DynamicPartitionControlAndroid::PrepareSnapshotPartitionsForUpdate(
955 uint32_t source_slot,
956 uint32_t target_slot,
Yifan Hongf033ecb2020-01-07 18:13:56 -0800957 const DeltaArchiveManifest& manifest,
958 uint64_t* required_size) {
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700959 TEST_AND_RETURN_FALSE(ExpectMetadataMounted());
Tianjie9f4dc7f2021-03-15 16:00:50 -0700960
961 std::string device_dir_str;
962 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
963 base::FilePath device_dir(device_dir_str);
964 auto super_device =
965 device_dir.Append(GetSuperPartitionName(source_slot)).value();
966 auto builder = LoadMetadataBuilder(super_device, source_slot);
967 if (builder == nullptr) {
968 LOG(ERROR) << "No metadata at "
969 << BootControlInterface::SlotName(source_slot);
970 return false;
971 }
972
973 TEST_AND_RETURN_FALSE(
974 CheckSuperPartitionAllocatableSpace(builder.get(), manifest, true));
975
Yifan Hong420db9b2019-07-23 20:50:33 -0700976 if (!snapshot_->BeginUpdate()) {
977 LOG(ERROR) << "Cannot begin new update.";
978 return false;
979 }
Yifan Hongf033ecb2020-01-07 18:13:56 -0800980 auto ret = snapshot_->CreateUpdateSnapshots(manifest);
981 if (!ret) {
982 LOG(ERROR) << "Cannot create update snapshots: " << ret.string();
983 if (required_size != nullptr &&
Yifan Hong0850bca2020-01-16 15:14:07 -0800984 ret.error_code() == Return::ErrorCode::NO_SPACE) {
Yifan Hongf033ecb2020-01-07 18:13:56 -0800985 *required_size = ret.required_size();
986 }
Yifan Hong420db9b2019-07-23 20:50:33 -0700987 return false;
988 }
989 return true;
990}
991
Yifan Hong700d7c12019-07-23 20:49:16 -0700992std::string DynamicPartitionControlAndroid::GetSuperPartitionName(
993 uint32_t slot) {
994 return fs_mgr_get_super_partition_name(slot);
995}
996
Yifan Hong012508e2019-07-22 18:30:40 -0700997bool DynamicPartitionControlAndroid::UpdatePartitionMetadata(
998 MetadataBuilder* builder,
999 uint32_t target_slot,
Yifan Hong13d41cb2019-09-16 13:18:22 -07001000 const DeltaArchiveManifest& manifest) {
Yifan Hong8d6df9a2020-08-13 13:59:54 -07001001 // Check preconditions.
Yifan Hong265a8e32021-04-16 13:30:02 -07001002 if (GetVirtualAbFeatureFlag().IsEnabled()) {
1003 CHECK(!target_supports_snapshot_ || IsRecovery())
1004 << "Must use snapshot on VAB device when target build supports VAB and "
1005 "not sideloading.";
1006 LOG_IF(INFO, !target_supports_snapshot_)
1007 << "Not using snapshot on VAB device because target build does not "
1008 "support snapshot. Secondary or downgrade OTA?";
1009 LOG_IF(INFO, IsRecovery())
1010 << "Not using snapshot on VAB device because sideloading.";
1011 }
Yifan Hong8d6df9a2020-08-13 13:59:54 -07001012
Yifan Honga4e7da32019-09-30 18:25:03 -07001013 // If applying downgrade from Virtual A/B to non-Virtual A/B, the left-over
1014 // COW group needs to be deleted to ensure there are enough space to create
1015 // target partitions.
1016 builder->RemoveGroupAndPartitions(android::snapshot::kCowGroupName);
1017
Yifan Hong012508e2019-07-22 18:30:40 -07001018 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
1019 DeleteGroupsWithSuffix(builder, target_suffix);
1020
Tianjie9f4dc7f2021-03-15 16:00:50 -07001021 TEST_AND_RETURN_FALSE(
1022 CheckSuperPartitionAllocatableSpace(builder, manifest, false));
Yifan Hong012508e2019-07-22 18:30:40 -07001023
Yifan Hong13d41cb2019-09-16 13:18:22 -07001024 // name of partition(e.g. "system") -> size in bytes
1025 std::map<std::string, uint64_t> partition_sizes;
1026 for (const auto& partition : manifest.partitions()) {
1027 partition_sizes.emplace(partition.partition_name(),
1028 partition.new_partition_info().size());
1029 }
1030
1031 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
1032 auto group_name_suffix = group.name() + target_suffix;
1033 if (!builder->AddGroup(group_name_suffix, group.size())) {
Yifan Hong012508e2019-07-22 18:30:40 -07001034 LOG(ERROR) << "Cannot add group " << group_name_suffix << " with size "
Yifan Hong13d41cb2019-09-16 13:18:22 -07001035 << group.size();
Yifan Hong012508e2019-07-22 18:30:40 -07001036 return false;
1037 }
1038 LOG(INFO) << "Added group " << group_name_suffix << " with size "
Yifan Hong13d41cb2019-09-16 13:18:22 -07001039 << group.size();
Yifan Hong012508e2019-07-22 18:30:40 -07001040
Yifan Hong13d41cb2019-09-16 13:18:22 -07001041 for (const auto& partition_name : group.partition_names()) {
1042 auto partition_sizes_it = partition_sizes.find(partition_name);
1043 if (partition_sizes_it == partition_sizes.end()) {
1044 // TODO(tbao): Support auto-filling partition info for framework-only
1045 // OTA.
1046 LOG(ERROR) << "dynamic_partition_metadata contains partition "
1047 << partition_name << " but it is not part of the manifest. "
1048 << "This is not supported.";
1049 return false;
1050 }
1051 uint64_t partition_size = partition_sizes_it->second;
1052
1053 auto partition_name_suffix = partition_name + target_suffix;
Yifan Hong012508e2019-07-22 18:30:40 -07001054 Partition* p = builder->AddPartition(
1055 partition_name_suffix, group_name_suffix, LP_PARTITION_ATTR_READONLY);
1056 if (!p) {
1057 LOG(ERROR) << "Cannot add partition " << partition_name_suffix
1058 << " to group " << group_name_suffix;
1059 return false;
1060 }
Yifan Hong13d41cb2019-09-16 13:18:22 -07001061 if (!builder->ResizePartition(p, partition_size)) {
Yifan Hong012508e2019-07-22 18:30:40 -07001062 LOG(ERROR) << "Cannot resize partition " << partition_name_suffix
Yifan Hong13d41cb2019-09-16 13:18:22 -07001063 << " to size " << partition_size << ". Not enough space?";
Yifan Hong012508e2019-07-22 18:30:40 -07001064 return false;
1065 }
David Anderson0e1c7fd2021-03-08 19:01:59 -08001066 if (p->size() < partition_size) {
1067 LOG(ERROR) << "Partition " << partition_name_suffix
1068 << " was expected to have size " << partition_size
1069 << ", but instead has size " << p->size();
1070 return false;
1071 }
Yifan Hong012508e2019-07-22 18:30:40 -07001072 LOG(INFO) << "Added partition " << partition_name_suffix << " to group "
Yifan Hong13d41cb2019-09-16 13:18:22 -07001073 << group_name_suffix << " with size " << partition_size;
Yifan Hong012508e2019-07-22 18:30:40 -07001074 }
1075 }
1076
1077 return true;
1078}
1079
Yifan Hong7b3910a2020-03-24 17:47:32 -07001080bool DynamicPartitionControlAndroid::FinishUpdate(bool powerwash_required) {
Yifan Hong4d7c5eb2020-04-03 11:31:50 -07001081 if (ExpectMetadataMounted()) {
1082 if (snapshot_->GetUpdateState() == UpdateState::Initiated) {
1083 LOG(INFO) << "Snapshot writes are done.";
1084 return snapshot_->FinishedSnapshotWrites(powerwash_required);
1085 }
1086 } else {
1087 LOG(INFO) << "Skip FinishedSnapshotWrites() because /metadata is not "
1088 << "mounted";
Yifan Hongf0f4a912019-09-26 17:51:33 -07001089 }
1090 return true;
Yifan Honga33bca42019-09-03 20:29:45 -07001091}
1092
Yifan Hong3a1a5612019-11-05 16:34:32 -08001093bool DynamicPartitionControlAndroid::GetPartitionDevice(
1094 const std::string& partition_name,
1095 uint32_t slot,
1096 uint32_t current_slot,
Tianjie51a5a392020-06-03 14:39:32 -07001097 bool not_in_payload,
1098 std::string* device,
1099 bool* is_dynamic) {
Kelvin Zhang66a9ebb2021-01-25 13:35:10 -05001100 auto partition_dev =
1101 GetPartitionDevice(partition_name, slot, current_slot, not_in_payload);
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001102 if (!partition_dev.has_value()) {
Yifan Hong3a1a5612019-11-05 16:34:32 -08001103 return false;
1104 }
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001105 if (device) {
1106 *device = std::move(partition_dev->rw_device_path);
1107 }
1108 if (is_dynamic) {
1109 *is_dynamic = partition_dev->is_dynamic;
1110 }
Yifan Hong3a1a5612019-11-05 16:34:32 -08001111 return true;
1112}
1113
Tianjie51a5a392020-06-03 14:39:32 -07001114bool DynamicPartitionControlAndroid::GetPartitionDevice(
1115 const std::string& partition_name,
1116 uint32_t slot,
1117 uint32_t current_slot,
1118 std::string* device) {
1119 return GetPartitionDevice(
1120 partition_name, slot, current_slot, false, device, nullptr);
1121}
1122
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001123static std::string GetStaticDevicePath(
1124 const base::FilePath& device_dir,
1125 const std::string& partition_name_suffixed) {
1126 base::FilePath path = device_dir.Append(partition_name_suffixed);
1127 return path.value();
1128}
1129
1130std::optional<PartitionDevice>
1131DynamicPartitionControlAndroid::GetPartitionDevice(
1132 const std::string& partition_name,
1133 uint32_t slot,
1134 uint32_t current_slot,
1135 bool not_in_payload) {
1136 std::string device_dir_str;
1137 if (!GetDeviceDir(&device_dir_str)) {
1138 LOG(ERROR) << "Failed to GetDeviceDir()";
1139 return {};
1140 }
1141 const base::FilePath device_dir(device_dir_str);
1142 // When VABC is enabled, we can't get device path for dynamic partitions in
1143 // target slot.
1144 const auto& partition_name_suffix =
1145 partition_name + SlotSuffixForSlotNumber(slot);
Kelvin Zhangebd115e2021-03-08 16:10:25 -05001146 if (UpdateUsesSnapshotCompression() && slot != current_slot &&
1147 IsDynamicPartition(partition_name, slot)) {
Kelvin Zhang91ad6622021-03-01 13:46:17 -05001148 return {
Kelvin Zhanga9b5d8c2021-05-05 09:17:46 -04001149 {.readonly_device_path = base::FilePath{std::string{VABC_DEVICE_DIR}}
1150 .Append(partition_name_suffix)
1151 .value(),
Kelvin Zhang91ad6622021-03-01 13:46:17 -05001152 .is_dynamic = true}};
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001153 }
1154
1155 // When looking up target partition devices, treat them as static if the
1156 // current payload doesn't encode them as dynamic partitions. This may happen
1157 // when applying a retrofit update on top of a dynamic-partitions-enabled
1158 // build.
1159 std::string device;
1160 if (GetDynamicPartitionsFeatureFlag().IsEnabled() &&
1161 (slot == current_slot || is_target_dynamic_)) {
1162 switch (GetDynamicPartitionDevice(device_dir,
1163 partition_name_suffix,
1164 slot,
1165 current_slot,
1166 not_in_payload,
1167 &device)) {
1168 case DynamicPartitionDeviceStatus::SUCCESS:
1169 return {{.rw_device_path = device,
Kelvin Zhanga9b5d8c2021-05-05 09:17:46 -04001170 .readonly_device_path = device,
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001171 .is_dynamic = true}};
1172
1173 case DynamicPartitionDeviceStatus::TRY_STATIC:
1174 break;
1175 case DynamicPartitionDeviceStatus::ERROR: // fallthrough
1176 default:
1177 return {};
1178 }
1179 }
1180 // Try static partitions.
1181 auto static_path = GetStaticDevicePath(device_dir, partition_name_suffix);
1182 if (!DeviceExists(static_path)) {
1183 LOG(ERROR) << "Device file " << static_path << " does not exist.";
1184 return {};
1185 }
1186
1187 return {{.rw_device_path = static_path,
Kelvin Zhanga9b5d8c2021-05-05 09:17:46 -04001188 .readonly_device_path = static_path,
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001189 .is_dynamic = false}};
1190}
1191
Yifan Hong3a1a5612019-11-05 16:34:32 -08001192bool DynamicPartitionControlAndroid::IsSuperBlockDevice(
1193 const base::FilePath& device_dir,
1194 uint32_t current_slot,
1195 const std::string& partition_name_suffix) {
1196 std::string source_device =
1197 device_dir.Append(GetSuperPartitionName(current_slot)).value();
1198 auto source_metadata = LoadMetadataBuilder(source_device, current_slot);
1199 return source_metadata->HasBlockDevice(partition_name_suffix);
1200}
1201
1202DynamicPartitionControlAndroid::DynamicPartitionDeviceStatus
1203DynamicPartitionControlAndroid::GetDynamicPartitionDevice(
1204 const base::FilePath& device_dir,
1205 const std::string& partition_name_suffix,
1206 uint32_t slot,
1207 uint32_t current_slot,
Tianjie51a5a392020-06-03 14:39:32 -07001208 bool not_in_payload,
Yifan Hong3a1a5612019-11-05 16:34:32 -08001209 std::string* device) {
1210 std::string super_device =
1211 device_dir.Append(GetSuperPartitionName(slot)).value();
1212
1213 auto builder = LoadMetadataBuilder(super_device, slot);
1214 if (builder == nullptr) {
1215 LOG(ERROR) << "No metadata in slot "
1216 << BootControlInterface::SlotName(slot);
1217 return DynamicPartitionDeviceStatus::ERROR;
1218 }
1219 if (builder->FindPartition(partition_name_suffix) == nullptr) {
1220 LOG(INFO) << partition_name_suffix
1221 << " is not in super partition metadata.";
1222
1223 if (IsSuperBlockDevice(device_dir, current_slot, partition_name_suffix)) {
1224 LOG(ERROR) << "The static partition " << partition_name_suffix
1225 << " is a block device for current metadata."
1226 << "It cannot be used as a logical partition.";
1227 return DynamicPartitionDeviceStatus::ERROR;
1228 }
1229
1230 return DynamicPartitionDeviceStatus::TRY_STATIC;
1231 }
1232
1233 if (slot == current_slot) {
1234 if (GetState(partition_name_suffix) != DmDeviceState::ACTIVE) {
1235 LOG(WARNING) << partition_name_suffix << " is at current slot but it is "
1236 << "not mapped. Now try to map it.";
1237 } else {
1238 if (GetDmDevicePathByName(partition_name_suffix, device)) {
1239 LOG(INFO) << partition_name_suffix
1240 << " is mapped on device mapper: " << *device;
1241 return DynamicPartitionDeviceStatus::SUCCESS;
1242 }
1243 LOG(ERROR) << partition_name_suffix << "is mapped but path is unknown.";
1244 return DynamicPartitionDeviceStatus::ERROR;
1245 }
1246 }
1247
Tianjie51a5a392020-06-03 14:39:32 -07001248 bool force_writable = (slot != current_slot) && !not_in_payload;
Yifan Hong3a1a5612019-11-05 16:34:32 -08001249 if (MapPartitionOnDeviceMapper(
1250 super_device, partition_name_suffix, slot, force_writable, device)) {
1251 return DynamicPartitionDeviceStatus::SUCCESS;
1252 }
1253 return DynamicPartitionDeviceStatus::ERROR;
1254}
1255
Yifan Hong6eec9952019-12-04 13:12:01 -08001256void DynamicPartitionControlAndroid::set_fake_mapped_devices(
1257 const std::set<std::string>& fake) {
1258 mapped_devices_ = fake;
1259}
1260
Yifan Hongbae27842019-10-24 16:56:12 -07001261bool DynamicPartitionControlAndroid::IsRecovery() {
Kelvin Zhanga22ef552020-10-12 19:03:52 -04001262 return constants::kIsRecovery;
Yifan Hongbae27842019-10-24 16:56:12 -07001263}
1264
1265static bool IsIncrementalUpdate(const DeltaArchiveManifest& manifest) {
1266 const auto& partitions = manifest.partitions();
1267 return std::any_of(partitions.begin(), partitions.end(), [](const auto& p) {
1268 return p.has_old_partition_info();
1269 });
1270}
1271
1272bool DynamicPartitionControlAndroid::DeleteSourcePartitions(
1273 MetadataBuilder* builder,
1274 uint32_t source_slot,
1275 const DeltaArchiveManifest& manifest) {
1276 TEST_AND_RETURN_FALSE(IsRecovery());
1277
1278 if (IsIncrementalUpdate(manifest)) {
1279 LOG(ERROR) << "Cannot sideload incremental OTA because snapshots cannot "
1280 << "be created.";
1281 if (GetVirtualAbFeatureFlag().IsLaunch()) {
1282 LOG(ERROR) << "Sideloading incremental updates on devices launches "
1283 << " Virtual A/B is not supported.";
1284 }
1285 return false;
1286 }
1287
1288 LOG(INFO) << "Will overwrite existing partitions. Slot "
1289 << BootControlInterface::SlotName(source_slot)
Tianjie9f4dc7f2021-03-15 16:00:50 -07001290 << " may be unbootable until update finishes!";
Yifan Hongbae27842019-10-24 16:56:12 -07001291 const std::string source_suffix = SlotSuffixForSlotNumber(source_slot);
1292 DeleteGroupsWithSuffix(builder, source_suffix);
1293
1294 return true;
1295}
1296
Yifan Hong90965502020-02-19 15:22:47 -08001297std::unique_ptr<AbstractAction>
1298DynamicPartitionControlAndroid::GetCleanupPreviousUpdateAction(
1299 BootControlInterface* boot_control,
1300 PrefsInterface* prefs,
1301 CleanupPreviousUpdateActionDelegateInterface* delegate) {
1302 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1303 return std::make_unique<NoOpAction>();
1304 }
1305 return std::make_unique<CleanupPreviousUpdateAction>(
1306 prefs, boot_control, snapshot_.get(), delegate);
1307}
1308
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001309bool DynamicPartitionControlAndroid::ResetUpdate(PrefsInterface* prefs) {
1310 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1311 return true;
1312 }
Kelvin Zhangff5380b2022-03-16 13:35:04 -07001313 for (auto& list : dynamic_partition_list_) {
1314 list.clear();
1315 }
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001316
1317 LOG(INFO) << __func__ << " resetting update state and deleting snapshots.";
1318 TEST_AND_RETURN_FALSE(prefs != nullptr);
1319
1320 // If the device has already booted into the target slot,
1321 // ResetUpdateProgress may pass but CancelUpdate fails.
1322 // This is expected. A scheduled CleanupPreviousUpdateAction should free
1323 // space when it is done.
Daniel Zhengf9784802023-06-08 08:39:48 -07001324 TEST_AND_RETURN_FALSE(DeltaPerformer::ResetUpdateProgress(
1325 prefs, false /* quick */, false /* skip dynamic partitions metadata */));
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001326
Yifan Hong4d7c5eb2020-04-03 11:31:50 -07001327 if (ExpectMetadataMounted()) {
1328 TEST_AND_RETURN_FALSE(snapshot_->CancelUpdate());
1329 } else {
1330 LOG(INFO) << "Skip cancelling update in ResetUpdate because /metadata is "
1331 << "not mounted";
1332 }
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001333
1334 return true;
1335}
1336
Tianjie99d570d2020-06-04 14:57:19 -07001337bool DynamicPartitionControlAndroid::ListDynamicPartitionsForSlot(
Tianjie3a55fc22021-02-13 16:02:22 -08001338 uint32_t slot,
1339 uint32_t current_slot,
1340 std::vector<std::string>* partitions) {
Kelvin Zhangebd115e2021-03-08 16:10:25 -05001341 CHECK(slot == source_slot_ || target_slot_ != UINT32_MAX)
1342 << " source slot: " << source_slot_ << " target slot: " << target_slot_
1343 << " slot: " << slot
1344 << " attempting to query dynamic partition metadata for target slot "
1345 "before PreparePartitionForUpdate() is called. The "
1346 "metadata in target slot isn't valid until "
1347 "PreparePartitionForUpdate() is called, contining execution would "
1348 "likely cause problems.";
Tianjie3a55fc22021-02-13 16:02:22 -08001349 bool slot_enables_dynamic_partitions =
1350 GetDynamicPartitionsFeatureFlag().IsEnabled();
1351 // Check if the target slot has dynamic partitions, this may happen when
1352 // applying a retrofit package.
1353 if (slot != current_slot) {
1354 slot_enables_dynamic_partitions =
1355 slot_enables_dynamic_partitions && is_target_dynamic_;
1356 }
1357
1358 if (!slot_enables_dynamic_partitions) {
1359 LOG(INFO) << "Dynamic partition is not enabled for slot " << slot;
1360 return true;
Tianjie99d570d2020-06-04 14:57:19 -07001361 }
1362
1363 std::string device_dir_str;
1364 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
1365 base::FilePath device_dir(device_dir_str);
Tianjie3a55fc22021-02-13 16:02:22 -08001366 auto super_device = device_dir.Append(GetSuperPartitionName(slot)).value();
1367 auto builder = LoadMetadataBuilder(super_device, slot);
Tianjie99d570d2020-06-04 14:57:19 -07001368 TEST_AND_RETURN_FALSE(builder != nullptr);
1369
1370 std::vector<std::string> result;
Tianjie3a55fc22021-02-13 16:02:22 -08001371 auto suffix = SlotSuffixForSlotNumber(slot);
Tianjie99d570d2020-06-04 14:57:19 -07001372 for (const auto& group : builder->ListGroups()) {
1373 for (const auto& partition : builder->ListPartitionsInGroup(group)) {
1374 std::string_view partition_name = partition->name();
1375 if (!android::base::ConsumeSuffix(&partition_name, suffix)) {
1376 continue;
1377 }
1378 result.emplace_back(partition_name);
1379 }
1380 }
1381 *partitions = std::move(result);
1382 return true;
1383}
1384
Tianjie24f96092020-06-30 12:26:25 -07001385bool DynamicPartitionControlAndroid::VerifyExtentsForUntouchedPartitions(
1386 uint32_t source_slot,
1387 uint32_t target_slot,
1388 const std::vector<std::string>& partitions) {
1389 std::string device_dir_str;
1390 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
1391 base::FilePath device_dir(device_dir_str);
1392
1393 auto source_super_device =
1394 device_dir.Append(GetSuperPartitionName(source_slot)).value();
1395 auto source_builder = LoadMetadataBuilder(source_super_device, source_slot);
1396 TEST_AND_RETURN_FALSE(source_builder != nullptr);
1397
1398 auto target_super_device =
1399 device_dir.Append(GetSuperPartitionName(target_slot)).value();
1400 auto target_builder = LoadMetadataBuilder(target_super_device, target_slot);
1401 TEST_AND_RETURN_FALSE(target_builder != nullptr);
1402
1403 return MetadataBuilder::VerifyExtentsAgainstSourceMetadata(
1404 *source_builder, source_slot, *target_builder, target_slot, partitions);
1405}
1406
Yifan Hong4d7c5eb2020-04-03 11:31:50 -07001407bool DynamicPartitionControlAndroid::ExpectMetadataMounted() {
1408 // No need to mount metadata for non-Virtual A/B devices.
1409 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1410 return false;
1411 }
1412 // Intentionally not checking |metadata_device_| in Android mode.
1413 // /metadata should always be mounted in Android mode. If it isn't, let caller
1414 // fails when calling into SnapshotManager.
1415 if (!IsRecovery()) {
1416 return true;
1417 }
1418 // In recovery mode, explicitly check |metadata_device_|.
1419 return metadata_device_ != nullptr;
1420}
1421
1422bool DynamicPartitionControlAndroid::EnsureMetadataMounted() {
1423 // No need to mount metadata for non-Virtual A/B devices.
1424 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1425 return true;
1426 }
1427
1428 if (metadata_device_ == nullptr) {
1429 metadata_device_ = snapshot_->EnsureMetadataMounted();
1430 }
1431 return metadata_device_ != nullptr;
1432}
1433
David Andersona4b7ba62023-05-10 21:41:37 -07001434std::unique_ptr<android::snapshot::ICowWriter>
Kelvin Zhang34618522020-09-28 09:21:02 -04001435DynamicPartitionControlAndroid::OpenCowWriter(
1436 const std::string& partition_name,
1437 const std::optional<std::string>& source_path,
David Andersona4b7ba62023-05-10 21:41:37 -07001438 std::optional<uint64_t> label) {
Kelvin Zhang34618522020-09-28 09:21:02 -04001439 auto suffix = SlotSuffixForSlotNumber(target_slot_);
1440
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -04001441 auto super_device = GetSuperDevice();
1442 if (!super_device.has_value()) {
Kelvin Zhang34618522020-09-28 09:21:02 -04001443 return nullptr;
1444 }
Kelvin Zhang34618522020-09-28 09:21:02 -04001445 CreateLogicalPartitionParams params = {
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -04001446 .block_device = super_device->value(),
Kelvin Zhang34618522020-09-28 09:21:02 -04001447 .metadata_slot = target_slot_,
1448 .partition_name = partition_name + suffix,
1449 .force_writable = true,
Kelvin Zhang877ddbe2020-11-09 13:37:56 -05001450 .timeout_ms = kMapSnapshotTimeout};
Kelvin Zhang34618522020-09-28 09:21:02 -04001451 // TODO(zhangkelvin) Open an APPEND mode CowWriter once there's an API to do
1452 // it.
David Andersona4b7ba62023-05-10 21:41:37 -07001453 return snapshot_->OpenSnapshotWriter(params, label);
Kelvin Zhang877ddbe2020-11-09 13:37:56 -05001454} // namespace chromeos_update_engine
Kelvin Zhang34618522020-09-28 09:21:02 -04001455
Kelvin Zhang1a0ed712022-01-26 16:09:05 -08001456std::unique_ptr<FileDescriptor> DynamicPartitionControlAndroid::OpenCowFd(
Kelvin Zhangc82511c2020-11-06 16:01:24 -05001457 const std::string& unsuffixed_partition_name,
1458 const std::optional<std::string>& source_path,
1459 bool is_append) {
David Andersona4b7ba62023-05-10 21:41:37 -07001460 auto cow_writer = OpenCowWriter(
1461 unsuffixed_partition_name, source_path, {kEndOfInstallLabel});
Kelvin Zhangc82511c2020-11-06 16:01:24 -05001462 if (cow_writer == nullptr) {
David Andersona4b7ba62023-05-10 21:41:37 -07001463 LOG(ERROR) << "OpenCowWriter failed";
Kelvin Zhangc82511c2020-11-06 16:01:24 -05001464 return nullptr;
1465 }
David Andersona4b7ba62023-05-10 21:41:37 -07001466 auto fd = cow_writer->OpenFileDescriptor(source_path);
1467 if (fd == nullptr) {
1468 LOG(ERROR) << "ICowReader::OpenFileDescriptor failed";
Kelvin Zhang21a49912021-03-12 14:28:33 -05001469 return nullptr;
1470 }
David Andersona4b7ba62023-05-10 21:41:37 -07001471 return std::make_unique<CowWriterFileDescriptor>(
1472 std::move(cow_writer), std::move(fd), source_path);
Kelvin Zhangc82511c2020-11-06 16:01:24 -05001473}
1474
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -04001475std::optional<base::FilePath> DynamicPartitionControlAndroid::GetSuperDevice() {
1476 std::string device_dir_str;
1477 if (!GetDeviceDir(&device_dir_str)) {
1478 LOG(ERROR) << "Failed to get device dir!";
1479 return {};
1480 }
1481 base::FilePath device_dir(device_dir_str);
1482 auto super_device = device_dir.Append(GetSuperPartitionName(target_slot_));
1483 return super_device;
1484}
1485
1486bool DynamicPartitionControlAndroid::MapAllPartitions() {
Kelvin Zhang877ddbe2020-11-09 13:37:56 -05001487 return snapshot_->MapAllSnapshots(kMapSnapshotTimeout);
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -04001488}
1489
Kelvin Zhangeb9de162020-11-16 15:47:28 -05001490bool DynamicPartitionControlAndroid::IsDynamicPartition(
Kelvin Zhangebd115e2021-03-08 16:10:25 -05001491 const std::string& partition_name, uint32_t slot) {
1492 if (slot >= dynamic_partition_list_.size()) {
1493 LOG(ERROR) << "Seeing unexpected slot # " << slot << " currently assuming "
1494 << dynamic_partition_list_.size() << " slots";
1495 return false;
1496 }
1497 auto& dynamic_partition_list = dynamic_partition_list_[slot];
1498 if (dynamic_partition_list.empty() &&
Kelvin Zhangeb9de162020-11-16 15:47:28 -05001499 GetDynamicPartitionsFeatureFlag().IsEnabled()) {
Tianjie3a55fc22021-02-13 16:02:22 -08001500 // Use the DAP config of the target slot.
1501 CHECK(ListDynamicPartitionsForSlot(
Kelvin Zhangebd115e2021-03-08 16:10:25 -05001502 slot, source_slot_, &dynamic_partition_list));
Kelvin Zhangeb9de162020-11-16 15:47:28 -05001503 }
Kelvin Zhangebd115e2021-03-08 16:10:25 -05001504 return std::find(dynamic_partition_list.begin(),
1505 dynamic_partition_list.end(),
1506 partition_name) != dynamic_partition_list.end();
Kelvin Zhangeb9de162020-11-16 15:47:28 -05001507}
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001508
Yifan Hongb0cbd392021-02-04 11:11:45 -08001509bool DynamicPartitionControlAndroid::UpdateUsesSnapshotCompression() {
Kelvin Zhang741c2d42021-04-13 12:40:38 -04001510 return GetVirtualAbFeatureFlag().IsEnabled() &&
1511 snapshot_->UpdateUsesCompression();
Yifan Hongb0cbd392021-02-04 11:11:45 -08001512}
1513
David Andersone35b4382022-03-08 23:18:29 -08001514FeatureFlag
1515DynamicPartitionControlAndroid::GetVirtualAbUserspaceSnapshotsFeatureFlag() {
1516 return virtual_ab_userspace_snapshots_;
1517}
1518
Yifan Hong537802d2018-08-15 13:15:42 -07001519} // namespace chromeos_update_engine