blob: 7486d095bd3e050f48db2eec7fae5d8d99d585d8 [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
582 // In recovery, just erase no matter what.
583 // - On devices with retrofit dynamic partitions, no logical partitions
584 // should be mounted at this point. Hence it should be safe to erase.
585 // Otherwise, do check that AVB is enabled on system_other before erasing.
586 if (!IsRecovery()) {
587 auto has_avb = IsAvbEnabledOnSystemOther();
588 TEST_AND_RETURN_FALSE(has_avb.has_value());
589 if (!has_avb.value()) {
590 LOG(INFO) << "AVB is not enabled on system_other. Skip erasing.";
591 return true;
592 }
593
594 // Found unexpected avb_keys for system_other on devices retrofitting
595 // dynamic partitions. Previous crash in update_engine may leave logical
596 // partitions mapped on physical system_other partition. It is difficult to
597 // handle these cases. Just fail.
598 if (GetDynamicPartitionsFeatureFlag().IsRetrofit()) {
599 LOG(ERROR) << "Cannot erase AVB footer on system_other on devices with "
600 << "retrofit dynamic partitions. They should not have AVB "
601 << "enabled on system_other.";
602 return false;
603 }
604 }
605
606 std::string device_dir_str;
607 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
608 base::FilePath device_dir(device_dir_str);
609
610 // On devices without dynamic partition, search for static partitions.
611 if (!GetDynamicPartitionsFeatureFlag().IsEnabled()) {
612 *path = device_dir.Append(partition_name_suffix).value();
613 TEST_AND_RETURN_FALSE(DeviceExists(*path));
614 return true;
615 }
616
617 auto source_super_device =
618 device_dir.Append(GetSuperPartitionName(source_slot)).value();
619
620 auto builder = LoadMetadataBuilder(source_super_device, source_slot);
621 if (builder == nullptr) {
622 if (IsRecovery()) {
623 // It might be corrupted for some reason. It should still be able to
624 // sideload.
625 LOG(WARNING) << "Super partition metadata cannot be read from the source "
626 << "slot, skip erasing.";
627 return true;
628 } else {
629 // Device has booted into Android mode, indicating that the super
630 // partition metadata should be there.
631 LOG(ERROR) << "Super partition metadata cannot be read from the source "
632 << "slot. This is unexpected on devices with dynamic "
633 << "partitions enabled.";
634 return false;
635 }
636 }
637 auto p = builder->FindPartition(partition_name_suffix);
638 if (p == nullptr) {
639 // If the source slot is flashed without system_other, it does not exist
640 // in super partition metadata at source slot. It is safe to skip it.
641 LOG(INFO) << "Can't find " << partition_name_suffix
642 << " in metadata source slot, skip erasing.";
643 return true;
644 }
645 // System_other created by flashing tools should be erased.
646 // If partition is created by update_engine (via NewForUpdate), it is a
647 // left-over partition from the previous update and does not contain
648 // system_other, hence there is no need to erase.
649 // Note the reverse is not necessary true. If the flag is not set, we don't
650 // know if the partition is created by update_engine or by flashing tools
651 // because older versions of super partition metadata does not contain this
652 // flag. It is okay to erase the AVB footer anyways.
653 if (p->attributes() & LP_PARTITION_ATTR_UPDATED) {
654 LOG(INFO) << partition_name_suffix
655 << " does not contain system_other, skip erasing.";
656 return true;
657 }
658
659 // Delete any pre-existing device with name |partition_name_suffix| and
660 // also remove it from |mapped_devices_|.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700661 // In recovery, metadata might not be mounted, and
662 // UnmapPartitionOnDeviceMapper might fail. However,
663 // it is unusual that system_other has already been mapped. Hence, just skip.
Yifan Hong29692902020-03-26 12:47:05 -0700664 TEST_AND_RETURN_FALSE(UnmapPartitionOnDeviceMapper(partition_name_suffix));
665 // Use CreateLogicalPartition directly to avoid mapping with existing
666 // snapshots.
667 CreateLogicalPartitionParams params = {
668 .block_device = source_super_device,
669 .metadata_slot = source_slot,
670 .partition_name = partition_name_suffix,
671 .force_writable = true,
672 .timeout_ms = kMapTimeout,
673 };
674 TEST_AND_RETURN_FALSE(CreateLogicalPartition(params, path));
675 *should_unmap = true;
676 return true;
677}
678
679bool DynamicPartitionControlAndroid::EraseSystemOtherAvbFooter(
680 uint32_t source_slot, uint32_t target_slot) {
681 LOG(INFO) << "Erasing AVB footer of system_other partition before update.";
682
683 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
684 const std::string partition_name_suffix = "system" + target_suffix;
685
686 std::string path;
687 bool should_unmap = false;
688
689 TEST_AND_RETURN_FALSE(GetSystemOtherPath(
690 source_slot, target_slot, partition_name_suffix, &path, &should_unmap));
691
692 if (path.empty()) {
693 return true;
694 }
695
696 bool ret = AvbFooterEraser(path).Erase();
697
698 // Delete |partition_name_suffix| from device mapper and from
699 // |mapped_devices_| again so that it does not interfere with update process.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700700 // In recovery, metadata might not be mounted, and
701 // UnmapPartitionOnDeviceMapper might fail. However, DestroyLogicalPartition
702 // should be called. If DestroyLogicalPartition does fail, it is still okay
703 // to skip the error here and let Prepare*() fail later.
Yifan Hong29692902020-03-26 12:47:05 -0700704 if (should_unmap) {
705 TEST_AND_RETURN_FALSE(UnmapPartitionOnDeviceMapper(partition_name_suffix));
706 }
707
708 return ret;
709}
710
Yifan Hong420db9b2019-07-23 20:50:33 -0700711bool DynamicPartitionControlAndroid::PrepareDynamicPartitionsForUpdate(
712 uint32_t source_slot,
713 uint32_t target_slot,
Yifan Hongbae27842019-10-24 16:56:12 -0700714 const DeltaArchiveManifest& manifest,
715 bool delete_source) {
Yifan Hong012508e2019-07-22 18:30:40 -0700716 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
717
718 // Unmap all the target dynamic partitions because they would become
719 // inconsistent with the new metadata.
Yifan Hong13d41cb2019-09-16 13:18:22 -0700720 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
721 for (const auto& partition_name : group.partition_names()) {
722 if (!UnmapPartitionOnDeviceMapper(partition_name + target_suffix)) {
Yifan Hong012508e2019-07-22 18:30:40 -0700723 return false;
724 }
725 }
726 }
727
728 std::string device_dir_str;
729 if (!GetDeviceDir(&device_dir_str)) {
730 return false;
731 }
732 base::FilePath device_dir(device_dir_str);
733 auto source_device =
Yifan Hong700d7c12019-07-23 20:49:16 -0700734 device_dir.Append(GetSuperPartitionName(source_slot)).value();
Yifan Hong012508e2019-07-22 18:30:40 -0700735
736 auto builder = LoadMetadataBuilder(source_device, source_slot, target_slot);
737 if (builder == nullptr) {
738 LOG(ERROR) << "No metadata at "
739 << BootControlInterface::SlotName(source_slot);
740 return false;
741 }
742
Yifan Hongbae27842019-10-24 16:56:12 -0700743 if (delete_source) {
744 TEST_AND_RETURN_FALSE(
745 DeleteSourcePartitions(builder.get(), source_slot, manifest));
746 }
747
Yifan Hong13d41cb2019-09-16 13:18:22 -0700748 if (!UpdatePartitionMetadata(builder.get(), target_slot, manifest)) {
Yifan Hong012508e2019-07-22 18:30:40 -0700749 return false;
750 }
751
752 auto target_device =
Yifan Hong700d7c12019-07-23 20:49:16 -0700753 device_dir.Append(GetSuperPartitionName(target_slot)).value();
Yifan Hong012508e2019-07-22 18:30:40 -0700754 return StoreMetadata(target_device, builder.get(), target_slot);
755}
756
Yifan Hong420db9b2019-07-23 20:50:33 -0700757bool DynamicPartitionControlAndroid::PrepareSnapshotPartitionsForUpdate(
758 uint32_t source_slot,
759 uint32_t target_slot,
Yifan Hongf033ecb2020-01-07 18:13:56 -0800760 const DeltaArchiveManifest& manifest,
761 uint64_t* required_size) {
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700762 TEST_AND_RETURN_FALSE(ExpectMetadataMounted());
Yifan Hong420db9b2019-07-23 20:50:33 -0700763 if (!snapshot_->BeginUpdate()) {
764 LOG(ERROR) << "Cannot begin new update.";
765 return false;
766 }
Yifan Hongf033ecb2020-01-07 18:13:56 -0800767 auto ret = snapshot_->CreateUpdateSnapshots(manifest);
768 if (!ret) {
769 LOG(ERROR) << "Cannot create update snapshots: " << ret.string();
770 if (required_size != nullptr &&
Yifan Hong0850bca2020-01-16 15:14:07 -0800771 ret.error_code() == Return::ErrorCode::NO_SPACE) {
Yifan Hongf033ecb2020-01-07 18:13:56 -0800772 *required_size = ret.required_size();
773 }
Yifan Hong420db9b2019-07-23 20:50:33 -0700774 return false;
775 }
776 return true;
777}
778
Yifan Hong700d7c12019-07-23 20:49:16 -0700779std::string DynamicPartitionControlAndroid::GetSuperPartitionName(
780 uint32_t slot) {
781 return fs_mgr_get_super_partition_name(slot);
782}
783
Yifan Hong012508e2019-07-22 18:30:40 -0700784bool DynamicPartitionControlAndroid::UpdatePartitionMetadata(
785 MetadataBuilder* builder,
786 uint32_t target_slot,
Yifan Hong13d41cb2019-09-16 13:18:22 -0700787 const DeltaArchiveManifest& manifest) {
Yifan Honga4e7da32019-09-30 18:25:03 -0700788 // If applying downgrade from Virtual A/B to non-Virtual A/B, the left-over
789 // COW group needs to be deleted to ensure there are enough space to create
790 // target partitions.
791 builder->RemoveGroupAndPartitions(android::snapshot::kCowGroupName);
792
Yifan Hong012508e2019-07-22 18:30:40 -0700793 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
794 DeleteGroupsWithSuffix(builder, target_suffix);
795
796 uint64_t total_size = 0;
Yifan Hong13d41cb2019-09-16 13:18:22 -0700797 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
798 total_size += group.size();
Yifan Hong012508e2019-07-22 18:30:40 -0700799 }
800
801 std::string expr;
802 uint64_t allocatable_space = builder->AllocatableSpace();
Yifan Hong186bb682019-07-23 14:04:39 -0700803 if (!GetDynamicPartitionsFeatureFlag().IsRetrofit()) {
Yifan Hong012508e2019-07-22 18:30:40 -0700804 allocatable_space /= 2;
805 expr = "half of ";
806 }
807 if (total_size > allocatable_space) {
808 LOG(ERROR) << "The maximum size of all groups with suffix " << target_suffix
809 << " (" << total_size << ") has exceeded " << expr
810 << "allocatable space for dynamic partitions "
811 << allocatable_space << ".";
812 return false;
813 }
814
Yifan Hong13d41cb2019-09-16 13:18:22 -0700815 // name of partition(e.g. "system") -> size in bytes
816 std::map<std::string, uint64_t> partition_sizes;
817 for (const auto& partition : manifest.partitions()) {
818 partition_sizes.emplace(partition.partition_name(),
819 partition.new_partition_info().size());
820 }
821
822 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
823 auto group_name_suffix = group.name() + target_suffix;
824 if (!builder->AddGroup(group_name_suffix, group.size())) {
Yifan Hong012508e2019-07-22 18:30:40 -0700825 LOG(ERROR) << "Cannot add group " << group_name_suffix << " with size "
Yifan Hong13d41cb2019-09-16 13:18:22 -0700826 << group.size();
Yifan Hong012508e2019-07-22 18:30:40 -0700827 return false;
828 }
829 LOG(INFO) << "Added group " << group_name_suffix << " with size "
Yifan Hong13d41cb2019-09-16 13:18:22 -0700830 << group.size();
Yifan Hong012508e2019-07-22 18:30:40 -0700831
Yifan Hong13d41cb2019-09-16 13:18:22 -0700832 for (const auto& partition_name : group.partition_names()) {
833 auto partition_sizes_it = partition_sizes.find(partition_name);
834 if (partition_sizes_it == partition_sizes.end()) {
835 // TODO(tbao): Support auto-filling partition info for framework-only
836 // OTA.
837 LOG(ERROR) << "dynamic_partition_metadata contains partition "
838 << partition_name << " but it is not part of the manifest. "
839 << "This is not supported.";
840 return false;
841 }
842 uint64_t partition_size = partition_sizes_it->second;
843
844 auto partition_name_suffix = partition_name + target_suffix;
Yifan Hong012508e2019-07-22 18:30:40 -0700845 Partition* p = builder->AddPartition(
846 partition_name_suffix, group_name_suffix, LP_PARTITION_ATTR_READONLY);
847 if (!p) {
848 LOG(ERROR) << "Cannot add partition " << partition_name_suffix
849 << " to group " << group_name_suffix;
850 return false;
851 }
Yifan Hong13d41cb2019-09-16 13:18:22 -0700852 if (!builder->ResizePartition(p, partition_size)) {
Yifan Hong012508e2019-07-22 18:30:40 -0700853 LOG(ERROR) << "Cannot resize partition " << partition_name_suffix
Yifan Hong13d41cb2019-09-16 13:18:22 -0700854 << " to size " << partition_size << ". Not enough space?";
Yifan Hong012508e2019-07-22 18:30:40 -0700855 return false;
856 }
857 LOG(INFO) << "Added partition " << partition_name_suffix << " to group "
Yifan Hong13d41cb2019-09-16 13:18:22 -0700858 << group_name_suffix << " with size " << partition_size;
Yifan Hong012508e2019-07-22 18:30:40 -0700859 }
860 }
861
862 return true;
863}
864
Yifan Hong7b3910a2020-03-24 17:47:32 -0700865bool DynamicPartitionControlAndroid::FinishUpdate(bool powerwash_required) {
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700866 if (ExpectMetadataMounted()) {
867 if (snapshot_->GetUpdateState() == UpdateState::Initiated) {
868 LOG(INFO) << "Snapshot writes are done.";
869 return snapshot_->FinishedSnapshotWrites(powerwash_required);
870 }
871 } else {
872 LOG(INFO) << "Skip FinishedSnapshotWrites() because /metadata is not "
873 << "mounted";
Yifan Hongf0f4a912019-09-26 17:51:33 -0700874 }
875 return true;
Yifan Honga33bca42019-09-03 20:29:45 -0700876}
877
Yifan Hong3a1a5612019-11-05 16:34:32 -0800878bool DynamicPartitionControlAndroid::GetPartitionDevice(
879 const std::string& partition_name,
880 uint32_t slot,
881 uint32_t current_slot,
882 std::string* device) {
883 const auto& partition_name_suffix =
884 partition_name + SlotSuffixForSlotNumber(slot);
885 std::string device_dir_str;
886 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
887 base::FilePath device_dir(device_dir_str);
888
889 // When looking up target partition devices, treat them as static if the
890 // current payload doesn't encode them as dynamic partitions. This may happen
891 // when applying a retrofit update on top of a dynamic-partitions-enabled
892 // build.
893 if (GetDynamicPartitionsFeatureFlag().IsEnabled() &&
894 (slot == current_slot || is_target_dynamic_)) {
895 switch (GetDynamicPartitionDevice(
896 device_dir, partition_name_suffix, slot, current_slot, device)) {
897 case DynamicPartitionDeviceStatus::SUCCESS:
898 return true;
899 case DynamicPartitionDeviceStatus::TRY_STATIC:
900 break;
901 case DynamicPartitionDeviceStatus::ERROR: // fallthrough
902 default:
903 return false;
904 }
905 }
906 base::FilePath path = device_dir.Append(partition_name_suffix);
907 if (!DeviceExists(path.value())) {
908 LOG(ERROR) << "Device file " << path.value() << " does not exist.";
909 return false;
910 }
911
912 *device = path.value();
913 return true;
914}
915
916bool DynamicPartitionControlAndroid::IsSuperBlockDevice(
917 const base::FilePath& device_dir,
918 uint32_t current_slot,
919 const std::string& partition_name_suffix) {
920 std::string source_device =
921 device_dir.Append(GetSuperPartitionName(current_slot)).value();
922 auto source_metadata = LoadMetadataBuilder(source_device, current_slot);
923 return source_metadata->HasBlockDevice(partition_name_suffix);
924}
925
926DynamicPartitionControlAndroid::DynamicPartitionDeviceStatus
927DynamicPartitionControlAndroid::GetDynamicPartitionDevice(
928 const base::FilePath& device_dir,
929 const std::string& partition_name_suffix,
930 uint32_t slot,
931 uint32_t current_slot,
932 std::string* device) {
933 std::string super_device =
934 device_dir.Append(GetSuperPartitionName(slot)).value();
935
936 auto builder = LoadMetadataBuilder(super_device, slot);
937 if (builder == nullptr) {
938 LOG(ERROR) << "No metadata in slot "
939 << BootControlInterface::SlotName(slot);
940 return DynamicPartitionDeviceStatus::ERROR;
941 }
942 if (builder->FindPartition(partition_name_suffix) == nullptr) {
943 LOG(INFO) << partition_name_suffix
944 << " is not in super partition metadata.";
945
946 if (IsSuperBlockDevice(device_dir, current_slot, partition_name_suffix)) {
947 LOG(ERROR) << "The static partition " << partition_name_suffix
948 << " is a block device for current metadata."
949 << "It cannot be used as a logical partition.";
950 return DynamicPartitionDeviceStatus::ERROR;
951 }
952
953 return DynamicPartitionDeviceStatus::TRY_STATIC;
954 }
955
956 if (slot == current_slot) {
957 if (GetState(partition_name_suffix) != DmDeviceState::ACTIVE) {
958 LOG(WARNING) << partition_name_suffix << " is at current slot but it is "
959 << "not mapped. Now try to map it.";
960 } else {
961 if (GetDmDevicePathByName(partition_name_suffix, device)) {
962 LOG(INFO) << partition_name_suffix
963 << " is mapped on device mapper: " << *device;
964 return DynamicPartitionDeviceStatus::SUCCESS;
965 }
966 LOG(ERROR) << partition_name_suffix << "is mapped but path is unknown.";
967 return DynamicPartitionDeviceStatus::ERROR;
968 }
969 }
970
971 bool force_writable = slot != current_slot;
972 if (MapPartitionOnDeviceMapper(
973 super_device, partition_name_suffix, slot, force_writable, device)) {
974 return DynamicPartitionDeviceStatus::SUCCESS;
975 }
976 return DynamicPartitionDeviceStatus::ERROR;
977}
978
Yifan Hong6eec9952019-12-04 13:12:01 -0800979void DynamicPartitionControlAndroid::set_fake_mapped_devices(
980 const std::set<std::string>& fake) {
981 mapped_devices_ = fake;
982}
983
Yifan Hongbae27842019-10-24 16:56:12 -0700984bool DynamicPartitionControlAndroid::IsRecovery() {
985 return kIsRecovery;
986}
987
988static bool IsIncrementalUpdate(const DeltaArchiveManifest& manifest) {
989 const auto& partitions = manifest.partitions();
990 return std::any_of(partitions.begin(), partitions.end(), [](const auto& p) {
991 return p.has_old_partition_info();
992 });
993}
994
995bool DynamicPartitionControlAndroid::DeleteSourcePartitions(
996 MetadataBuilder* builder,
997 uint32_t source_slot,
998 const DeltaArchiveManifest& manifest) {
999 TEST_AND_RETURN_FALSE(IsRecovery());
1000
1001 if (IsIncrementalUpdate(manifest)) {
1002 LOG(ERROR) << "Cannot sideload incremental OTA because snapshots cannot "
1003 << "be created.";
1004 if (GetVirtualAbFeatureFlag().IsLaunch()) {
1005 LOG(ERROR) << "Sideloading incremental updates on devices launches "
1006 << " Virtual A/B is not supported.";
1007 }
1008 return false;
1009 }
1010
1011 LOG(INFO) << "Will overwrite existing partitions. Slot "
1012 << BootControlInterface::SlotName(source_slot)
1013 << "may be unbootable until update finishes!";
1014 const std::string source_suffix = SlotSuffixForSlotNumber(source_slot);
1015 DeleteGroupsWithSuffix(builder, source_suffix);
1016
1017 return true;
1018}
1019
Yifan Hong90965502020-02-19 15:22:47 -08001020std::unique_ptr<AbstractAction>
1021DynamicPartitionControlAndroid::GetCleanupPreviousUpdateAction(
1022 BootControlInterface* boot_control,
1023 PrefsInterface* prefs,
1024 CleanupPreviousUpdateActionDelegateInterface* delegate) {
1025 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1026 return std::make_unique<NoOpAction>();
1027 }
1028 return std::make_unique<CleanupPreviousUpdateAction>(
1029 prefs, boot_control, snapshot_.get(), delegate);
1030}
1031
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001032bool DynamicPartitionControlAndroid::ResetUpdate(PrefsInterface* prefs) {
1033 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1034 return true;
1035 }
1036
1037 LOG(INFO) << __func__ << " resetting update state and deleting snapshots.";
1038 TEST_AND_RETURN_FALSE(prefs != nullptr);
1039
1040 // If the device has already booted into the target slot,
1041 // ResetUpdateProgress may pass but CancelUpdate fails.
1042 // This is expected. A scheduled CleanupPreviousUpdateAction should free
1043 // space when it is done.
1044 TEST_AND_RETURN_FALSE(DeltaPerformer::ResetUpdateProgress(
1045 prefs, false /* quick */, false /* skip dynamic partitions metadata */));
1046
Yifan Hong4d7c5eb2020-04-03 11:31:50 -07001047 if (ExpectMetadataMounted()) {
1048 TEST_AND_RETURN_FALSE(snapshot_->CancelUpdate());
1049 } else {
1050 LOG(INFO) << "Skip cancelling update in ResetUpdate because /metadata is "
1051 << "not mounted";
1052 }
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001053
1054 return true;
1055}
1056
Yifan Hong4d7c5eb2020-04-03 11:31:50 -07001057bool DynamicPartitionControlAndroid::ExpectMetadataMounted() {
1058 // No need to mount metadata for non-Virtual A/B devices.
1059 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1060 return false;
1061 }
1062 // Intentionally not checking |metadata_device_| in Android mode.
1063 // /metadata should always be mounted in Android mode. If it isn't, let caller
1064 // fails when calling into SnapshotManager.
1065 if (!IsRecovery()) {
1066 return true;
1067 }
1068 // In recovery mode, explicitly check |metadata_device_|.
1069 return metadata_device_ != nullptr;
1070}
1071
1072bool DynamicPartitionControlAndroid::EnsureMetadataMounted() {
1073 // No need to mount metadata for non-Virtual A/B devices.
1074 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1075 return true;
1076 }
1077
1078 if (metadata_device_ == nullptr) {
1079 metadata_device_ = snapshot_->EnsureMetadataMounted();
1080 }
1081 return metadata_device_ != nullptr;
1082}
1083
Yifan Hong537802d2018-08-15 13:15:42 -07001084} // namespace chromeos_update_engine