blob: a310f2090ca486d600f81e593e4e909571c608c6 [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 Hong537802d2018-08-15 13:15:42 -070038
Yifan Hong90965502020-02-19 15:22:47 -080039#include "update_engine/cleanup_previous_update_action.h"
Yifan Hong537802d2018-08-15 13:15:42 -070040#include "update_engine/common/boot_control_interface.h"
41#include "update_engine/common/utils.h"
Yifan Hong012508e2019-07-22 18:30:40 -070042#include "update_engine/dynamic_partition_utils.h"
Yifan Hong6a6d0f12020-03-11 13:20:52 -070043#include "update_engine/payload_consumer/delta_performer.h"
Yifan Hong537802d2018-08-15 13:15:42 -070044
45using android::base::GetBoolProperty;
Yifan Hong29692902020-03-26 12:47:05 -070046using android::base::GetProperty;
Yifan Hong537802d2018-08-15 13:15:42 -070047using android::base::Join;
48using android::dm::DeviceMapper;
49using android::dm::DmDeviceState;
50using android::fs_mgr::CreateLogicalPartition;
David Andersonbb90dfb2019-08-13 14:14:56 -070051using android::fs_mgr::CreateLogicalPartitionParams;
Yifan Hong537802d2018-08-15 13:15:42 -070052using android::fs_mgr::DestroyLogicalPartition;
Yifan Hong29692902020-03-26 12:47:05 -070053using android::fs_mgr::Fstab;
Yifan Hong537802d2018-08-15 13:15:42 -070054using android::fs_mgr::MetadataBuilder;
Yifan Hong012508e2019-07-22 18:30:40 -070055using android::fs_mgr::Partition;
Yifan Hong6e706b12018-11-09 16:50:51 -080056using android::fs_mgr::PartitionOpener;
Yifan Hong012508e2019-07-22 18:30:40 -070057using android::fs_mgr::SlotSuffixForSlotNumber;
Yifan Hongf5261562020-03-10 10:28:10 -070058using android::snapshot::OptimizeSourceCopyOperation;
Yifan Hong0850bca2020-01-16 15:14:07 -080059using android::snapshot::Return;
Yifan Hongf033ecb2020-01-07 18:13:56 -080060using android::snapshot::SnapshotManager;
Yifan Hong2257ee12020-01-13 18:33:00 -080061using android::snapshot::UpdateState;
Yifan Hong537802d2018-08-15 13:15:42 -070062
63namespace chromeos_update_engine {
64
Yifan Hong6e706b12018-11-09 16:50:51 -080065constexpr char kUseDynamicPartitions[] = "ro.boot.dynamic_partitions";
66constexpr char kRetrfoitDynamicPartitions[] =
67 "ro.boot.dynamic_partitions_retrofit";
Yifan Hong413d5722019-07-23 14:21:09 -070068constexpr char kVirtualAbEnabled[] = "ro.virtual_ab.enabled";
69constexpr char kVirtualAbRetrofit[] = "ro.virtual_ab.retrofit";
Yifan Hong29692902020-03-26 12:47:05 -070070constexpr char kPostinstallFstabPrefix[] = "ro.postinstall.fstab.prefix";
Yifan Hong420db9b2019-07-23 20:50:33 -070071// Map timeout for dynamic partitions.
72constexpr std::chrono::milliseconds kMapTimeout{1000};
73// Map timeout for dynamic partitions with snapshots. Since several devices
74// needs to be mapped, this timeout is longer than |kMapTimeout|.
75constexpr std::chrono::milliseconds kMapSnapshotTimeout{5000};
76
Yifan Hongbae27842019-10-24 16:56:12 -070077#ifdef __ANDROID_RECOVERY__
78constexpr bool kIsRecovery = true;
79#else
80constexpr bool kIsRecovery = false;
81#endif
82
Yifan Hong537802d2018-08-15 13:15:42 -070083DynamicPartitionControlAndroid::~DynamicPartitionControlAndroid() {
Yifan Hongbae27842019-10-24 16:56:12 -070084 Cleanup();
Yifan Hong537802d2018-08-15 13:15:42 -070085}
86
Yifan Hong186bb682019-07-23 14:04:39 -070087static FeatureFlag GetFeatureFlag(const char* enable_prop,
88 const char* retrofit_prop) {
89 bool retrofit = GetBoolProperty(retrofit_prop, false);
90 bool enabled = GetBoolProperty(enable_prop, false);
91 if (retrofit && !enabled) {
92 LOG(ERROR) << retrofit_prop << " is true but " << enable_prop
93 << " is not. These sysprops are inconsistent. Assume that "
94 << enable_prop << " is true from now on.";
95 }
96 if (retrofit) {
97 return FeatureFlag(FeatureFlag::Value::RETROFIT);
98 }
99 if (enabled) {
100 return FeatureFlag(FeatureFlag::Value::LAUNCH);
101 }
102 return FeatureFlag(FeatureFlag::Value::NONE);
Yifan Hong537802d2018-08-15 13:15:42 -0700103}
104
Yifan Hongb38e1af2019-10-17 14:59:22 -0700105DynamicPartitionControlAndroid::DynamicPartitionControlAndroid()
106 : dynamic_partitions_(
107 GetFeatureFlag(kUseDynamicPartitions, kRetrfoitDynamicPartitions)),
108 virtual_ab_(GetFeatureFlag(kVirtualAbEnabled, kVirtualAbRetrofit)) {
109 if (GetVirtualAbFeatureFlag().IsEnabled()) {
Yifan Hongf033ecb2020-01-07 18:13:56 -0800110 snapshot_ = SnapshotManager::New();
Yifan Hongb38e1af2019-10-17 14:59:22 -0700111 CHECK(snapshot_ != nullptr) << "Cannot initialize SnapshotManager.";
112 }
113}
114
Yifan Hong186bb682019-07-23 14:04:39 -0700115FeatureFlag DynamicPartitionControlAndroid::GetDynamicPartitionsFeatureFlag() {
Yifan Hongb38e1af2019-10-17 14:59:22 -0700116 return dynamic_partitions_;
Yifan Hong6e706b12018-11-09 16:50:51 -0800117}
118
Yifan Hong413d5722019-07-23 14:21:09 -0700119FeatureFlag DynamicPartitionControlAndroid::GetVirtualAbFeatureFlag() {
Yifan Hongb38e1af2019-10-17 14:59:22 -0700120 return virtual_ab_;
Yifan Hong413d5722019-07-23 14:21:09 -0700121}
122
Yifan Hongf5261562020-03-10 10:28:10 -0700123bool DynamicPartitionControlAndroid::OptimizeOperation(
124 const std::string& partition_name,
125 const InstallOperation& operation,
126 InstallOperation* optimized) {
Alessio Balsini2a3b4a22019-11-25 16:46:51 +0000127 switch (operation.type()) {
128 case InstallOperation::SOURCE_COPY:
129 return target_supports_snapshot_ &&
130 GetVirtualAbFeatureFlag().IsEnabled() &&
Yifan Hong6eec9952019-12-04 13:12:01 -0800131 mapped_devices_.count(partition_name +
132 SlotSuffixForSlotNumber(target_slot_)) > 0 &&
Yifan Hongf5261562020-03-10 10:28:10 -0700133 OptimizeSourceCopyOperation(operation, optimized);
Alessio Balsini2a3b4a22019-11-25 16:46:51 +0000134 break;
135 default:
136 break;
137 }
Alessio Balsini14980e22019-11-26 11:46:06 +0000138 return false;
139}
140
Yifan Hong8546a712019-03-28 14:42:53 -0700141bool DynamicPartitionControlAndroid::MapPartitionInternal(
Yifan Hong537802d2018-08-15 13:15:42 -0700142 const std::string& super_device,
143 const std::string& target_partition_name,
144 uint32_t slot,
Yifan Hongaf65ef12018-10-29 11:09:06 -0700145 bool force_writable,
Yifan Hong537802d2018-08-15 13:15:42 -0700146 std::string* path) {
David Andersonbb90dfb2019-08-13 14:14:56 -0700147 CreateLogicalPartitionParams params = {
148 .block_device = super_device,
149 .metadata_slot = slot,
150 .partition_name = target_partition_name,
151 .force_writable = force_writable,
David Andersonbb90dfb2019-08-13 14:14:56 -0700152 };
Yifan Hong420db9b2019-07-23 20:50:33 -0700153 bool success = false;
Yifan Hongf0f4a912019-09-26 17:51:33 -0700154 if (GetVirtualAbFeatureFlag().IsEnabled() && target_supports_snapshot_ &&
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700155 force_writable && ExpectMetadataMounted()) {
Yifan Hong420db9b2019-07-23 20:50:33 -0700156 // Only target partitions are mapped with force_writable. On Virtual
157 // A/B devices, target partitions may overlap with source partitions, so
158 // they must be mapped with snapshot.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700159 // One exception is when /metadata is not mounted. Fallback to
160 // CreateLogicalPartition as snapshots are not created in the first place.
Yifan Hong420db9b2019-07-23 20:50:33 -0700161 params.timeout_ms = kMapSnapshotTimeout;
162 success = snapshot_->MapUpdateSnapshot(params, path);
163 } else {
164 params.timeout_ms = kMapTimeout;
165 success = CreateLogicalPartition(params, path);
166 }
David Andersonbb90dfb2019-08-13 14:14:56 -0700167
Yifan Hong420db9b2019-07-23 20:50:33 -0700168 if (!success) {
Yifan Hong537802d2018-08-15 13:15:42 -0700169 LOG(ERROR) << "Cannot map " << target_partition_name << " in "
170 << super_device << " on device mapper.";
171 return false;
172 }
173 LOG(INFO) << "Succesfully mapped " << target_partition_name
Yifan Hongaf65ef12018-10-29 11:09:06 -0700174 << " to device mapper (force_writable = " << force_writable
175 << "); device path at " << *path;
Yifan Hong537802d2018-08-15 13:15:42 -0700176 mapped_devices_.insert(target_partition_name);
177 return true;
178}
179
Yifan Hong8546a712019-03-28 14:42:53 -0700180bool DynamicPartitionControlAndroid::MapPartitionOnDeviceMapper(
181 const std::string& super_device,
182 const std::string& target_partition_name,
183 uint32_t slot,
184 bool force_writable,
185 std::string* path) {
186 DmDeviceState state = GetState(target_partition_name);
187 if (state == DmDeviceState::ACTIVE) {
188 if (mapped_devices_.find(target_partition_name) != mapped_devices_.end()) {
189 if (GetDmDevicePathByName(target_partition_name, path)) {
190 LOG(INFO) << target_partition_name
191 << " is mapped on device mapper: " << *path;
192 return true;
193 }
194 LOG(ERROR) << target_partition_name << " is mapped but path is unknown.";
195 return false;
196 }
197 // If target_partition_name is not in mapped_devices_ but state is ACTIVE,
198 // the device might be mapped incorrectly before. Attempt to unmap it.
199 // Note that for source partitions, if GetState() == ACTIVE, callers (e.g.
200 // BootControlAndroid) should not call MapPartitionOnDeviceMapper, but
201 // should directly call GetDmDevicePathByName.
David Anderson4c891c92019-06-21 17:45:23 -0700202 if (!UnmapPartitionOnDeviceMapper(target_partition_name)) {
Yifan Hong8546a712019-03-28 14:42:53 -0700203 LOG(ERROR) << target_partition_name
204 << " is mapped before the update, and it cannot be unmapped.";
205 return false;
206 }
207 state = GetState(target_partition_name);
208 if (state != DmDeviceState::INVALID) {
209 LOG(ERROR) << target_partition_name << " is unmapped but state is "
210 << static_cast<std::underlying_type_t<DmDeviceState>>(state);
211 return false;
212 }
213 }
214 if (state == DmDeviceState::INVALID) {
215 return MapPartitionInternal(
216 super_device, target_partition_name, slot, force_writable, path);
217 }
218
219 LOG(ERROR) << target_partition_name
220 << " is mapped on device mapper but state is unknown: "
221 << static_cast<std::underlying_type_t<DmDeviceState>>(state);
222 return false;
223}
224
Yifan Hong537802d2018-08-15 13:15:42 -0700225bool DynamicPartitionControlAndroid::UnmapPartitionOnDeviceMapper(
David Anderson4c891c92019-06-21 17:45:23 -0700226 const std::string& target_partition_name) {
Yifan Hong537802d2018-08-15 13:15:42 -0700227 if (DeviceMapper::Instance().GetState(target_partition_name) !=
228 DmDeviceState::INVALID) {
Yifan Hong420db9b2019-07-23 20:50:33 -0700229 // Partitions at target slot on non-Virtual A/B devices are mapped as
230 // dm-linear. Also, on Virtual A/B devices, system_other may be mapped for
231 // preopt apps as dm-linear.
232 // Call DestroyLogicalPartition to handle these cases.
233 bool success = DestroyLogicalPartition(target_partition_name);
234
235 // On a Virtual A/B device, |target_partition_name| may be a leftover from
236 // a paused update. Clean up any underlying devices.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700237 if (ExpectMetadataMounted()) {
Yifan Hong420db9b2019-07-23 20:50:33 -0700238 success &= snapshot_->UnmapUpdateSnapshot(target_partition_name);
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700239 } else {
240 LOG(INFO) << "Skip UnmapUpdateSnapshot(" << target_partition_name
241 << ") because metadata is not mounted";
Yifan Hong420db9b2019-07-23 20:50:33 -0700242 }
243
244 if (!success) {
Yifan Hong537802d2018-08-15 13:15:42 -0700245 LOG(ERROR) << "Cannot unmap " << target_partition_name
246 << " from device mapper.";
247 return false;
248 }
249 LOG(INFO) << "Successfully unmapped " << target_partition_name
250 << " from device mapper.";
251 }
252 mapped_devices_.erase(target_partition_name);
253 return true;
254}
255
Yifan Hongbae27842019-10-24 16:56:12 -0700256void DynamicPartitionControlAndroid::UnmapAllPartitions() {
Tao Bao8c4d0082019-08-08 08:56:16 -0700257 if (mapped_devices_.empty()) {
258 return;
259 }
Yifan Hong537802d2018-08-15 13:15:42 -0700260 // UnmapPartitionOnDeviceMapper removes objects from mapped_devices_, hence
261 // a copy is needed for the loop.
262 std::set<std::string> mapped = mapped_devices_;
263 LOG(INFO) << "Destroying [" << Join(mapped, ", ") << "] from device mapper";
264 for (const auto& partition_name : mapped) {
David Anderson4c891c92019-06-21 17:45:23 -0700265 ignore_result(UnmapPartitionOnDeviceMapper(partition_name));
Yifan Hong537802d2018-08-15 13:15:42 -0700266 }
267}
268
269void DynamicPartitionControlAndroid::Cleanup() {
Yifan Hongbae27842019-10-24 16:56:12 -0700270 UnmapAllPartitions();
271 metadata_device_.reset();
Yifan Hong537802d2018-08-15 13:15:42 -0700272}
273
274bool DynamicPartitionControlAndroid::DeviceExists(const std::string& path) {
275 return base::PathExists(base::FilePath(path));
276}
277
278android::dm::DmDeviceState DynamicPartitionControlAndroid::GetState(
279 const std::string& name) {
280 return DeviceMapper::Instance().GetState(name);
281}
282
283bool DynamicPartitionControlAndroid::GetDmDevicePathByName(
284 const std::string& name, std::string* path) {
285 return DeviceMapper::Instance().GetDmDevicePathByName(name, path);
286}
287
288std::unique_ptr<MetadataBuilder>
289DynamicPartitionControlAndroid::LoadMetadataBuilder(
Yifan Hong012508e2019-07-22 18:30:40 -0700290 const std::string& super_device, uint32_t source_slot) {
291 return LoadMetadataBuilder(
292 super_device, source_slot, BootControlInterface::kInvalidSlot);
293}
294
295std::unique_ptr<MetadataBuilder>
296DynamicPartitionControlAndroid::LoadMetadataBuilder(
Yifan Hong6e706b12018-11-09 16:50:51 -0800297 const std::string& super_device,
298 uint32_t source_slot,
299 uint32_t target_slot) {
Yifan Hong30fa5f52019-08-05 16:39:59 -0700300 std::unique_ptr<MetadataBuilder> builder;
301 if (target_slot == BootControlInterface::kInvalidSlot) {
302 builder =
303 MetadataBuilder::New(PartitionOpener(), super_device, source_slot);
304 } else {
Yifan Hong50a56c62019-10-14 19:35:05 -0700305 bool always_keep_source_slot = !target_supports_snapshot_;
306 builder = MetadataBuilder::NewForUpdate(PartitionOpener(),
307 super_device,
308 source_slot,
309 target_slot,
310 always_keep_source_slot);
Yifan Hong30fa5f52019-08-05 16:39:59 -0700311 }
Yifan Hong6e706b12018-11-09 16:50:51 -0800312
Yifan Hong537802d2018-08-15 13:15:42 -0700313 if (builder == nullptr) {
314 LOG(WARNING) << "No metadata slot "
315 << BootControlInterface::SlotName(source_slot) << " in "
316 << super_device;
Yifan Hongf48a0052018-10-29 16:30:43 -0700317 return nullptr;
Yifan Hong537802d2018-08-15 13:15:42 -0700318 }
319 LOG(INFO) << "Loaded metadata from slot "
320 << BootControlInterface::SlotName(source_slot) << " in "
321 << super_device;
322 return builder;
323}
324
325bool DynamicPartitionControlAndroid::StoreMetadata(
326 const std::string& super_device,
327 MetadataBuilder* builder,
328 uint32_t target_slot) {
329 auto metadata = builder->Export();
330 if (metadata == nullptr) {
331 LOG(ERROR) << "Cannot export metadata to slot "
332 << BootControlInterface::SlotName(target_slot) << " in "
333 << super_device;
334 return false;
335 }
336
Yifan Hong186bb682019-07-23 14:04:39 -0700337 if (GetDynamicPartitionsFeatureFlag().IsRetrofit()) {
Yifan Hong6e706b12018-11-09 16:50:51 -0800338 if (!FlashPartitionTable(super_device, *metadata)) {
339 LOG(ERROR) << "Cannot write metadata to " << super_device;
340 return false;
341 }
342 LOG(INFO) << "Written metadata to " << super_device;
343 } else {
344 if (!UpdatePartitionTable(super_device, *metadata, target_slot)) {
345 LOG(ERROR) << "Cannot write metadata to slot "
346 << BootControlInterface::SlotName(target_slot) << " in "
347 << super_device;
348 return false;
349 }
350 LOG(INFO) << "Copied metadata to slot "
351 << BootControlInterface::SlotName(target_slot) << " in "
352 << super_device;
Yifan Hong537802d2018-08-15 13:15:42 -0700353 }
354
Yifan Hong537802d2018-08-15 13:15:42 -0700355 return true;
356}
357
358bool DynamicPartitionControlAndroid::GetDeviceDir(std::string* out) {
359 // We can't use fs_mgr to look up |partition_name| because fstab
360 // doesn't list every slot partition (it uses the slotselect option
361 // to mask the suffix).
362 //
363 // We can however assume that there's an entry for the /misc mount
364 // point and use that to get the device file for the misc
365 // partition. This helps us locate the disk that |partition_name|
366 // resides on. From there we'll assume that a by-name scheme is used
367 // so we can just replace the trailing "misc" by the given
368 // |partition_name| and suffix corresponding to |slot|, e.g.
369 //
370 // /dev/block/platform/soc.0/7824900.sdhci/by-name/misc ->
371 // /dev/block/platform/soc.0/7824900.sdhci/by-name/boot_a
372 //
373 // If needed, it's possible to relax the by-name assumption in the
374 // future by trawling /sys/block looking for the appropriate sibling
375 // of misc and then finding an entry in /dev matching the sysfs
376 // entry.
377
378 std::string err, misc_device = get_bootloader_message_blk_device(&err);
379 if (misc_device.empty()) {
380 LOG(ERROR) << "Unable to get misc block device: " << err;
381 return false;
382 }
383
384 if (!utils::IsSymlink(misc_device.c_str())) {
385 LOG(ERROR) << "Device file " << misc_device << " for /misc "
386 << "is not a symlink.";
387 return false;
388 }
389 *out = base::FilePath(misc_device).DirName().value();
390 return true;
391}
Yifan Hong012508e2019-07-22 18:30:40 -0700392
393bool DynamicPartitionControlAndroid::PreparePartitionsForUpdate(
394 uint32_t source_slot,
395 uint32_t target_slot,
Yifan Hongf0f4a912019-09-26 17:51:33 -0700396 const DeltaArchiveManifest& manifest,
Yifan Hongf033ecb2020-01-07 18:13:56 -0800397 bool update,
398 uint64_t* required_size) {
Yifan Hong6eec9952019-12-04 13:12:01 -0800399 source_slot_ = source_slot;
400 target_slot_ = target_slot;
Yifan Hongf033ecb2020-01-07 18:13:56 -0800401 if (required_size != nullptr) {
402 *required_size = 0;
403 }
Yifan Hong6eec9952019-12-04 13:12:01 -0800404
Yifan Hong3a1a5612019-11-05 16:34:32 -0800405 if (fs_mgr_overlayfs_is_setup()) {
406 // Non DAP devices can use overlayfs as well.
407 LOG(WARNING)
408 << "overlayfs overrides are active and can interfere with our "
409 "resources.\n"
410 << "run adb enable-verity to deactivate if required and try again.";
411 }
412
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700413 // If metadata is erased but not formatted, it is possible to not mount
414 // it in recovery. It is acceptable to skip mounting and choose fallback path
415 // (PrepareDynamicPartitionsForUpdate) when sideloading full OTAs.
416 TEST_AND_RETURN_FALSE(EnsureMetadataMounted() || IsRecovery());
Yifan Hong29692902020-03-26 12:47:05 -0700417
418 if (update) {
419 TEST_AND_RETURN_FALSE(EraseSystemOtherAvbFooter(source_slot, target_slot));
420 }
421
Yifan Hong3a1a5612019-11-05 16:34:32 -0800422 if (!GetDynamicPartitionsFeatureFlag().IsEnabled()) {
423 return true;
424 }
425
426 if (target_slot == source_slot) {
427 LOG(ERROR) << "Cannot call PreparePartitionsForUpdate on current slot.";
428 return false;
429 }
430
431 // Although the current build supports dynamic partitions, the given payload
432 // doesn't use it for target partitions. This could happen when applying a
433 // retrofit update. Skip updating the partition metadata for the target slot.
434 is_target_dynamic_ = !manifest.dynamic_partition_metadata().groups().empty();
435 if (!is_target_dynamic_) {
436 return true;
437 }
438
Yifan Hongf0f4a912019-09-26 17:51:33 -0700439 target_supports_snapshot_ =
440 manifest.dynamic_partition_metadata().snapshot_enabled();
441
442 if (!update)
443 return true;
444
Yifan Hongbae27842019-10-24 16:56:12 -0700445 bool delete_source = false;
446
Yifan Hong6d888562019-10-01 13:00:31 -0700447 if (GetVirtualAbFeatureFlag().IsEnabled()) {
448 // On Virtual A/B device, either CancelUpdate() or BeginUpdate() must be
449 // called before calling UnmapUpdateSnapshot.
450 // - If target_supports_snapshot_, PrepareSnapshotPartitionsForUpdate()
451 // calls BeginUpdate() which resets update state
Yifan Hongbae27842019-10-24 16:56:12 -0700452 // - If !target_supports_snapshot_ or PrepareSnapshotPartitionsForUpdate
453 // failed in recovery, explicitly CancelUpdate().
Yifan Hong6d888562019-10-01 13:00:31 -0700454 if (target_supports_snapshot_) {
Yifan Hongbae27842019-10-24 16:56:12 -0700455 if (PrepareSnapshotPartitionsForUpdate(
456 source_slot, target_slot, manifest, required_size)) {
457 return true;
458 }
459
460 // Virtual A/B device doing Virtual A/B update in Android mode must use
461 // snapshots.
462 if (!IsRecovery()) {
463 LOG(ERROR) << "PrepareSnapshotPartitionsForUpdate failed in Android "
464 << "mode";
465 return false;
466 }
467
468 delete_source = true;
469 LOG(INFO) << "PrepareSnapshotPartitionsForUpdate failed in recovery. "
470 << "Attempt to overwrite existing partitions if possible";
471 } else {
472 // Downgrading to an non-Virtual A/B build or is secondary OTA.
473 LOG(INFO) << "Using regular A/B on Virtual A/B because package disabled "
474 << "snapshots.";
Yifan Hong6d888562019-10-01 13:00:31 -0700475 }
Yifan Hongbae27842019-10-24 16:56:12 -0700476
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700477 // In recovery, if /metadata is not mounted, it is likely that metadata
478 // partition is erased and not formatted yet. After sideloading, when
479 // rebooting into the new version, init will erase metadata partition,
480 // hence the failure of CancelUpdate() can be ignored here.
481 // However, if metadata is mounted and CancelUpdate fails, sideloading
482 // should not proceed because during next boot, snapshots will overlay on
483 // the devices incorrectly.
484 if (ExpectMetadataMounted()) {
485 TEST_AND_RETURN_FALSE(snapshot_->CancelUpdate());
486 } else {
487 LOG(INFO) << "Skip canceling previous update because metadata is not "
488 << "mounted";
Yifan Hong6d888562019-10-01 13:00:31 -0700489 }
Yifan Hong420db9b2019-07-23 20:50:33 -0700490 }
Yifan Hongbae27842019-10-24 16:56:12 -0700491
492 return PrepareDynamicPartitionsForUpdate(
493 source_slot, target_slot, manifest, delete_source);
Yifan Hong420db9b2019-07-23 20:50:33 -0700494}
495
Yifan Hong29692902020-03-26 12:47:05 -0700496namespace {
497// Try our best to erase AVB footer.
498class AvbFooterEraser {
499 public:
500 explicit AvbFooterEraser(const std::string& path) : path_(path) {}
501 bool Erase() {
502 // Try to mark the block device read-only. Ignore any
503 // failure since this won't work when passing regular files.
504 ignore_result(utils::SetBlockDeviceReadOnly(path_, false /* readonly */));
505
506 fd_.reset(new EintrSafeFileDescriptor());
507 int flags = O_WRONLY | O_TRUNC | O_CLOEXEC | O_SYNC;
508 TEST_AND_RETURN_FALSE(fd_->Open(path_.c_str(), flags));
509
510 // Need to write end-AVB_FOOTER_SIZE to end.
511 static_assert(AVB_FOOTER_SIZE > 0);
512 off64_t offset = fd_->Seek(-AVB_FOOTER_SIZE, SEEK_END);
513 TEST_AND_RETURN_FALSE_ERRNO(offset >= 0);
514 uint64_t write_size = AVB_FOOTER_SIZE;
515 LOG(INFO) << "Zeroing " << path_ << " @ [" << offset << ", "
516 << (offset + write_size) << "] (" << write_size << " bytes)";
517 brillo::Blob zeros(write_size);
518 TEST_AND_RETURN_FALSE(utils::WriteAll(fd_, zeros.data(), zeros.size()));
519 return true;
520 }
521 ~AvbFooterEraser() {
522 TEST_AND_RETURN(fd_ != nullptr && fd_->IsOpen());
523 if (!fd_->Close()) {
524 LOG(WARNING) << "Failed to close fd for " << path_;
525 }
526 }
527
528 private:
529 std::string path_;
530 FileDescriptorPtr fd_;
531};
532
533} // namespace
534
535std::optional<bool>
536DynamicPartitionControlAndroid::IsAvbEnabledOnSystemOther() {
537 auto prefix = GetProperty(kPostinstallFstabPrefix, "");
538 if (prefix.empty()) {
539 LOG(WARNING) << "Cannot get " << kPostinstallFstabPrefix;
540 return std::nullopt;
541 }
542 auto path = base::FilePath(prefix).Append("etc/fstab.postinstall").value();
543 return IsAvbEnabledInFstab(path);
544}
545
546std::optional<bool> DynamicPartitionControlAndroid::IsAvbEnabledInFstab(
547 const std::string& path) {
548 Fstab fstab;
549 if (!ReadFstabFromFile(path, &fstab)) {
550 LOG(WARNING) << "Cannot read fstab from " << path;
551 return std::nullopt;
552 }
553 for (const auto& entry : fstab) {
554 if (!entry.avb_keys.empty()) {
555 return true;
556 }
557 }
558 return false;
559}
560
561bool DynamicPartitionControlAndroid::GetSystemOtherPath(
562 uint32_t source_slot,
563 uint32_t target_slot,
564 const std::string& partition_name_suffix,
565 std::string* path,
566 bool* should_unmap) {
567 path->clear();
568 *should_unmap = false;
569
570 // In recovery, just erase no matter what.
571 // - On devices with retrofit dynamic partitions, no logical partitions
572 // should be mounted at this point. Hence it should be safe to erase.
573 // Otherwise, do check that AVB is enabled on system_other before erasing.
574 if (!IsRecovery()) {
575 auto has_avb = IsAvbEnabledOnSystemOther();
576 TEST_AND_RETURN_FALSE(has_avb.has_value());
577 if (!has_avb.value()) {
578 LOG(INFO) << "AVB is not enabled on system_other. Skip erasing.";
579 return true;
580 }
581
582 // Found unexpected avb_keys for system_other on devices retrofitting
583 // dynamic partitions. Previous crash in update_engine may leave logical
584 // partitions mapped on physical system_other partition. It is difficult to
585 // handle these cases. Just fail.
586 if (GetDynamicPartitionsFeatureFlag().IsRetrofit()) {
587 LOG(ERROR) << "Cannot erase AVB footer on system_other on devices with "
588 << "retrofit dynamic partitions. They should not have AVB "
589 << "enabled on system_other.";
590 return false;
591 }
592 }
593
594 std::string device_dir_str;
595 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
596 base::FilePath device_dir(device_dir_str);
597
598 // On devices without dynamic partition, search for static partitions.
599 if (!GetDynamicPartitionsFeatureFlag().IsEnabled()) {
600 *path = device_dir.Append(partition_name_suffix).value();
601 TEST_AND_RETURN_FALSE(DeviceExists(*path));
602 return true;
603 }
604
605 auto source_super_device =
606 device_dir.Append(GetSuperPartitionName(source_slot)).value();
607
608 auto builder = LoadMetadataBuilder(source_super_device, source_slot);
609 if (builder == nullptr) {
610 if (IsRecovery()) {
611 // It might be corrupted for some reason. It should still be able to
612 // sideload.
613 LOG(WARNING) << "Super partition metadata cannot be read from the source "
614 << "slot, skip erasing.";
615 return true;
616 } else {
617 // Device has booted into Android mode, indicating that the super
618 // partition metadata should be there.
619 LOG(ERROR) << "Super partition metadata cannot be read from the source "
620 << "slot. This is unexpected on devices with dynamic "
621 << "partitions enabled.";
622 return false;
623 }
624 }
625 auto p = builder->FindPartition(partition_name_suffix);
626 if (p == nullptr) {
627 // If the source slot is flashed without system_other, it does not exist
628 // in super partition metadata at source slot. It is safe to skip it.
629 LOG(INFO) << "Can't find " << partition_name_suffix
630 << " in metadata source slot, skip erasing.";
631 return true;
632 }
633 // System_other created by flashing tools should be erased.
634 // If partition is created by update_engine (via NewForUpdate), it is a
635 // left-over partition from the previous update and does not contain
636 // system_other, hence there is no need to erase.
637 // Note the reverse is not necessary true. If the flag is not set, we don't
638 // know if the partition is created by update_engine or by flashing tools
639 // because older versions of super partition metadata does not contain this
640 // flag. It is okay to erase the AVB footer anyways.
641 if (p->attributes() & LP_PARTITION_ATTR_UPDATED) {
642 LOG(INFO) << partition_name_suffix
643 << " does not contain system_other, skip erasing.";
644 return true;
645 }
646
647 // Delete any pre-existing device with name |partition_name_suffix| and
648 // also remove it from |mapped_devices_|.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700649 // In recovery, metadata might not be mounted, and
650 // UnmapPartitionOnDeviceMapper might fail. However,
651 // it is unusual that system_other has already been mapped. Hence, just skip.
Yifan Hong29692902020-03-26 12:47:05 -0700652 TEST_AND_RETURN_FALSE(UnmapPartitionOnDeviceMapper(partition_name_suffix));
653 // Use CreateLogicalPartition directly to avoid mapping with existing
654 // snapshots.
655 CreateLogicalPartitionParams params = {
656 .block_device = source_super_device,
657 .metadata_slot = source_slot,
658 .partition_name = partition_name_suffix,
659 .force_writable = true,
660 .timeout_ms = kMapTimeout,
661 };
662 TEST_AND_RETURN_FALSE(CreateLogicalPartition(params, path));
663 *should_unmap = true;
664 return true;
665}
666
667bool DynamicPartitionControlAndroid::EraseSystemOtherAvbFooter(
668 uint32_t source_slot, uint32_t target_slot) {
669 LOG(INFO) << "Erasing AVB footer of system_other partition before update.";
670
671 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
672 const std::string partition_name_suffix = "system" + target_suffix;
673
674 std::string path;
675 bool should_unmap = false;
676
677 TEST_AND_RETURN_FALSE(GetSystemOtherPath(
678 source_slot, target_slot, partition_name_suffix, &path, &should_unmap));
679
680 if (path.empty()) {
681 return true;
682 }
683
684 bool ret = AvbFooterEraser(path).Erase();
685
686 // Delete |partition_name_suffix| from device mapper and from
687 // |mapped_devices_| again so that it does not interfere with update process.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700688 // In recovery, metadata might not be mounted, and
689 // UnmapPartitionOnDeviceMapper might fail. However, DestroyLogicalPartition
690 // should be called. If DestroyLogicalPartition does fail, it is still okay
691 // to skip the error here and let Prepare*() fail later.
Yifan Hong29692902020-03-26 12:47:05 -0700692 if (should_unmap) {
693 TEST_AND_RETURN_FALSE(UnmapPartitionOnDeviceMapper(partition_name_suffix));
694 }
695
696 return ret;
697}
698
Yifan Hong420db9b2019-07-23 20:50:33 -0700699bool DynamicPartitionControlAndroid::PrepareDynamicPartitionsForUpdate(
700 uint32_t source_slot,
701 uint32_t target_slot,
Yifan Hongbae27842019-10-24 16:56:12 -0700702 const DeltaArchiveManifest& manifest,
703 bool delete_source) {
Yifan Hong012508e2019-07-22 18:30:40 -0700704 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
705
706 // Unmap all the target dynamic partitions because they would become
707 // inconsistent with the new metadata.
Yifan Hong13d41cb2019-09-16 13:18:22 -0700708 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
709 for (const auto& partition_name : group.partition_names()) {
710 if (!UnmapPartitionOnDeviceMapper(partition_name + target_suffix)) {
Yifan Hong012508e2019-07-22 18:30:40 -0700711 return false;
712 }
713 }
714 }
715
716 std::string device_dir_str;
717 if (!GetDeviceDir(&device_dir_str)) {
718 return false;
719 }
720 base::FilePath device_dir(device_dir_str);
721 auto source_device =
Yifan Hong700d7c12019-07-23 20:49:16 -0700722 device_dir.Append(GetSuperPartitionName(source_slot)).value();
Yifan Hong012508e2019-07-22 18:30:40 -0700723
724 auto builder = LoadMetadataBuilder(source_device, source_slot, target_slot);
725 if (builder == nullptr) {
726 LOG(ERROR) << "No metadata at "
727 << BootControlInterface::SlotName(source_slot);
728 return false;
729 }
730
Yifan Hongbae27842019-10-24 16:56:12 -0700731 if (delete_source) {
732 TEST_AND_RETURN_FALSE(
733 DeleteSourcePartitions(builder.get(), source_slot, manifest));
734 }
735
Yifan Hong13d41cb2019-09-16 13:18:22 -0700736 if (!UpdatePartitionMetadata(builder.get(), target_slot, manifest)) {
Yifan Hong012508e2019-07-22 18:30:40 -0700737 return false;
738 }
739
740 auto target_device =
Yifan Hong700d7c12019-07-23 20:49:16 -0700741 device_dir.Append(GetSuperPartitionName(target_slot)).value();
Yifan Hong012508e2019-07-22 18:30:40 -0700742 return StoreMetadata(target_device, builder.get(), target_slot);
743}
744
Yifan Hong420db9b2019-07-23 20:50:33 -0700745bool DynamicPartitionControlAndroid::PrepareSnapshotPartitionsForUpdate(
746 uint32_t source_slot,
747 uint32_t target_slot,
Yifan Hongf033ecb2020-01-07 18:13:56 -0800748 const DeltaArchiveManifest& manifest,
749 uint64_t* required_size) {
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700750 TEST_AND_RETURN_FALSE(ExpectMetadataMounted());
Yifan Hong420db9b2019-07-23 20:50:33 -0700751 if (!snapshot_->BeginUpdate()) {
752 LOG(ERROR) << "Cannot begin new update.";
753 return false;
754 }
Yifan Hongf033ecb2020-01-07 18:13:56 -0800755 auto ret = snapshot_->CreateUpdateSnapshots(manifest);
756 if (!ret) {
757 LOG(ERROR) << "Cannot create update snapshots: " << ret.string();
758 if (required_size != nullptr &&
Yifan Hong0850bca2020-01-16 15:14:07 -0800759 ret.error_code() == Return::ErrorCode::NO_SPACE) {
Yifan Hongf033ecb2020-01-07 18:13:56 -0800760 *required_size = ret.required_size();
761 }
Yifan Hong420db9b2019-07-23 20:50:33 -0700762 return false;
763 }
764 return true;
765}
766
Yifan Hong700d7c12019-07-23 20:49:16 -0700767std::string DynamicPartitionControlAndroid::GetSuperPartitionName(
768 uint32_t slot) {
769 return fs_mgr_get_super_partition_name(slot);
770}
771
Yifan Hong012508e2019-07-22 18:30:40 -0700772bool DynamicPartitionControlAndroid::UpdatePartitionMetadata(
773 MetadataBuilder* builder,
774 uint32_t target_slot,
Yifan Hong13d41cb2019-09-16 13:18:22 -0700775 const DeltaArchiveManifest& manifest) {
Yifan Honga4e7da32019-09-30 18:25:03 -0700776 // If applying downgrade from Virtual A/B to non-Virtual A/B, the left-over
777 // COW group needs to be deleted to ensure there are enough space to create
778 // target partitions.
779 builder->RemoveGroupAndPartitions(android::snapshot::kCowGroupName);
780
Yifan Hong012508e2019-07-22 18:30:40 -0700781 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
782 DeleteGroupsWithSuffix(builder, target_suffix);
783
784 uint64_t total_size = 0;
Yifan Hong13d41cb2019-09-16 13:18:22 -0700785 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
786 total_size += group.size();
Yifan Hong012508e2019-07-22 18:30:40 -0700787 }
788
789 std::string expr;
790 uint64_t allocatable_space = builder->AllocatableSpace();
Yifan Hong186bb682019-07-23 14:04:39 -0700791 if (!GetDynamicPartitionsFeatureFlag().IsRetrofit()) {
Yifan Hong012508e2019-07-22 18:30:40 -0700792 allocatable_space /= 2;
793 expr = "half of ";
794 }
795 if (total_size > allocatable_space) {
796 LOG(ERROR) << "The maximum size of all groups with suffix " << target_suffix
797 << " (" << total_size << ") has exceeded " << expr
798 << "allocatable space for dynamic partitions "
799 << allocatable_space << ".";
800 return false;
801 }
802
Yifan Hong13d41cb2019-09-16 13:18:22 -0700803 // name of partition(e.g. "system") -> size in bytes
804 std::map<std::string, uint64_t> partition_sizes;
805 for (const auto& partition : manifest.partitions()) {
806 partition_sizes.emplace(partition.partition_name(),
807 partition.new_partition_info().size());
808 }
809
810 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
811 auto group_name_suffix = group.name() + target_suffix;
812 if (!builder->AddGroup(group_name_suffix, group.size())) {
Yifan Hong012508e2019-07-22 18:30:40 -0700813 LOG(ERROR) << "Cannot add group " << group_name_suffix << " with size "
Yifan Hong13d41cb2019-09-16 13:18:22 -0700814 << group.size();
Yifan Hong012508e2019-07-22 18:30:40 -0700815 return false;
816 }
817 LOG(INFO) << "Added group " << group_name_suffix << " with size "
Yifan Hong13d41cb2019-09-16 13:18:22 -0700818 << group.size();
Yifan Hong012508e2019-07-22 18:30:40 -0700819
Yifan Hong13d41cb2019-09-16 13:18:22 -0700820 for (const auto& partition_name : group.partition_names()) {
821 auto partition_sizes_it = partition_sizes.find(partition_name);
822 if (partition_sizes_it == partition_sizes.end()) {
823 // TODO(tbao): Support auto-filling partition info for framework-only
824 // OTA.
825 LOG(ERROR) << "dynamic_partition_metadata contains partition "
826 << partition_name << " but it is not part of the manifest. "
827 << "This is not supported.";
828 return false;
829 }
830 uint64_t partition_size = partition_sizes_it->second;
831
832 auto partition_name_suffix = partition_name + target_suffix;
Yifan Hong012508e2019-07-22 18:30:40 -0700833 Partition* p = builder->AddPartition(
834 partition_name_suffix, group_name_suffix, LP_PARTITION_ATTR_READONLY);
835 if (!p) {
836 LOG(ERROR) << "Cannot add partition " << partition_name_suffix
837 << " to group " << group_name_suffix;
838 return false;
839 }
Yifan Hong13d41cb2019-09-16 13:18:22 -0700840 if (!builder->ResizePartition(p, partition_size)) {
Yifan Hong012508e2019-07-22 18:30:40 -0700841 LOG(ERROR) << "Cannot resize partition " << partition_name_suffix
Yifan Hong13d41cb2019-09-16 13:18:22 -0700842 << " to size " << partition_size << ". Not enough space?";
Yifan Hong012508e2019-07-22 18:30:40 -0700843 return false;
844 }
845 LOG(INFO) << "Added partition " << partition_name_suffix << " to group "
Yifan Hong13d41cb2019-09-16 13:18:22 -0700846 << group_name_suffix << " with size " << partition_size;
Yifan Hong012508e2019-07-22 18:30:40 -0700847 }
848 }
849
850 return true;
851}
852
Yifan Hong7b3910a2020-03-24 17:47:32 -0700853bool DynamicPartitionControlAndroid::FinishUpdate(bool powerwash_required) {
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700854 if (ExpectMetadataMounted()) {
855 if (snapshot_->GetUpdateState() == UpdateState::Initiated) {
856 LOG(INFO) << "Snapshot writes are done.";
857 return snapshot_->FinishedSnapshotWrites(powerwash_required);
858 }
859 } else {
860 LOG(INFO) << "Skip FinishedSnapshotWrites() because /metadata is not "
861 << "mounted";
Yifan Hongf0f4a912019-09-26 17:51:33 -0700862 }
863 return true;
Yifan Honga33bca42019-09-03 20:29:45 -0700864}
865
Yifan Hong3a1a5612019-11-05 16:34:32 -0800866bool DynamicPartitionControlAndroid::GetPartitionDevice(
867 const std::string& partition_name,
868 uint32_t slot,
869 uint32_t current_slot,
870 std::string* device) {
871 const auto& partition_name_suffix =
872 partition_name + SlotSuffixForSlotNumber(slot);
873 std::string device_dir_str;
874 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
875 base::FilePath device_dir(device_dir_str);
876
877 // When looking up target partition devices, treat them as static if the
878 // current payload doesn't encode them as dynamic partitions. This may happen
879 // when applying a retrofit update on top of a dynamic-partitions-enabled
880 // build.
881 if (GetDynamicPartitionsFeatureFlag().IsEnabled() &&
882 (slot == current_slot || is_target_dynamic_)) {
883 switch (GetDynamicPartitionDevice(
884 device_dir, partition_name_suffix, slot, current_slot, device)) {
885 case DynamicPartitionDeviceStatus::SUCCESS:
886 return true;
887 case DynamicPartitionDeviceStatus::TRY_STATIC:
888 break;
889 case DynamicPartitionDeviceStatus::ERROR: // fallthrough
890 default:
891 return false;
892 }
893 }
894 base::FilePath path = device_dir.Append(partition_name_suffix);
895 if (!DeviceExists(path.value())) {
896 LOG(ERROR) << "Device file " << path.value() << " does not exist.";
897 return false;
898 }
899
900 *device = path.value();
901 return true;
902}
903
904bool DynamicPartitionControlAndroid::IsSuperBlockDevice(
905 const base::FilePath& device_dir,
906 uint32_t current_slot,
907 const std::string& partition_name_suffix) {
908 std::string source_device =
909 device_dir.Append(GetSuperPartitionName(current_slot)).value();
910 auto source_metadata = LoadMetadataBuilder(source_device, current_slot);
911 return source_metadata->HasBlockDevice(partition_name_suffix);
912}
913
914DynamicPartitionControlAndroid::DynamicPartitionDeviceStatus
915DynamicPartitionControlAndroid::GetDynamicPartitionDevice(
916 const base::FilePath& device_dir,
917 const std::string& partition_name_suffix,
918 uint32_t slot,
919 uint32_t current_slot,
920 std::string* device) {
921 std::string super_device =
922 device_dir.Append(GetSuperPartitionName(slot)).value();
923
924 auto builder = LoadMetadataBuilder(super_device, slot);
925 if (builder == nullptr) {
926 LOG(ERROR) << "No metadata in slot "
927 << BootControlInterface::SlotName(slot);
928 return DynamicPartitionDeviceStatus::ERROR;
929 }
930 if (builder->FindPartition(partition_name_suffix) == nullptr) {
931 LOG(INFO) << partition_name_suffix
932 << " is not in super partition metadata.";
933
934 if (IsSuperBlockDevice(device_dir, current_slot, partition_name_suffix)) {
935 LOG(ERROR) << "The static partition " << partition_name_suffix
936 << " is a block device for current metadata."
937 << "It cannot be used as a logical partition.";
938 return DynamicPartitionDeviceStatus::ERROR;
939 }
940
941 return DynamicPartitionDeviceStatus::TRY_STATIC;
942 }
943
944 if (slot == current_slot) {
945 if (GetState(partition_name_suffix) != DmDeviceState::ACTIVE) {
946 LOG(WARNING) << partition_name_suffix << " is at current slot but it is "
947 << "not mapped. Now try to map it.";
948 } else {
949 if (GetDmDevicePathByName(partition_name_suffix, device)) {
950 LOG(INFO) << partition_name_suffix
951 << " is mapped on device mapper: " << *device;
952 return DynamicPartitionDeviceStatus::SUCCESS;
953 }
954 LOG(ERROR) << partition_name_suffix << "is mapped but path is unknown.";
955 return DynamicPartitionDeviceStatus::ERROR;
956 }
957 }
958
959 bool force_writable = slot != current_slot;
960 if (MapPartitionOnDeviceMapper(
961 super_device, partition_name_suffix, slot, force_writable, device)) {
962 return DynamicPartitionDeviceStatus::SUCCESS;
963 }
964 return DynamicPartitionDeviceStatus::ERROR;
965}
966
Yifan Hong6eec9952019-12-04 13:12:01 -0800967void DynamicPartitionControlAndroid::set_fake_mapped_devices(
968 const std::set<std::string>& fake) {
969 mapped_devices_ = fake;
970}
971
Yifan Hongbae27842019-10-24 16:56:12 -0700972bool DynamicPartitionControlAndroid::IsRecovery() {
973 return kIsRecovery;
974}
975
976static bool IsIncrementalUpdate(const DeltaArchiveManifest& manifest) {
977 const auto& partitions = manifest.partitions();
978 return std::any_of(partitions.begin(), partitions.end(), [](const auto& p) {
979 return p.has_old_partition_info();
980 });
981}
982
983bool DynamicPartitionControlAndroid::DeleteSourcePartitions(
984 MetadataBuilder* builder,
985 uint32_t source_slot,
986 const DeltaArchiveManifest& manifest) {
987 TEST_AND_RETURN_FALSE(IsRecovery());
988
989 if (IsIncrementalUpdate(manifest)) {
990 LOG(ERROR) << "Cannot sideload incremental OTA because snapshots cannot "
991 << "be created.";
992 if (GetVirtualAbFeatureFlag().IsLaunch()) {
993 LOG(ERROR) << "Sideloading incremental updates on devices launches "
994 << " Virtual A/B is not supported.";
995 }
996 return false;
997 }
998
999 LOG(INFO) << "Will overwrite existing partitions. Slot "
1000 << BootControlInterface::SlotName(source_slot)
1001 << "may be unbootable until update finishes!";
1002 const std::string source_suffix = SlotSuffixForSlotNumber(source_slot);
1003 DeleteGroupsWithSuffix(builder, source_suffix);
1004
1005 return true;
1006}
1007
Yifan Hong90965502020-02-19 15:22:47 -08001008std::unique_ptr<AbstractAction>
1009DynamicPartitionControlAndroid::GetCleanupPreviousUpdateAction(
1010 BootControlInterface* boot_control,
1011 PrefsInterface* prefs,
1012 CleanupPreviousUpdateActionDelegateInterface* delegate) {
1013 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1014 return std::make_unique<NoOpAction>();
1015 }
1016 return std::make_unique<CleanupPreviousUpdateAction>(
1017 prefs, boot_control, snapshot_.get(), delegate);
1018}
1019
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001020bool DynamicPartitionControlAndroid::ResetUpdate(PrefsInterface* prefs) {
1021 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1022 return true;
1023 }
1024
1025 LOG(INFO) << __func__ << " resetting update state and deleting snapshots.";
1026 TEST_AND_RETURN_FALSE(prefs != nullptr);
1027
1028 // If the device has already booted into the target slot,
1029 // ResetUpdateProgress may pass but CancelUpdate fails.
1030 // This is expected. A scheduled CleanupPreviousUpdateAction should free
1031 // space when it is done.
1032 TEST_AND_RETURN_FALSE(DeltaPerformer::ResetUpdateProgress(
1033 prefs, false /* quick */, false /* skip dynamic partitions metadata */));
1034
Yifan Hong4d7c5eb2020-04-03 11:31:50 -07001035 if (ExpectMetadataMounted()) {
1036 TEST_AND_RETURN_FALSE(snapshot_->CancelUpdate());
1037 } else {
1038 LOG(INFO) << "Skip cancelling update in ResetUpdate because /metadata is "
1039 << "not mounted";
1040 }
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001041
1042 return true;
1043}
1044
Yifan Hong4d7c5eb2020-04-03 11:31:50 -07001045bool DynamicPartitionControlAndroid::ExpectMetadataMounted() {
1046 // No need to mount metadata for non-Virtual A/B devices.
1047 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1048 return false;
1049 }
1050 // Intentionally not checking |metadata_device_| in Android mode.
1051 // /metadata should always be mounted in Android mode. If it isn't, let caller
1052 // fails when calling into SnapshotManager.
1053 if (!IsRecovery()) {
1054 return true;
1055 }
1056 // In recovery mode, explicitly check |metadata_device_|.
1057 return metadata_device_ != nullptr;
1058}
1059
1060bool DynamicPartitionControlAndroid::EnsureMetadataMounted() {
1061 // No need to mount metadata for non-Virtual A/B devices.
1062 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1063 return true;
1064 }
1065
1066 if (metadata_device_ == nullptr) {
1067 metadata_device_ = snapshot_->EnsureMetadataMounted();
1068 }
1069 return metadata_device_ != nullptr;
1070}
1071
Yifan Hong537802d2018-08-15 13:15:42 -07001072} // namespace chromeos_update_engine