blob: 657eec9a134b5d1ca26ad66163df90137970160b [file] [log] [blame]
Yifan Hong537802d2018-08-15 13:15:42 -07001//
2// Copyright (C) 2018 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
16
Amin Hassaniec7bc112020-10-29 16:47:58 -070017#include "update_engine/aosp/dynamic_partition_control_android.h"
Yifan Hong537802d2018-08-15 13:15:42 -070018
Kelvin Zhang91d95fa2020-11-05 13:52:00 -050019#include <algorithm>
Yifan Hong420db9b2019-07-23 20:50:33 -070020#include <chrono> // NOLINT(build/c++11) - using libsnapshot / liblp API
Kelvin Zhang34618522020-09-28 09:21:02 -040021#include <cstdint>
Yifan Hong13d41cb2019-09-16 13:18:22 -070022#include <map>
Yifan Hong537802d2018-08-15 13:15:42 -070023#include <memory>
24#include <set>
25#include <string>
Tianjie99d570d2020-06-04 14:57:19 -070026#include <string_view>
27#include <utility>
Yifan Hong012508e2019-07-22 18:30:40 -070028#include <vector>
Yifan Hong537802d2018-08-15 13:15:42 -070029
30#include <android-base/properties.h>
31#include <android-base/strings.h>
32#include <base/files/file_util.h>
33#include <base/logging.h>
Yifan Hong012508e2019-07-22 18:30:40 -070034#include <base/strings/string_util.h>
Yifan Hong537802d2018-08-15 13:15:42 -070035#include <bootloader_message/bootloader_message.h>
Yifan Hong012508e2019-07-22 18:30:40 -070036#include <fs_mgr.h>
Yifan Hong537802d2018-08-15 13:15:42 -070037#include <fs_mgr_dm_linear.h>
Yifan Hong3a1a5612019-11-05 16:34:32 -080038#include <fs_mgr_overlayfs.h>
Yifan Hong29692902020-03-26 12:47:05 -070039#include <libavb/libavb.h>
Yifan Hong3a1a5612019-11-05 16:34:32 -080040#include <libdm/dm.h>
Kelvin Zhang34618522020-09-28 09:21:02 -040041#include <liblp/liblp.h>
42#include <libsnapshot/cow_writer.h>
Yifan Hong420db9b2019-07-23 20:50:33 -070043#include <libsnapshot/snapshot.h>
Yifan Hongf9cb4492020-04-15 13:00:20 -070044#include <libsnapshot/snapshot_stub.h>
Yifan Hong537802d2018-08-15 13:15:42 -070045
Amin Hassaniec7bc112020-10-29 16:47:58 -070046#include "update_engine/aosp/cleanup_previous_update_action.h"
47#include "update_engine/aosp/dynamic_partition_utils.h"
Yifan Hong537802d2018-08-15 13:15:42 -070048#include "update_engine/common/boot_control_interface.h"
Kelvin Zhangb9a5f612021-01-22 14:34:05 -050049#include "update_engine/common/dynamic_partition_control_interface.h"
50#include "update_engine/common/platform_constants.h"
Yifan Hong537802d2018-08-15 13:15:42 -070051#include "update_engine/common/utils.h"
Yifan Hong6a6d0f12020-03-11 13:20:52 -070052#include "update_engine/payload_consumer/delta_performer.h"
Yifan Hong537802d2018-08-15 13:15:42 -070053
54using android::base::GetBoolProperty;
Yifan Hong29692902020-03-26 12:47:05 -070055using android::base::GetProperty;
Yifan Hong537802d2018-08-15 13:15:42 -070056using android::base::Join;
57using android::dm::DeviceMapper;
58using android::dm::DmDeviceState;
59using android::fs_mgr::CreateLogicalPartition;
David Andersonbb90dfb2019-08-13 14:14:56 -070060using android::fs_mgr::CreateLogicalPartitionParams;
Yifan Hong537802d2018-08-15 13:15:42 -070061using android::fs_mgr::DestroyLogicalPartition;
Yifan Hong29692902020-03-26 12:47:05 -070062using android::fs_mgr::Fstab;
Yifan Hong537802d2018-08-15 13:15:42 -070063using android::fs_mgr::MetadataBuilder;
Yifan Hong012508e2019-07-22 18:30:40 -070064using android::fs_mgr::Partition;
Yifan Hong6e706b12018-11-09 16:50:51 -080065using android::fs_mgr::PartitionOpener;
Yifan Hong012508e2019-07-22 18:30:40 -070066using android::fs_mgr::SlotSuffixForSlotNumber;
Yifan Hongf5261562020-03-10 10:28:10 -070067using android::snapshot::OptimizeSourceCopyOperation;
Yifan Hong0850bca2020-01-16 15:14:07 -080068using android::snapshot::Return;
Yifan Hongf033ecb2020-01-07 18:13:56 -080069using android::snapshot::SnapshotManager;
Yifan Hongf9cb4492020-04-15 13:00:20 -070070using android::snapshot::SnapshotManagerStub;
Yifan Hong2257ee12020-01-13 18:33:00 -080071using android::snapshot::UpdateState;
Yifan Hong537802d2018-08-15 13:15:42 -070072
73namespace chromeos_update_engine {
74
Yifan Hong6e706b12018-11-09 16:50:51 -080075constexpr char kUseDynamicPartitions[] = "ro.boot.dynamic_partitions";
76constexpr char kRetrfoitDynamicPartitions[] =
77 "ro.boot.dynamic_partitions_retrofit";
Yifan Hong413d5722019-07-23 14:21:09 -070078constexpr char kVirtualAbEnabled[] = "ro.virtual_ab.enabled";
79constexpr char kVirtualAbRetrofit[] = "ro.virtual_ab.retrofit";
Kelvin Zhangda1b3142020-09-24 17:09:02 -040080constexpr char kVirtualAbCompressionEnabled[] =
81 "ro.virtual_ab.compression.enabled";
82
83// Currently, android doesn't have a retrofit prop for VAB Compression. However,
84// struct FeatureFlag forces us to determine if a feature is 'retrofit'. So this
85// is here just to simplify code. Replace it with real retrofit prop name once
86// there is one.
87constexpr char kVirtualAbCompressionRetrofit[] = "";
Yifan Hong29692902020-03-26 12:47:05 -070088constexpr char kPostinstallFstabPrefix[] = "ro.postinstall.fstab.prefix";
Yifan Hong420db9b2019-07-23 20:50:33 -070089// Map timeout for dynamic partitions.
90constexpr std::chrono::milliseconds kMapTimeout{1000};
91// Map timeout for dynamic partitions with snapshots. Since several devices
92// needs to be mapped, this timeout is longer than |kMapTimeout|.
93constexpr std::chrono::milliseconds kMapSnapshotTimeout{5000};
94
Yifan Hong537802d2018-08-15 13:15:42 -070095DynamicPartitionControlAndroid::~DynamicPartitionControlAndroid() {
Yifan Hongbae27842019-10-24 16:56:12 -070096 Cleanup();
Yifan Hong537802d2018-08-15 13:15:42 -070097}
98
Yifan Hong186bb682019-07-23 14:04:39 -070099static FeatureFlag GetFeatureFlag(const char* enable_prop,
100 const char* retrofit_prop) {
Kelvin Zhangda1b3142020-09-24 17:09:02 -0400101 // Default retrofit to false if retrofit_prop is empty.
102 bool retrofit = retrofit_prop && retrofit_prop[0] != '\0' &&
103 GetBoolProperty(retrofit_prop, false);
Yifan Hong186bb682019-07-23 14:04:39 -0700104 bool enabled = GetBoolProperty(enable_prop, false);
105 if (retrofit && !enabled) {
106 LOG(ERROR) << retrofit_prop << " is true but " << enable_prop
107 << " is not. These sysprops are inconsistent. Assume that "
108 << enable_prop << " is true from now on.";
109 }
110 if (retrofit) {
111 return FeatureFlag(FeatureFlag::Value::RETROFIT);
112 }
113 if (enabled) {
114 return FeatureFlag(FeatureFlag::Value::LAUNCH);
115 }
116 return FeatureFlag(FeatureFlag::Value::NONE);
Yifan Hong537802d2018-08-15 13:15:42 -0700117}
118
Yifan Hongb38e1af2019-10-17 14:59:22 -0700119DynamicPartitionControlAndroid::DynamicPartitionControlAndroid()
120 : dynamic_partitions_(
121 GetFeatureFlag(kUseDynamicPartitions, kRetrfoitDynamicPartitions)),
Kelvin Zhangda1b3142020-09-24 17:09:02 -0400122 virtual_ab_(GetFeatureFlag(kVirtualAbEnabled, kVirtualAbRetrofit)),
123 virtual_ab_compression_(GetFeatureFlag(kVirtualAbCompressionEnabled,
124 kVirtualAbCompressionRetrofit)) {
Yifan Hongb38e1af2019-10-17 14:59:22 -0700125 if (GetVirtualAbFeatureFlag().IsEnabled()) {
Yifan Hongf033ecb2020-01-07 18:13:56 -0800126 snapshot_ = SnapshotManager::New();
Yifan Hongf9cb4492020-04-15 13:00:20 -0700127 } else {
128 snapshot_ = SnapshotManagerStub::New();
Yifan Hongb38e1af2019-10-17 14:59:22 -0700129 }
Yifan Hongf9cb4492020-04-15 13:00:20 -0700130 CHECK(snapshot_ != nullptr) << "Cannot initialize SnapshotManager.";
Yifan Hongb38e1af2019-10-17 14:59:22 -0700131}
132
Yifan Hong186bb682019-07-23 14:04:39 -0700133FeatureFlag DynamicPartitionControlAndroid::GetDynamicPartitionsFeatureFlag() {
Yifan Hongb38e1af2019-10-17 14:59:22 -0700134 return dynamic_partitions_;
Yifan Hong6e706b12018-11-09 16:50:51 -0800135}
136
Yifan Hong413d5722019-07-23 14:21:09 -0700137FeatureFlag DynamicPartitionControlAndroid::GetVirtualAbFeatureFlag() {
Yifan Hongb38e1af2019-10-17 14:59:22 -0700138 return virtual_ab_;
Yifan Hong413d5722019-07-23 14:21:09 -0700139}
140
Kelvin Zhangda1b3142020-09-24 17:09:02 -0400141FeatureFlag
142DynamicPartitionControlAndroid::GetVirtualAbCompressionFeatureFlag() {
Kelvin Zhangb9a5f612021-01-22 14:34:05 -0500143 if constexpr (constants::kIsRecovery) {
144 // Don't attempt VABC in recovery
145 return FeatureFlag(FeatureFlag::Value::NONE);
146 }
Kelvin Zhangda1b3142020-09-24 17:09:02 -0400147 return virtual_ab_compression_;
148}
149
Yifan Hongf5261562020-03-10 10:28:10 -0700150bool DynamicPartitionControlAndroid::OptimizeOperation(
151 const std::string& partition_name,
152 const InstallOperation& operation,
153 InstallOperation* optimized) {
Alessio Balsini2a3b4a22019-11-25 16:46:51 +0000154 switch (operation.type()) {
155 case InstallOperation::SOURCE_COPY:
156 return target_supports_snapshot_ &&
157 GetVirtualAbFeatureFlag().IsEnabled() &&
Yifan Hong6eec9952019-12-04 13:12:01 -0800158 mapped_devices_.count(partition_name +
159 SlotSuffixForSlotNumber(target_slot_)) > 0 &&
Yifan Hongf5261562020-03-10 10:28:10 -0700160 OptimizeSourceCopyOperation(operation, optimized);
Alessio Balsini2a3b4a22019-11-25 16:46:51 +0000161 break;
162 default:
163 break;
164 }
Alessio Balsini14980e22019-11-26 11:46:06 +0000165 return false;
166}
167
Yifan Hong8546a712019-03-28 14:42:53 -0700168bool DynamicPartitionControlAndroid::MapPartitionInternal(
Yifan Hong537802d2018-08-15 13:15:42 -0700169 const std::string& super_device,
170 const std::string& target_partition_name,
171 uint32_t slot,
Yifan Hongaf65ef12018-10-29 11:09:06 -0700172 bool force_writable,
Yifan Hong537802d2018-08-15 13:15:42 -0700173 std::string* path) {
David Andersonbb90dfb2019-08-13 14:14:56 -0700174 CreateLogicalPartitionParams params = {
175 .block_device = super_device,
176 .metadata_slot = slot,
177 .partition_name = target_partition_name,
178 .force_writable = force_writable,
David Andersonbb90dfb2019-08-13 14:14:56 -0700179 };
Yifan Hong420db9b2019-07-23 20:50:33 -0700180 bool success = false;
Yifan Hongf0f4a912019-09-26 17:51:33 -0700181 if (GetVirtualAbFeatureFlag().IsEnabled() && target_supports_snapshot_ &&
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700182 force_writable && ExpectMetadataMounted()) {
Yifan Hong420db9b2019-07-23 20:50:33 -0700183 // Only target partitions are mapped with force_writable. On Virtual
184 // A/B devices, target partitions may overlap with source partitions, so
185 // they must be mapped with snapshot.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700186 // One exception is when /metadata is not mounted. Fallback to
187 // CreateLogicalPartition as snapshots are not created in the first place.
Yifan Hong420db9b2019-07-23 20:50:33 -0700188 params.timeout_ms = kMapSnapshotTimeout;
189 success = snapshot_->MapUpdateSnapshot(params, path);
190 } else {
191 params.timeout_ms = kMapTimeout;
192 success = CreateLogicalPartition(params, path);
193 }
David Andersonbb90dfb2019-08-13 14:14:56 -0700194
Yifan Hong420db9b2019-07-23 20:50:33 -0700195 if (!success) {
Yifan Hong537802d2018-08-15 13:15:42 -0700196 LOG(ERROR) << "Cannot map " << target_partition_name << " in "
197 << super_device << " on device mapper.";
198 return false;
199 }
200 LOG(INFO) << "Succesfully mapped " << target_partition_name
Yifan Hongaf65ef12018-10-29 11:09:06 -0700201 << " to device mapper (force_writable = " << force_writable
202 << "); device path at " << *path;
Yifan Hong537802d2018-08-15 13:15:42 -0700203 mapped_devices_.insert(target_partition_name);
204 return true;
205}
206
Yifan Hong8546a712019-03-28 14:42:53 -0700207bool DynamicPartitionControlAndroid::MapPartitionOnDeviceMapper(
208 const std::string& super_device,
209 const std::string& target_partition_name,
210 uint32_t slot,
211 bool force_writable,
212 std::string* path) {
213 DmDeviceState state = GetState(target_partition_name);
214 if (state == DmDeviceState::ACTIVE) {
215 if (mapped_devices_.find(target_partition_name) != mapped_devices_.end()) {
216 if (GetDmDevicePathByName(target_partition_name, path)) {
217 LOG(INFO) << target_partition_name
218 << " is mapped on device mapper: " << *path;
219 return true;
220 }
221 LOG(ERROR) << target_partition_name << " is mapped but path is unknown.";
222 return false;
223 }
224 // If target_partition_name is not in mapped_devices_ but state is ACTIVE,
225 // the device might be mapped incorrectly before. Attempt to unmap it.
226 // Note that for source partitions, if GetState() == ACTIVE, callers (e.g.
227 // BootControlAndroid) should not call MapPartitionOnDeviceMapper, but
228 // should directly call GetDmDevicePathByName.
David Anderson4c891c92019-06-21 17:45:23 -0700229 if (!UnmapPartitionOnDeviceMapper(target_partition_name)) {
Yifan Hong8546a712019-03-28 14:42:53 -0700230 LOG(ERROR) << target_partition_name
231 << " is mapped before the update, and it cannot be unmapped.";
232 return false;
233 }
234 state = GetState(target_partition_name);
235 if (state != DmDeviceState::INVALID) {
236 LOG(ERROR) << target_partition_name << " is unmapped but state is "
237 << static_cast<std::underlying_type_t<DmDeviceState>>(state);
238 return false;
239 }
240 }
241 if (state == DmDeviceState::INVALID) {
242 return MapPartitionInternal(
243 super_device, target_partition_name, slot, force_writable, path);
244 }
245
246 LOG(ERROR) << target_partition_name
247 << " is mapped on device mapper but state is unknown: "
248 << static_cast<std::underlying_type_t<DmDeviceState>>(state);
249 return false;
250}
251
Yifan Hong537802d2018-08-15 13:15:42 -0700252bool DynamicPartitionControlAndroid::UnmapPartitionOnDeviceMapper(
David Anderson4c891c92019-06-21 17:45:23 -0700253 const std::string& target_partition_name) {
Yifan Hong537802d2018-08-15 13:15:42 -0700254 if (DeviceMapper::Instance().GetState(target_partition_name) !=
255 DmDeviceState::INVALID) {
Yifan Hong420db9b2019-07-23 20:50:33 -0700256 // Partitions at target slot on non-Virtual A/B devices are mapped as
257 // dm-linear. Also, on Virtual A/B devices, system_other may be mapped for
258 // preopt apps as dm-linear.
259 // Call DestroyLogicalPartition to handle these cases.
260 bool success = DestroyLogicalPartition(target_partition_name);
261
262 // On a Virtual A/B device, |target_partition_name| may be a leftover from
263 // a paused update. Clean up any underlying devices.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700264 if (ExpectMetadataMounted()) {
Yifan Hong420db9b2019-07-23 20:50:33 -0700265 success &= snapshot_->UnmapUpdateSnapshot(target_partition_name);
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700266 } else {
267 LOG(INFO) << "Skip UnmapUpdateSnapshot(" << target_partition_name
268 << ") because metadata is not mounted";
Yifan Hong420db9b2019-07-23 20:50:33 -0700269 }
270
271 if (!success) {
Yifan Hong537802d2018-08-15 13:15:42 -0700272 LOG(ERROR) << "Cannot unmap " << target_partition_name
273 << " from device mapper.";
274 return false;
275 }
276 LOG(INFO) << "Successfully unmapped " << target_partition_name
277 << " from device mapper.";
278 }
279 mapped_devices_.erase(target_partition_name);
280 return true;
281}
282
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -0400283bool DynamicPartitionControlAndroid::UnmapAllPartitions() {
Tao Bao8c4d0082019-08-08 08:56:16 -0700284 if (mapped_devices_.empty()) {
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -0400285 return false;
Tao Bao8c4d0082019-08-08 08:56:16 -0700286 }
Yifan Hong537802d2018-08-15 13:15:42 -0700287 // UnmapPartitionOnDeviceMapper removes objects from mapped_devices_, hence
288 // a copy is needed for the loop.
289 std::set<std::string> mapped = mapped_devices_;
290 LOG(INFO) << "Destroying [" << Join(mapped, ", ") << "] from device mapper";
291 for (const auto& partition_name : mapped) {
David Anderson4c891c92019-06-21 17:45:23 -0700292 ignore_result(UnmapPartitionOnDeviceMapper(partition_name));
Yifan Hong537802d2018-08-15 13:15:42 -0700293 }
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -0400294 return true;
Yifan Hong537802d2018-08-15 13:15:42 -0700295}
296
297void DynamicPartitionControlAndroid::Cleanup() {
Yifan Hongbae27842019-10-24 16:56:12 -0700298 UnmapAllPartitions();
299 metadata_device_.reset();
Yifan Hong537802d2018-08-15 13:15:42 -0700300}
301
302bool DynamicPartitionControlAndroid::DeviceExists(const std::string& path) {
303 return base::PathExists(base::FilePath(path));
304}
305
306android::dm::DmDeviceState DynamicPartitionControlAndroid::GetState(
307 const std::string& name) {
308 return DeviceMapper::Instance().GetState(name);
309}
310
311bool DynamicPartitionControlAndroid::GetDmDevicePathByName(
312 const std::string& name, std::string* path) {
313 return DeviceMapper::Instance().GetDmDevicePathByName(name, path);
314}
315
316std::unique_ptr<MetadataBuilder>
317DynamicPartitionControlAndroid::LoadMetadataBuilder(
Tianjie24f96092020-06-30 12:26:25 -0700318 const std::string& super_device, uint32_t slot) {
319 auto builder = MetadataBuilder::New(PartitionOpener(), super_device, slot);
320 if (builder == nullptr) {
321 LOG(WARNING) << "No metadata slot " << BootControlInterface::SlotName(slot)
322 << " in " << super_device;
323 return nullptr;
324 }
325 LOG(INFO) << "Loaded metadata from slot "
326 << BootControlInterface::SlotName(slot) << " in " << super_device;
327 return builder;
Yifan Hong012508e2019-07-22 18:30:40 -0700328}
329
330std::unique_ptr<MetadataBuilder>
331DynamicPartitionControlAndroid::LoadMetadataBuilder(
Yifan Hong6e706b12018-11-09 16:50:51 -0800332 const std::string& super_device,
333 uint32_t source_slot,
334 uint32_t target_slot) {
Tianjie24f96092020-06-30 12:26:25 -0700335 bool always_keep_source_slot = !target_supports_snapshot_;
336 auto builder = MetadataBuilder::NewForUpdate(PartitionOpener(),
337 super_device,
338 source_slot,
339 target_slot,
340 always_keep_source_slot);
Yifan Hong537802d2018-08-15 13:15:42 -0700341 if (builder == nullptr) {
342 LOG(WARNING) << "No metadata slot "
343 << BootControlInterface::SlotName(source_slot) << " in "
344 << super_device;
Yifan Hongf48a0052018-10-29 16:30:43 -0700345 return nullptr;
Yifan Hong537802d2018-08-15 13:15:42 -0700346 }
Tianjie24f96092020-06-30 12:26:25 -0700347 LOG(INFO) << "Created metadata for new update from slot "
Yifan Hong537802d2018-08-15 13:15:42 -0700348 << BootControlInterface::SlotName(source_slot) << " in "
349 << super_device;
350 return builder;
351}
352
353bool DynamicPartitionControlAndroid::StoreMetadata(
354 const std::string& super_device,
355 MetadataBuilder* builder,
356 uint32_t target_slot) {
357 auto metadata = builder->Export();
358 if (metadata == nullptr) {
359 LOG(ERROR) << "Cannot export metadata to slot "
360 << BootControlInterface::SlotName(target_slot) << " in "
361 << super_device;
362 return false;
363 }
364
Yifan Hong186bb682019-07-23 14:04:39 -0700365 if (GetDynamicPartitionsFeatureFlag().IsRetrofit()) {
Yifan Hong6e706b12018-11-09 16:50:51 -0800366 if (!FlashPartitionTable(super_device, *metadata)) {
367 LOG(ERROR) << "Cannot write metadata to " << super_device;
368 return false;
369 }
370 LOG(INFO) << "Written metadata to " << super_device;
371 } else {
372 if (!UpdatePartitionTable(super_device, *metadata, target_slot)) {
373 LOG(ERROR) << "Cannot write metadata to slot "
374 << BootControlInterface::SlotName(target_slot) << " in "
375 << super_device;
376 return false;
377 }
378 LOG(INFO) << "Copied metadata to slot "
379 << BootControlInterface::SlotName(target_slot) << " in "
380 << super_device;
Yifan Hong537802d2018-08-15 13:15:42 -0700381 }
382
Yifan Hong537802d2018-08-15 13:15:42 -0700383 return true;
384}
385
386bool DynamicPartitionControlAndroid::GetDeviceDir(std::string* out) {
387 // We can't use fs_mgr to look up |partition_name| because fstab
388 // doesn't list every slot partition (it uses the slotselect option
389 // to mask the suffix).
390 //
391 // We can however assume that there's an entry for the /misc mount
392 // point and use that to get the device file for the misc
393 // partition. This helps us locate the disk that |partition_name|
394 // resides on. From there we'll assume that a by-name scheme is used
395 // so we can just replace the trailing "misc" by the given
396 // |partition_name| and suffix corresponding to |slot|, e.g.
397 //
398 // /dev/block/platform/soc.0/7824900.sdhci/by-name/misc ->
399 // /dev/block/platform/soc.0/7824900.sdhci/by-name/boot_a
400 //
401 // If needed, it's possible to relax the by-name assumption in the
402 // future by trawling /sys/block looking for the appropriate sibling
403 // of misc and then finding an entry in /dev matching the sysfs
404 // entry.
405
406 std::string err, misc_device = get_bootloader_message_blk_device(&err);
407 if (misc_device.empty()) {
408 LOG(ERROR) << "Unable to get misc block device: " << err;
409 return false;
410 }
411
412 if (!utils::IsSymlink(misc_device.c_str())) {
413 LOG(ERROR) << "Device file " << misc_device << " for /misc "
414 << "is not a symlink.";
415 return false;
416 }
417 *out = base::FilePath(misc_device).DirName().value();
418 return true;
419}
Yifan Hong012508e2019-07-22 18:30:40 -0700420
421bool DynamicPartitionControlAndroid::PreparePartitionsForUpdate(
422 uint32_t source_slot,
423 uint32_t target_slot,
Yifan Hongf0f4a912019-09-26 17:51:33 -0700424 const DeltaArchiveManifest& manifest,
Yifan Hongf033ecb2020-01-07 18:13:56 -0800425 bool update,
426 uint64_t* required_size) {
Yifan Hong6eec9952019-12-04 13:12:01 -0800427 source_slot_ = source_slot;
428 target_slot_ = target_slot;
Yifan Hongf033ecb2020-01-07 18:13:56 -0800429 if (required_size != nullptr) {
430 *required_size = 0;
431 }
Yifan Hong6eec9952019-12-04 13:12:01 -0800432
Yifan Hong3a1a5612019-11-05 16:34:32 -0800433 if (fs_mgr_overlayfs_is_setup()) {
434 // Non DAP devices can use overlayfs as well.
435 LOG(WARNING)
436 << "overlayfs overrides are active and can interfere with our "
437 "resources.\n"
438 << "run adb enable-verity to deactivate if required and try again.";
439 }
440
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700441 // If metadata is erased but not formatted, it is possible to not mount
442 // it in recovery. It is acceptable to skip mounting and choose fallback path
443 // (PrepareDynamicPartitionsForUpdate) when sideloading full OTAs.
444 TEST_AND_RETURN_FALSE(EnsureMetadataMounted() || IsRecovery());
Yifan Hong29692902020-03-26 12:47:05 -0700445
446 if (update) {
447 TEST_AND_RETURN_FALSE(EraseSystemOtherAvbFooter(source_slot, target_slot));
448 }
449
Yifan Hong3a1a5612019-11-05 16:34:32 -0800450 if (!GetDynamicPartitionsFeatureFlag().IsEnabled()) {
451 return true;
452 }
453
454 if (target_slot == source_slot) {
455 LOG(ERROR) << "Cannot call PreparePartitionsForUpdate on current slot.";
456 return false;
457 }
458
Yifan Hongf6f75c22020-07-31 15:20:25 -0700459 if (!SetTargetBuildVars(manifest)) {
460 return false;
461 }
462
Yifan Hong3a1a5612019-11-05 16:34:32 -0800463 // Although the current build supports dynamic partitions, the given payload
464 // doesn't use it for target partitions. This could happen when applying a
465 // retrofit update. Skip updating the partition metadata for the target slot.
Yifan Hong3a1a5612019-11-05 16:34:32 -0800466 if (!is_target_dynamic_) {
467 return true;
468 }
469
Yifan Hongf0f4a912019-09-26 17:51:33 -0700470 if (!update)
471 return true;
472
Yifan Hongbae27842019-10-24 16:56:12 -0700473 bool delete_source = false;
474
Yifan Hong6d888562019-10-01 13:00:31 -0700475 if (GetVirtualAbFeatureFlag().IsEnabled()) {
476 // On Virtual A/B device, either CancelUpdate() or BeginUpdate() must be
477 // called before calling UnmapUpdateSnapshot.
478 // - If target_supports_snapshot_, PrepareSnapshotPartitionsForUpdate()
479 // calls BeginUpdate() which resets update state
Yifan Hongbae27842019-10-24 16:56:12 -0700480 // - If !target_supports_snapshot_ or PrepareSnapshotPartitionsForUpdate
481 // failed in recovery, explicitly CancelUpdate().
Yifan Hong6d888562019-10-01 13:00:31 -0700482 if (target_supports_snapshot_) {
Yifan Hongbae27842019-10-24 16:56:12 -0700483 if (PrepareSnapshotPartitionsForUpdate(
484 source_slot, target_slot, manifest, required_size)) {
485 return true;
486 }
487
488 // Virtual A/B device doing Virtual A/B update in Android mode must use
489 // snapshots.
490 if (!IsRecovery()) {
491 LOG(ERROR) << "PrepareSnapshotPartitionsForUpdate failed in Android "
492 << "mode";
493 return false;
494 }
495
496 delete_source = true;
497 LOG(INFO) << "PrepareSnapshotPartitionsForUpdate failed in recovery. "
498 << "Attempt to overwrite existing partitions if possible";
499 } else {
500 // Downgrading to an non-Virtual A/B build or is secondary OTA.
501 LOG(INFO) << "Using regular A/B on Virtual A/B because package disabled "
502 << "snapshots.";
Yifan Hong6d888562019-10-01 13:00:31 -0700503 }
Yifan Hongbae27842019-10-24 16:56:12 -0700504
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700505 // In recovery, if /metadata is not mounted, it is likely that metadata
506 // partition is erased and not formatted yet. After sideloading, when
507 // rebooting into the new version, init will erase metadata partition,
508 // hence the failure of CancelUpdate() can be ignored here.
509 // However, if metadata is mounted and CancelUpdate fails, sideloading
510 // should not proceed because during next boot, snapshots will overlay on
511 // the devices incorrectly.
512 if (ExpectMetadataMounted()) {
513 TEST_AND_RETURN_FALSE(snapshot_->CancelUpdate());
514 } else {
515 LOG(INFO) << "Skip canceling previous update because metadata is not "
516 << "mounted";
Yifan Hong6d888562019-10-01 13:00:31 -0700517 }
Yifan Hong420db9b2019-07-23 20:50:33 -0700518 }
Yifan Hongbae27842019-10-24 16:56:12 -0700519
Tianjie24f96092020-06-30 12:26:25 -0700520 // TODO(xunchang) support partial update on non VAB enabled devices.
Yifan Hong5c5743f2020-04-16 12:59:07 -0700521 TEST_AND_RETURN_FALSE(PrepareDynamicPartitionsForUpdate(
522 source_slot, target_slot, manifest, delete_source));
523
524 if (required_size != nullptr) {
525 *required_size = 0;
526 }
527 return true;
Yifan Hong420db9b2019-07-23 20:50:33 -0700528}
529
Yifan Hongf6f75c22020-07-31 15:20:25 -0700530bool DynamicPartitionControlAndroid::SetTargetBuildVars(
531 const DeltaArchiveManifest& manifest) {
532 // Precondition: current build supports dynamic partition.
533 CHECK(GetDynamicPartitionsFeatureFlag().IsEnabled());
534
535 bool is_target_dynamic =
536 !manifest.dynamic_partition_metadata().groups().empty();
537 bool target_supports_snapshot =
538 manifest.dynamic_partition_metadata().snapshot_enabled();
539
540 if (manifest.partial_update()) {
541 // Partial updates requires DAP. On partial updates that does not involve
542 // dynamic partitions, groups() can be empty, so also assume
543 // is_target_dynamic in this case. This assumption should be safe because we
544 // also check target_supports_snapshot below, which presumably also implies
545 // target build supports dynamic partition.
546 if (!is_target_dynamic) {
547 LOG(INFO) << "Assuming target build supports dynamic partitions for "
548 "partial updates.";
549 is_target_dynamic = true;
550 }
551
552 // Partial updates requires Virtual A/B. Double check that both current
553 // build and target build supports Virtual A/B.
554 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
555 LOG(ERROR) << "Partial update cannot be applied on a device that does "
556 "not support snapshots.";
557 return false;
558 }
559 if (!target_supports_snapshot) {
560 LOG(ERROR) << "Cannot apply partial update to a build that does not "
561 "support snapshots.";
562 return false;
563 }
564 }
565
566 // Store the flags.
567 is_target_dynamic_ = is_target_dynamic;
568 // If !is_target_dynamic_, leave target_supports_snapshot_ unset because
569 // snapshots would not work without dynamic partition.
570 if (is_target_dynamic_) {
571 target_supports_snapshot_ = target_supports_snapshot;
572 }
573 return true;
574}
575
Yifan Hong29692902020-03-26 12:47:05 -0700576namespace {
577// Try our best to erase AVB footer.
578class AvbFooterEraser {
579 public:
580 explicit AvbFooterEraser(const std::string& path) : path_(path) {}
581 bool Erase() {
582 // Try to mark the block device read-only. Ignore any
583 // failure since this won't work when passing regular files.
584 ignore_result(utils::SetBlockDeviceReadOnly(path_, false /* readonly */));
585
586 fd_.reset(new EintrSafeFileDescriptor());
587 int flags = O_WRONLY | O_TRUNC | O_CLOEXEC | O_SYNC;
588 TEST_AND_RETURN_FALSE(fd_->Open(path_.c_str(), flags));
589
590 // Need to write end-AVB_FOOTER_SIZE to end.
591 static_assert(AVB_FOOTER_SIZE > 0);
592 off64_t offset = fd_->Seek(-AVB_FOOTER_SIZE, SEEK_END);
593 TEST_AND_RETURN_FALSE_ERRNO(offset >= 0);
594 uint64_t write_size = AVB_FOOTER_SIZE;
595 LOG(INFO) << "Zeroing " << path_ << " @ [" << offset << ", "
596 << (offset + write_size) << "] (" << write_size << " bytes)";
597 brillo::Blob zeros(write_size);
598 TEST_AND_RETURN_FALSE(utils::WriteAll(fd_, zeros.data(), zeros.size()));
599 return true;
600 }
601 ~AvbFooterEraser() {
602 TEST_AND_RETURN(fd_ != nullptr && fd_->IsOpen());
603 if (!fd_->Close()) {
604 LOG(WARNING) << "Failed to close fd for " << path_;
605 }
606 }
607
608 private:
609 std::string path_;
610 FileDescriptorPtr fd_;
611};
612
613} // namespace
614
615std::optional<bool>
616DynamicPartitionControlAndroid::IsAvbEnabledOnSystemOther() {
617 auto prefix = GetProperty(kPostinstallFstabPrefix, "");
618 if (prefix.empty()) {
619 LOG(WARNING) << "Cannot get " << kPostinstallFstabPrefix;
620 return std::nullopt;
621 }
622 auto path = base::FilePath(prefix).Append("etc/fstab.postinstall").value();
623 return IsAvbEnabledInFstab(path);
624}
625
626std::optional<bool> DynamicPartitionControlAndroid::IsAvbEnabledInFstab(
627 const std::string& path) {
628 Fstab fstab;
629 if (!ReadFstabFromFile(path, &fstab)) {
Yifan Hong93cde302020-04-27 12:59:29 -0700630 PLOG(WARNING) << "Cannot read fstab from " << path;
631 if (errno == ENOENT) {
632 return false;
633 }
Yifan Hong29692902020-03-26 12:47:05 -0700634 return std::nullopt;
635 }
636 for (const auto& entry : fstab) {
637 if (!entry.avb_keys.empty()) {
638 return true;
639 }
640 }
641 return false;
642}
643
644bool DynamicPartitionControlAndroid::GetSystemOtherPath(
645 uint32_t source_slot,
646 uint32_t target_slot,
647 const std::string& partition_name_suffix,
648 std::string* path,
649 bool* should_unmap) {
650 path->clear();
651 *should_unmap = false;
652
P.Adarsh Reddy13e4195d2020-06-08 23:17:36 +0530653 // Check that AVB is enabled on system_other before erasing.
654 auto has_avb = IsAvbEnabledOnSystemOther();
655 TEST_AND_RETURN_FALSE(has_avb.has_value());
656 if (!has_avb.value()) {
657 LOG(INFO) << "AVB is not enabled on system_other. Skip erasing.";
658 return true;
659 }
Yifan Hong29692902020-03-26 12:47:05 -0700660
P.Adarsh Reddy13e4195d2020-06-08 23:17:36 +0530661 if (!IsRecovery()) {
Yifan Hong29692902020-03-26 12:47:05 -0700662 // Found unexpected avb_keys for system_other on devices retrofitting
663 // dynamic partitions. Previous crash in update_engine may leave logical
664 // partitions mapped on physical system_other partition. It is difficult to
665 // handle these cases. Just fail.
666 if (GetDynamicPartitionsFeatureFlag().IsRetrofit()) {
667 LOG(ERROR) << "Cannot erase AVB footer on system_other on devices with "
668 << "retrofit dynamic partitions. They should not have AVB "
669 << "enabled on system_other.";
670 return false;
671 }
672 }
673
674 std::string device_dir_str;
675 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
676 base::FilePath device_dir(device_dir_str);
677
678 // On devices without dynamic partition, search for static partitions.
679 if (!GetDynamicPartitionsFeatureFlag().IsEnabled()) {
680 *path = device_dir.Append(partition_name_suffix).value();
681 TEST_AND_RETURN_FALSE(DeviceExists(*path));
682 return true;
683 }
684
685 auto source_super_device =
686 device_dir.Append(GetSuperPartitionName(source_slot)).value();
687
688 auto builder = LoadMetadataBuilder(source_super_device, source_slot);
689 if (builder == nullptr) {
690 if (IsRecovery()) {
691 // It might be corrupted for some reason. It should still be able to
692 // sideload.
693 LOG(WARNING) << "Super partition metadata cannot be read from the source "
694 << "slot, skip erasing.";
695 return true;
696 } else {
697 // Device has booted into Android mode, indicating that the super
698 // partition metadata should be there.
699 LOG(ERROR) << "Super partition metadata cannot be read from the source "
700 << "slot. This is unexpected on devices with dynamic "
701 << "partitions enabled.";
702 return false;
703 }
704 }
705 auto p = builder->FindPartition(partition_name_suffix);
706 if (p == nullptr) {
707 // If the source slot is flashed without system_other, it does not exist
708 // in super partition metadata at source slot. It is safe to skip it.
709 LOG(INFO) << "Can't find " << partition_name_suffix
710 << " in metadata source slot, skip erasing.";
711 return true;
712 }
713 // System_other created by flashing tools should be erased.
714 // If partition is created by update_engine (via NewForUpdate), it is a
715 // left-over partition from the previous update and does not contain
716 // system_other, hence there is no need to erase.
717 // Note the reverse is not necessary true. If the flag is not set, we don't
718 // know if the partition is created by update_engine or by flashing tools
719 // because older versions of super partition metadata does not contain this
720 // flag. It is okay to erase the AVB footer anyways.
721 if (p->attributes() & LP_PARTITION_ATTR_UPDATED) {
722 LOG(INFO) << partition_name_suffix
723 << " does not contain system_other, skip erasing.";
724 return true;
725 }
726
Yifan Hong64331b32020-05-13 16:50:40 -0700727 if (p->size() < AVB_FOOTER_SIZE) {
728 LOG(INFO) << partition_name_suffix << " has length " << p->size()
729 << "( < AVB_FOOTER_SIZE " << AVB_FOOTER_SIZE
730 << "), skip erasing.";
731 return true;
732 }
733
Yifan Hong29692902020-03-26 12:47:05 -0700734 // Delete any pre-existing device with name |partition_name_suffix| and
735 // also remove it from |mapped_devices_|.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700736 // In recovery, metadata might not be mounted, and
737 // UnmapPartitionOnDeviceMapper might fail. However,
738 // it is unusual that system_other has already been mapped. Hence, just skip.
Yifan Hong29692902020-03-26 12:47:05 -0700739 TEST_AND_RETURN_FALSE(UnmapPartitionOnDeviceMapper(partition_name_suffix));
740 // Use CreateLogicalPartition directly to avoid mapping with existing
741 // snapshots.
742 CreateLogicalPartitionParams params = {
743 .block_device = source_super_device,
744 .metadata_slot = source_slot,
745 .partition_name = partition_name_suffix,
746 .force_writable = true,
747 .timeout_ms = kMapTimeout,
748 };
749 TEST_AND_RETURN_FALSE(CreateLogicalPartition(params, path));
750 *should_unmap = true;
751 return true;
752}
753
754bool DynamicPartitionControlAndroid::EraseSystemOtherAvbFooter(
755 uint32_t source_slot, uint32_t target_slot) {
756 LOG(INFO) << "Erasing AVB footer of system_other partition before update.";
757
758 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
759 const std::string partition_name_suffix = "system" + target_suffix;
760
761 std::string path;
762 bool should_unmap = false;
763
764 TEST_AND_RETURN_FALSE(GetSystemOtherPath(
765 source_slot, target_slot, partition_name_suffix, &path, &should_unmap));
766
767 if (path.empty()) {
768 return true;
769 }
770
771 bool ret = AvbFooterEraser(path).Erase();
772
773 // Delete |partition_name_suffix| from device mapper and from
774 // |mapped_devices_| again so that it does not interfere with update process.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700775 // In recovery, metadata might not be mounted, and
776 // UnmapPartitionOnDeviceMapper might fail. However, DestroyLogicalPartition
777 // should be called. If DestroyLogicalPartition does fail, it is still okay
778 // to skip the error here and let Prepare*() fail later.
Yifan Hong29692902020-03-26 12:47:05 -0700779 if (should_unmap) {
780 TEST_AND_RETURN_FALSE(UnmapPartitionOnDeviceMapper(partition_name_suffix));
781 }
782
783 return ret;
784}
785
Yifan Hong420db9b2019-07-23 20:50:33 -0700786bool DynamicPartitionControlAndroid::PrepareDynamicPartitionsForUpdate(
787 uint32_t source_slot,
788 uint32_t target_slot,
Yifan Hongbae27842019-10-24 16:56:12 -0700789 const DeltaArchiveManifest& manifest,
790 bool delete_source) {
Yifan Hong012508e2019-07-22 18:30:40 -0700791 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
792
793 // Unmap all the target dynamic partitions because they would become
794 // inconsistent with the new metadata.
Yifan Hong13d41cb2019-09-16 13:18:22 -0700795 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
796 for (const auto& partition_name : group.partition_names()) {
797 if (!UnmapPartitionOnDeviceMapper(partition_name + target_suffix)) {
Yifan Hong012508e2019-07-22 18:30:40 -0700798 return false;
799 }
800 }
801 }
802
803 std::string device_dir_str;
804 if (!GetDeviceDir(&device_dir_str)) {
805 return false;
806 }
807 base::FilePath device_dir(device_dir_str);
808 auto source_device =
Yifan Hong700d7c12019-07-23 20:49:16 -0700809 device_dir.Append(GetSuperPartitionName(source_slot)).value();
Yifan Hong012508e2019-07-22 18:30:40 -0700810
811 auto builder = LoadMetadataBuilder(source_device, source_slot, target_slot);
812 if (builder == nullptr) {
813 LOG(ERROR) << "No metadata at "
814 << BootControlInterface::SlotName(source_slot);
815 return false;
816 }
817
Yifan Hongbae27842019-10-24 16:56:12 -0700818 if (delete_source) {
819 TEST_AND_RETURN_FALSE(
820 DeleteSourcePartitions(builder.get(), source_slot, manifest));
821 }
822
Yifan Hong13d41cb2019-09-16 13:18:22 -0700823 if (!UpdatePartitionMetadata(builder.get(), target_slot, manifest)) {
Yifan Hong012508e2019-07-22 18:30:40 -0700824 return false;
825 }
826
827 auto target_device =
Yifan Hong700d7c12019-07-23 20:49:16 -0700828 device_dir.Append(GetSuperPartitionName(target_slot)).value();
Yifan Hong012508e2019-07-22 18:30:40 -0700829 return StoreMetadata(target_device, builder.get(), target_slot);
830}
831
Yifan Hong420db9b2019-07-23 20:50:33 -0700832bool DynamicPartitionControlAndroid::PrepareSnapshotPartitionsForUpdate(
833 uint32_t source_slot,
834 uint32_t target_slot,
Yifan Hongf033ecb2020-01-07 18:13:56 -0800835 const DeltaArchiveManifest& manifest,
836 uint64_t* required_size) {
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700837 TEST_AND_RETURN_FALSE(ExpectMetadataMounted());
Yifan Hong420db9b2019-07-23 20:50:33 -0700838 if (!snapshot_->BeginUpdate()) {
839 LOG(ERROR) << "Cannot begin new update.";
840 return false;
841 }
Yifan Hongf033ecb2020-01-07 18:13:56 -0800842 auto ret = snapshot_->CreateUpdateSnapshots(manifest);
843 if (!ret) {
844 LOG(ERROR) << "Cannot create update snapshots: " << ret.string();
845 if (required_size != nullptr &&
Yifan Hong0850bca2020-01-16 15:14:07 -0800846 ret.error_code() == Return::ErrorCode::NO_SPACE) {
Yifan Hongf033ecb2020-01-07 18:13:56 -0800847 *required_size = ret.required_size();
848 }
Yifan Hong420db9b2019-07-23 20:50:33 -0700849 return false;
850 }
851 return true;
852}
853
Yifan Hong700d7c12019-07-23 20:49:16 -0700854std::string DynamicPartitionControlAndroid::GetSuperPartitionName(
855 uint32_t slot) {
856 return fs_mgr_get_super_partition_name(slot);
857}
858
Yifan Hong012508e2019-07-22 18:30:40 -0700859bool DynamicPartitionControlAndroid::UpdatePartitionMetadata(
860 MetadataBuilder* builder,
861 uint32_t target_slot,
Yifan Hong13d41cb2019-09-16 13:18:22 -0700862 const DeltaArchiveManifest& manifest) {
Yifan Hong8d6df9a2020-08-13 13:59:54 -0700863 // Check preconditions.
864 CHECK(!GetVirtualAbFeatureFlag().IsEnabled() || IsRecovery())
865 << "UpdatePartitionMetadata is called on a Virtual A/B device "
866 "but source partitions is not deleted. This is not allowed.";
867
Yifan Honga4e7da32019-09-30 18:25:03 -0700868 // If applying downgrade from Virtual A/B to non-Virtual A/B, the left-over
869 // COW group needs to be deleted to ensure there are enough space to create
870 // target partitions.
871 builder->RemoveGroupAndPartitions(android::snapshot::kCowGroupName);
872
Yifan Hong012508e2019-07-22 18:30:40 -0700873 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
874 DeleteGroupsWithSuffix(builder, target_suffix);
875
876 uint64_t total_size = 0;
Yifan Hong13d41cb2019-09-16 13:18:22 -0700877 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
878 total_size += group.size();
Yifan Hong012508e2019-07-22 18:30:40 -0700879 }
880
881 std::string expr;
882 uint64_t allocatable_space = builder->AllocatableSpace();
Yifan Hong8d6df9a2020-08-13 13:59:54 -0700883 // On device retrofitting dynamic partitions, allocatable_space = super.
884 // On device launching dynamic partitions w/o VAB,
885 // allocatable_space = super / 2.
886 // On device launching dynamic partitions with VAB, allocatable_space = super.
887 if (!GetDynamicPartitionsFeatureFlag().IsRetrofit() &&
888 !GetVirtualAbFeatureFlag().IsEnabled()) {
Yifan Hong012508e2019-07-22 18:30:40 -0700889 allocatable_space /= 2;
890 expr = "half of ";
891 }
892 if (total_size > allocatable_space) {
893 LOG(ERROR) << "The maximum size of all groups with suffix " << target_suffix
894 << " (" << total_size << ") has exceeded " << expr
895 << "allocatable space for dynamic partitions "
896 << allocatable_space << ".";
897 return false;
898 }
899
Yifan Hong13d41cb2019-09-16 13:18:22 -0700900 // name of partition(e.g. "system") -> size in bytes
901 std::map<std::string, uint64_t> partition_sizes;
902 for (const auto& partition : manifest.partitions()) {
903 partition_sizes.emplace(partition.partition_name(),
904 partition.new_partition_info().size());
905 }
906
907 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
908 auto group_name_suffix = group.name() + target_suffix;
909 if (!builder->AddGroup(group_name_suffix, group.size())) {
Yifan Hong012508e2019-07-22 18:30:40 -0700910 LOG(ERROR) << "Cannot add group " << group_name_suffix << " with size "
Yifan Hong13d41cb2019-09-16 13:18:22 -0700911 << group.size();
Yifan Hong012508e2019-07-22 18:30:40 -0700912 return false;
913 }
914 LOG(INFO) << "Added group " << group_name_suffix << " with size "
Yifan Hong13d41cb2019-09-16 13:18:22 -0700915 << group.size();
Yifan Hong012508e2019-07-22 18:30:40 -0700916
Yifan Hong13d41cb2019-09-16 13:18:22 -0700917 for (const auto& partition_name : group.partition_names()) {
918 auto partition_sizes_it = partition_sizes.find(partition_name);
919 if (partition_sizes_it == partition_sizes.end()) {
920 // TODO(tbao): Support auto-filling partition info for framework-only
921 // OTA.
922 LOG(ERROR) << "dynamic_partition_metadata contains partition "
923 << partition_name << " but it is not part of the manifest. "
924 << "This is not supported.";
925 return false;
926 }
927 uint64_t partition_size = partition_sizes_it->second;
928
929 auto partition_name_suffix = partition_name + target_suffix;
Yifan Hong012508e2019-07-22 18:30:40 -0700930 Partition* p = builder->AddPartition(
931 partition_name_suffix, group_name_suffix, LP_PARTITION_ATTR_READONLY);
932 if (!p) {
933 LOG(ERROR) << "Cannot add partition " << partition_name_suffix
934 << " to group " << group_name_suffix;
935 return false;
936 }
Yifan Hong13d41cb2019-09-16 13:18:22 -0700937 if (!builder->ResizePartition(p, partition_size)) {
Yifan Hong012508e2019-07-22 18:30:40 -0700938 LOG(ERROR) << "Cannot resize partition " << partition_name_suffix
Yifan Hong13d41cb2019-09-16 13:18:22 -0700939 << " to size " << partition_size << ". Not enough space?";
Yifan Hong012508e2019-07-22 18:30:40 -0700940 return false;
941 }
942 LOG(INFO) << "Added partition " << partition_name_suffix << " to group "
Yifan Hong13d41cb2019-09-16 13:18:22 -0700943 << group_name_suffix << " with size " << partition_size;
Yifan Hong012508e2019-07-22 18:30:40 -0700944 }
945 }
946
947 return true;
948}
949
Yifan Hong7b3910a2020-03-24 17:47:32 -0700950bool DynamicPartitionControlAndroid::FinishUpdate(bool powerwash_required) {
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700951 if (ExpectMetadataMounted()) {
952 if (snapshot_->GetUpdateState() == UpdateState::Initiated) {
953 LOG(INFO) << "Snapshot writes are done.";
954 return snapshot_->FinishedSnapshotWrites(powerwash_required);
955 }
956 } else {
957 LOG(INFO) << "Skip FinishedSnapshotWrites() because /metadata is not "
958 << "mounted";
Yifan Hongf0f4a912019-09-26 17:51:33 -0700959 }
960 return true;
Yifan Honga33bca42019-09-03 20:29:45 -0700961}
962
Yifan Hong3a1a5612019-11-05 16:34:32 -0800963bool DynamicPartitionControlAndroid::GetPartitionDevice(
964 const std::string& partition_name,
965 uint32_t slot,
966 uint32_t current_slot,
Tianjie51a5a392020-06-03 14:39:32 -0700967 bool not_in_payload,
968 std::string* device,
969 bool* is_dynamic) {
Kelvin Zhang66a9ebb2021-01-25 13:35:10 -0500970 auto partition_dev =
971 GetPartitionDevice(partition_name, slot, current_slot, not_in_payload);
Kelvin Zhang91d95fa2020-11-05 13:52:00 -0500972 if (!partition_dev.has_value()) {
Yifan Hong3a1a5612019-11-05 16:34:32 -0800973 return false;
974 }
Kelvin Zhang91d95fa2020-11-05 13:52:00 -0500975 if (device) {
976 *device = std::move(partition_dev->rw_device_path);
977 }
978 if (is_dynamic) {
979 *is_dynamic = partition_dev->is_dynamic;
980 }
Yifan Hong3a1a5612019-11-05 16:34:32 -0800981 return true;
982}
983
Tianjie51a5a392020-06-03 14:39:32 -0700984bool DynamicPartitionControlAndroid::GetPartitionDevice(
985 const std::string& partition_name,
986 uint32_t slot,
987 uint32_t current_slot,
988 std::string* device) {
989 return GetPartitionDevice(
990 partition_name, slot, current_slot, false, device, nullptr);
991}
992
Kelvin Zhang91d95fa2020-11-05 13:52:00 -0500993static std::string GetStaticDevicePath(
994 const base::FilePath& device_dir,
995 const std::string& partition_name_suffixed) {
996 base::FilePath path = device_dir.Append(partition_name_suffixed);
997 return path.value();
998}
999
1000std::optional<PartitionDevice>
1001DynamicPartitionControlAndroid::GetPartitionDevice(
1002 const std::string& partition_name,
1003 uint32_t slot,
1004 uint32_t current_slot,
1005 bool not_in_payload) {
1006 std::string device_dir_str;
1007 if (!GetDeviceDir(&device_dir_str)) {
1008 LOG(ERROR) << "Failed to GetDeviceDir()";
1009 return {};
1010 }
1011 const base::FilePath device_dir(device_dir_str);
1012 // When VABC is enabled, we can't get device path for dynamic partitions in
1013 // target slot.
1014 const auto& partition_name_suffix =
1015 partition_name + SlotSuffixForSlotNumber(slot);
Kelvin Zhang06188352021-02-10 13:21:47 -05001016 if (UpdateUsesSnapshotCompression() && IsDynamicPartition(partition_name) &&
1017 slot != current_slot) {
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001018 return {{.mountable_device_path =
1019 GetStaticDevicePath(device_dir, partition_name_suffix),
1020 .is_dynamic = true}};
1021 }
1022
1023 // When looking up target partition devices, treat them as static if the
1024 // current payload doesn't encode them as dynamic partitions. This may happen
1025 // when applying a retrofit update on top of a dynamic-partitions-enabled
1026 // build.
1027 std::string device;
1028 if (GetDynamicPartitionsFeatureFlag().IsEnabled() &&
1029 (slot == current_slot || is_target_dynamic_)) {
1030 switch (GetDynamicPartitionDevice(device_dir,
1031 partition_name_suffix,
1032 slot,
1033 current_slot,
1034 not_in_payload,
1035 &device)) {
1036 case DynamicPartitionDeviceStatus::SUCCESS:
1037 return {{.rw_device_path = device,
1038 .mountable_device_path = device,
1039 .is_dynamic = true}};
1040
1041 case DynamicPartitionDeviceStatus::TRY_STATIC:
1042 break;
1043 case DynamicPartitionDeviceStatus::ERROR: // fallthrough
1044 default:
1045 return {};
1046 }
1047 }
1048 // Try static partitions.
1049 auto static_path = GetStaticDevicePath(device_dir, partition_name_suffix);
1050 if (!DeviceExists(static_path)) {
1051 LOG(ERROR) << "Device file " << static_path << " does not exist.";
1052 return {};
1053 }
1054
1055 return {{.rw_device_path = static_path,
1056 .mountable_device_path = static_path,
1057 .is_dynamic = false}};
1058}
1059
Yifan Hong3a1a5612019-11-05 16:34:32 -08001060bool DynamicPartitionControlAndroid::IsSuperBlockDevice(
1061 const base::FilePath& device_dir,
1062 uint32_t current_slot,
1063 const std::string& partition_name_suffix) {
1064 std::string source_device =
1065 device_dir.Append(GetSuperPartitionName(current_slot)).value();
1066 auto source_metadata = LoadMetadataBuilder(source_device, current_slot);
1067 return source_metadata->HasBlockDevice(partition_name_suffix);
1068}
1069
1070DynamicPartitionControlAndroid::DynamicPartitionDeviceStatus
1071DynamicPartitionControlAndroid::GetDynamicPartitionDevice(
1072 const base::FilePath& device_dir,
1073 const std::string& partition_name_suffix,
1074 uint32_t slot,
1075 uint32_t current_slot,
Tianjie51a5a392020-06-03 14:39:32 -07001076 bool not_in_payload,
Yifan Hong3a1a5612019-11-05 16:34:32 -08001077 std::string* device) {
1078 std::string super_device =
1079 device_dir.Append(GetSuperPartitionName(slot)).value();
1080
1081 auto builder = LoadMetadataBuilder(super_device, slot);
1082 if (builder == nullptr) {
1083 LOG(ERROR) << "No metadata in slot "
1084 << BootControlInterface::SlotName(slot);
1085 return DynamicPartitionDeviceStatus::ERROR;
1086 }
1087 if (builder->FindPartition(partition_name_suffix) == nullptr) {
1088 LOG(INFO) << partition_name_suffix
1089 << " is not in super partition metadata.";
1090
1091 if (IsSuperBlockDevice(device_dir, current_slot, partition_name_suffix)) {
1092 LOG(ERROR) << "The static partition " << partition_name_suffix
1093 << " is a block device for current metadata."
1094 << "It cannot be used as a logical partition.";
1095 return DynamicPartitionDeviceStatus::ERROR;
1096 }
1097
1098 return DynamicPartitionDeviceStatus::TRY_STATIC;
1099 }
1100
1101 if (slot == current_slot) {
1102 if (GetState(partition_name_suffix) != DmDeviceState::ACTIVE) {
1103 LOG(WARNING) << partition_name_suffix << " is at current slot but it is "
1104 << "not mapped. Now try to map it.";
1105 } else {
1106 if (GetDmDevicePathByName(partition_name_suffix, device)) {
1107 LOG(INFO) << partition_name_suffix
1108 << " is mapped on device mapper: " << *device;
1109 return DynamicPartitionDeviceStatus::SUCCESS;
1110 }
1111 LOG(ERROR) << partition_name_suffix << "is mapped but path is unknown.";
1112 return DynamicPartitionDeviceStatus::ERROR;
1113 }
1114 }
1115
Tianjie51a5a392020-06-03 14:39:32 -07001116 bool force_writable = (slot != current_slot) && !not_in_payload;
Yifan Hong3a1a5612019-11-05 16:34:32 -08001117 if (MapPartitionOnDeviceMapper(
1118 super_device, partition_name_suffix, slot, force_writable, device)) {
1119 return DynamicPartitionDeviceStatus::SUCCESS;
1120 }
1121 return DynamicPartitionDeviceStatus::ERROR;
1122}
1123
Yifan Hong6eec9952019-12-04 13:12:01 -08001124void DynamicPartitionControlAndroid::set_fake_mapped_devices(
1125 const std::set<std::string>& fake) {
1126 mapped_devices_ = fake;
1127}
1128
Yifan Hongbae27842019-10-24 16:56:12 -07001129bool DynamicPartitionControlAndroid::IsRecovery() {
Kelvin Zhanga22ef552020-10-12 19:03:52 -04001130 return constants::kIsRecovery;
Yifan Hongbae27842019-10-24 16:56:12 -07001131}
1132
1133static bool IsIncrementalUpdate(const DeltaArchiveManifest& manifest) {
1134 const auto& partitions = manifest.partitions();
1135 return std::any_of(partitions.begin(), partitions.end(), [](const auto& p) {
1136 return p.has_old_partition_info();
1137 });
1138}
1139
1140bool DynamicPartitionControlAndroid::DeleteSourcePartitions(
1141 MetadataBuilder* builder,
1142 uint32_t source_slot,
1143 const DeltaArchiveManifest& manifest) {
1144 TEST_AND_RETURN_FALSE(IsRecovery());
1145
1146 if (IsIncrementalUpdate(manifest)) {
1147 LOG(ERROR) << "Cannot sideload incremental OTA because snapshots cannot "
1148 << "be created.";
1149 if (GetVirtualAbFeatureFlag().IsLaunch()) {
1150 LOG(ERROR) << "Sideloading incremental updates on devices launches "
1151 << " Virtual A/B is not supported.";
1152 }
1153 return false;
1154 }
1155
1156 LOG(INFO) << "Will overwrite existing partitions. Slot "
1157 << BootControlInterface::SlotName(source_slot)
1158 << "may be unbootable until update finishes!";
1159 const std::string source_suffix = SlotSuffixForSlotNumber(source_slot);
1160 DeleteGroupsWithSuffix(builder, source_suffix);
1161
1162 return true;
1163}
1164
Yifan Hong90965502020-02-19 15:22:47 -08001165std::unique_ptr<AbstractAction>
1166DynamicPartitionControlAndroid::GetCleanupPreviousUpdateAction(
1167 BootControlInterface* boot_control,
1168 PrefsInterface* prefs,
1169 CleanupPreviousUpdateActionDelegateInterface* delegate) {
1170 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1171 return std::make_unique<NoOpAction>();
1172 }
1173 return std::make_unique<CleanupPreviousUpdateAction>(
1174 prefs, boot_control, snapshot_.get(), delegate);
1175}
1176
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001177bool DynamicPartitionControlAndroid::ResetUpdate(PrefsInterface* prefs) {
1178 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1179 return true;
1180 }
1181
1182 LOG(INFO) << __func__ << " resetting update state and deleting snapshots.";
1183 TEST_AND_RETURN_FALSE(prefs != nullptr);
1184
1185 // If the device has already booted into the target slot,
1186 // ResetUpdateProgress may pass but CancelUpdate fails.
1187 // This is expected. A scheduled CleanupPreviousUpdateAction should free
1188 // space when it is done.
1189 TEST_AND_RETURN_FALSE(DeltaPerformer::ResetUpdateProgress(
1190 prefs, false /* quick */, false /* skip dynamic partitions metadata */));
1191
Yifan Hong4d7c5eb2020-04-03 11:31:50 -07001192 if (ExpectMetadataMounted()) {
1193 TEST_AND_RETURN_FALSE(snapshot_->CancelUpdate());
1194 } else {
1195 LOG(INFO) << "Skip cancelling update in ResetUpdate because /metadata is "
1196 << "not mounted";
1197 }
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001198
1199 return true;
1200}
1201
Tianjie99d570d2020-06-04 14:57:19 -07001202bool DynamicPartitionControlAndroid::ListDynamicPartitionsForSlot(
Tianjie3a55fc22021-02-13 16:02:22 -08001203 uint32_t slot,
1204 uint32_t current_slot,
1205 std::vector<std::string>* partitions) {
1206 bool slot_enables_dynamic_partitions =
1207 GetDynamicPartitionsFeatureFlag().IsEnabled();
1208 // Check if the target slot has dynamic partitions, this may happen when
1209 // applying a retrofit package.
1210 if (slot != current_slot) {
1211 slot_enables_dynamic_partitions =
1212 slot_enables_dynamic_partitions && is_target_dynamic_;
1213 }
1214
1215 if (!slot_enables_dynamic_partitions) {
1216 LOG(INFO) << "Dynamic partition is not enabled for slot " << slot;
1217 return true;
Tianjie99d570d2020-06-04 14:57:19 -07001218 }
1219
1220 std::string device_dir_str;
1221 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
1222 base::FilePath device_dir(device_dir_str);
Tianjie3a55fc22021-02-13 16:02:22 -08001223 auto super_device = device_dir.Append(GetSuperPartitionName(slot)).value();
1224 auto builder = LoadMetadataBuilder(super_device, slot);
Tianjie99d570d2020-06-04 14:57:19 -07001225 TEST_AND_RETURN_FALSE(builder != nullptr);
1226
1227 std::vector<std::string> result;
Tianjie3a55fc22021-02-13 16:02:22 -08001228 auto suffix = SlotSuffixForSlotNumber(slot);
Tianjie99d570d2020-06-04 14:57:19 -07001229 for (const auto& group : builder->ListGroups()) {
1230 for (const auto& partition : builder->ListPartitionsInGroup(group)) {
1231 std::string_view partition_name = partition->name();
1232 if (!android::base::ConsumeSuffix(&partition_name, suffix)) {
1233 continue;
1234 }
1235 result.emplace_back(partition_name);
1236 }
1237 }
1238 *partitions = std::move(result);
1239 return true;
1240}
1241
Tianjie24f96092020-06-30 12:26:25 -07001242bool DynamicPartitionControlAndroid::VerifyExtentsForUntouchedPartitions(
1243 uint32_t source_slot,
1244 uint32_t target_slot,
1245 const std::vector<std::string>& partitions) {
1246 std::string device_dir_str;
1247 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
1248 base::FilePath device_dir(device_dir_str);
1249
1250 auto source_super_device =
1251 device_dir.Append(GetSuperPartitionName(source_slot)).value();
1252 auto source_builder = LoadMetadataBuilder(source_super_device, source_slot);
1253 TEST_AND_RETURN_FALSE(source_builder != nullptr);
1254
1255 auto target_super_device =
1256 device_dir.Append(GetSuperPartitionName(target_slot)).value();
1257 auto target_builder = LoadMetadataBuilder(target_super_device, target_slot);
1258 TEST_AND_RETURN_FALSE(target_builder != nullptr);
1259
1260 return MetadataBuilder::VerifyExtentsAgainstSourceMetadata(
1261 *source_builder, source_slot, *target_builder, target_slot, partitions);
1262}
1263
Yifan Hong4d7c5eb2020-04-03 11:31:50 -07001264bool DynamicPartitionControlAndroid::ExpectMetadataMounted() {
1265 // No need to mount metadata for non-Virtual A/B devices.
1266 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1267 return false;
1268 }
1269 // Intentionally not checking |metadata_device_| in Android mode.
1270 // /metadata should always be mounted in Android mode. If it isn't, let caller
1271 // fails when calling into SnapshotManager.
1272 if (!IsRecovery()) {
1273 return true;
1274 }
1275 // In recovery mode, explicitly check |metadata_device_|.
1276 return metadata_device_ != nullptr;
1277}
1278
1279bool DynamicPartitionControlAndroid::EnsureMetadataMounted() {
1280 // No need to mount metadata for non-Virtual A/B devices.
1281 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1282 return true;
1283 }
1284
1285 if (metadata_device_ == nullptr) {
1286 metadata_device_ = snapshot_->EnsureMetadataMounted();
1287 }
1288 return metadata_device_ != nullptr;
1289}
1290
Kelvin Zhang34618522020-09-28 09:21:02 -04001291std::unique_ptr<android::snapshot::ISnapshotWriter>
1292DynamicPartitionControlAndroid::OpenCowWriter(
1293 const std::string& partition_name,
1294 const std::optional<std::string>& source_path,
1295 bool is_append) {
1296 auto suffix = SlotSuffixForSlotNumber(target_slot_);
1297
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -04001298 auto super_device = GetSuperDevice();
1299 if (!super_device.has_value()) {
Kelvin Zhang34618522020-09-28 09:21:02 -04001300 return nullptr;
1301 }
Kelvin Zhang34618522020-09-28 09:21:02 -04001302 CreateLogicalPartitionParams params = {
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -04001303 .block_device = super_device->value(),
Kelvin Zhang34618522020-09-28 09:21:02 -04001304 .metadata_slot = target_slot_,
1305 .partition_name = partition_name + suffix,
1306 .force_writable = true,
Kelvin Zhang877ddbe2020-11-09 13:37:56 -05001307 .timeout_ms = kMapSnapshotTimeout};
Kelvin Zhang34618522020-09-28 09:21:02 -04001308 // TODO(zhangkelvin) Open an APPEND mode CowWriter once there's an API to do
1309 // it.
1310 return snapshot_->OpenSnapshotWriter(params, std::move(source_path));
Kelvin Zhang877ddbe2020-11-09 13:37:56 -05001311} // namespace chromeos_update_engine
Kelvin Zhang34618522020-09-28 09:21:02 -04001312
Kelvin Zhangc82511c2020-11-06 16:01:24 -05001313FileDescriptorPtr DynamicPartitionControlAndroid::OpenCowReader(
1314 const std::string& unsuffixed_partition_name,
1315 const std::optional<std::string>& source_path,
1316 bool is_append) {
1317 auto cow_writer =
1318 OpenCowWriter(unsuffixed_partition_name, source_path, is_append);
1319 if (cow_writer == nullptr) {
1320 return nullptr;
1321 }
Kelvin Zhangec205cf2020-09-28 13:23:40 -04001322 cow_writer->InitializeAppend(kEndOfInstallLabel);
Kelvin Zhangc82511c2020-11-06 16:01:24 -05001323 return cow_writer->OpenReader();
1324}
1325
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -04001326std::optional<base::FilePath> DynamicPartitionControlAndroid::GetSuperDevice() {
1327 std::string device_dir_str;
1328 if (!GetDeviceDir(&device_dir_str)) {
1329 LOG(ERROR) << "Failed to get device dir!";
1330 return {};
1331 }
1332 base::FilePath device_dir(device_dir_str);
1333 auto super_device = device_dir.Append(GetSuperPartitionName(target_slot_));
1334 return super_device;
1335}
1336
1337bool DynamicPartitionControlAndroid::MapAllPartitions() {
Kelvin Zhang877ddbe2020-11-09 13:37:56 -05001338 return snapshot_->MapAllSnapshots(kMapSnapshotTimeout);
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -04001339}
1340
Kelvin Zhangeb9de162020-11-16 15:47:28 -05001341bool DynamicPartitionControlAndroid::IsDynamicPartition(
1342 const std::string& partition_name) {
1343 if (dynamic_partition_list_.empty() &&
1344 GetDynamicPartitionsFeatureFlag().IsEnabled()) {
Tianjie3a55fc22021-02-13 16:02:22 -08001345 // Use the DAP config of the target slot.
1346 CHECK(ListDynamicPartitionsForSlot(
1347 target_slot_, source_slot_, &dynamic_partition_list_));
Kelvin Zhangeb9de162020-11-16 15:47:28 -05001348 }
1349 return std::find(dynamic_partition_list_.begin(),
1350 dynamic_partition_list_.end(),
1351 partition_name) != dynamic_partition_list_.end();
1352}
Kelvin Zhang91d95fa2020-11-05 13:52:00 -05001353
Yifan Hongb0cbd392021-02-04 11:11:45 -08001354bool DynamicPartitionControlAndroid::UpdateUsesSnapshotCompression() {
1355 return snapshot_->UpdateUsesCompression();
1356}
1357
Yifan Hong537802d2018-08-15 13:15:42 -07001358} // namespace chromeos_update_engine