blob: e39e7bc7d67385dc6a476b5129f710435ff35858 [file] [log] [blame]
Yifan Hong537802d2018-08-15 13:15:42 -07001//
2// Copyright (C) 2018 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
16
Amin Hassaniec7bc112020-10-29 16:47:58 -070017#include "update_engine/aosp/dynamic_partition_control_android.h"
Yifan Hong537802d2018-08-15 13:15:42 -070018
Kelvin Zhang91d95fa2020-11-05 13:52:00 -050019#include <algorithm>
Yifan Hong420db9b2019-07-23 20:50:33 -070020#include <chrono> // NOLINT(build/c++11) - using libsnapshot / liblp API
Kelvin Zhang34618522020-09-28 09:21:02 -040021#include <cstdint>
Yifan Hong13d41cb2019-09-16 13:18:22 -070022#include <map>
Yifan Hong537802d2018-08-15 13:15:42 -070023#include <memory>
24#include <set>
25#include <string>
Tianjie99d570d2020-06-04 14:57:19 -070026#include <string_view>
27#include <utility>
Yifan Hong012508e2019-07-22 18:30:40 -070028#include <vector>
Yifan Hong537802d2018-08-15 13:15:42 -070029
30#include <android-base/properties.h>
31#include <android-base/strings.h>
32#include <base/files/file_util.h>
33#include <base/logging.h>
Yifan Hong012508e2019-07-22 18:30:40 -070034#include <base/strings/string_util.h>
Yifan Hong3a1293a2021-04-16 13:21:20 -070035#include <base/strings/stringprintf.h>
Yifan Hong537802d2018-08-15 13:15:42 -070036#include <bootloader_message/bootloader_message.h>
Yifan Hong012508e2019-07-22 18:30:40 -070037#include <fs_mgr.h>
Yifan Hong537802d2018-08-15 13:15:42 -070038#include <fs_mgr_dm_linear.h>
Yifan Hong3a1a5612019-11-05 16:34:32 -080039#include <fs_mgr_overlayfs.h>
Yifan Hong29692902020-03-26 12:47:05 -070040#include <libavb/libavb.h>
Yifan Hong3a1a5612019-11-05 16:34:32 -080041#include <libdm/dm.h>
Kelvin Zhang34618522020-09-28 09:21:02 -040042#include <liblp/liblp.h>
43#include <libsnapshot/cow_writer.h>
Yifan Hong420db9b2019-07-23 20:50:33 -070044#include <libsnapshot/snapshot.h>
Yifan Hongf9cb4492020-04-15 13:00:20 -070045#include <libsnapshot/snapshot_stub.h>
Yifan Hong537802d2018-08-15 13:15:42 -070046
Amin Hassaniec7bc112020-10-29 16:47:58 -070047#include "update_engine/aosp/cleanup_previous_update_action.h"
48#include "update_engine/aosp/dynamic_partition_utils.h"
Yifan Hong537802d2018-08-15 13:15:42 -070049#include "update_engine/common/boot_control_interface.h"
Kelvin Zhangb9a5f612021-01-22 14:34:05 -050050#include "update_engine/common/dynamic_partition_control_interface.h"
51#include "update_engine/common/platform_constants.h"
Yifan Hong537802d2018-08-15 13:15:42 -070052#include "update_engine/common/utils.h"
Kelvin Zhang21a49912021-03-12 14:28:33 -050053#include "update_engine/payload_consumer/cow_writer_file_descriptor.h"
Yifan Hong6a6d0f12020-03-11 13:20:52 -070054#include "update_engine/payload_consumer/delta_performer.h"
Yifan Hong537802d2018-08-15 13:15:42 -070055
56using android::base::GetBoolProperty;
Yifan Hong29692902020-03-26 12:47:05 -070057using android::base::GetProperty;
Yifan Hong537802d2018-08-15 13:15:42 -070058using android::base::Join;
59using android::dm::DeviceMapper;
60using android::dm::DmDeviceState;
61using android::fs_mgr::CreateLogicalPartition;
David Andersonbb90dfb2019-08-13 14:14:56 -070062using android::fs_mgr::CreateLogicalPartitionParams;
Yifan Hong537802d2018-08-15 13:15:42 -070063using android::fs_mgr::DestroyLogicalPartition;
Yifan Hong29692902020-03-26 12:47:05 -070064using android::fs_mgr::Fstab;
Yifan Hong537802d2018-08-15 13:15:42 -070065using android::fs_mgr::MetadataBuilder;
Yifan Hong012508e2019-07-22 18:30:40 -070066using android::fs_mgr::Partition;
Yifan Hong6e706b12018-11-09 16:50:51 -080067using android::fs_mgr::PartitionOpener;
Yifan Hong012508e2019-07-22 18:30:40 -070068using android::fs_mgr::SlotSuffixForSlotNumber;
Yifan Hongf5261562020-03-10 10:28:10 -070069using android::snapshot::OptimizeSourceCopyOperation;
Yifan Hong0850bca2020-01-16 15:14:07 -080070using android::snapshot::Return;
Yifan Hongf033ecb2020-01-07 18:13:56 -080071using android::snapshot::SnapshotManager;
Yifan Hongf9cb4492020-04-15 13:00:20 -070072using android::snapshot::SnapshotManagerStub;
Yifan Hong2257ee12020-01-13 18:33:00 -080073using android::snapshot::UpdateState;
Yifan Hong3a1293a2021-04-16 13:21:20 -070074using base::StringPrintf;
Yifan Hong537802d2018-08-15 13:15:42 -070075
76namespace chromeos_update_engine {
77
Yifan Hong6e706b12018-11-09 16:50:51 -080078constexpr char kUseDynamicPartitions[] = "ro.boot.dynamic_partitions";
79constexpr char kRetrfoitDynamicPartitions[] =
80 "ro.boot.dynamic_partitions_retrofit";
Yifan Hong413d5722019-07-23 14:21:09 -070081constexpr char kVirtualAbEnabled[] = "ro.virtual_ab.enabled";
82constexpr char kVirtualAbRetrofit[] = "ro.virtual_ab.retrofit";
Kelvin Zhangda1b3142020-09-24 17:09:02 -040083constexpr char kVirtualAbCompressionEnabled[] =
84 "ro.virtual_ab.compression.enabled";
85
86// Currently, android doesn't have a retrofit prop for VAB Compression. However,
87// struct FeatureFlag forces us to determine if a feature is 'retrofit'. So this
88// is here just to simplify code. Replace it with real retrofit prop name once
89// there is one.
90constexpr char kVirtualAbCompressionRetrofit[] = "";
Yifan Hong29692902020-03-26 12:47:05 -070091constexpr char kPostinstallFstabPrefix[] = "ro.postinstall.fstab.prefix";
Yifan Hong420db9b2019-07-23 20:50:33 -070092// Map timeout for dynamic partitions.
93constexpr std::chrono::milliseconds kMapTimeout{1000};
94// Map timeout for dynamic partitions with snapshots. Since several devices
95// needs to be mapped, this timeout is longer than |kMapTimeout|.
Kelvin Zhangcf3280b2021-09-01 19:36:01 -070096constexpr std::chrono::milliseconds kMapSnapshotTimeout{10000};
Yifan Hong420db9b2019-07-23 20:50:33 -070097
Yifan Hong537802d2018-08-15 13:15:42 -070098DynamicPartitionControlAndroid::~DynamicPartitionControlAndroid() {
Yifan Hongbae27842019-10-24 16:56:12 -070099 Cleanup();
Yifan Hong537802d2018-08-15 13:15:42 -0700100}
101
Yifan Hong186bb682019-07-23 14:04:39 -0700102static FeatureFlag GetFeatureFlag(const char* enable_prop,
103 const char* retrofit_prop) {
Kelvin Zhangda1b3142020-09-24 17:09:02 -0400104 // Default retrofit to false if retrofit_prop is empty.
105 bool retrofit = retrofit_prop && retrofit_prop[0] != '\0' &&
106 GetBoolProperty(retrofit_prop, false);
Yifan Hong186bb682019-07-23 14:04:39 -0700107 bool enabled = GetBoolProperty(enable_prop, false);
108 if (retrofit && !enabled) {
109 LOG(ERROR) << retrofit_prop << " is true but " << enable_prop
110 << " is not. These sysprops are inconsistent. Assume that "
111 << enable_prop << " is true from now on.";
112 }
113 if (retrofit) {
114 return FeatureFlag(FeatureFlag::Value::RETROFIT);
115 }
116 if (enabled) {
117 return FeatureFlag(FeatureFlag::Value::LAUNCH);
118 }
119 return FeatureFlag(FeatureFlag::Value::NONE);
Yifan Hong537802d2018-08-15 13:15:42 -0700120}
121
Kelvin Zhangebd115e2021-03-08 16:10:25 -0500122DynamicPartitionControlAndroid::DynamicPartitionControlAndroid(
123 uint32_t source_slot)
Yifan Hongb38e1af2019-10-17 14:59:22 -0700124 : dynamic_partitions_(
125 GetFeatureFlag(kUseDynamicPartitions, kRetrfoitDynamicPartitions)),
Kelvin Zhangda1b3142020-09-24 17:09:02 -0400126 virtual_ab_(GetFeatureFlag(kVirtualAbEnabled, kVirtualAbRetrofit)),
127 virtual_ab_compression_(GetFeatureFlag(kVirtualAbCompressionEnabled,
Kelvin Zhangebd115e2021-03-08 16:10:25 -0500128 kVirtualAbCompressionRetrofit)),
129 source_slot_(source_slot) {
Yifan Hongb38e1af2019-10-17 14:59:22 -0700130 if (GetVirtualAbFeatureFlag().IsEnabled()) {
Yifan Hongf033ecb2020-01-07 18:13:56 -0800131 snapshot_ = SnapshotManager::New();
Yifan Hongf9cb4492020-04-15 13:00:20 -0700132 } else {
133 snapshot_ = SnapshotManagerStub::New();
Yifan Hongb38e1af2019-10-17 14:59:22 -0700134 }
Yifan Hongf9cb4492020-04-15 13:00:20 -0700135 CHECK(snapshot_ != nullptr) << "Cannot initialize SnapshotManager.";
Yifan Hongb38e1af2019-10-17 14:59:22 -0700136}
137
Yifan Hong186bb682019-07-23 14:04:39 -0700138FeatureFlag DynamicPartitionControlAndroid::GetDynamicPartitionsFeatureFlag() {
Yifan Hongb38e1af2019-10-17 14:59:22 -0700139 return dynamic_partitions_;
Yifan Hong6e706b12018-11-09 16:50:51 -0800140}
141
Yifan Hong413d5722019-07-23 14:21:09 -0700142FeatureFlag DynamicPartitionControlAndroid::GetVirtualAbFeatureFlag() {
Yifan Hongb38e1af2019-10-17 14:59:22 -0700143 return virtual_ab_;
Yifan Hong413d5722019-07-23 14:21:09 -0700144}
145
Kelvin Zhangda1b3142020-09-24 17:09:02 -0400146FeatureFlag
147DynamicPartitionControlAndroid::GetVirtualAbCompressionFeatureFlag() {
Kelvin Zhangb9a5f612021-01-22 14:34:05 -0500148 if constexpr (constants::kIsRecovery) {
149 // Don't attempt VABC in recovery
150 return FeatureFlag(FeatureFlag::Value::NONE);
151 }
Kelvin Zhangda1b3142020-09-24 17:09:02 -0400152 return virtual_ab_compression_;
153}
154
Yifan Hongf5261562020-03-10 10:28:10 -0700155bool DynamicPartitionControlAndroid::OptimizeOperation(
156 const std::string& partition_name,
157 const InstallOperation& operation,
158 InstallOperation* optimized) {
Alessio Balsini2a3b4a22019-11-25 16:46:51 +0000159 switch (operation.type()) {
160 case InstallOperation::SOURCE_COPY:
161 return target_supports_snapshot_ &&
162 GetVirtualAbFeatureFlag().IsEnabled() &&
Yifan Hong6eec9952019-12-04 13:12:01 -0800163 mapped_devices_.count(partition_name +
164 SlotSuffixForSlotNumber(target_slot_)) > 0 &&
Yifan Hongf5261562020-03-10 10:28:10 -0700165 OptimizeSourceCopyOperation(operation, optimized);
Alessio Balsini2a3b4a22019-11-25 16:46:51 +0000166 break;
167 default:
168 break;
169 }
Alessio Balsini14980e22019-11-26 11:46:06 +0000170 return false;
171}
172
Yifan Hong8546a712019-03-28 14:42:53 -0700173bool DynamicPartitionControlAndroid::MapPartitionInternal(
Yifan Hong537802d2018-08-15 13:15:42 -0700174 const std::string& super_device,
175 const std::string& target_partition_name,
176 uint32_t slot,
Yifan Hongaf65ef12018-10-29 11:09:06 -0700177 bool force_writable,
Yifan Hong537802d2018-08-15 13:15:42 -0700178 std::string* path) {
David Andersonbb90dfb2019-08-13 14:14:56 -0700179 CreateLogicalPartitionParams params = {
180 .block_device = super_device,
181 .metadata_slot = slot,
182 .partition_name = target_partition_name,
183 .force_writable = force_writable,
David Andersonbb90dfb2019-08-13 14:14:56 -0700184 };
Yifan Hong420db9b2019-07-23 20:50:33 -0700185 bool success = false;
Yifan Hongf0f4a912019-09-26 17:51:33 -0700186 if (GetVirtualAbFeatureFlag().IsEnabled() && target_supports_snapshot_ &&
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700187 force_writable && ExpectMetadataMounted()) {
Yifan Hong420db9b2019-07-23 20:50:33 -0700188 // Only target partitions are mapped with force_writable. On Virtual
189 // A/B devices, target partitions may overlap with source partitions, so
190 // they must be mapped with snapshot.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700191 // One exception is when /metadata is not mounted. Fallback to
192 // CreateLogicalPartition as snapshots are not created in the first place.
Yifan Hong420db9b2019-07-23 20:50:33 -0700193 params.timeout_ms = kMapSnapshotTimeout;
194 success = snapshot_->MapUpdateSnapshot(params, path);
195 } else {
196 params.timeout_ms = kMapTimeout;
197 success = CreateLogicalPartition(params, path);
198 }
David Andersonbb90dfb2019-08-13 14:14:56 -0700199
Yifan Hong420db9b2019-07-23 20:50:33 -0700200 if (!success) {
Yifan Hong537802d2018-08-15 13:15:42 -0700201 LOG(ERROR) << "Cannot map " << target_partition_name << " in "
202 << super_device << " on device mapper.";
203 return false;
204 }
205 LOG(INFO) << "Succesfully mapped " << target_partition_name
Yifan Hongaf65ef12018-10-29 11:09:06 -0700206 << " to device mapper (force_writable = " << force_writable
207 << "); device path at " << *path;
Yifan Hong537802d2018-08-15 13:15:42 -0700208 mapped_devices_.insert(target_partition_name);
209 return true;
210}
211
Yifan Hong8546a712019-03-28 14:42:53 -0700212bool DynamicPartitionControlAndroid::MapPartitionOnDeviceMapper(
213 const std::string& super_device,
214 const std::string& target_partition_name,
215 uint32_t slot,
216 bool force_writable,
217 std::string* path) {
218 DmDeviceState state = GetState(target_partition_name);
219 if (state == DmDeviceState::ACTIVE) {
220 if (mapped_devices_.find(target_partition_name) != mapped_devices_.end()) {
221 if (GetDmDevicePathByName(target_partition_name, path)) {
222 LOG(INFO) << target_partition_name
223 << " is mapped on device mapper: " << *path;
224 return true;
225 }
226 LOG(ERROR) << target_partition_name << " is mapped but path is unknown.";
227 return false;
228 }
229 // If target_partition_name is not in mapped_devices_ but state is ACTIVE,
230 // the device might be mapped incorrectly before. Attempt to unmap it.
231 // Note that for source partitions, if GetState() == ACTIVE, callers (e.g.
232 // BootControlAndroid) should not call MapPartitionOnDeviceMapper, but
233 // should directly call GetDmDevicePathByName.
David Anderson4c891c92019-06-21 17:45:23 -0700234 if (!UnmapPartitionOnDeviceMapper(target_partition_name)) {
Yifan Hong8546a712019-03-28 14:42:53 -0700235 LOG(ERROR) << target_partition_name
236 << " is mapped before the update, and it cannot be unmapped.";
237 return false;
238 }
239 state = GetState(target_partition_name);
240 if (state != DmDeviceState::INVALID) {
241 LOG(ERROR) << target_partition_name << " is unmapped but state is "
242 << static_cast<std::underlying_type_t<DmDeviceState>>(state);
243 return false;
244 }
245 }
246 if (state == DmDeviceState::INVALID) {
247 return MapPartitionInternal(
248 super_device, target_partition_name, slot, force_writable, path);
249 }
250
251 LOG(ERROR) << target_partition_name
252 << " is mapped on device mapper but state is unknown: "
253 << static_cast<std::underlying_type_t<DmDeviceState>>(state);
254 return false;
255}
256
Yifan Hong537802d2018-08-15 13:15:42 -0700257bool DynamicPartitionControlAndroid::UnmapPartitionOnDeviceMapper(
David Anderson4c891c92019-06-21 17:45:23 -0700258 const std::string& target_partition_name) {
Yifan Hong537802d2018-08-15 13:15:42 -0700259 if (DeviceMapper::Instance().GetState(target_partition_name) !=
260 DmDeviceState::INVALID) {
Yifan Hong420db9b2019-07-23 20:50:33 -0700261 // Partitions at target slot on non-Virtual A/B devices are mapped as
262 // dm-linear. Also, on Virtual A/B devices, system_other may be mapped for
263 // preopt apps as dm-linear.
264 // Call DestroyLogicalPartition to handle these cases.
265 bool success = DestroyLogicalPartition(target_partition_name);
266
267 // On a Virtual A/B device, |target_partition_name| may be a leftover from
268 // a paused update. Clean up any underlying devices.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700269 if (ExpectMetadataMounted()) {
Yifan Hong420db9b2019-07-23 20:50:33 -0700270 success &= snapshot_->UnmapUpdateSnapshot(target_partition_name);
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700271 } else {
272 LOG(INFO) << "Skip UnmapUpdateSnapshot(" << target_partition_name
273 << ") because metadata is not mounted";
Yifan Hong420db9b2019-07-23 20:50:33 -0700274 }
275
276 if (!success) {
Yifan Hong537802d2018-08-15 13:15:42 -0700277 LOG(ERROR) << "Cannot unmap " << target_partition_name
278 << " from device mapper.";
279 return false;
280 }
281 LOG(INFO) << "Successfully unmapped " << target_partition_name
282 << " from device mapper.";
283 }
284 mapped_devices_.erase(target_partition_name);
285 return true;
286}
287
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -0400288bool DynamicPartitionControlAndroid::UnmapAllPartitions() {
Kelvin Zhangf7ef12a2021-03-22 12:59:06 -0400289 snapshot_->UnmapAllSnapshots();
Tao Bao8c4d0082019-08-08 08:56:16 -0700290 if (mapped_devices_.empty()) {
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -0400291 return false;
Tao Bao8c4d0082019-08-08 08:56:16 -0700292 }
Yifan Hong537802d2018-08-15 13:15:42 -0700293 // UnmapPartitionOnDeviceMapper removes objects from mapped_devices_, hence
294 // a copy is needed for the loop.
295 std::set<std::string> mapped = mapped_devices_;
296 LOG(INFO) << "Destroying [" << Join(mapped, ", ") << "] from device mapper";
297 for (const auto& partition_name : mapped) {
David Anderson4c891c92019-06-21 17:45:23 -0700298 ignore_result(UnmapPartitionOnDeviceMapper(partition_name));
Yifan Hong537802d2018-08-15 13:15:42 -0700299 }
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -0400300 return true;
Yifan Hong537802d2018-08-15 13:15:42 -0700301}
302
303void DynamicPartitionControlAndroid::Cleanup() {
Yifan Hongbae27842019-10-24 16:56:12 -0700304 UnmapAllPartitions();
305 metadata_device_.reset();
Yifan Hong537802d2018-08-15 13:15:42 -0700306}
307
308bool DynamicPartitionControlAndroid::DeviceExists(const std::string& path) {
309 return base::PathExists(base::FilePath(path));
310}
311
312android::dm::DmDeviceState DynamicPartitionControlAndroid::GetState(
313 const std::string& name) {
314 return DeviceMapper::Instance().GetState(name);
315}
316
317bool DynamicPartitionControlAndroid::GetDmDevicePathByName(
318 const std::string& name, std::string* path) {
319 return DeviceMapper::Instance().GetDmDevicePathByName(name, path);
320}
321
322std::unique_ptr<MetadataBuilder>
323DynamicPartitionControlAndroid::LoadMetadataBuilder(
Tianjie24f96092020-06-30 12:26:25 -0700324 const std::string& super_device, uint32_t slot) {
325 auto builder = MetadataBuilder::New(PartitionOpener(), super_device, slot);
326 if (builder == nullptr) {
327 LOG(WARNING) << "No metadata slot " << BootControlInterface::SlotName(slot)
328 << " in " << super_device;
329 return nullptr;
330 }
331 LOG(INFO) << "Loaded metadata from slot "
332 << BootControlInterface::SlotName(slot) << " in " << super_device;
333 return builder;
Yifan Hong012508e2019-07-22 18:30:40 -0700334}
335
336std::unique_ptr<MetadataBuilder>
337DynamicPartitionControlAndroid::LoadMetadataBuilder(
Yifan Hong6e706b12018-11-09 16:50:51 -0800338 const std::string& super_device,
339 uint32_t source_slot,
340 uint32_t target_slot) {
Tianjie24f96092020-06-30 12:26:25 -0700341 bool always_keep_source_slot = !target_supports_snapshot_;
342 auto builder = MetadataBuilder::NewForUpdate(PartitionOpener(),
343 super_device,
344 source_slot,
345 target_slot,
346 always_keep_source_slot);
Yifan Hong537802d2018-08-15 13:15:42 -0700347 if (builder == nullptr) {
348 LOG(WARNING) << "No metadata slot "
349 << BootControlInterface::SlotName(source_slot) << " in "
350 << super_device;
Yifan Hongf48a0052018-10-29 16:30:43 -0700351 return nullptr;
Yifan Hong537802d2018-08-15 13:15:42 -0700352 }
Tianjie24f96092020-06-30 12:26:25 -0700353 LOG(INFO) << "Created metadata for new update from slot "
Yifan Hong537802d2018-08-15 13:15:42 -0700354 << BootControlInterface::SlotName(source_slot) << " in "
355 << super_device;
356 return builder;
357}
358
359bool DynamicPartitionControlAndroid::StoreMetadata(
360 const std::string& super_device,
361 MetadataBuilder* builder,
362 uint32_t target_slot) {
363 auto metadata = builder->Export();
364 if (metadata == nullptr) {
365 LOG(ERROR) << "Cannot export metadata to slot "
366 << BootControlInterface::SlotName(target_slot) << " in "
367 << super_device;
368 return false;
369 }
370
Yifan Hong186bb682019-07-23 14:04:39 -0700371 if (GetDynamicPartitionsFeatureFlag().IsRetrofit()) {
Yifan Hong6e706b12018-11-09 16:50:51 -0800372 if (!FlashPartitionTable(super_device, *metadata)) {
373 LOG(ERROR) << "Cannot write metadata to " << super_device;
374 return false;
375 }
376 LOG(INFO) << "Written metadata to " << super_device;
377 } else {
378 if (!UpdatePartitionTable(super_device, *metadata, target_slot)) {
379 LOG(ERROR) << "Cannot write metadata to slot "
380 << BootControlInterface::SlotName(target_slot) << " in "
381 << super_device;
382 return false;
383 }
384 LOG(INFO) << "Copied metadata to slot "
385 << BootControlInterface::SlotName(target_slot) << " in "
386 << super_device;
Yifan Hong537802d2018-08-15 13:15:42 -0700387 }
388
Yifan Hong537802d2018-08-15 13:15:42 -0700389 return true;
390}
391
392bool DynamicPartitionControlAndroid::GetDeviceDir(std::string* out) {
393 // We can't use fs_mgr to look up |partition_name| because fstab
394 // doesn't list every slot partition (it uses the slotselect option
395 // to mask the suffix).
396 //
397 // We can however assume that there's an entry for the /misc mount
398 // point and use that to get the device file for the misc
399 // partition. This helps us locate the disk that |partition_name|
400 // resides on. From there we'll assume that a by-name scheme is used
401 // so we can just replace the trailing "misc" by the given
402 // |partition_name| and suffix corresponding to |slot|, e.g.
403 //
404 // /dev/block/platform/soc.0/7824900.sdhci/by-name/misc ->
405 // /dev/block/platform/soc.0/7824900.sdhci/by-name/boot_a
406 //
407 // If needed, it's possible to relax the by-name assumption in the
408 // future by trawling /sys/block looking for the appropriate sibling
409 // of misc and then finding an entry in /dev matching the sysfs
410 // entry.
411
412 std::string err, misc_device = get_bootloader_message_blk_device(&err);
413 if (misc_device.empty()) {
414 LOG(ERROR) << "Unable to get misc block device: " << err;
415 return false;
416 }
417
418 if (!utils::IsSymlink(misc_device.c_str())) {
419 LOG(ERROR) << "Device file " << misc_device << " for /misc "
420 << "is not a symlink.";
421 return false;
422 }
423 *out = base::FilePath(misc_device).DirName().value();
424 return true;
425}
Yifan Hong012508e2019-07-22 18:30:40 -0700426
427bool DynamicPartitionControlAndroid::PreparePartitionsForUpdate(
428 uint32_t source_slot,
429 uint32_t target_slot,
Yifan Hongf0f4a912019-09-26 17:51:33 -0700430 const DeltaArchiveManifest& manifest,
Yifan Hongf033ecb2020-01-07 18:13:56 -0800431 bool update,
432 uint64_t* required_size) {
Yifan Hong6eec9952019-12-04 13:12:01 -0800433 source_slot_ = source_slot;
434 target_slot_ = target_slot;
Yifan Hongf033ecb2020-01-07 18:13:56 -0800435 if (required_size != nullptr) {
436 *required_size = 0;
437 }
Yifan Hong6eec9952019-12-04 13:12:01 -0800438
Yifan Hong3a1a5612019-11-05 16:34:32 -0800439 if (fs_mgr_overlayfs_is_setup()) {
440 // Non DAP devices can use overlayfs as well.
441 LOG(WARNING)
442 << "overlayfs overrides are active and can interfere with our "
443 "resources.\n"
444 << "run adb enable-verity to deactivate if required and try again.";
445 }
446
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700447 // If metadata is erased but not formatted, it is possible to not mount
448 // it in recovery. It is acceptable to skip mounting and choose fallback path
449 // (PrepareDynamicPartitionsForUpdate) when sideloading full OTAs.
450 TEST_AND_RETURN_FALSE(EnsureMetadataMounted() || IsRecovery());
Yifan Hong29692902020-03-26 12:47:05 -0700451
452 if (update) {
453 TEST_AND_RETURN_FALSE(EraseSystemOtherAvbFooter(source_slot, target_slot));
454 }
455
Yifan Hong3a1a5612019-11-05 16:34:32 -0800456 if (!GetDynamicPartitionsFeatureFlag().IsEnabled()) {
457 return true;
458 }
459
460 if (target_slot == source_slot) {
461 LOG(ERROR) << "Cannot call PreparePartitionsForUpdate on current slot.";
462 return false;
463 }
464
Yifan Hongf6f75c22020-07-31 15:20:25 -0700465 if (!SetTargetBuildVars(manifest)) {
466 return false;
467 }
Kelvin Zhangff5380b2022-03-16 13:35:04 -0700468 for (auto& list : dynamic_partition_list_) {
469 list.clear();
470 }
Yifan Hongf6f75c22020-07-31 15:20:25 -0700471
Yifan Hong3a1a5612019-11-05 16:34:32 -0800472 // Although the current build supports dynamic partitions, the given payload
473 // doesn't use it for target partitions. This could happen when applying a
474 // retrofit update. Skip updating the partition metadata for the target slot.
Yifan Hong3a1a5612019-11-05 16:34:32 -0800475 if (!is_target_dynamic_) {
476 return true;
477 }
478
Yifan Hongf0f4a912019-09-26 17:51:33 -0700479 if (!update)
480 return true;
481
Yifan Hongbae27842019-10-24 16:56:12 -0700482 bool delete_source = false;
483
Yifan Hong6d888562019-10-01 13:00:31 -0700484 if (GetVirtualAbFeatureFlag().IsEnabled()) {
485 // On Virtual A/B device, either CancelUpdate() or BeginUpdate() must be
486 // called before calling UnmapUpdateSnapshot.
487 // - If target_supports_snapshot_, PrepareSnapshotPartitionsForUpdate()
488 // calls BeginUpdate() which resets update state
Yifan Hongbae27842019-10-24 16:56:12 -0700489 // - If !target_supports_snapshot_ or PrepareSnapshotPartitionsForUpdate
490 // failed in recovery, explicitly CancelUpdate().
Yifan Hong6d888562019-10-01 13:00:31 -0700491 if (target_supports_snapshot_) {
Yifan Hongbae27842019-10-24 16:56:12 -0700492 if (PrepareSnapshotPartitionsForUpdate(
493 source_slot, target_slot, manifest, required_size)) {
494 return true;
495 }
496
497 // Virtual A/B device doing Virtual A/B update in Android mode must use
498 // snapshots.
499 if (!IsRecovery()) {
500 LOG(ERROR) << "PrepareSnapshotPartitionsForUpdate failed in Android "
501 << "mode";
502 return false;
503 }
504
505 delete_source = true;
506 LOG(INFO) << "PrepareSnapshotPartitionsForUpdate failed in recovery. "
507 << "Attempt to overwrite existing partitions if possible";
508 } else {
509 // Downgrading to an non-Virtual A/B build or is secondary OTA.
510 LOG(INFO) << "Using regular A/B on Virtual A/B because package disabled "
511 << "snapshots.";
Yifan Hong6d888562019-10-01 13:00:31 -0700512 }
Yifan Hongbae27842019-10-24 16:56:12 -0700513
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700514 // In recovery, if /metadata is not mounted, it is likely that metadata
515 // partition is erased and not formatted yet. After sideloading, when
516 // rebooting into the new version, init will erase metadata partition,
517 // hence the failure of CancelUpdate() can be ignored here.
518 // However, if metadata is mounted and CancelUpdate fails, sideloading
519 // should not proceed because during next boot, snapshots will overlay on
520 // the devices incorrectly.
521 if (ExpectMetadataMounted()) {
522 TEST_AND_RETURN_FALSE(snapshot_->CancelUpdate());
523 } else {
524 LOG(INFO) << "Skip canceling previous update because metadata is not "
525 << "mounted";
Yifan Hong6d888562019-10-01 13:00:31 -0700526 }
Yifan Hong420db9b2019-07-23 20:50:33 -0700527 }
Yifan Hongbae27842019-10-24 16:56:12 -0700528
Tianjie24f96092020-06-30 12:26:25 -0700529 // TODO(xunchang) support partial update on non VAB enabled devices.
Yifan Hong5c5743f2020-04-16 12:59:07 -0700530 TEST_AND_RETURN_FALSE(PrepareDynamicPartitionsForUpdate(
531 source_slot, target_slot, manifest, delete_source));
532
533 if (required_size != nullptr) {
534 *required_size = 0;
535 }
536 return true;
Yifan Hong420db9b2019-07-23 20:50:33 -0700537}
538
Yifan Hongf6f75c22020-07-31 15:20:25 -0700539bool DynamicPartitionControlAndroid::SetTargetBuildVars(
540 const DeltaArchiveManifest& manifest) {
541 // Precondition: current build supports dynamic partition.
542 CHECK(GetDynamicPartitionsFeatureFlag().IsEnabled());
543
544 bool is_target_dynamic =
545 !manifest.dynamic_partition_metadata().groups().empty();
546 bool target_supports_snapshot =
547 manifest.dynamic_partition_metadata().snapshot_enabled();
548
549 if (manifest.partial_update()) {
550 // Partial updates requires DAP. On partial updates that does not involve
551 // dynamic partitions, groups() can be empty, so also assume
552 // is_target_dynamic in this case. This assumption should be safe because we
553 // also check target_supports_snapshot below, which presumably also implies
554 // target build supports dynamic partition.
555 if (!is_target_dynamic) {
556 LOG(INFO) << "Assuming target build supports dynamic partitions for "
557 "partial updates.";
558 is_target_dynamic = true;
559 }
560
561 // Partial updates requires Virtual A/B. Double check that both current
562 // build and target build supports Virtual A/B.
563 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
564 LOG(ERROR) << "Partial update cannot be applied on a device that does "
565 "not support snapshots.";
566 return false;
567 }
568 if (!target_supports_snapshot) {
569 LOG(ERROR) << "Cannot apply partial update to a build that does not "
570 "support snapshots.";
571 return false;
572 }
573 }
574
575 // Store the flags.
576 is_target_dynamic_ = is_target_dynamic;
577 // If !is_target_dynamic_, leave target_supports_snapshot_ unset because
578 // snapshots would not work without dynamic partition.
579 if (is_target_dynamic_) {
580 target_supports_snapshot_ = target_supports_snapshot;
581 }
582 return true;
583}
584
Yifan Hong29692902020-03-26 12:47:05 -0700585namespace {
586// Try our best to erase AVB footer.
587class AvbFooterEraser {
588 public:
589 explicit AvbFooterEraser(const std::string& path) : path_(path) {}
590 bool Erase() {
591 // Try to mark the block device read-only. Ignore any
592 // failure since this won't work when passing regular files.
593 ignore_result(utils::SetBlockDeviceReadOnly(path_, false /* readonly */));
594
595 fd_.reset(new EintrSafeFileDescriptor());
596 int flags = O_WRONLY | O_TRUNC | O_CLOEXEC | O_SYNC;
597 TEST_AND_RETURN_FALSE(fd_->Open(path_.c_str(), flags));
598
599 // Need to write end-AVB_FOOTER_SIZE to end.
600 static_assert(AVB_FOOTER_SIZE > 0);
601 off64_t offset = fd_->Seek(-AVB_FOOTER_SIZE, SEEK_END);
602 TEST_AND_RETURN_FALSE_ERRNO(offset >= 0);
603 uint64_t write_size = AVB_FOOTER_SIZE;
604 LOG(INFO) << "Zeroing " << path_ << " @ [" << offset << ", "
605 << (offset + write_size) << "] (" << write_size << " bytes)";
606 brillo::Blob zeros(write_size);
607 TEST_AND_RETURN_FALSE(utils::WriteAll(fd_, zeros.data(), zeros.size()));
608 return true;
609 }
610 ~AvbFooterEraser() {
611 TEST_AND_RETURN(fd_ != nullptr && fd_->IsOpen());
612 if (!fd_->Close()) {
613 LOG(WARNING) << "Failed to close fd for " << path_;
614 }
615 }
616
617 private:
618 std::string path_;
619 FileDescriptorPtr fd_;
620};
621
622} // namespace
623
624std::optional<bool>
625DynamicPartitionControlAndroid::IsAvbEnabledOnSystemOther() {
626 auto prefix = GetProperty(kPostinstallFstabPrefix, "");
627 if (prefix.empty()) {
628 LOG(WARNING) << "Cannot get " << kPostinstallFstabPrefix;
629 return std::nullopt;
630 }
631 auto path = base::FilePath(prefix).Append("etc/fstab.postinstall").value();
632 return IsAvbEnabledInFstab(path);
633}
634
635std::optional<bool> DynamicPartitionControlAndroid::IsAvbEnabledInFstab(
636 const std::string& path) {
637 Fstab fstab;
638 if (!ReadFstabFromFile(path, &fstab)) {
Yifan Hong93cde302020-04-27 12:59:29 -0700639 PLOG(WARNING) << "Cannot read fstab from " << path;
640 if (errno == ENOENT) {
641 return false;
642 }
Yifan Hong29692902020-03-26 12:47:05 -0700643 return std::nullopt;
644 }
645 for (const auto& entry : fstab) {
646 if (!entry.avb_keys.empty()) {
647 return true;
648 }
649 }
650 return false;
651}
652
653bool DynamicPartitionControlAndroid::GetSystemOtherPath(
654 uint32_t source_slot,
655 uint32_t target_slot,
656 const std::string& partition_name_suffix,
657 std::string* path,
658 bool* should_unmap) {
659 path->clear();
660 *should_unmap = false;
661
P.Adarsh Reddy13e4195d2020-06-08 23:17:36 +0530662 // Check that AVB is enabled on system_other before erasing.
663 auto has_avb = IsAvbEnabledOnSystemOther();
664 TEST_AND_RETURN_FALSE(has_avb.has_value());
665 if (!has_avb.value()) {
666 LOG(INFO) << "AVB is not enabled on system_other. Skip erasing.";
667 return true;
668 }
Yifan Hong29692902020-03-26 12:47:05 -0700669
P.Adarsh Reddy13e4195d2020-06-08 23:17:36 +0530670 if (!IsRecovery()) {
Yifan Hong29692902020-03-26 12:47:05 -0700671 // Found unexpected avb_keys for system_other on devices retrofitting
672 // dynamic partitions. Previous crash in update_engine may leave logical
673 // partitions mapped on physical system_other partition. It is difficult to
674 // handle these cases. Just fail.
675 if (GetDynamicPartitionsFeatureFlag().IsRetrofit()) {
676 LOG(ERROR) << "Cannot erase AVB footer on system_other on devices with "
677 << "retrofit dynamic partitions. They should not have AVB "
678 << "enabled on system_other.";
679 return false;
680 }
681 }
682
683 std::string device_dir_str;
684 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
685 base::FilePath device_dir(device_dir_str);
686
687 // On devices without dynamic partition, search for static partitions.
688 if (!GetDynamicPartitionsFeatureFlag().IsEnabled()) {
689 *path = device_dir.Append(partition_name_suffix).value();
690 TEST_AND_RETURN_FALSE(DeviceExists(*path));
691 return true;
692 }
693
694 auto source_super_device =
695 device_dir.Append(GetSuperPartitionName(source_slot)).value();
696
697 auto builder = LoadMetadataBuilder(source_super_device, source_slot);
698 if (builder == nullptr) {
699 if (IsRecovery()) {
700 // It might be corrupted for some reason. It should still be able to
701 // sideload.
702 LOG(WARNING) << "Super partition metadata cannot be read from the source "
703 << "slot, skip erasing.";
704 return true;
705 } else {
706 // Device has booted into Android mode, indicating that the super
707 // partition metadata should be there.
708 LOG(ERROR) << "Super partition metadata cannot be read from the source "
709 << "slot. This is unexpected on devices with dynamic "
710 << "partitions enabled.";
711 return false;
712 }
713 }
714 auto p = builder->FindPartition(partition_name_suffix);
715 if (p == nullptr) {
716 // If the source slot is flashed without system_other, it does not exist
717 // in super partition metadata at source slot. It is safe to skip it.
718 LOG(INFO) << "Can't find " << partition_name_suffix
719 << " in metadata source slot, skip erasing.";
720 return true;
721 }
722 // System_other created by flashing tools should be erased.
723 // If partition is created by update_engine (via NewForUpdate), it is a
724 // left-over partition from the previous update and does not contain
725 // system_other, hence there is no need to erase.
726 // Note the reverse is not necessary true. If the flag is not set, we don't
727 // know if the partition is created by update_engine or by flashing tools
728 // because older versions of super partition metadata does not contain this
729 // flag. It is okay to erase the AVB footer anyways.
730 if (p->attributes() & LP_PARTITION_ATTR_UPDATED) {
731 LOG(INFO) << partition_name_suffix
732 << " does not contain system_other, skip erasing.";
733 return true;
734 }
735
Yifan Hong64331b32020-05-13 16:50:40 -0700736 if (p->size() < AVB_FOOTER_SIZE) {
737 LOG(INFO) << partition_name_suffix << " has length " << p->size()
738 << "( < AVB_FOOTER_SIZE " << AVB_FOOTER_SIZE
739 << "), skip erasing.";
740 return true;
741 }
742
Yifan Hong29692902020-03-26 12:47:05 -0700743 // Delete any pre-existing device with name |partition_name_suffix| and
744 // also remove it from |mapped_devices_|.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700745 // In recovery, metadata might not be mounted, and
746 // UnmapPartitionOnDeviceMapper might fail. However,
747 // it is unusual that system_other has already been mapped. Hence, just skip.
Yifan Hong29692902020-03-26 12:47:05 -0700748 TEST_AND_RETURN_FALSE(UnmapPartitionOnDeviceMapper(partition_name_suffix));
749 // Use CreateLogicalPartition directly to avoid mapping with existing
750 // snapshots.
751 CreateLogicalPartitionParams params = {
752 .block_device = source_super_device,
753 .metadata_slot = source_slot,
754 .partition_name = partition_name_suffix,
755 .force_writable = true,
756 .timeout_ms = kMapTimeout,
757 };
758 TEST_AND_RETURN_FALSE(CreateLogicalPartition(params, path));
759 *should_unmap = true;
760 return true;
761}
762
763bool DynamicPartitionControlAndroid::EraseSystemOtherAvbFooter(
764 uint32_t source_slot, uint32_t target_slot) {
765 LOG(INFO) << "Erasing AVB footer of system_other partition before update.";
766
767 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
768 const std::string partition_name_suffix = "system" + target_suffix;
769
770 std::string path;
771 bool should_unmap = false;
772
773 TEST_AND_RETURN_FALSE(GetSystemOtherPath(
774 source_slot, target_slot, partition_name_suffix, &path, &should_unmap));
775
776 if (path.empty()) {
777 return true;
778 }
779
780 bool ret = AvbFooterEraser(path).Erase();
781
782 // Delete |partition_name_suffix| from device mapper and from
783 // |mapped_devices_| again so that it does not interfere with update process.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700784 // In recovery, metadata might not be mounted, and
785 // UnmapPartitionOnDeviceMapper might fail. However, DestroyLogicalPartition
786 // should be called. If DestroyLogicalPartition does fail, it is still okay
787 // to skip the error here and let Prepare*() fail later.
Yifan Hong29692902020-03-26 12:47:05 -0700788 if (should_unmap) {
789 TEST_AND_RETURN_FALSE(UnmapPartitionOnDeviceMapper(partition_name_suffix));
790 }
791
792 return ret;
793}
794
Yifan Hong420db9b2019-07-23 20:50:33 -0700795bool DynamicPartitionControlAndroid::PrepareDynamicPartitionsForUpdate(
796 uint32_t source_slot,
797 uint32_t target_slot,
Yifan Hongbae27842019-10-24 16:56:12 -0700798 const DeltaArchiveManifest& manifest,
799 bool delete_source) {
Yifan Hong012508e2019-07-22 18:30:40 -0700800 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
801
802 // Unmap all the target dynamic partitions because they would become
803 // inconsistent with the new metadata.
Yifan Hong13d41cb2019-09-16 13:18:22 -0700804 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
805 for (const auto& partition_name : group.partition_names()) {
806 if (!UnmapPartitionOnDeviceMapper(partition_name + target_suffix)) {
Yifan Hong012508e2019-07-22 18:30:40 -0700807 return false;
808 }
809 }
810 }
811
812 std::string device_dir_str;
Tianjie9f4dc7f2021-03-15 16:00:50 -0700813 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
Yifan Hong012508e2019-07-22 18:30:40 -0700814 base::FilePath device_dir(device_dir_str);
815 auto source_device =
Yifan Hong700d7c12019-07-23 20:49:16 -0700816 device_dir.Append(GetSuperPartitionName(source_slot)).value();
Yifan Hong012508e2019-07-22 18:30:40 -0700817
818 auto builder = LoadMetadataBuilder(source_device, source_slot, target_slot);
819 if (builder == nullptr) {
820 LOG(ERROR) << "No metadata at "
821 << BootControlInterface::SlotName(source_slot);
822 return false;
823 }
824
Yifan Hongbae27842019-10-24 16:56:12 -0700825 if (delete_source) {
826 TEST_AND_RETURN_FALSE(
827 DeleteSourcePartitions(builder.get(), source_slot, manifest));
828 }
829
Tianjie9f4dc7f2021-03-15 16:00:50 -0700830 TEST_AND_RETURN_FALSE(
831 UpdatePartitionMetadata(builder.get(), target_slot, manifest));
Yifan Hong012508e2019-07-22 18:30:40 -0700832
833 auto target_device =
Yifan Hong700d7c12019-07-23 20:49:16 -0700834 device_dir.Append(GetSuperPartitionName(target_slot)).value();
Yifan Hong012508e2019-07-22 18:30:40 -0700835 return StoreMetadata(target_device, builder.get(), target_slot);
836}
837
Yifan Hong3a1293a2021-04-16 13:21:20 -0700838DynamicPartitionControlAndroid::SpaceLimit
839DynamicPartitionControlAndroid::GetSpaceLimit(bool use_snapshot) {
840 // On device retrofitting dynamic partitions, allocatable_space = "super",
841 // where "super" is the sum of all block devices for that slot. Since block
842 // devices are dedicated for the corresponding slot, there's no need to halve
843 // the allocatable space.
844 if (GetDynamicPartitionsFeatureFlag().IsRetrofit())
845 return SpaceLimit::ERROR_IF_EXCEEDED_SUPER;
846
847 // On device launching dynamic partitions w/o VAB, regardless of recovery
848 // sideload, super partition must be big enough to hold both A and B slots of
849 // groups. Hence,
850 // allocatable_space = super / 2
851 if (!GetVirtualAbFeatureFlag().IsEnabled())
852 return SpaceLimit::ERROR_IF_EXCEEDED_HALF_OF_SUPER;
853
854 // Source build supports VAB. Super partition must be big enough to hold
855 // one slot of groups (ERROR_IF_EXCEEDED_SUPER). However, there are cases
856 // where additional warning messages needs to be written.
857
858 // If using snapshot updates, implying that target build also uses VAB,
859 // allocatable_space = super
860 if (use_snapshot)
861 return SpaceLimit::ERROR_IF_EXCEEDED_SUPER;
862
863 // Source build supports VAB but not using snapshot updates. There are
864 // several cases, as listed below.
865 // Sideloading: allocatable_space = super.
866 if (IsRecovery())
867 return SpaceLimit::ERROR_IF_EXCEEDED_SUPER;
868
869 // On launch VAB device, this implies secondary payload.
870 // Technically, we don't have to check anything, but sum(groups) < super
871 // still applies.
872 if (!GetVirtualAbFeatureFlag().IsRetrofit())
873 return SpaceLimit::ERROR_IF_EXCEEDED_SUPER;
874
875 // On retrofit VAB device, either of the following:
876 // - downgrading: allocatable_space = super / 2
877 // - secondary payload: don't check anything
878 // These two cases are indistinguishable,
879 // hence emit warning if sum(groups) > super / 2
880 return SpaceLimit::WARN_IF_EXCEEDED_HALF_OF_SUPER;
881}
882
Tianjie9f4dc7f2021-03-15 16:00:50 -0700883bool DynamicPartitionControlAndroid::CheckSuperPartitionAllocatableSpace(
884 android::fs_mgr::MetadataBuilder* builder,
885 const DeltaArchiveManifest& manifest,
886 bool use_snapshot) {
Yifan Hong3a1293a2021-04-16 13:21:20 -0700887 uint64_t sum_groups = 0;
Tianjie9f4dc7f2021-03-15 16:00:50 -0700888 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
Yifan Hong3a1293a2021-04-16 13:21:20 -0700889 sum_groups += group.size();
Tianjie9f4dc7f2021-03-15 16:00:50 -0700890 }
891
Yifan Hong3a1293a2021-04-16 13:21:20 -0700892 uint64_t full_space = builder->AllocatableSpace();
893 uint64_t half_space = full_space / 2;
894 constexpr const char* fmt =
895 "The maximum size of all groups for the target slot (%" PRIu64
896 ") has exceeded %sallocatable space for dynamic partitions %" PRIu64 ".";
897 switch (GetSpaceLimit(use_snapshot)) {
898 case SpaceLimit::ERROR_IF_EXCEEDED_HALF_OF_SUPER: {
899 if (sum_groups > half_space) {
900 LOG(ERROR) << StringPrintf(fmt, sum_groups, "HALF OF ", half_space);
901 return false;
902 }
903 // If test passes, it implies that the following two conditions also pass.
904 break;
905 }
906 case SpaceLimit::WARN_IF_EXCEEDED_HALF_OF_SUPER: {
907 if (sum_groups > half_space) {
908 LOG(WARNING) << StringPrintf(fmt, sum_groups, "HALF OF ", half_space)
909 << " This is allowed for downgrade or secondary OTA on "
910 "retrofit VAB device.";
911 }
912 // still check sum(groups) < super
913 [[fallthrough]];
914 }
915 case SpaceLimit::ERROR_IF_EXCEEDED_SUPER: {
916 if (sum_groups > full_space) {
917 LOG(ERROR) << base::StringPrintf(fmt, sum_groups, "", full_space);
918 return false;
919 }
920 break;
921 }
Tianjie9f4dc7f2021-03-15 16:00:50 -0700922 }
923
924 return true;
925}
926
Yifan Hong420db9b2019-07-23 20:50:33 -0700927bool DynamicPartitionControlAndroid::PrepareSnapshotPartitionsForUpdate(
928 uint32_t source_slot,
929 uint32_t target_slot,
Yifan Hongf033ecb2020-01-07 18:13:56 -0800930 const DeltaArchiveManifest& manifest,
931 uint64_t* required_size) {
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700932 TEST_AND_RETURN_FALSE(ExpectMetadataMounted());
Tianjie9f4dc7f2021-03-15 16:00:50 -0700933
934 std::string device_dir_str;
935 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
936 base::FilePath device_dir(device_dir_str);
937 auto super_device =
938 device_dir.Append(GetSuperPartitionName(source_slot)).value();
939 auto builder = LoadMetadataBuilder(super_device, source_slot);
940 if (builder == nullptr) {
941 LOG(ERROR) << "No metadata at "
942 << BootControlInterface::SlotName(source_slot);
943 return false;
944 }
945
946 TEST_AND_RETURN_FALSE(
947 CheckSuperPartitionAllocatableSpace(builder.get(), manifest, true));
948
Yifan Hong420db9b2019-07-23 20:50:33 -0700949 if (!snapshot_->BeginUpdate()) {
950 LOG(ERROR) << "Cannot begin new update.";
951 return false;
952 }
Yifan Hongf033ecb2020-01-07 18:13:56 -0800953 auto ret = snapshot_->CreateUpdateSnapshots(manifest);
954 if (!ret) {
955 LOG(ERROR) << "Cannot create update snapshots: " << ret.string();
956 if (required_size != nullptr &&
Yifan Hong0850bca2020-01-16 15:14:07 -0800957 ret.error_code() == Return::ErrorCode::NO_SPACE) {
Yifan Hongf033ecb2020-01-07 18:13:56 -0800958 *required_size = ret.required_size();
959 }
Yifan Hong420db9b2019-07-23 20:50:33 -0700960 return false;
961 }
962 return true;
963}
964
Yifan Hong700d7c12019-07-23 20:49:16 -0700965std::string DynamicPartitionControlAndroid::GetSuperPartitionName(
966 uint32_t slot) {
967 return fs_mgr_get_super_partition_name(slot);
968}
969
Yifan Hong012508e2019-07-22 18:30:40 -0700970bool DynamicPartitionControlAndroid::UpdatePartitionMetadata(
971 MetadataBuilder* builder,
972 uint32_t target_slot,
Yifan Hong13d41cb2019-09-16 13:18:22 -0700973 const DeltaArchiveManifest& manifest) {
Yifan Hong8d6df9a2020-08-13 13:59:54 -0700974 // Check preconditions.
Yifan Hong265a8e32021-04-16 13:30:02 -0700975 if (GetVirtualAbFeatureFlag().IsEnabled()) {
976 CHECK(!target_supports_snapshot_ || IsRecovery())
977 << "Must use snapshot on VAB device when target build supports VAB and "
978 "not sideloading.";
979 LOG_IF(INFO, !target_supports_snapshot_)
980 << "Not using snapshot on VAB device because target build does not "
981 "support snapshot. Secondary or downgrade OTA?";
982 LOG_IF(INFO, IsRecovery())
983 << "Not using snapshot on VAB device because sideloading.";
984 }
Yifan Hong8d6df9a2020-08-13 13:59:54 -0700985
Yifan Honga4e7da32019-09-30 18:25:03 -0700986 // If applying downgrade from Virtual A/B to non-Virtual A/B, the left-over
987 // COW group needs to be deleted to ensure there are enough space to create
988 // target partitions.
989 builder->RemoveGroupAndPartitions(android::snapshot::kCowGroupName);
990
Yifan Hong012508e2019-07-22 18:30:40 -0700991 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
992 DeleteGroupsWithSuffix(builder, target_suffix);
993
Tianjie9f4dc7f2021-03-15 16:00:50 -0700994 TEST_AND_RETURN_FALSE(
995 CheckSuperPartitionAllocatableSpace(builder, manifest, false));
Yifan Hong012508e2019-07-22 18:30:40 -0700996
Yifan Hong13d41cb2019-09-16 13:18:22 -0700997 // name of partition(e.g. "system") -> size in bytes
998 std::map<std::string, uint64_t> partition_sizes;
999 for (const auto& partition : manifest.partitions()) {
1000 partition_sizes.emplace(partition.partition_name(),
1001 partition.new_partition_info().size());
1002 }
1003
1004 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
1005 auto group_name_suffix = group.name() + target_suffix;
1006 if (!builder->AddGroup(group_name_suffix, group.size())) {
Yifan Hong012508e2019-07-22 18:30:40 -07001007 LOG(ERROR) << "Cannot add group " << group_name_suffix << " with size "
Yifan Hong13d41cb2019-09-16 13:18:22 -07001008 << group.size();
Yifan Hong012508e2019-07-22 18:30:40 -07001009 return false;
1010 }
1011 LOG(INFO) << "Added group " << group_name_suffix << " with size "
Yifan Hong13d41cb2019-09-16 13:18:22 -07001012 << group.size();
Yifan Hong012508e2019-07-22 18:30:40 -07001013
Yifan Hong13d41cb2019-09-16 13:18:22 -07001014 for (const auto& partition_name : group.partition_names()) {
1015 auto partition_sizes_it = partition_sizes.find(partition_name);
1016 if (partition_sizes_it == partition_sizes.end()) {
1017 // TODO(tbao): Support auto-filling partition info for framework-only
1018 // OTA.
1019 LOG(ERROR) << "dynamic_partition_metadata contains partition "
1020 << partition_name << " but it is not part of the manifest. "
1021 << "This is not supported.";
1022 return false;
1023 }
1024 uint64_t partition_size = partition_sizes_it->second;
1025
1026 auto partition_name_suffix = partition_name + target_suffix;
Yifan Hong012508e2019-07-22 18:30:40 -07001027 Partition* p = builder->AddPartition(
1028 partition_name_suffix, group_name_suffix, LP_PARTITION_ATTR_READONLY);
1029 if (!p) {
1030 LOG(ERROR) << "Cannot add partition " << partition_name_suffix
1031 << " to group " << group_name_suffix;
1032 return false;
1033 }
Yifan Hong13d41cb2019-09-16 13:18:22 -07001034 if (!builder->ResizePartition(p, partition_size)) {
Yifan Hong012508e2019-07-22 18:30:40 -07001035 LOG(ERROR) << "Cannot resize partition " << partition_name_suffix
Yifan Hong13d41cb2019-09-16 13:18:22 -07001036 << " to size " << partition_size << ". Not enough space?";
Yifan Hong012508e2019-07-22 18:30:40 -07001037 return false;
1038 }
David Anderson0e1c7fd2021-03-08 19:01:59 -08001039 if (p->size() < partition_size) {
1040 LOG(ERROR) << "Partition " << partition_name_suffix
1041 << " was expected to have size " << partition_size
1042 << ", but instead has size " << p->size();
1043 return false;
1044 }
Yifan Hong012508e2019-07-22 18:30:40 -07001045 LOG(INFO) << "Added partition " << partition_name_suffix << " to group "
Yifan Hong13d41cb2019-09-16 13:18:22 -07001046 << group_name_suffix << " with size " << partition_size;
Yifan Hong012508e2019-07-22 18:30:40 -07001047 }
1048 }
1049
1050 return true;
1051}
1052
Yifan Hong7b3910a2020-03-24 17:47:32 -07001053bool DynamicPartitionControlAndroid::FinishUpdate(bool powerwash_required) {
Yifan Hong4d7c5eb2020-04-03 11:31:50 -07001054 if (ExpectMetadataMounted()) {
1055 if (snapshot_->GetUpdateState() == UpdateState::Initiated) {
1056 LOG(INFO) << "Snapshot writes are done.";
1057 return snapshot_->FinishedSnapshotWrites(powerwash_required);
1058 }
1059 } else {
1060 LOG(INFO) << "Skip FinishedSnapshotWrites() because /metadata is not "
1061 << "mounted";
Yifan Hongf0f4a912019-09-26 17:51:33 -07001062 }
1063 return true;
Yifan Honga33bca42019-09-03 20:29:45 -07001064}
1065
Yifan Hong3a1a5612019-11-05 16:34:32 -08001066bool DynamicPartitionControlAndroid::GetPartitionDevice(
1067 const std::string& partition_name,
1068 uint32_t slot,
1069 uint32_t current_slot,
Tianjie51a5a392020-06-03 14:39:32 -07001070 bool not_in_payload,
1071 std::string* device,
1072 bool* is_dynamic) {
Kelvin Zhang66a9ebb2021-01-25 13:35:10 -05001073 auto partition_dev =
1074 GetPartitionDevice(partition_name, slot, current_slot, not_in_payload);
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001075 if (!partition_dev.has_value()) {
Yifan Hong3a1a5612019-11-05 16:34:32 -08001076 return false;
1077 }
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001078 if (device) {
1079 *device = std::move(partition_dev->rw_device_path);
1080 }
1081 if (is_dynamic) {
1082 *is_dynamic = partition_dev->is_dynamic;
1083 }
Yifan Hong3a1a5612019-11-05 16:34:32 -08001084 return true;
1085}
1086
Tianjie51a5a392020-06-03 14:39:32 -07001087bool DynamicPartitionControlAndroid::GetPartitionDevice(
1088 const std::string& partition_name,
1089 uint32_t slot,
1090 uint32_t current_slot,
1091 std::string* device) {
1092 return GetPartitionDevice(
1093 partition_name, slot, current_slot, false, device, nullptr);
1094}
1095
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001096static std::string GetStaticDevicePath(
1097 const base::FilePath& device_dir,
1098 const std::string& partition_name_suffixed) {
1099 base::FilePath path = device_dir.Append(partition_name_suffixed);
1100 return path.value();
1101}
1102
1103std::optional<PartitionDevice>
1104DynamicPartitionControlAndroid::GetPartitionDevice(
1105 const std::string& partition_name,
1106 uint32_t slot,
1107 uint32_t current_slot,
1108 bool not_in_payload) {
1109 std::string device_dir_str;
1110 if (!GetDeviceDir(&device_dir_str)) {
1111 LOG(ERROR) << "Failed to GetDeviceDir()";
1112 return {};
1113 }
1114 const base::FilePath device_dir(device_dir_str);
1115 // When VABC is enabled, we can't get device path for dynamic partitions in
1116 // target slot.
1117 const auto& partition_name_suffix =
1118 partition_name + SlotSuffixForSlotNumber(slot);
Kelvin Zhangebd115e2021-03-08 16:10:25 -05001119 if (UpdateUsesSnapshotCompression() && slot != current_slot &&
1120 IsDynamicPartition(partition_name, slot)) {
Kelvin Zhang91ad6622021-03-01 13:46:17 -05001121 return {
Kelvin Zhanga9b5d8c2021-05-05 09:17:46 -04001122 {.readonly_device_path = base::FilePath{std::string{VABC_DEVICE_DIR}}
1123 .Append(partition_name_suffix)
1124 .value(),
Kelvin Zhang91ad6622021-03-01 13:46:17 -05001125 .is_dynamic = true}};
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001126 }
1127
1128 // When looking up target partition devices, treat them as static if the
1129 // current payload doesn't encode them as dynamic partitions. This may happen
1130 // when applying a retrofit update on top of a dynamic-partitions-enabled
1131 // build.
1132 std::string device;
1133 if (GetDynamicPartitionsFeatureFlag().IsEnabled() &&
1134 (slot == current_slot || is_target_dynamic_)) {
1135 switch (GetDynamicPartitionDevice(device_dir,
1136 partition_name_suffix,
1137 slot,
1138 current_slot,
1139 not_in_payload,
1140 &device)) {
1141 case DynamicPartitionDeviceStatus::SUCCESS:
1142 return {{.rw_device_path = device,
Kelvin Zhanga9b5d8c2021-05-05 09:17:46 -04001143 .readonly_device_path = device,
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001144 .is_dynamic = true}};
1145
1146 case DynamicPartitionDeviceStatus::TRY_STATIC:
1147 break;
1148 case DynamicPartitionDeviceStatus::ERROR: // fallthrough
1149 default:
1150 return {};
1151 }
1152 }
1153 // Try static partitions.
1154 auto static_path = GetStaticDevicePath(device_dir, partition_name_suffix);
1155 if (!DeviceExists(static_path)) {
1156 LOG(ERROR) << "Device file " << static_path << " does not exist.";
1157 return {};
1158 }
1159
1160 return {{.rw_device_path = static_path,
Kelvin Zhanga9b5d8c2021-05-05 09:17:46 -04001161 .readonly_device_path = static_path,
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001162 .is_dynamic = false}};
1163}
1164
Yifan Hong3a1a5612019-11-05 16:34:32 -08001165bool DynamicPartitionControlAndroid::IsSuperBlockDevice(
1166 const base::FilePath& device_dir,
1167 uint32_t current_slot,
1168 const std::string& partition_name_suffix) {
1169 std::string source_device =
1170 device_dir.Append(GetSuperPartitionName(current_slot)).value();
1171 auto source_metadata = LoadMetadataBuilder(source_device, current_slot);
1172 return source_metadata->HasBlockDevice(partition_name_suffix);
1173}
1174
1175DynamicPartitionControlAndroid::DynamicPartitionDeviceStatus
1176DynamicPartitionControlAndroid::GetDynamicPartitionDevice(
1177 const base::FilePath& device_dir,
1178 const std::string& partition_name_suffix,
1179 uint32_t slot,
1180 uint32_t current_slot,
Tianjie51a5a392020-06-03 14:39:32 -07001181 bool not_in_payload,
Yifan Hong3a1a5612019-11-05 16:34:32 -08001182 std::string* device) {
1183 std::string super_device =
1184 device_dir.Append(GetSuperPartitionName(slot)).value();
1185
1186 auto builder = LoadMetadataBuilder(super_device, slot);
1187 if (builder == nullptr) {
1188 LOG(ERROR) << "No metadata in slot "
1189 << BootControlInterface::SlotName(slot);
1190 return DynamicPartitionDeviceStatus::ERROR;
1191 }
1192 if (builder->FindPartition(partition_name_suffix) == nullptr) {
1193 LOG(INFO) << partition_name_suffix
1194 << " is not in super partition metadata.";
1195
1196 if (IsSuperBlockDevice(device_dir, current_slot, partition_name_suffix)) {
1197 LOG(ERROR) << "The static partition " << partition_name_suffix
1198 << " is a block device for current metadata."
1199 << "It cannot be used as a logical partition.";
1200 return DynamicPartitionDeviceStatus::ERROR;
1201 }
1202
1203 return DynamicPartitionDeviceStatus::TRY_STATIC;
1204 }
1205
1206 if (slot == current_slot) {
1207 if (GetState(partition_name_suffix) != DmDeviceState::ACTIVE) {
1208 LOG(WARNING) << partition_name_suffix << " is at current slot but it is "
1209 << "not mapped. Now try to map it.";
1210 } else {
1211 if (GetDmDevicePathByName(partition_name_suffix, device)) {
1212 LOG(INFO) << partition_name_suffix
1213 << " is mapped on device mapper: " << *device;
1214 return DynamicPartitionDeviceStatus::SUCCESS;
1215 }
1216 LOG(ERROR) << partition_name_suffix << "is mapped but path is unknown.";
1217 return DynamicPartitionDeviceStatus::ERROR;
1218 }
1219 }
1220
Tianjie51a5a392020-06-03 14:39:32 -07001221 bool force_writable = (slot != current_slot) && !not_in_payload;
Yifan Hong3a1a5612019-11-05 16:34:32 -08001222 if (MapPartitionOnDeviceMapper(
1223 super_device, partition_name_suffix, slot, force_writable, device)) {
1224 return DynamicPartitionDeviceStatus::SUCCESS;
1225 }
1226 return DynamicPartitionDeviceStatus::ERROR;
1227}
1228
Yifan Hong6eec9952019-12-04 13:12:01 -08001229void DynamicPartitionControlAndroid::set_fake_mapped_devices(
1230 const std::set<std::string>& fake) {
1231 mapped_devices_ = fake;
1232}
1233
Yifan Hongbae27842019-10-24 16:56:12 -07001234bool DynamicPartitionControlAndroid::IsRecovery() {
Kelvin Zhanga22ef552020-10-12 19:03:52 -04001235 return constants::kIsRecovery;
Yifan Hongbae27842019-10-24 16:56:12 -07001236}
1237
1238static bool IsIncrementalUpdate(const DeltaArchiveManifest& manifest) {
1239 const auto& partitions = manifest.partitions();
1240 return std::any_of(partitions.begin(), partitions.end(), [](const auto& p) {
1241 return p.has_old_partition_info();
1242 });
1243}
1244
1245bool DynamicPartitionControlAndroid::DeleteSourcePartitions(
1246 MetadataBuilder* builder,
1247 uint32_t source_slot,
1248 const DeltaArchiveManifest& manifest) {
1249 TEST_AND_RETURN_FALSE(IsRecovery());
1250
1251 if (IsIncrementalUpdate(manifest)) {
1252 LOG(ERROR) << "Cannot sideload incremental OTA because snapshots cannot "
1253 << "be created.";
1254 if (GetVirtualAbFeatureFlag().IsLaunch()) {
1255 LOG(ERROR) << "Sideloading incremental updates on devices launches "
1256 << " Virtual A/B is not supported.";
1257 }
1258 return false;
1259 }
1260
1261 LOG(INFO) << "Will overwrite existing partitions. Slot "
1262 << BootControlInterface::SlotName(source_slot)
Tianjie9f4dc7f2021-03-15 16:00:50 -07001263 << " may be unbootable until update finishes!";
Yifan Hongbae27842019-10-24 16:56:12 -07001264 const std::string source_suffix = SlotSuffixForSlotNumber(source_slot);
1265 DeleteGroupsWithSuffix(builder, source_suffix);
1266
1267 return true;
1268}
1269
Yifan Hong90965502020-02-19 15:22:47 -08001270std::unique_ptr<AbstractAction>
1271DynamicPartitionControlAndroid::GetCleanupPreviousUpdateAction(
1272 BootControlInterface* boot_control,
1273 PrefsInterface* prefs,
1274 CleanupPreviousUpdateActionDelegateInterface* delegate) {
1275 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1276 return std::make_unique<NoOpAction>();
1277 }
1278 return std::make_unique<CleanupPreviousUpdateAction>(
1279 prefs, boot_control, snapshot_.get(), delegate);
1280}
1281
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001282bool DynamicPartitionControlAndroid::ResetUpdate(PrefsInterface* prefs) {
1283 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1284 return true;
1285 }
Kelvin Zhangff5380b2022-03-16 13:35:04 -07001286 for (auto& list : dynamic_partition_list_) {
1287 list.clear();
1288 }
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001289
1290 LOG(INFO) << __func__ << " resetting update state and deleting snapshots.";
1291 TEST_AND_RETURN_FALSE(prefs != nullptr);
1292
1293 // If the device has already booted into the target slot,
1294 // ResetUpdateProgress may pass but CancelUpdate fails.
1295 // This is expected. A scheduled CleanupPreviousUpdateAction should free
1296 // space when it is done.
1297 TEST_AND_RETURN_FALSE(DeltaPerformer::ResetUpdateProgress(
1298 prefs, false /* quick */, false /* skip dynamic partitions metadata */));
1299
Yifan Hong4d7c5eb2020-04-03 11:31:50 -07001300 if (ExpectMetadataMounted()) {
1301 TEST_AND_RETURN_FALSE(snapshot_->CancelUpdate());
1302 } else {
1303 LOG(INFO) << "Skip cancelling update in ResetUpdate because /metadata is "
1304 << "not mounted";
1305 }
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001306
1307 return true;
1308}
1309
Tianjie99d570d2020-06-04 14:57:19 -07001310bool DynamicPartitionControlAndroid::ListDynamicPartitionsForSlot(
Tianjie3a55fc22021-02-13 16:02:22 -08001311 uint32_t slot,
1312 uint32_t current_slot,
1313 std::vector<std::string>* partitions) {
Kelvin Zhangebd115e2021-03-08 16:10:25 -05001314 CHECK(slot == source_slot_ || target_slot_ != UINT32_MAX)
1315 << " source slot: " << source_slot_ << " target slot: " << target_slot_
1316 << " slot: " << slot
1317 << " attempting to query dynamic partition metadata for target slot "
1318 "before PreparePartitionForUpdate() is called. The "
1319 "metadata in target slot isn't valid until "
1320 "PreparePartitionForUpdate() is called, contining execution would "
1321 "likely cause problems.";
Tianjie3a55fc22021-02-13 16:02:22 -08001322 bool slot_enables_dynamic_partitions =
1323 GetDynamicPartitionsFeatureFlag().IsEnabled();
1324 // Check if the target slot has dynamic partitions, this may happen when
1325 // applying a retrofit package.
1326 if (slot != current_slot) {
1327 slot_enables_dynamic_partitions =
1328 slot_enables_dynamic_partitions && is_target_dynamic_;
1329 }
1330
1331 if (!slot_enables_dynamic_partitions) {
1332 LOG(INFO) << "Dynamic partition is not enabled for slot " << slot;
1333 return true;
Tianjie99d570d2020-06-04 14:57:19 -07001334 }
1335
1336 std::string device_dir_str;
1337 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
1338 base::FilePath device_dir(device_dir_str);
Tianjie3a55fc22021-02-13 16:02:22 -08001339 auto super_device = device_dir.Append(GetSuperPartitionName(slot)).value();
1340 auto builder = LoadMetadataBuilder(super_device, slot);
Tianjie99d570d2020-06-04 14:57:19 -07001341 TEST_AND_RETURN_FALSE(builder != nullptr);
1342
1343 std::vector<std::string> result;
Tianjie3a55fc22021-02-13 16:02:22 -08001344 auto suffix = SlotSuffixForSlotNumber(slot);
Tianjie99d570d2020-06-04 14:57:19 -07001345 for (const auto& group : builder->ListGroups()) {
1346 for (const auto& partition : builder->ListPartitionsInGroup(group)) {
1347 std::string_view partition_name = partition->name();
1348 if (!android::base::ConsumeSuffix(&partition_name, suffix)) {
1349 continue;
1350 }
1351 result.emplace_back(partition_name);
1352 }
1353 }
1354 *partitions = std::move(result);
1355 return true;
1356}
1357
Tianjie24f96092020-06-30 12:26:25 -07001358bool DynamicPartitionControlAndroid::VerifyExtentsForUntouchedPartitions(
1359 uint32_t source_slot,
1360 uint32_t target_slot,
1361 const std::vector<std::string>& partitions) {
1362 std::string device_dir_str;
1363 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
1364 base::FilePath device_dir(device_dir_str);
1365
1366 auto source_super_device =
1367 device_dir.Append(GetSuperPartitionName(source_slot)).value();
1368 auto source_builder = LoadMetadataBuilder(source_super_device, source_slot);
1369 TEST_AND_RETURN_FALSE(source_builder != nullptr);
1370
1371 auto target_super_device =
1372 device_dir.Append(GetSuperPartitionName(target_slot)).value();
1373 auto target_builder = LoadMetadataBuilder(target_super_device, target_slot);
1374 TEST_AND_RETURN_FALSE(target_builder != nullptr);
1375
1376 return MetadataBuilder::VerifyExtentsAgainstSourceMetadata(
1377 *source_builder, source_slot, *target_builder, target_slot, partitions);
1378}
1379
Yifan Hong4d7c5eb2020-04-03 11:31:50 -07001380bool DynamicPartitionControlAndroid::ExpectMetadataMounted() {
1381 // No need to mount metadata for non-Virtual A/B devices.
1382 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1383 return false;
1384 }
1385 // Intentionally not checking |metadata_device_| in Android mode.
1386 // /metadata should always be mounted in Android mode. If it isn't, let caller
1387 // fails when calling into SnapshotManager.
1388 if (!IsRecovery()) {
1389 return true;
1390 }
1391 // In recovery mode, explicitly check |metadata_device_|.
1392 return metadata_device_ != nullptr;
1393}
1394
1395bool DynamicPartitionControlAndroid::EnsureMetadataMounted() {
1396 // No need to mount metadata for non-Virtual A/B devices.
1397 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1398 return true;
1399 }
1400
1401 if (metadata_device_ == nullptr) {
1402 metadata_device_ = snapshot_->EnsureMetadataMounted();
1403 }
1404 return metadata_device_ != nullptr;
1405}
1406
Kelvin Zhang34618522020-09-28 09:21:02 -04001407std::unique_ptr<android::snapshot::ISnapshotWriter>
1408DynamicPartitionControlAndroid::OpenCowWriter(
1409 const std::string& partition_name,
1410 const std::optional<std::string>& source_path,
1411 bool is_append) {
1412 auto suffix = SlotSuffixForSlotNumber(target_slot_);
1413
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -04001414 auto super_device = GetSuperDevice();
1415 if (!super_device.has_value()) {
Kelvin Zhang34618522020-09-28 09:21:02 -04001416 return nullptr;
1417 }
Kelvin Zhang34618522020-09-28 09:21:02 -04001418 CreateLogicalPartitionParams params = {
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -04001419 .block_device = super_device->value(),
Kelvin Zhang34618522020-09-28 09:21:02 -04001420 .metadata_slot = target_slot_,
1421 .partition_name = partition_name + suffix,
1422 .force_writable = true,
Kelvin Zhang877ddbe2020-11-09 13:37:56 -05001423 .timeout_ms = kMapSnapshotTimeout};
Kelvin Zhang34618522020-09-28 09:21:02 -04001424 // TODO(zhangkelvin) Open an APPEND mode CowWriter once there's an API to do
1425 // it.
1426 return snapshot_->OpenSnapshotWriter(params, std::move(source_path));
Kelvin Zhang877ddbe2020-11-09 13:37:56 -05001427} // namespace chromeos_update_engine
Kelvin Zhang34618522020-09-28 09:21:02 -04001428
Kelvin Zhang1a0ed712022-01-26 16:09:05 -08001429std::unique_ptr<FileDescriptor> DynamicPartitionControlAndroid::OpenCowFd(
Kelvin Zhangc82511c2020-11-06 16:01:24 -05001430 const std::string& unsuffixed_partition_name,
1431 const std::optional<std::string>& source_path,
1432 bool is_append) {
1433 auto cow_writer =
1434 OpenCowWriter(unsuffixed_partition_name, source_path, is_append);
1435 if (cow_writer == nullptr) {
1436 return nullptr;
1437 }
Kelvin Zhang21a49912021-03-12 14:28:33 -05001438 if (!cow_writer->InitializeAppend(kEndOfInstallLabel)) {
Kelvin Zhang77804b42021-12-30 09:04:54 -08001439 LOG(ERROR) << "Failed to InitializeAppend(" << kEndOfInstallLabel << ")";
Kelvin Zhang21a49912021-03-12 14:28:33 -05001440 return nullptr;
1441 }
Kelvin Zhang77804b42021-12-30 09:04:54 -08001442 auto reader = cow_writer->OpenReader();
1443 if (reader == nullptr) {
1444 LOG(ERROR) << "ICowWriter::OpenReader() failed.";
1445 return nullptr;
1446 }
Kelvin Zhang1a0ed712022-01-26 16:09:05 -08001447 return std::make_unique<CowWriterFileDescriptor>(std::move(cow_writer),
Kelvin Zhang77804b42021-12-30 09:04:54 -08001448 std::move(reader));
Kelvin Zhangc82511c2020-11-06 16:01:24 -05001449}
1450
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -04001451std::optional<base::FilePath> DynamicPartitionControlAndroid::GetSuperDevice() {
1452 std::string device_dir_str;
1453 if (!GetDeviceDir(&device_dir_str)) {
1454 LOG(ERROR) << "Failed to get device dir!";
1455 return {};
1456 }
1457 base::FilePath device_dir(device_dir_str);
1458 auto super_device = device_dir.Append(GetSuperPartitionName(target_slot_));
1459 return super_device;
1460}
1461
1462bool DynamicPartitionControlAndroid::MapAllPartitions() {
Kelvin Zhang877ddbe2020-11-09 13:37:56 -05001463 return snapshot_->MapAllSnapshots(kMapSnapshotTimeout);
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -04001464}
1465
Kelvin Zhangeb9de162020-11-16 15:47:28 -05001466bool DynamicPartitionControlAndroid::IsDynamicPartition(
Kelvin Zhangebd115e2021-03-08 16:10:25 -05001467 const std::string& partition_name, uint32_t slot) {
1468 if (slot >= dynamic_partition_list_.size()) {
1469 LOG(ERROR) << "Seeing unexpected slot # " << slot << " currently assuming "
1470 << dynamic_partition_list_.size() << " slots";
1471 return false;
1472 }
1473 auto& dynamic_partition_list = dynamic_partition_list_[slot];
1474 if (dynamic_partition_list.empty() &&
Kelvin Zhangeb9de162020-11-16 15:47:28 -05001475 GetDynamicPartitionsFeatureFlag().IsEnabled()) {
Tianjie3a55fc22021-02-13 16:02:22 -08001476 // Use the DAP config of the target slot.
1477 CHECK(ListDynamicPartitionsForSlot(
Kelvin Zhangebd115e2021-03-08 16:10:25 -05001478 slot, source_slot_, &dynamic_partition_list));
Kelvin Zhangeb9de162020-11-16 15:47:28 -05001479 }
Kelvin Zhangebd115e2021-03-08 16:10:25 -05001480 return std::find(dynamic_partition_list.begin(),
1481 dynamic_partition_list.end(),
1482 partition_name) != dynamic_partition_list.end();
Kelvin Zhangeb9de162020-11-16 15:47:28 -05001483}
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001484
Yifan Hongb0cbd392021-02-04 11:11:45 -08001485bool DynamicPartitionControlAndroid::UpdateUsesSnapshotCompression() {
Kelvin Zhang741c2d42021-04-13 12:40:38 -04001486 return GetVirtualAbFeatureFlag().IsEnabled() &&
1487 snapshot_->UpdateUsesCompression();
Yifan Hongb0cbd392021-02-04 11:11:45 -08001488}
1489
Yifan Hong537802d2018-08-15 13:15:42 -07001490} // namespace chromeos_update_engine