blob: 79c269c40eaeaff78210d692199993d62e136699 [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
17#include "update_engine/dynamic_partition_control_android.h"
18
Yifan Hong420db9b2019-07-23 20:50:33 -070019#include <chrono> // NOLINT(build/c++11) - using libsnapshot / liblp API
Yifan Hong13d41cb2019-09-16 13:18:22 -070020#include <map>
Yifan Hong537802d2018-08-15 13:15:42 -070021#include <memory>
22#include <set>
23#include <string>
Yifan Hong012508e2019-07-22 18:30:40 -070024#include <vector>
Yifan Hong537802d2018-08-15 13:15:42 -070025
26#include <android-base/properties.h>
27#include <android-base/strings.h>
28#include <base/files/file_util.h>
29#include <base/logging.h>
Yifan Hong012508e2019-07-22 18:30:40 -070030#include <base/strings/string_util.h>
Yifan Hong537802d2018-08-15 13:15:42 -070031#include <bootloader_message/bootloader_message.h>
Yifan Hong012508e2019-07-22 18:30:40 -070032#include <fs_mgr.h>
Yifan Hong537802d2018-08-15 13:15:42 -070033#include <fs_mgr_dm_linear.h>
Yifan Hong3a1a5612019-11-05 16:34:32 -080034#include <fs_mgr_overlayfs.h>
Yifan Hong29692902020-03-26 12:47:05 -070035#include <libavb/libavb.h>
Yifan Hong3a1a5612019-11-05 16:34:32 -080036#include <libdm/dm.h>
Yifan Hong420db9b2019-07-23 20:50:33 -070037#include <libsnapshot/snapshot.h>
Yifan Hongf9cb4492020-04-15 13:00:20 -070038#include <libsnapshot/snapshot_stub.h>
Yifan Hong537802d2018-08-15 13:15:42 -070039
Yifan Hong90965502020-02-19 15:22:47 -080040#include "update_engine/cleanup_previous_update_action.h"
Yifan Hong537802d2018-08-15 13:15:42 -070041#include "update_engine/common/boot_control_interface.h"
42#include "update_engine/common/utils.h"
Yifan Hong012508e2019-07-22 18:30:40 -070043#include "update_engine/dynamic_partition_utils.h"
Yifan Hong6a6d0f12020-03-11 13:20:52 -070044#include "update_engine/payload_consumer/delta_performer.h"
Yifan Hong537802d2018-08-15 13:15:42 -070045
46using android::base::GetBoolProperty;
Yifan Hong29692902020-03-26 12:47:05 -070047using android::base::GetProperty;
Yifan Hong537802d2018-08-15 13:15:42 -070048using android::base::Join;
49using android::dm::DeviceMapper;
50using android::dm::DmDeviceState;
51using android::fs_mgr::CreateLogicalPartition;
David Andersonbb90dfb2019-08-13 14:14:56 -070052using android::fs_mgr::CreateLogicalPartitionParams;
Yifan Hong537802d2018-08-15 13:15:42 -070053using android::fs_mgr::DestroyLogicalPartition;
Yifan Hong29692902020-03-26 12:47:05 -070054using android::fs_mgr::Fstab;
Yifan Hong537802d2018-08-15 13:15:42 -070055using android::fs_mgr::MetadataBuilder;
Yifan Hong012508e2019-07-22 18:30:40 -070056using android::fs_mgr::Partition;
Yifan Hong6e706b12018-11-09 16:50:51 -080057using android::fs_mgr::PartitionOpener;
Yifan Hong012508e2019-07-22 18:30:40 -070058using android::fs_mgr::SlotSuffixForSlotNumber;
Yifan Hongf5261562020-03-10 10:28:10 -070059using android::snapshot::OptimizeSourceCopyOperation;
Yifan Hong0850bca2020-01-16 15:14:07 -080060using android::snapshot::Return;
Yifan Hongf033ecb2020-01-07 18:13:56 -080061using android::snapshot::SnapshotManager;
Yifan Hongf9cb4492020-04-15 13:00:20 -070062using android::snapshot::SnapshotManagerStub;
Yifan Hong2257ee12020-01-13 18:33:00 -080063using android::snapshot::UpdateState;
Yifan Hong537802d2018-08-15 13:15:42 -070064
65namespace chromeos_update_engine {
66
Yifan Hong6e706b12018-11-09 16:50:51 -080067constexpr char kUseDynamicPartitions[] = "ro.boot.dynamic_partitions";
68constexpr char kRetrfoitDynamicPartitions[] =
69 "ro.boot.dynamic_partitions_retrofit";
Yifan Hong413d5722019-07-23 14:21:09 -070070constexpr char kVirtualAbEnabled[] = "ro.virtual_ab.enabled";
71constexpr char kVirtualAbRetrofit[] = "ro.virtual_ab.retrofit";
Yifan Hong29692902020-03-26 12:47:05 -070072constexpr char kPostinstallFstabPrefix[] = "ro.postinstall.fstab.prefix";
Yifan Hong420db9b2019-07-23 20:50:33 -070073// Map timeout for dynamic partitions.
74constexpr std::chrono::milliseconds kMapTimeout{1000};
75// Map timeout for dynamic partitions with snapshots. Since several devices
76// needs to be mapped, this timeout is longer than |kMapTimeout|.
77constexpr std::chrono::milliseconds kMapSnapshotTimeout{5000};
78
Yifan Hongbae27842019-10-24 16:56:12 -070079#ifdef __ANDROID_RECOVERY__
80constexpr bool kIsRecovery = true;
81#else
82constexpr bool kIsRecovery = false;
83#endif
84
Yifan Hong537802d2018-08-15 13:15:42 -070085DynamicPartitionControlAndroid::~DynamicPartitionControlAndroid() {
Yifan Hongbae27842019-10-24 16:56:12 -070086 Cleanup();
Yifan Hong537802d2018-08-15 13:15:42 -070087}
88
Yifan Hong186bb682019-07-23 14:04:39 -070089static FeatureFlag GetFeatureFlag(const char* enable_prop,
90 const char* retrofit_prop) {
91 bool retrofit = GetBoolProperty(retrofit_prop, false);
92 bool enabled = GetBoolProperty(enable_prop, false);
93 if (retrofit && !enabled) {
94 LOG(ERROR) << retrofit_prop << " is true but " << enable_prop
95 << " is not. These sysprops are inconsistent. Assume that "
96 << enable_prop << " is true from now on.";
97 }
98 if (retrofit) {
99 return FeatureFlag(FeatureFlag::Value::RETROFIT);
100 }
101 if (enabled) {
102 return FeatureFlag(FeatureFlag::Value::LAUNCH);
103 }
104 return FeatureFlag(FeatureFlag::Value::NONE);
Yifan Hong537802d2018-08-15 13:15:42 -0700105}
106
Yifan Hongb38e1af2019-10-17 14:59:22 -0700107DynamicPartitionControlAndroid::DynamicPartitionControlAndroid()
108 : dynamic_partitions_(
109 GetFeatureFlag(kUseDynamicPartitions, kRetrfoitDynamicPartitions)),
110 virtual_ab_(GetFeatureFlag(kVirtualAbEnabled, kVirtualAbRetrofit)) {
111 if (GetVirtualAbFeatureFlag().IsEnabled()) {
Yifan Hongf033ecb2020-01-07 18:13:56 -0800112 snapshot_ = SnapshotManager::New();
Yifan Hongf9cb4492020-04-15 13:00:20 -0700113 } else {
114 snapshot_ = SnapshotManagerStub::New();
Yifan Hongb38e1af2019-10-17 14:59:22 -0700115 }
Yifan Hongf9cb4492020-04-15 13:00:20 -0700116 CHECK(snapshot_ != nullptr) << "Cannot initialize SnapshotManager.";
Yifan Hongb38e1af2019-10-17 14:59:22 -0700117}
118
Yifan Hong186bb682019-07-23 14:04:39 -0700119FeatureFlag DynamicPartitionControlAndroid::GetDynamicPartitionsFeatureFlag() {
Yifan Hongb38e1af2019-10-17 14:59:22 -0700120 return dynamic_partitions_;
Yifan Hong6e706b12018-11-09 16:50:51 -0800121}
122
Yifan Hong413d5722019-07-23 14:21:09 -0700123FeatureFlag DynamicPartitionControlAndroid::GetVirtualAbFeatureFlag() {
Yifan Hongb38e1af2019-10-17 14:59:22 -0700124 return virtual_ab_;
Yifan Hong413d5722019-07-23 14:21:09 -0700125}
126
Yifan Hongf5261562020-03-10 10:28:10 -0700127bool DynamicPartitionControlAndroid::OptimizeOperation(
128 const std::string& partition_name,
129 const InstallOperation& operation,
130 InstallOperation* optimized) {
Alessio Balsini2a3b4a22019-11-25 16:46:51 +0000131 switch (operation.type()) {
132 case InstallOperation::SOURCE_COPY:
133 return target_supports_snapshot_ &&
134 GetVirtualAbFeatureFlag().IsEnabled() &&
Yifan Hong6eec9952019-12-04 13:12:01 -0800135 mapped_devices_.count(partition_name +
136 SlotSuffixForSlotNumber(target_slot_)) > 0 &&
Yifan Hongf5261562020-03-10 10:28:10 -0700137 OptimizeSourceCopyOperation(operation, optimized);
Alessio Balsini2a3b4a22019-11-25 16:46:51 +0000138 break;
139 default:
140 break;
141 }
Alessio Balsini14980e22019-11-26 11:46:06 +0000142 return false;
143}
144
Yifan Hong8546a712019-03-28 14:42:53 -0700145bool DynamicPartitionControlAndroid::MapPartitionInternal(
Yifan Hong537802d2018-08-15 13:15:42 -0700146 const std::string& super_device,
147 const std::string& target_partition_name,
148 uint32_t slot,
Yifan Hongaf65ef12018-10-29 11:09:06 -0700149 bool force_writable,
Yifan Hong537802d2018-08-15 13:15:42 -0700150 std::string* path) {
David Andersonbb90dfb2019-08-13 14:14:56 -0700151 CreateLogicalPartitionParams params = {
152 .block_device = super_device,
153 .metadata_slot = slot,
154 .partition_name = target_partition_name,
155 .force_writable = force_writable,
David Andersonbb90dfb2019-08-13 14:14:56 -0700156 };
Yifan Hong420db9b2019-07-23 20:50:33 -0700157 bool success = false;
Yifan Hongf0f4a912019-09-26 17:51:33 -0700158 if (GetVirtualAbFeatureFlag().IsEnabled() && target_supports_snapshot_ &&
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700159 force_writable && ExpectMetadataMounted()) {
Yifan Hong420db9b2019-07-23 20:50:33 -0700160 // Only target partitions are mapped with force_writable. On Virtual
161 // A/B devices, target partitions may overlap with source partitions, so
162 // they must be mapped with snapshot.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700163 // One exception is when /metadata is not mounted. Fallback to
164 // CreateLogicalPartition as snapshots are not created in the first place.
Yifan Hong420db9b2019-07-23 20:50:33 -0700165 params.timeout_ms = kMapSnapshotTimeout;
166 success = snapshot_->MapUpdateSnapshot(params, path);
167 } else {
168 params.timeout_ms = kMapTimeout;
169 success = CreateLogicalPartition(params, path);
170 }
David Andersonbb90dfb2019-08-13 14:14:56 -0700171
Yifan Hong420db9b2019-07-23 20:50:33 -0700172 if (!success) {
Yifan Hong537802d2018-08-15 13:15:42 -0700173 LOG(ERROR) << "Cannot map " << target_partition_name << " in "
174 << super_device << " on device mapper.";
175 return false;
176 }
177 LOG(INFO) << "Succesfully mapped " << target_partition_name
Yifan Hongaf65ef12018-10-29 11:09:06 -0700178 << " to device mapper (force_writable = " << force_writable
179 << "); device path at " << *path;
Yifan Hong537802d2018-08-15 13:15:42 -0700180 mapped_devices_.insert(target_partition_name);
181 return true;
182}
183
Yifan Hong8546a712019-03-28 14:42:53 -0700184bool DynamicPartitionControlAndroid::MapPartitionOnDeviceMapper(
185 const std::string& super_device,
186 const std::string& target_partition_name,
187 uint32_t slot,
188 bool force_writable,
189 std::string* path) {
190 DmDeviceState state = GetState(target_partition_name);
191 if (state == DmDeviceState::ACTIVE) {
192 if (mapped_devices_.find(target_partition_name) != mapped_devices_.end()) {
193 if (GetDmDevicePathByName(target_partition_name, path)) {
194 LOG(INFO) << target_partition_name
195 << " is mapped on device mapper: " << *path;
196 return true;
197 }
198 LOG(ERROR) << target_partition_name << " is mapped but path is unknown.";
199 return false;
200 }
201 // If target_partition_name is not in mapped_devices_ but state is ACTIVE,
202 // the device might be mapped incorrectly before. Attempt to unmap it.
203 // Note that for source partitions, if GetState() == ACTIVE, callers (e.g.
204 // BootControlAndroid) should not call MapPartitionOnDeviceMapper, but
205 // should directly call GetDmDevicePathByName.
David Anderson4c891c92019-06-21 17:45:23 -0700206 if (!UnmapPartitionOnDeviceMapper(target_partition_name)) {
Yifan Hong8546a712019-03-28 14:42:53 -0700207 LOG(ERROR) << target_partition_name
208 << " is mapped before the update, and it cannot be unmapped.";
209 return false;
210 }
211 state = GetState(target_partition_name);
212 if (state != DmDeviceState::INVALID) {
213 LOG(ERROR) << target_partition_name << " is unmapped but state is "
214 << static_cast<std::underlying_type_t<DmDeviceState>>(state);
215 return false;
216 }
217 }
218 if (state == DmDeviceState::INVALID) {
219 return MapPartitionInternal(
220 super_device, target_partition_name, slot, force_writable, path);
221 }
222
223 LOG(ERROR) << target_partition_name
224 << " is mapped on device mapper but state is unknown: "
225 << static_cast<std::underlying_type_t<DmDeviceState>>(state);
226 return false;
227}
228
Yifan Hong537802d2018-08-15 13:15:42 -0700229bool DynamicPartitionControlAndroid::UnmapPartitionOnDeviceMapper(
David Anderson4c891c92019-06-21 17:45:23 -0700230 const std::string& target_partition_name) {
Yifan Hong537802d2018-08-15 13:15:42 -0700231 if (DeviceMapper::Instance().GetState(target_partition_name) !=
232 DmDeviceState::INVALID) {
Yifan Hong420db9b2019-07-23 20:50:33 -0700233 // Partitions at target slot on non-Virtual A/B devices are mapped as
234 // dm-linear. Also, on Virtual A/B devices, system_other may be mapped for
235 // preopt apps as dm-linear.
236 // Call DestroyLogicalPartition to handle these cases.
237 bool success = DestroyLogicalPartition(target_partition_name);
238
239 // On a Virtual A/B device, |target_partition_name| may be a leftover from
240 // a paused update. Clean up any underlying devices.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700241 if (ExpectMetadataMounted()) {
Yifan Hong420db9b2019-07-23 20:50:33 -0700242 success &= snapshot_->UnmapUpdateSnapshot(target_partition_name);
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700243 } else {
244 LOG(INFO) << "Skip UnmapUpdateSnapshot(" << target_partition_name
245 << ") because metadata is not mounted";
Yifan Hong420db9b2019-07-23 20:50:33 -0700246 }
247
248 if (!success) {
Yifan Hong537802d2018-08-15 13:15:42 -0700249 LOG(ERROR) << "Cannot unmap " << target_partition_name
250 << " from device mapper.";
251 return false;
252 }
253 LOG(INFO) << "Successfully unmapped " << target_partition_name
254 << " from device mapper.";
255 }
256 mapped_devices_.erase(target_partition_name);
257 return true;
258}
259
Yifan Hongbae27842019-10-24 16:56:12 -0700260void DynamicPartitionControlAndroid::UnmapAllPartitions() {
Tao Bao8c4d0082019-08-08 08:56:16 -0700261 if (mapped_devices_.empty()) {
262 return;
263 }
Yifan Hong537802d2018-08-15 13:15:42 -0700264 // UnmapPartitionOnDeviceMapper removes objects from mapped_devices_, hence
265 // a copy is needed for the loop.
266 std::set<std::string> mapped = mapped_devices_;
267 LOG(INFO) << "Destroying [" << Join(mapped, ", ") << "] from device mapper";
268 for (const auto& partition_name : mapped) {
David Anderson4c891c92019-06-21 17:45:23 -0700269 ignore_result(UnmapPartitionOnDeviceMapper(partition_name));
Yifan Hong537802d2018-08-15 13:15:42 -0700270 }
271}
272
273void DynamicPartitionControlAndroid::Cleanup() {
Yifan Hongbae27842019-10-24 16:56:12 -0700274 UnmapAllPartitions();
275 metadata_device_.reset();
Yifan Hong537802d2018-08-15 13:15:42 -0700276}
277
278bool DynamicPartitionControlAndroid::DeviceExists(const std::string& path) {
279 return base::PathExists(base::FilePath(path));
280}
281
282android::dm::DmDeviceState DynamicPartitionControlAndroid::GetState(
283 const std::string& name) {
284 return DeviceMapper::Instance().GetState(name);
285}
286
287bool DynamicPartitionControlAndroid::GetDmDevicePathByName(
288 const std::string& name, std::string* path) {
289 return DeviceMapper::Instance().GetDmDevicePathByName(name, path);
290}
291
292std::unique_ptr<MetadataBuilder>
293DynamicPartitionControlAndroid::LoadMetadataBuilder(
Yifan Hong012508e2019-07-22 18:30:40 -0700294 const std::string& super_device, uint32_t source_slot) {
295 return LoadMetadataBuilder(
296 super_device, source_slot, BootControlInterface::kInvalidSlot);
297}
298
299std::unique_ptr<MetadataBuilder>
300DynamicPartitionControlAndroid::LoadMetadataBuilder(
Yifan Hong6e706b12018-11-09 16:50:51 -0800301 const std::string& super_device,
302 uint32_t source_slot,
303 uint32_t target_slot) {
Yifan Hong30fa5f52019-08-05 16:39:59 -0700304 std::unique_ptr<MetadataBuilder> builder;
305 if (target_slot == BootControlInterface::kInvalidSlot) {
306 builder =
307 MetadataBuilder::New(PartitionOpener(), super_device, source_slot);
308 } else {
Yifan Hong50a56c62019-10-14 19:35:05 -0700309 bool always_keep_source_slot = !target_supports_snapshot_;
310 builder = MetadataBuilder::NewForUpdate(PartitionOpener(),
311 super_device,
312 source_slot,
313 target_slot,
314 always_keep_source_slot);
Yifan Hong30fa5f52019-08-05 16:39:59 -0700315 }
Yifan Hong6e706b12018-11-09 16:50:51 -0800316
Yifan Hong537802d2018-08-15 13:15:42 -0700317 if (builder == nullptr) {
318 LOG(WARNING) << "No metadata slot "
319 << BootControlInterface::SlotName(source_slot) << " in "
320 << super_device;
Yifan Hongf48a0052018-10-29 16:30:43 -0700321 return nullptr;
Yifan Hong537802d2018-08-15 13:15:42 -0700322 }
323 LOG(INFO) << "Loaded metadata from slot "
324 << BootControlInterface::SlotName(source_slot) << " in "
325 << super_device;
326 return builder;
327}
328
329bool DynamicPartitionControlAndroid::StoreMetadata(
330 const std::string& super_device,
331 MetadataBuilder* builder,
332 uint32_t target_slot) {
333 auto metadata = builder->Export();
334 if (metadata == nullptr) {
335 LOG(ERROR) << "Cannot export metadata to slot "
336 << BootControlInterface::SlotName(target_slot) << " in "
337 << super_device;
338 return false;
339 }
340
Yifan Hong186bb682019-07-23 14:04:39 -0700341 if (GetDynamicPartitionsFeatureFlag().IsRetrofit()) {
Yifan Hong6e706b12018-11-09 16:50:51 -0800342 if (!FlashPartitionTable(super_device, *metadata)) {
343 LOG(ERROR) << "Cannot write metadata to " << super_device;
344 return false;
345 }
346 LOG(INFO) << "Written metadata to " << super_device;
347 } else {
348 if (!UpdatePartitionTable(super_device, *metadata, target_slot)) {
349 LOG(ERROR) << "Cannot write metadata to slot "
350 << BootControlInterface::SlotName(target_slot) << " in "
351 << super_device;
352 return false;
353 }
354 LOG(INFO) << "Copied metadata to slot "
355 << BootControlInterface::SlotName(target_slot) << " in "
356 << super_device;
Yifan Hong537802d2018-08-15 13:15:42 -0700357 }
358
Yifan Hong537802d2018-08-15 13:15:42 -0700359 return true;
360}
361
362bool DynamicPartitionControlAndroid::GetDeviceDir(std::string* out) {
363 // We can't use fs_mgr to look up |partition_name| because fstab
364 // doesn't list every slot partition (it uses the slotselect option
365 // to mask the suffix).
366 //
367 // We can however assume that there's an entry for the /misc mount
368 // point and use that to get the device file for the misc
369 // partition. This helps us locate the disk that |partition_name|
370 // resides on. From there we'll assume that a by-name scheme is used
371 // so we can just replace the trailing "misc" by the given
372 // |partition_name| and suffix corresponding to |slot|, e.g.
373 //
374 // /dev/block/platform/soc.0/7824900.sdhci/by-name/misc ->
375 // /dev/block/platform/soc.0/7824900.sdhci/by-name/boot_a
376 //
377 // If needed, it's possible to relax the by-name assumption in the
378 // future by trawling /sys/block looking for the appropriate sibling
379 // of misc and then finding an entry in /dev matching the sysfs
380 // entry.
381
382 std::string err, misc_device = get_bootloader_message_blk_device(&err);
383 if (misc_device.empty()) {
384 LOG(ERROR) << "Unable to get misc block device: " << err;
385 return false;
386 }
387
388 if (!utils::IsSymlink(misc_device.c_str())) {
389 LOG(ERROR) << "Device file " << misc_device << " for /misc "
390 << "is not a symlink.";
391 return false;
392 }
393 *out = base::FilePath(misc_device).DirName().value();
394 return true;
395}
Yifan Hong012508e2019-07-22 18:30:40 -0700396
397bool DynamicPartitionControlAndroid::PreparePartitionsForUpdate(
398 uint32_t source_slot,
399 uint32_t target_slot,
Yifan Hongf0f4a912019-09-26 17:51:33 -0700400 const DeltaArchiveManifest& manifest,
Yifan Hongf033ecb2020-01-07 18:13:56 -0800401 bool update,
402 uint64_t* required_size) {
Yifan Hong6eec9952019-12-04 13:12:01 -0800403 source_slot_ = source_slot;
404 target_slot_ = target_slot;
Yifan Hongf033ecb2020-01-07 18:13:56 -0800405 if (required_size != nullptr) {
406 *required_size = 0;
407 }
Yifan Hong6eec9952019-12-04 13:12:01 -0800408
Yifan Hong3a1a5612019-11-05 16:34:32 -0800409 if (fs_mgr_overlayfs_is_setup()) {
410 // Non DAP devices can use overlayfs as well.
411 LOG(WARNING)
412 << "overlayfs overrides are active and can interfere with our "
413 "resources.\n"
414 << "run adb enable-verity to deactivate if required and try again.";
415 }
416
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700417 // If metadata is erased but not formatted, it is possible to not mount
418 // it in recovery. It is acceptable to skip mounting and choose fallback path
419 // (PrepareDynamicPartitionsForUpdate) when sideloading full OTAs.
420 TEST_AND_RETURN_FALSE(EnsureMetadataMounted() || IsRecovery());
Yifan Hong29692902020-03-26 12:47:05 -0700421
422 if (update) {
423 TEST_AND_RETURN_FALSE(EraseSystemOtherAvbFooter(source_slot, target_slot));
424 }
425
Yifan Hong3a1a5612019-11-05 16:34:32 -0800426 if (!GetDynamicPartitionsFeatureFlag().IsEnabled()) {
427 return true;
428 }
429
430 if (target_slot == source_slot) {
431 LOG(ERROR) << "Cannot call PreparePartitionsForUpdate on current slot.";
432 return false;
433 }
434
435 // Although the current build supports dynamic partitions, the given payload
436 // doesn't use it for target partitions. This could happen when applying a
437 // retrofit update. Skip updating the partition metadata for the target slot.
438 is_target_dynamic_ = !manifest.dynamic_partition_metadata().groups().empty();
439 if (!is_target_dynamic_) {
440 return true;
441 }
442
Yifan Hongf0f4a912019-09-26 17:51:33 -0700443 target_supports_snapshot_ =
444 manifest.dynamic_partition_metadata().snapshot_enabled();
445
446 if (!update)
447 return true;
448
Yifan Hongbae27842019-10-24 16:56:12 -0700449 bool delete_source = false;
450
Yifan Hong6d888562019-10-01 13:00:31 -0700451 if (GetVirtualAbFeatureFlag().IsEnabled()) {
452 // On Virtual A/B device, either CancelUpdate() or BeginUpdate() must be
453 // called before calling UnmapUpdateSnapshot.
454 // - If target_supports_snapshot_, PrepareSnapshotPartitionsForUpdate()
455 // calls BeginUpdate() which resets update state
Yifan Hongbae27842019-10-24 16:56:12 -0700456 // - If !target_supports_snapshot_ or PrepareSnapshotPartitionsForUpdate
457 // failed in recovery, explicitly CancelUpdate().
Yifan Hong6d888562019-10-01 13:00:31 -0700458 if (target_supports_snapshot_) {
Yifan Hongbae27842019-10-24 16:56:12 -0700459 if (PrepareSnapshotPartitionsForUpdate(
460 source_slot, target_slot, manifest, required_size)) {
461 return true;
462 }
463
464 // Virtual A/B device doing Virtual A/B update in Android mode must use
465 // snapshots.
466 if (!IsRecovery()) {
467 LOG(ERROR) << "PrepareSnapshotPartitionsForUpdate failed in Android "
468 << "mode";
469 return false;
470 }
471
472 delete_source = true;
473 LOG(INFO) << "PrepareSnapshotPartitionsForUpdate failed in recovery. "
474 << "Attempt to overwrite existing partitions if possible";
475 } else {
476 // Downgrading to an non-Virtual A/B build or is secondary OTA.
477 LOG(INFO) << "Using regular A/B on Virtual A/B because package disabled "
478 << "snapshots.";
Yifan Hong6d888562019-10-01 13:00:31 -0700479 }
Yifan Hongbae27842019-10-24 16:56:12 -0700480
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700481 // In recovery, if /metadata is not mounted, it is likely that metadata
482 // partition is erased and not formatted yet. After sideloading, when
483 // rebooting into the new version, init will erase metadata partition,
484 // hence the failure of CancelUpdate() can be ignored here.
485 // However, if metadata is mounted and CancelUpdate fails, sideloading
486 // should not proceed because during next boot, snapshots will overlay on
487 // the devices incorrectly.
488 if (ExpectMetadataMounted()) {
489 TEST_AND_RETURN_FALSE(snapshot_->CancelUpdate());
490 } else {
491 LOG(INFO) << "Skip canceling previous update because metadata is not "
492 << "mounted";
Yifan Hong6d888562019-10-01 13:00:31 -0700493 }
Yifan Hong420db9b2019-07-23 20:50:33 -0700494 }
Yifan Hongbae27842019-10-24 16:56:12 -0700495
Yifan Hong5c5743f2020-04-16 12:59:07 -0700496 TEST_AND_RETURN_FALSE(PrepareDynamicPartitionsForUpdate(
497 source_slot, target_slot, manifest, delete_source));
498
499 if (required_size != nullptr) {
500 *required_size = 0;
501 }
502 return true;
Yifan Hong420db9b2019-07-23 20:50:33 -0700503}
504
Yifan Hong29692902020-03-26 12:47:05 -0700505namespace {
506// Try our best to erase AVB footer.
507class AvbFooterEraser {
508 public:
509 explicit AvbFooterEraser(const std::string& path) : path_(path) {}
510 bool Erase() {
511 // Try to mark the block device read-only. Ignore any
512 // failure since this won't work when passing regular files.
513 ignore_result(utils::SetBlockDeviceReadOnly(path_, false /* readonly */));
514
515 fd_.reset(new EintrSafeFileDescriptor());
516 int flags = O_WRONLY | O_TRUNC | O_CLOEXEC | O_SYNC;
517 TEST_AND_RETURN_FALSE(fd_->Open(path_.c_str(), flags));
518
519 // Need to write end-AVB_FOOTER_SIZE to end.
520 static_assert(AVB_FOOTER_SIZE > 0);
521 off64_t offset = fd_->Seek(-AVB_FOOTER_SIZE, SEEK_END);
522 TEST_AND_RETURN_FALSE_ERRNO(offset >= 0);
523 uint64_t write_size = AVB_FOOTER_SIZE;
524 LOG(INFO) << "Zeroing " << path_ << " @ [" << offset << ", "
525 << (offset + write_size) << "] (" << write_size << " bytes)";
526 brillo::Blob zeros(write_size);
527 TEST_AND_RETURN_FALSE(utils::WriteAll(fd_, zeros.data(), zeros.size()));
528 return true;
529 }
530 ~AvbFooterEraser() {
531 TEST_AND_RETURN(fd_ != nullptr && fd_->IsOpen());
532 if (!fd_->Close()) {
533 LOG(WARNING) << "Failed to close fd for " << path_;
534 }
535 }
536
537 private:
538 std::string path_;
539 FileDescriptorPtr fd_;
540};
541
542} // namespace
543
544std::optional<bool>
545DynamicPartitionControlAndroid::IsAvbEnabledOnSystemOther() {
546 auto prefix = GetProperty(kPostinstallFstabPrefix, "");
547 if (prefix.empty()) {
548 LOG(WARNING) << "Cannot get " << kPostinstallFstabPrefix;
549 return std::nullopt;
550 }
551 auto path = base::FilePath(prefix).Append("etc/fstab.postinstall").value();
552 return IsAvbEnabledInFstab(path);
553}
554
555std::optional<bool> DynamicPartitionControlAndroid::IsAvbEnabledInFstab(
556 const std::string& path) {
557 Fstab fstab;
558 if (!ReadFstabFromFile(path, &fstab)) {
Yifan Hong93cde302020-04-27 12:59:29 -0700559 PLOG(WARNING) << "Cannot read fstab from " << path;
560 if (errno == ENOENT) {
561 return false;
562 }
Yifan Hong29692902020-03-26 12:47:05 -0700563 return std::nullopt;
564 }
565 for (const auto& entry : fstab) {
566 if (!entry.avb_keys.empty()) {
567 return true;
568 }
569 }
570 return false;
571}
572
573bool DynamicPartitionControlAndroid::GetSystemOtherPath(
574 uint32_t source_slot,
575 uint32_t target_slot,
576 const std::string& partition_name_suffix,
577 std::string* path,
578 bool* should_unmap) {
579 path->clear();
580 *should_unmap = false;
581
P.Adarsh Reddy13e4195d2020-06-08 23:17:36 +0530582 // Check that AVB is enabled on system_other before erasing.
583 auto has_avb = IsAvbEnabledOnSystemOther();
584 TEST_AND_RETURN_FALSE(has_avb.has_value());
585 if (!has_avb.value()) {
586 LOG(INFO) << "AVB is not enabled on system_other. Skip erasing.";
587 return true;
588 }
Yifan Hong29692902020-03-26 12:47:05 -0700589
P.Adarsh Reddy13e4195d2020-06-08 23:17:36 +0530590 if (!IsRecovery()) {
Yifan Hong29692902020-03-26 12:47:05 -0700591 // Found unexpected avb_keys for system_other on devices retrofitting
592 // dynamic partitions. Previous crash in update_engine may leave logical
593 // partitions mapped on physical system_other partition. It is difficult to
594 // handle these cases. Just fail.
595 if (GetDynamicPartitionsFeatureFlag().IsRetrofit()) {
596 LOG(ERROR) << "Cannot erase AVB footer on system_other on devices with "
597 << "retrofit dynamic partitions. They should not have AVB "
598 << "enabled on system_other.";
599 return false;
600 }
601 }
602
603 std::string device_dir_str;
604 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
605 base::FilePath device_dir(device_dir_str);
606
607 // On devices without dynamic partition, search for static partitions.
608 if (!GetDynamicPartitionsFeatureFlag().IsEnabled()) {
609 *path = device_dir.Append(partition_name_suffix).value();
610 TEST_AND_RETURN_FALSE(DeviceExists(*path));
611 return true;
612 }
613
614 auto source_super_device =
615 device_dir.Append(GetSuperPartitionName(source_slot)).value();
616
617 auto builder = LoadMetadataBuilder(source_super_device, source_slot);
618 if (builder == nullptr) {
619 if (IsRecovery()) {
620 // It might be corrupted for some reason. It should still be able to
621 // sideload.
622 LOG(WARNING) << "Super partition metadata cannot be read from the source "
623 << "slot, skip erasing.";
624 return true;
625 } else {
626 // Device has booted into Android mode, indicating that the super
627 // partition metadata should be there.
628 LOG(ERROR) << "Super partition metadata cannot be read from the source "
629 << "slot. This is unexpected on devices with dynamic "
630 << "partitions enabled.";
631 return false;
632 }
633 }
634 auto p = builder->FindPartition(partition_name_suffix);
635 if (p == nullptr) {
636 // If the source slot is flashed without system_other, it does not exist
637 // in super partition metadata at source slot. It is safe to skip it.
638 LOG(INFO) << "Can't find " << partition_name_suffix
639 << " in metadata source slot, skip erasing.";
640 return true;
641 }
642 // System_other created by flashing tools should be erased.
643 // If partition is created by update_engine (via NewForUpdate), it is a
644 // left-over partition from the previous update and does not contain
645 // system_other, hence there is no need to erase.
646 // Note the reverse is not necessary true. If the flag is not set, we don't
647 // know if the partition is created by update_engine or by flashing tools
648 // because older versions of super partition metadata does not contain this
649 // flag. It is okay to erase the AVB footer anyways.
650 if (p->attributes() & LP_PARTITION_ATTR_UPDATED) {
651 LOG(INFO) << partition_name_suffix
652 << " does not contain system_other, skip erasing.";
653 return true;
654 }
655
Yifan Hong64331b32020-05-13 16:50:40 -0700656 if (p->size() < AVB_FOOTER_SIZE) {
657 LOG(INFO) << partition_name_suffix << " has length " << p->size()
658 << "( < AVB_FOOTER_SIZE " << AVB_FOOTER_SIZE
659 << "), skip erasing.";
660 return true;
661 }
662
Yifan Hong29692902020-03-26 12:47:05 -0700663 // Delete any pre-existing device with name |partition_name_suffix| and
664 // also remove it from |mapped_devices_|.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700665 // In recovery, metadata might not be mounted, and
666 // UnmapPartitionOnDeviceMapper might fail. However,
667 // it is unusual that system_other has already been mapped. Hence, just skip.
Yifan Hong29692902020-03-26 12:47:05 -0700668 TEST_AND_RETURN_FALSE(UnmapPartitionOnDeviceMapper(partition_name_suffix));
669 // Use CreateLogicalPartition directly to avoid mapping with existing
670 // snapshots.
671 CreateLogicalPartitionParams params = {
672 .block_device = source_super_device,
673 .metadata_slot = source_slot,
674 .partition_name = partition_name_suffix,
675 .force_writable = true,
676 .timeout_ms = kMapTimeout,
677 };
678 TEST_AND_RETURN_FALSE(CreateLogicalPartition(params, path));
679 *should_unmap = true;
680 return true;
681}
682
683bool DynamicPartitionControlAndroid::EraseSystemOtherAvbFooter(
684 uint32_t source_slot, uint32_t target_slot) {
685 LOG(INFO) << "Erasing AVB footer of system_other partition before update.";
686
687 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
688 const std::string partition_name_suffix = "system" + target_suffix;
689
690 std::string path;
691 bool should_unmap = false;
692
693 TEST_AND_RETURN_FALSE(GetSystemOtherPath(
694 source_slot, target_slot, partition_name_suffix, &path, &should_unmap));
695
696 if (path.empty()) {
697 return true;
698 }
699
700 bool ret = AvbFooterEraser(path).Erase();
701
702 // Delete |partition_name_suffix| from device mapper and from
703 // |mapped_devices_| again so that it does not interfere with update process.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700704 // In recovery, metadata might not be mounted, and
705 // UnmapPartitionOnDeviceMapper might fail. However, DestroyLogicalPartition
706 // should be called. If DestroyLogicalPartition does fail, it is still okay
707 // to skip the error here and let Prepare*() fail later.
Yifan Hong29692902020-03-26 12:47:05 -0700708 if (should_unmap) {
709 TEST_AND_RETURN_FALSE(UnmapPartitionOnDeviceMapper(partition_name_suffix));
710 }
711
712 return ret;
713}
714
Yifan Hong420db9b2019-07-23 20:50:33 -0700715bool DynamicPartitionControlAndroid::PrepareDynamicPartitionsForUpdate(
716 uint32_t source_slot,
717 uint32_t target_slot,
Yifan Hongbae27842019-10-24 16:56:12 -0700718 const DeltaArchiveManifest& manifest,
719 bool delete_source) {
Yifan Hong012508e2019-07-22 18:30:40 -0700720 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
721
722 // Unmap all the target dynamic partitions because they would become
723 // inconsistent with the new metadata.
Yifan Hong13d41cb2019-09-16 13:18:22 -0700724 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
725 for (const auto& partition_name : group.partition_names()) {
726 if (!UnmapPartitionOnDeviceMapper(partition_name + target_suffix)) {
Yifan Hong012508e2019-07-22 18:30:40 -0700727 return false;
728 }
729 }
730 }
731
732 std::string device_dir_str;
733 if (!GetDeviceDir(&device_dir_str)) {
734 return false;
735 }
736 base::FilePath device_dir(device_dir_str);
737 auto source_device =
Yifan Hong700d7c12019-07-23 20:49:16 -0700738 device_dir.Append(GetSuperPartitionName(source_slot)).value();
Yifan Hong012508e2019-07-22 18:30:40 -0700739
740 auto builder = LoadMetadataBuilder(source_device, source_slot, target_slot);
741 if (builder == nullptr) {
742 LOG(ERROR) << "No metadata at "
743 << BootControlInterface::SlotName(source_slot);
744 return false;
745 }
746
Yifan Hongbae27842019-10-24 16:56:12 -0700747 if (delete_source) {
748 TEST_AND_RETURN_FALSE(
749 DeleteSourcePartitions(builder.get(), source_slot, manifest));
750 }
751
Yifan Hong13d41cb2019-09-16 13:18:22 -0700752 if (!UpdatePartitionMetadata(builder.get(), target_slot, manifest)) {
Yifan Hong012508e2019-07-22 18:30:40 -0700753 return false;
754 }
755
756 auto target_device =
Yifan Hong700d7c12019-07-23 20:49:16 -0700757 device_dir.Append(GetSuperPartitionName(target_slot)).value();
Yifan Hong012508e2019-07-22 18:30:40 -0700758 return StoreMetadata(target_device, builder.get(), target_slot);
759}
760
Yifan Hong420db9b2019-07-23 20:50:33 -0700761bool DynamicPartitionControlAndroid::PrepareSnapshotPartitionsForUpdate(
762 uint32_t source_slot,
763 uint32_t target_slot,
Yifan Hongf033ecb2020-01-07 18:13:56 -0800764 const DeltaArchiveManifest& manifest,
765 uint64_t* required_size) {
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700766 TEST_AND_RETURN_FALSE(ExpectMetadataMounted());
Yifan Hong420db9b2019-07-23 20:50:33 -0700767 if (!snapshot_->BeginUpdate()) {
768 LOG(ERROR) << "Cannot begin new update.";
769 return false;
770 }
Yifan Hongf033ecb2020-01-07 18:13:56 -0800771 auto ret = snapshot_->CreateUpdateSnapshots(manifest);
772 if (!ret) {
773 LOG(ERROR) << "Cannot create update snapshots: " << ret.string();
774 if (required_size != nullptr &&
Yifan Hong0850bca2020-01-16 15:14:07 -0800775 ret.error_code() == Return::ErrorCode::NO_SPACE) {
Yifan Hongf033ecb2020-01-07 18:13:56 -0800776 *required_size = ret.required_size();
777 }
Yifan Hong420db9b2019-07-23 20:50:33 -0700778 return false;
779 }
780 return true;
781}
782
Yifan Hong700d7c12019-07-23 20:49:16 -0700783std::string DynamicPartitionControlAndroid::GetSuperPartitionName(
784 uint32_t slot) {
785 return fs_mgr_get_super_partition_name(slot);
786}
787
Yifan Hong012508e2019-07-22 18:30:40 -0700788bool DynamicPartitionControlAndroid::UpdatePartitionMetadata(
789 MetadataBuilder* builder,
790 uint32_t target_slot,
Yifan Hong13d41cb2019-09-16 13:18:22 -0700791 const DeltaArchiveManifest& manifest) {
Yifan Honga4e7da32019-09-30 18:25:03 -0700792 // If applying downgrade from Virtual A/B to non-Virtual A/B, the left-over
793 // COW group needs to be deleted to ensure there are enough space to create
794 // target partitions.
795 builder->RemoveGroupAndPartitions(android::snapshot::kCowGroupName);
796
Yifan Hong012508e2019-07-22 18:30:40 -0700797 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
798 DeleteGroupsWithSuffix(builder, target_suffix);
799
800 uint64_t total_size = 0;
Yifan Hong13d41cb2019-09-16 13:18:22 -0700801 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
802 total_size += group.size();
Yifan Hong012508e2019-07-22 18:30:40 -0700803 }
804
805 std::string expr;
806 uint64_t allocatable_space = builder->AllocatableSpace();
Yifan Hong186bb682019-07-23 14:04:39 -0700807 if (!GetDynamicPartitionsFeatureFlag().IsRetrofit()) {
Yifan Hong012508e2019-07-22 18:30:40 -0700808 allocatable_space /= 2;
809 expr = "half of ";
810 }
811 if (total_size > allocatable_space) {
812 LOG(ERROR) << "The maximum size of all groups with suffix " << target_suffix
813 << " (" << total_size << ") has exceeded " << expr
814 << "allocatable space for dynamic partitions "
815 << allocatable_space << ".";
816 return false;
817 }
818
Yifan Hong13d41cb2019-09-16 13:18:22 -0700819 // name of partition(e.g. "system") -> size in bytes
820 std::map<std::string, uint64_t> partition_sizes;
821 for (const auto& partition : manifest.partitions()) {
822 partition_sizes.emplace(partition.partition_name(),
823 partition.new_partition_info().size());
824 }
825
826 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
827 auto group_name_suffix = group.name() + target_suffix;
828 if (!builder->AddGroup(group_name_suffix, group.size())) {
Yifan Hong012508e2019-07-22 18:30:40 -0700829 LOG(ERROR) << "Cannot add group " << group_name_suffix << " with size "
Yifan Hong13d41cb2019-09-16 13:18:22 -0700830 << group.size();
Yifan Hong012508e2019-07-22 18:30:40 -0700831 return false;
832 }
833 LOG(INFO) << "Added group " << group_name_suffix << " with size "
Yifan Hong13d41cb2019-09-16 13:18:22 -0700834 << group.size();
Yifan Hong012508e2019-07-22 18:30:40 -0700835
Yifan Hong13d41cb2019-09-16 13:18:22 -0700836 for (const auto& partition_name : group.partition_names()) {
837 auto partition_sizes_it = partition_sizes.find(partition_name);
838 if (partition_sizes_it == partition_sizes.end()) {
839 // TODO(tbao): Support auto-filling partition info for framework-only
840 // OTA.
841 LOG(ERROR) << "dynamic_partition_metadata contains partition "
842 << partition_name << " but it is not part of the manifest. "
843 << "This is not supported.";
844 return false;
845 }
846 uint64_t partition_size = partition_sizes_it->second;
847
848 auto partition_name_suffix = partition_name + target_suffix;
Yifan Hong012508e2019-07-22 18:30:40 -0700849 Partition* p = builder->AddPartition(
850 partition_name_suffix, group_name_suffix, LP_PARTITION_ATTR_READONLY);
851 if (!p) {
852 LOG(ERROR) << "Cannot add partition " << partition_name_suffix
853 << " to group " << group_name_suffix;
854 return false;
855 }
Yifan Hong13d41cb2019-09-16 13:18:22 -0700856 if (!builder->ResizePartition(p, partition_size)) {
Yifan Hong012508e2019-07-22 18:30:40 -0700857 LOG(ERROR) << "Cannot resize partition " << partition_name_suffix
Yifan Hong13d41cb2019-09-16 13:18:22 -0700858 << " to size " << partition_size << ". Not enough space?";
Yifan Hong012508e2019-07-22 18:30:40 -0700859 return false;
860 }
861 LOG(INFO) << "Added partition " << partition_name_suffix << " to group "
Yifan Hong13d41cb2019-09-16 13:18:22 -0700862 << group_name_suffix << " with size " << partition_size;
Yifan Hong012508e2019-07-22 18:30:40 -0700863 }
864 }
865
866 return true;
867}
868
Yifan Hong7b3910a2020-03-24 17:47:32 -0700869bool DynamicPartitionControlAndroid::FinishUpdate(bool powerwash_required) {
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700870 if (ExpectMetadataMounted()) {
871 if (snapshot_->GetUpdateState() == UpdateState::Initiated) {
872 LOG(INFO) << "Snapshot writes are done.";
873 return snapshot_->FinishedSnapshotWrites(powerwash_required);
874 }
875 } else {
876 LOG(INFO) << "Skip FinishedSnapshotWrites() because /metadata is not "
877 << "mounted";
Yifan Hongf0f4a912019-09-26 17:51:33 -0700878 }
879 return true;
Yifan Honga33bca42019-09-03 20:29:45 -0700880}
881
Yifan Hong3a1a5612019-11-05 16:34:32 -0800882bool DynamicPartitionControlAndroid::GetPartitionDevice(
883 const std::string& partition_name,
884 uint32_t slot,
885 uint32_t current_slot,
Tianjie51a5a392020-06-03 14:39:32 -0700886 bool not_in_payload,
887 std::string* device,
888 bool* is_dynamic) {
Yifan Hong3a1a5612019-11-05 16:34:32 -0800889 const auto& partition_name_suffix =
890 partition_name + SlotSuffixForSlotNumber(slot);
891 std::string device_dir_str;
892 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
893 base::FilePath device_dir(device_dir_str);
894
Tianjie51a5a392020-06-03 14:39:32 -0700895 if (is_dynamic) {
896 *is_dynamic = false;
897 }
898
Yifan Hong3a1a5612019-11-05 16:34:32 -0800899 // When looking up target partition devices, treat them as static if the
900 // current payload doesn't encode them as dynamic partitions. This may happen
901 // when applying a retrofit update on top of a dynamic-partitions-enabled
902 // build.
903 if (GetDynamicPartitionsFeatureFlag().IsEnabled() &&
904 (slot == current_slot || is_target_dynamic_)) {
Tianjie51a5a392020-06-03 14:39:32 -0700905 switch (GetDynamicPartitionDevice(device_dir,
906 partition_name_suffix,
907 slot,
908 current_slot,
909 not_in_payload,
910 device)) {
Yifan Hong3a1a5612019-11-05 16:34:32 -0800911 case DynamicPartitionDeviceStatus::SUCCESS:
Tianjie51a5a392020-06-03 14:39:32 -0700912 if (is_dynamic) {
913 *is_dynamic = true;
914 }
Yifan Hong3a1a5612019-11-05 16:34:32 -0800915 return true;
916 case DynamicPartitionDeviceStatus::TRY_STATIC:
917 break;
918 case DynamicPartitionDeviceStatus::ERROR: // fallthrough
919 default:
920 return false;
921 }
922 }
923 base::FilePath path = device_dir.Append(partition_name_suffix);
924 if (!DeviceExists(path.value())) {
925 LOG(ERROR) << "Device file " << path.value() << " does not exist.";
926 return false;
927 }
928
929 *device = path.value();
930 return true;
931}
932
Tianjie51a5a392020-06-03 14:39:32 -0700933bool DynamicPartitionControlAndroid::GetPartitionDevice(
934 const std::string& partition_name,
935 uint32_t slot,
936 uint32_t current_slot,
937 std::string* device) {
938 return GetPartitionDevice(
939 partition_name, slot, current_slot, false, device, nullptr);
940}
941
Yifan Hong3a1a5612019-11-05 16:34:32 -0800942bool DynamicPartitionControlAndroid::IsSuperBlockDevice(
943 const base::FilePath& device_dir,
944 uint32_t current_slot,
945 const std::string& partition_name_suffix) {
946 std::string source_device =
947 device_dir.Append(GetSuperPartitionName(current_slot)).value();
948 auto source_metadata = LoadMetadataBuilder(source_device, current_slot);
949 return source_metadata->HasBlockDevice(partition_name_suffix);
950}
951
952DynamicPartitionControlAndroid::DynamicPartitionDeviceStatus
953DynamicPartitionControlAndroid::GetDynamicPartitionDevice(
954 const base::FilePath& device_dir,
955 const std::string& partition_name_suffix,
956 uint32_t slot,
957 uint32_t current_slot,
Tianjie51a5a392020-06-03 14:39:32 -0700958 bool not_in_payload,
Yifan Hong3a1a5612019-11-05 16:34:32 -0800959 std::string* device) {
960 std::string super_device =
961 device_dir.Append(GetSuperPartitionName(slot)).value();
962
963 auto builder = LoadMetadataBuilder(super_device, slot);
964 if (builder == nullptr) {
965 LOG(ERROR) << "No metadata in slot "
966 << BootControlInterface::SlotName(slot);
967 return DynamicPartitionDeviceStatus::ERROR;
968 }
969 if (builder->FindPartition(partition_name_suffix) == nullptr) {
970 LOG(INFO) << partition_name_suffix
971 << " is not in super partition metadata.";
972
973 if (IsSuperBlockDevice(device_dir, current_slot, partition_name_suffix)) {
974 LOG(ERROR) << "The static partition " << partition_name_suffix
975 << " is a block device for current metadata."
976 << "It cannot be used as a logical partition.";
977 return DynamicPartitionDeviceStatus::ERROR;
978 }
979
980 return DynamicPartitionDeviceStatus::TRY_STATIC;
981 }
982
983 if (slot == current_slot) {
984 if (GetState(partition_name_suffix) != DmDeviceState::ACTIVE) {
985 LOG(WARNING) << partition_name_suffix << " is at current slot but it is "
986 << "not mapped. Now try to map it.";
987 } else {
988 if (GetDmDevicePathByName(partition_name_suffix, device)) {
989 LOG(INFO) << partition_name_suffix
990 << " is mapped on device mapper: " << *device;
991 return DynamicPartitionDeviceStatus::SUCCESS;
992 }
993 LOG(ERROR) << partition_name_suffix << "is mapped but path is unknown.";
994 return DynamicPartitionDeviceStatus::ERROR;
995 }
996 }
997
Tianjie51a5a392020-06-03 14:39:32 -0700998 bool force_writable = (slot != current_slot) && !not_in_payload;
Yifan Hong3a1a5612019-11-05 16:34:32 -0800999 if (MapPartitionOnDeviceMapper(
1000 super_device, partition_name_suffix, slot, force_writable, device)) {
1001 return DynamicPartitionDeviceStatus::SUCCESS;
1002 }
1003 return DynamicPartitionDeviceStatus::ERROR;
1004}
1005
Yifan Hong6eec9952019-12-04 13:12:01 -08001006void DynamicPartitionControlAndroid::set_fake_mapped_devices(
1007 const std::set<std::string>& fake) {
1008 mapped_devices_ = fake;
1009}
1010
Yifan Hongbae27842019-10-24 16:56:12 -07001011bool DynamicPartitionControlAndroid::IsRecovery() {
1012 return kIsRecovery;
1013}
1014
1015static bool IsIncrementalUpdate(const DeltaArchiveManifest& manifest) {
1016 const auto& partitions = manifest.partitions();
1017 return std::any_of(partitions.begin(), partitions.end(), [](const auto& p) {
1018 return p.has_old_partition_info();
1019 });
1020}
1021
1022bool DynamicPartitionControlAndroid::DeleteSourcePartitions(
1023 MetadataBuilder* builder,
1024 uint32_t source_slot,
1025 const DeltaArchiveManifest& manifest) {
1026 TEST_AND_RETURN_FALSE(IsRecovery());
1027
1028 if (IsIncrementalUpdate(manifest)) {
1029 LOG(ERROR) << "Cannot sideload incremental OTA because snapshots cannot "
1030 << "be created.";
1031 if (GetVirtualAbFeatureFlag().IsLaunch()) {
1032 LOG(ERROR) << "Sideloading incremental updates on devices launches "
1033 << " Virtual A/B is not supported.";
1034 }
1035 return false;
1036 }
1037
1038 LOG(INFO) << "Will overwrite existing partitions. Slot "
1039 << BootControlInterface::SlotName(source_slot)
1040 << "may be unbootable until update finishes!";
1041 const std::string source_suffix = SlotSuffixForSlotNumber(source_slot);
1042 DeleteGroupsWithSuffix(builder, source_suffix);
1043
1044 return true;
1045}
1046
Yifan Hong90965502020-02-19 15:22:47 -08001047std::unique_ptr<AbstractAction>
1048DynamicPartitionControlAndroid::GetCleanupPreviousUpdateAction(
1049 BootControlInterface* boot_control,
1050 PrefsInterface* prefs,
1051 CleanupPreviousUpdateActionDelegateInterface* delegate) {
1052 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1053 return std::make_unique<NoOpAction>();
1054 }
1055 return std::make_unique<CleanupPreviousUpdateAction>(
1056 prefs, boot_control, snapshot_.get(), delegate);
1057}
1058
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001059bool DynamicPartitionControlAndroid::ResetUpdate(PrefsInterface* prefs) {
1060 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1061 return true;
1062 }
1063
1064 LOG(INFO) << __func__ << " resetting update state and deleting snapshots.";
1065 TEST_AND_RETURN_FALSE(prefs != nullptr);
1066
1067 // If the device has already booted into the target slot,
1068 // ResetUpdateProgress may pass but CancelUpdate fails.
1069 // This is expected. A scheduled CleanupPreviousUpdateAction should free
1070 // space when it is done.
1071 TEST_AND_RETURN_FALSE(DeltaPerformer::ResetUpdateProgress(
1072 prefs, false /* quick */, false /* skip dynamic partitions metadata */));
1073
Yifan Hong4d7c5eb2020-04-03 11:31:50 -07001074 if (ExpectMetadataMounted()) {
1075 TEST_AND_RETURN_FALSE(snapshot_->CancelUpdate());
1076 } else {
1077 LOG(INFO) << "Skip cancelling update in ResetUpdate because /metadata is "
1078 << "not mounted";
1079 }
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001080
1081 return true;
1082}
1083
Yifan Hong4d7c5eb2020-04-03 11:31:50 -07001084bool DynamicPartitionControlAndroid::ExpectMetadataMounted() {
1085 // No need to mount metadata for non-Virtual A/B devices.
1086 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1087 return false;
1088 }
1089 // Intentionally not checking |metadata_device_| in Android mode.
1090 // /metadata should always be mounted in Android mode. If it isn't, let caller
1091 // fails when calling into SnapshotManager.
1092 if (!IsRecovery()) {
1093 return true;
1094 }
1095 // In recovery mode, explicitly check |metadata_device_|.
1096 return metadata_device_ != nullptr;
1097}
1098
1099bool DynamicPartitionControlAndroid::EnsureMetadataMounted() {
1100 // No need to mount metadata for non-Virtual A/B devices.
1101 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1102 return true;
1103 }
1104
1105 if (metadata_device_ == nullptr) {
1106 metadata_device_ = snapshot_->EnsureMetadataMounted();
1107 }
1108 return metadata_device_ != nullptr;
1109}
1110
Yifan Hong537802d2018-08-15 13:15:42 -07001111} // namespace chromeos_update_engine