blob: ca12b3db453331089c5b15bc489546effcffe0b1 [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
Yifan Hong420db9b2019-07-23 20:50:33 -070019#include <chrono> // NOLINT(build/c++11) - using libsnapshot / liblp API
Kelvin Zhang34618522020-09-28 09:21:02 -040020#include <cstdint>
Yifan Hong13d41cb2019-09-16 13:18:22 -070021#include <map>
Yifan Hong537802d2018-08-15 13:15:42 -070022#include <memory>
23#include <set>
24#include <string>
Tianjie99d570d2020-06-04 14:57:19 -070025#include <string_view>
26#include <utility>
Yifan Hong012508e2019-07-22 18:30:40 -070027#include <vector>
Yifan Hong537802d2018-08-15 13:15:42 -070028
29#include <android-base/properties.h>
30#include <android-base/strings.h>
31#include <base/files/file_util.h>
32#include <base/logging.h>
Yifan Hong012508e2019-07-22 18:30:40 -070033#include <base/strings/string_util.h>
Yifan Hong537802d2018-08-15 13:15:42 -070034#include <bootloader_message/bootloader_message.h>
Yifan Hong012508e2019-07-22 18:30:40 -070035#include <fs_mgr.h>
Yifan Hong537802d2018-08-15 13:15:42 -070036#include <fs_mgr_dm_linear.h>
Yifan Hong3a1a5612019-11-05 16:34:32 -080037#include <fs_mgr_overlayfs.h>
Yifan Hong29692902020-03-26 12:47:05 -070038#include <libavb/libavb.h>
Yifan Hong3a1a5612019-11-05 16:34:32 -080039#include <libdm/dm.h>
Kelvin Zhang34618522020-09-28 09:21:02 -040040#include <liblp/liblp.h>
41#include <libsnapshot/cow_writer.h>
Yifan Hong420db9b2019-07-23 20:50:33 -070042#include <libsnapshot/snapshot.h>
Yifan Hongf9cb4492020-04-15 13:00:20 -070043#include <libsnapshot/snapshot_stub.h>
Yifan Hong537802d2018-08-15 13:15:42 -070044
Amin Hassaniec7bc112020-10-29 16:47:58 -070045#include "update_engine/aosp/cleanup_previous_update_action.h"
46#include "update_engine/aosp/dynamic_partition_utils.h"
Yifan Hong537802d2018-08-15 13:15:42 -070047#include "update_engine/common/boot_control_interface.h"
48#include "update_engine/common/utils.h"
Yifan Hong6a6d0f12020-03-11 13:20:52 -070049#include "update_engine/payload_consumer/delta_performer.h"
Yifan Hong537802d2018-08-15 13:15:42 -070050
51using android::base::GetBoolProperty;
Yifan Hong29692902020-03-26 12:47:05 -070052using android::base::GetProperty;
Yifan Hong537802d2018-08-15 13:15:42 -070053using android::base::Join;
54using android::dm::DeviceMapper;
55using android::dm::DmDeviceState;
56using android::fs_mgr::CreateLogicalPartition;
David Andersonbb90dfb2019-08-13 14:14:56 -070057using android::fs_mgr::CreateLogicalPartitionParams;
Yifan Hong537802d2018-08-15 13:15:42 -070058using android::fs_mgr::DestroyLogicalPartition;
Yifan Hong29692902020-03-26 12:47:05 -070059using android::fs_mgr::Fstab;
Yifan Hong537802d2018-08-15 13:15:42 -070060using android::fs_mgr::MetadataBuilder;
Yifan Hong012508e2019-07-22 18:30:40 -070061using android::fs_mgr::Partition;
Yifan Hong6e706b12018-11-09 16:50:51 -080062using android::fs_mgr::PartitionOpener;
Yifan Hong012508e2019-07-22 18:30:40 -070063using android::fs_mgr::SlotSuffixForSlotNumber;
Yifan Hongf5261562020-03-10 10:28:10 -070064using android::snapshot::OptimizeSourceCopyOperation;
Yifan Hong0850bca2020-01-16 15:14:07 -080065using android::snapshot::Return;
Yifan Hongf033ecb2020-01-07 18:13:56 -080066using android::snapshot::SnapshotManager;
Yifan Hongf9cb4492020-04-15 13:00:20 -070067using android::snapshot::SnapshotManagerStub;
Yifan Hong2257ee12020-01-13 18:33:00 -080068using android::snapshot::UpdateState;
Yifan Hong537802d2018-08-15 13:15:42 -070069
70namespace chromeos_update_engine {
71
Yifan Hong6e706b12018-11-09 16:50:51 -080072constexpr char kUseDynamicPartitions[] = "ro.boot.dynamic_partitions";
73constexpr char kRetrfoitDynamicPartitions[] =
74 "ro.boot.dynamic_partitions_retrofit";
Yifan Hong413d5722019-07-23 14:21:09 -070075constexpr char kVirtualAbEnabled[] = "ro.virtual_ab.enabled";
76constexpr char kVirtualAbRetrofit[] = "ro.virtual_ab.retrofit";
Kelvin Zhangda1b3142020-09-24 17:09:02 -040077constexpr char kVirtualAbCompressionEnabled[] =
78 "ro.virtual_ab.compression.enabled";
79
80// Currently, android doesn't have a retrofit prop for VAB Compression. However,
81// struct FeatureFlag forces us to determine if a feature is 'retrofit'. So this
82// is here just to simplify code. Replace it with real retrofit prop name once
83// there is one.
84constexpr char kVirtualAbCompressionRetrofit[] = "";
Yifan Hong29692902020-03-26 12:47:05 -070085constexpr char kPostinstallFstabPrefix[] = "ro.postinstall.fstab.prefix";
Yifan Hong420db9b2019-07-23 20:50:33 -070086// Map timeout for dynamic partitions.
87constexpr std::chrono::milliseconds kMapTimeout{1000};
88// Map timeout for dynamic partitions with snapshots. Since several devices
89// needs to be mapped, this timeout is longer than |kMapTimeout|.
90constexpr std::chrono::milliseconds kMapSnapshotTimeout{5000};
91
Yifan Hong537802d2018-08-15 13:15:42 -070092DynamicPartitionControlAndroid::~DynamicPartitionControlAndroid() {
Yifan Hongbae27842019-10-24 16:56:12 -070093 Cleanup();
Yifan Hong537802d2018-08-15 13:15:42 -070094}
95
Yifan Hong186bb682019-07-23 14:04:39 -070096static FeatureFlag GetFeatureFlag(const char* enable_prop,
97 const char* retrofit_prop) {
Kelvin Zhangda1b3142020-09-24 17:09:02 -040098 // Default retrofit to false if retrofit_prop is empty.
99 bool retrofit = retrofit_prop && retrofit_prop[0] != '\0' &&
100 GetBoolProperty(retrofit_prop, false);
Yifan Hong186bb682019-07-23 14:04:39 -0700101 bool enabled = GetBoolProperty(enable_prop, false);
102 if (retrofit && !enabled) {
103 LOG(ERROR) << retrofit_prop << " is true but " << enable_prop
104 << " is not. These sysprops are inconsistent. Assume that "
105 << enable_prop << " is true from now on.";
106 }
107 if (retrofit) {
108 return FeatureFlag(FeatureFlag::Value::RETROFIT);
109 }
110 if (enabled) {
111 return FeatureFlag(FeatureFlag::Value::LAUNCH);
112 }
113 return FeatureFlag(FeatureFlag::Value::NONE);
Yifan Hong537802d2018-08-15 13:15:42 -0700114}
115
Yifan Hongb38e1af2019-10-17 14:59:22 -0700116DynamicPartitionControlAndroid::DynamicPartitionControlAndroid()
117 : dynamic_partitions_(
118 GetFeatureFlag(kUseDynamicPartitions, kRetrfoitDynamicPartitions)),
Kelvin Zhangda1b3142020-09-24 17:09:02 -0400119 virtual_ab_(GetFeatureFlag(kVirtualAbEnabled, kVirtualAbRetrofit)),
120 virtual_ab_compression_(GetFeatureFlag(kVirtualAbCompressionEnabled,
121 kVirtualAbCompressionRetrofit)) {
Yifan Hongb38e1af2019-10-17 14:59:22 -0700122 if (GetVirtualAbFeatureFlag().IsEnabled()) {
Yifan Hongf033ecb2020-01-07 18:13:56 -0800123 snapshot_ = SnapshotManager::New();
Yifan Hongf9cb4492020-04-15 13:00:20 -0700124 } else {
125 snapshot_ = SnapshotManagerStub::New();
Yifan Hongb38e1af2019-10-17 14:59:22 -0700126 }
Yifan Hongf9cb4492020-04-15 13:00:20 -0700127 CHECK(snapshot_ != nullptr) << "Cannot initialize SnapshotManager.";
Yifan Hongb38e1af2019-10-17 14:59:22 -0700128}
129
Yifan Hong186bb682019-07-23 14:04:39 -0700130FeatureFlag DynamicPartitionControlAndroid::GetDynamicPartitionsFeatureFlag() {
Yifan Hongb38e1af2019-10-17 14:59:22 -0700131 return dynamic_partitions_;
Yifan Hong6e706b12018-11-09 16:50:51 -0800132}
133
Yifan Hong413d5722019-07-23 14:21:09 -0700134FeatureFlag DynamicPartitionControlAndroid::GetVirtualAbFeatureFlag() {
Yifan Hongb38e1af2019-10-17 14:59:22 -0700135 return virtual_ab_;
Yifan Hong413d5722019-07-23 14:21:09 -0700136}
137
Kelvin Zhangda1b3142020-09-24 17:09:02 -0400138FeatureFlag
139DynamicPartitionControlAndroid::GetVirtualAbCompressionFeatureFlag() {
140 return virtual_ab_compression_;
141}
142
Yifan Hongf5261562020-03-10 10:28:10 -0700143bool DynamicPartitionControlAndroid::OptimizeOperation(
144 const std::string& partition_name,
145 const InstallOperation& operation,
146 InstallOperation* optimized) {
Alessio Balsini2a3b4a22019-11-25 16:46:51 +0000147 switch (operation.type()) {
148 case InstallOperation::SOURCE_COPY:
149 return target_supports_snapshot_ &&
150 GetVirtualAbFeatureFlag().IsEnabled() &&
Yifan Hong6eec9952019-12-04 13:12:01 -0800151 mapped_devices_.count(partition_name +
152 SlotSuffixForSlotNumber(target_slot_)) > 0 &&
Yifan Hongf5261562020-03-10 10:28:10 -0700153 OptimizeSourceCopyOperation(operation, optimized);
Alessio Balsini2a3b4a22019-11-25 16:46:51 +0000154 break;
155 default:
156 break;
157 }
Alessio Balsini14980e22019-11-26 11:46:06 +0000158 return false;
159}
160
Yifan Hong8546a712019-03-28 14:42:53 -0700161bool DynamicPartitionControlAndroid::MapPartitionInternal(
Yifan Hong537802d2018-08-15 13:15:42 -0700162 const std::string& super_device,
163 const std::string& target_partition_name,
164 uint32_t slot,
Yifan Hongaf65ef12018-10-29 11:09:06 -0700165 bool force_writable,
Yifan Hong537802d2018-08-15 13:15:42 -0700166 std::string* path) {
David Andersonbb90dfb2019-08-13 14:14:56 -0700167 CreateLogicalPartitionParams params = {
168 .block_device = super_device,
169 .metadata_slot = slot,
170 .partition_name = target_partition_name,
171 .force_writable = force_writable,
David Andersonbb90dfb2019-08-13 14:14:56 -0700172 };
Yifan Hong420db9b2019-07-23 20:50:33 -0700173 bool success = false;
Yifan Hongf0f4a912019-09-26 17:51:33 -0700174 if (GetVirtualAbFeatureFlag().IsEnabled() && target_supports_snapshot_ &&
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700175 force_writable && ExpectMetadataMounted()) {
Yifan Hong420db9b2019-07-23 20:50:33 -0700176 // Only target partitions are mapped with force_writable. On Virtual
177 // A/B devices, target partitions may overlap with source partitions, so
178 // they must be mapped with snapshot.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700179 // One exception is when /metadata is not mounted. Fallback to
180 // CreateLogicalPartition as snapshots are not created in the first place.
Yifan Hong420db9b2019-07-23 20:50:33 -0700181 params.timeout_ms = kMapSnapshotTimeout;
182 success = snapshot_->MapUpdateSnapshot(params, path);
183 } else {
184 params.timeout_ms = kMapTimeout;
185 success = CreateLogicalPartition(params, path);
186 }
David Andersonbb90dfb2019-08-13 14:14:56 -0700187
Yifan Hong420db9b2019-07-23 20:50:33 -0700188 if (!success) {
Yifan Hong537802d2018-08-15 13:15:42 -0700189 LOG(ERROR) << "Cannot map " << target_partition_name << " in "
190 << super_device << " on device mapper.";
191 return false;
192 }
193 LOG(INFO) << "Succesfully mapped " << target_partition_name
Yifan Hongaf65ef12018-10-29 11:09:06 -0700194 << " to device mapper (force_writable = " << force_writable
195 << "); device path at " << *path;
Yifan Hong537802d2018-08-15 13:15:42 -0700196 mapped_devices_.insert(target_partition_name);
197 return true;
198}
199
Yifan Hong8546a712019-03-28 14:42:53 -0700200bool DynamicPartitionControlAndroid::MapPartitionOnDeviceMapper(
201 const std::string& super_device,
202 const std::string& target_partition_name,
203 uint32_t slot,
204 bool force_writable,
205 std::string* path) {
206 DmDeviceState state = GetState(target_partition_name);
207 if (state == DmDeviceState::ACTIVE) {
208 if (mapped_devices_.find(target_partition_name) != mapped_devices_.end()) {
209 if (GetDmDevicePathByName(target_partition_name, path)) {
210 LOG(INFO) << target_partition_name
211 << " is mapped on device mapper: " << *path;
212 return true;
213 }
214 LOG(ERROR) << target_partition_name << " is mapped but path is unknown.";
215 return false;
216 }
217 // If target_partition_name is not in mapped_devices_ but state is ACTIVE,
218 // the device might be mapped incorrectly before. Attempt to unmap it.
219 // Note that for source partitions, if GetState() == ACTIVE, callers (e.g.
220 // BootControlAndroid) should not call MapPartitionOnDeviceMapper, but
221 // should directly call GetDmDevicePathByName.
David Anderson4c891c92019-06-21 17:45:23 -0700222 if (!UnmapPartitionOnDeviceMapper(target_partition_name)) {
Yifan Hong8546a712019-03-28 14:42:53 -0700223 LOG(ERROR) << target_partition_name
224 << " is mapped before the update, and it cannot be unmapped.";
225 return false;
226 }
227 state = GetState(target_partition_name);
228 if (state != DmDeviceState::INVALID) {
229 LOG(ERROR) << target_partition_name << " is unmapped but state is "
230 << static_cast<std::underlying_type_t<DmDeviceState>>(state);
231 return false;
232 }
233 }
234 if (state == DmDeviceState::INVALID) {
235 return MapPartitionInternal(
236 super_device, target_partition_name, slot, force_writable, path);
237 }
238
239 LOG(ERROR) << target_partition_name
240 << " is mapped on device mapper but state is unknown: "
241 << static_cast<std::underlying_type_t<DmDeviceState>>(state);
242 return false;
243}
244
Yifan Hong537802d2018-08-15 13:15:42 -0700245bool DynamicPartitionControlAndroid::UnmapPartitionOnDeviceMapper(
David Anderson4c891c92019-06-21 17:45:23 -0700246 const std::string& target_partition_name) {
Yifan Hong537802d2018-08-15 13:15:42 -0700247 if (DeviceMapper::Instance().GetState(target_partition_name) !=
248 DmDeviceState::INVALID) {
Yifan Hong420db9b2019-07-23 20:50:33 -0700249 // Partitions at target slot on non-Virtual A/B devices are mapped as
250 // dm-linear. Also, on Virtual A/B devices, system_other may be mapped for
251 // preopt apps as dm-linear.
252 // Call DestroyLogicalPartition to handle these cases.
253 bool success = DestroyLogicalPartition(target_partition_name);
254
255 // On a Virtual A/B device, |target_partition_name| may be a leftover from
256 // a paused update. Clean up any underlying devices.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700257 if (ExpectMetadataMounted()) {
Yifan Hong420db9b2019-07-23 20:50:33 -0700258 success &= snapshot_->UnmapUpdateSnapshot(target_partition_name);
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700259 } else {
260 LOG(INFO) << "Skip UnmapUpdateSnapshot(" << target_partition_name
261 << ") because metadata is not mounted";
Yifan Hong420db9b2019-07-23 20:50:33 -0700262 }
263
264 if (!success) {
Yifan Hong537802d2018-08-15 13:15:42 -0700265 LOG(ERROR) << "Cannot unmap " << target_partition_name
266 << " from device mapper.";
267 return false;
268 }
269 LOG(INFO) << "Successfully unmapped " << target_partition_name
270 << " from device mapper.";
271 }
272 mapped_devices_.erase(target_partition_name);
273 return true;
274}
275
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -0400276bool DynamicPartitionControlAndroid::UnmapAllPartitions() {
Tao Bao8c4d0082019-08-08 08:56:16 -0700277 if (mapped_devices_.empty()) {
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -0400278 return false;
Tao Bao8c4d0082019-08-08 08:56:16 -0700279 }
Yifan Hong537802d2018-08-15 13:15:42 -0700280 // UnmapPartitionOnDeviceMapper removes objects from mapped_devices_, hence
281 // a copy is needed for the loop.
282 std::set<std::string> mapped = mapped_devices_;
283 LOG(INFO) << "Destroying [" << Join(mapped, ", ") << "] from device mapper";
284 for (const auto& partition_name : mapped) {
David Anderson4c891c92019-06-21 17:45:23 -0700285 ignore_result(UnmapPartitionOnDeviceMapper(partition_name));
Yifan Hong537802d2018-08-15 13:15:42 -0700286 }
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -0400287 return true;
Yifan Hong537802d2018-08-15 13:15:42 -0700288}
289
290void DynamicPartitionControlAndroid::Cleanup() {
Yifan Hongbae27842019-10-24 16:56:12 -0700291 UnmapAllPartitions();
292 metadata_device_.reset();
Yifan Hong537802d2018-08-15 13:15:42 -0700293}
294
295bool DynamicPartitionControlAndroid::DeviceExists(const std::string& path) {
296 return base::PathExists(base::FilePath(path));
297}
298
299android::dm::DmDeviceState DynamicPartitionControlAndroid::GetState(
300 const std::string& name) {
301 return DeviceMapper::Instance().GetState(name);
302}
303
304bool DynamicPartitionControlAndroid::GetDmDevicePathByName(
305 const std::string& name, std::string* path) {
306 return DeviceMapper::Instance().GetDmDevicePathByName(name, path);
307}
308
309std::unique_ptr<MetadataBuilder>
310DynamicPartitionControlAndroid::LoadMetadataBuilder(
Tianjie24f96092020-06-30 12:26:25 -0700311 const std::string& super_device, uint32_t slot) {
312 auto builder = MetadataBuilder::New(PartitionOpener(), super_device, slot);
313 if (builder == nullptr) {
314 LOG(WARNING) << "No metadata slot " << BootControlInterface::SlotName(slot)
315 << " in " << super_device;
316 return nullptr;
317 }
318 LOG(INFO) << "Loaded metadata from slot "
319 << BootControlInterface::SlotName(slot) << " in " << super_device;
320 return builder;
Yifan Hong012508e2019-07-22 18:30:40 -0700321}
322
323std::unique_ptr<MetadataBuilder>
324DynamicPartitionControlAndroid::LoadMetadataBuilder(
Yifan Hong6e706b12018-11-09 16:50:51 -0800325 const std::string& super_device,
326 uint32_t source_slot,
327 uint32_t target_slot) {
Tianjie24f96092020-06-30 12:26:25 -0700328 bool always_keep_source_slot = !target_supports_snapshot_;
329 auto builder = MetadataBuilder::NewForUpdate(PartitionOpener(),
330 super_device,
331 source_slot,
332 target_slot,
333 always_keep_source_slot);
Yifan Hong537802d2018-08-15 13:15:42 -0700334 if (builder == nullptr) {
335 LOG(WARNING) << "No metadata slot "
336 << BootControlInterface::SlotName(source_slot) << " in "
337 << super_device;
Yifan Hongf48a0052018-10-29 16:30:43 -0700338 return nullptr;
Yifan Hong537802d2018-08-15 13:15:42 -0700339 }
Tianjie24f96092020-06-30 12:26:25 -0700340 LOG(INFO) << "Created metadata for new update from slot "
Yifan Hong537802d2018-08-15 13:15:42 -0700341 << BootControlInterface::SlotName(source_slot) << " in "
342 << super_device;
343 return builder;
344}
345
346bool DynamicPartitionControlAndroid::StoreMetadata(
347 const std::string& super_device,
348 MetadataBuilder* builder,
349 uint32_t target_slot) {
350 auto metadata = builder->Export();
351 if (metadata == nullptr) {
352 LOG(ERROR) << "Cannot export metadata to slot "
353 << BootControlInterface::SlotName(target_slot) << " in "
354 << super_device;
355 return false;
356 }
357
Yifan Hong186bb682019-07-23 14:04:39 -0700358 if (GetDynamicPartitionsFeatureFlag().IsRetrofit()) {
Yifan Hong6e706b12018-11-09 16:50:51 -0800359 if (!FlashPartitionTable(super_device, *metadata)) {
360 LOG(ERROR) << "Cannot write metadata to " << super_device;
361 return false;
362 }
363 LOG(INFO) << "Written metadata to " << super_device;
364 } else {
365 if (!UpdatePartitionTable(super_device, *metadata, target_slot)) {
366 LOG(ERROR) << "Cannot write metadata to slot "
367 << BootControlInterface::SlotName(target_slot) << " in "
368 << super_device;
369 return false;
370 }
371 LOG(INFO) << "Copied metadata to slot "
372 << BootControlInterface::SlotName(target_slot) << " in "
373 << super_device;
Yifan Hong537802d2018-08-15 13:15:42 -0700374 }
375
Yifan Hong537802d2018-08-15 13:15:42 -0700376 return true;
377}
378
379bool DynamicPartitionControlAndroid::GetDeviceDir(std::string* out) {
380 // We can't use fs_mgr to look up |partition_name| because fstab
381 // doesn't list every slot partition (it uses the slotselect option
382 // to mask the suffix).
383 //
384 // We can however assume that there's an entry for the /misc mount
385 // point and use that to get the device file for the misc
386 // partition. This helps us locate the disk that |partition_name|
387 // resides on. From there we'll assume that a by-name scheme is used
388 // so we can just replace the trailing "misc" by the given
389 // |partition_name| and suffix corresponding to |slot|, e.g.
390 //
391 // /dev/block/platform/soc.0/7824900.sdhci/by-name/misc ->
392 // /dev/block/platform/soc.0/7824900.sdhci/by-name/boot_a
393 //
394 // If needed, it's possible to relax the by-name assumption in the
395 // future by trawling /sys/block looking for the appropriate sibling
396 // of misc and then finding an entry in /dev matching the sysfs
397 // entry.
398
399 std::string err, misc_device = get_bootloader_message_blk_device(&err);
400 if (misc_device.empty()) {
401 LOG(ERROR) << "Unable to get misc block device: " << err;
402 return false;
403 }
404
405 if (!utils::IsSymlink(misc_device.c_str())) {
406 LOG(ERROR) << "Device file " << misc_device << " for /misc "
407 << "is not a symlink.";
408 return false;
409 }
410 *out = base::FilePath(misc_device).DirName().value();
411 return true;
412}
Yifan Hong012508e2019-07-22 18:30:40 -0700413
414bool DynamicPartitionControlAndroid::PreparePartitionsForUpdate(
415 uint32_t source_slot,
416 uint32_t target_slot,
Yifan Hongf0f4a912019-09-26 17:51:33 -0700417 const DeltaArchiveManifest& manifest,
Yifan Hongf033ecb2020-01-07 18:13:56 -0800418 bool update,
419 uint64_t* required_size) {
Yifan Hong6eec9952019-12-04 13:12:01 -0800420 source_slot_ = source_slot;
421 target_slot_ = target_slot;
Yifan Hongf033ecb2020-01-07 18:13:56 -0800422 if (required_size != nullptr) {
423 *required_size = 0;
424 }
Yifan Hong6eec9952019-12-04 13:12:01 -0800425
Yifan Hong3a1a5612019-11-05 16:34:32 -0800426 if (fs_mgr_overlayfs_is_setup()) {
427 // Non DAP devices can use overlayfs as well.
428 LOG(WARNING)
429 << "overlayfs overrides are active and can interfere with our "
430 "resources.\n"
431 << "run adb enable-verity to deactivate if required and try again.";
432 }
433
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700434 // If metadata is erased but not formatted, it is possible to not mount
435 // it in recovery. It is acceptable to skip mounting and choose fallback path
436 // (PrepareDynamicPartitionsForUpdate) when sideloading full OTAs.
437 TEST_AND_RETURN_FALSE(EnsureMetadataMounted() || IsRecovery());
Yifan Hong29692902020-03-26 12:47:05 -0700438
439 if (update) {
440 TEST_AND_RETURN_FALSE(EraseSystemOtherAvbFooter(source_slot, target_slot));
441 }
442
Yifan Hong3a1a5612019-11-05 16:34:32 -0800443 if (!GetDynamicPartitionsFeatureFlag().IsEnabled()) {
444 return true;
445 }
446
447 if (target_slot == source_slot) {
448 LOG(ERROR) << "Cannot call PreparePartitionsForUpdate on current slot.";
449 return false;
450 }
451
Yifan Hongf6f75c22020-07-31 15:20:25 -0700452 if (!SetTargetBuildVars(manifest)) {
453 return false;
454 }
455
Yifan Hong3a1a5612019-11-05 16:34:32 -0800456 // Although the current build supports dynamic partitions, the given payload
457 // doesn't use it for target partitions. This could happen when applying a
458 // retrofit update. Skip updating the partition metadata for the target slot.
Yifan Hong3a1a5612019-11-05 16:34:32 -0800459 if (!is_target_dynamic_) {
460 return true;
461 }
462
Yifan Hongf0f4a912019-09-26 17:51:33 -0700463 if (!update)
464 return true;
465
Yifan Hongbae27842019-10-24 16:56:12 -0700466 bool delete_source = false;
467
Yifan Hong6d888562019-10-01 13:00:31 -0700468 if (GetVirtualAbFeatureFlag().IsEnabled()) {
469 // On Virtual A/B device, either CancelUpdate() or BeginUpdate() must be
470 // called before calling UnmapUpdateSnapshot.
471 // - If target_supports_snapshot_, PrepareSnapshotPartitionsForUpdate()
472 // calls BeginUpdate() which resets update state
Yifan Hongbae27842019-10-24 16:56:12 -0700473 // - If !target_supports_snapshot_ or PrepareSnapshotPartitionsForUpdate
474 // failed in recovery, explicitly CancelUpdate().
Yifan Hong6d888562019-10-01 13:00:31 -0700475 if (target_supports_snapshot_) {
Yifan Hongbae27842019-10-24 16:56:12 -0700476 if (PrepareSnapshotPartitionsForUpdate(
477 source_slot, target_slot, manifest, required_size)) {
478 return true;
479 }
480
481 // Virtual A/B device doing Virtual A/B update in Android mode must use
482 // snapshots.
483 if (!IsRecovery()) {
484 LOG(ERROR) << "PrepareSnapshotPartitionsForUpdate failed in Android "
485 << "mode";
486 return false;
487 }
488
489 delete_source = true;
490 LOG(INFO) << "PrepareSnapshotPartitionsForUpdate failed in recovery. "
491 << "Attempt to overwrite existing partitions if possible";
492 } else {
493 // Downgrading to an non-Virtual A/B build or is secondary OTA.
494 LOG(INFO) << "Using regular A/B on Virtual A/B because package disabled "
495 << "snapshots.";
Yifan Hong6d888562019-10-01 13:00:31 -0700496 }
Yifan Hongbae27842019-10-24 16:56:12 -0700497
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700498 // In recovery, if /metadata is not mounted, it is likely that metadata
499 // partition is erased and not formatted yet. After sideloading, when
500 // rebooting into the new version, init will erase metadata partition,
501 // hence the failure of CancelUpdate() can be ignored here.
502 // However, if metadata is mounted and CancelUpdate fails, sideloading
503 // should not proceed because during next boot, snapshots will overlay on
504 // the devices incorrectly.
505 if (ExpectMetadataMounted()) {
506 TEST_AND_RETURN_FALSE(snapshot_->CancelUpdate());
507 } else {
508 LOG(INFO) << "Skip canceling previous update because metadata is not "
509 << "mounted";
Yifan Hong6d888562019-10-01 13:00:31 -0700510 }
Yifan Hong420db9b2019-07-23 20:50:33 -0700511 }
Yifan Hongbae27842019-10-24 16:56:12 -0700512
Tianjie24f96092020-06-30 12:26:25 -0700513 // TODO(xunchang) support partial update on non VAB enabled devices.
Yifan Hong5c5743f2020-04-16 12:59:07 -0700514 TEST_AND_RETURN_FALSE(PrepareDynamicPartitionsForUpdate(
515 source_slot, target_slot, manifest, delete_source));
516
517 if (required_size != nullptr) {
518 *required_size = 0;
519 }
520 return true;
Yifan Hong420db9b2019-07-23 20:50:33 -0700521}
522
Yifan Hongf6f75c22020-07-31 15:20:25 -0700523bool DynamicPartitionControlAndroid::SetTargetBuildVars(
524 const DeltaArchiveManifest& manifest) {
525 // Precondition: current build supports dynamic partition.
526 CHECK(GetDynamicPartitionsFeatureFlag().IsEnabled());
527
528 bool is_target_dynamic =
529 !manifest.dynamic_partition_metadata().groups().empty();
530 bool target_supports_snapshot =
531 manifest.dynamic_partition_metadata().snapshot_enabled();
532
533 if (manifest.partial_update()) {
534 // Partial updates requires DAP. On partial updates that does not involve
535 // dynamic partitions, groups() can be empty, so also assume
536 // is_target_dynamic in this case. This assumption should be safe because we
537 // also check target_supports_snapshot below, which presumably also implies
538 // target build supports dynamic partition.
539 if (!is_target_dynamic) {
540 LOG(INFO) << "Assuming target build supports dynamic partitions for "
541 "partial updates.";
542 is_target_dynamic = true;
543 }
544
545 // Partial updates requires Virtual A/B. Double check that both current
546 // build and target build supports Virtual A/B.
547 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
548 LOG(ERROR) << "Partial update cannot be applied on a device that does "
549 "not support snapshots.";
550 return false;
551 }
552 if (!target_supports_snapshot) {
553 LOG(ERROR) << "Cannot apply partial update to a build that does not "
554 "support snapshots.";
555 return false;
556 }
557 }
558
559 // Store the flags.
560 is_target_dynamic_ = is_target_dynamic;
561 // If !is_target_dynamic_, leave target_supports_snapshot_ unset because
562 // snapshots would not work without dynamic partition.
563 if (is_target_dynamic_) {
564 target_supports_snapshot_ = target_supports_snapshot;
565 }
566 return true;
567}
568
Yifan Hong29692902020-03-26 12:47:05 -0700569namespace {
570// Try our best to erase AVB footer.
571class AvbFooterEraser {
572 public:
573 explicit AvbFooterEraser(const std::string& path) : path_(path) {}
574 bool Erase() {
575 // Try to mark the block device read-only. Ignore any
576 // failure since this won't work when passing regular files.
577 ignore_result(utils::SetBlockDeviceReadOnly(path_, false /* readonly */));
578
579 fd_.reset(new EintrSafeFileDescriptor());
580 int flags = O_WRONLY | O_TRUNC | O_CLOEXEC | O_SYNC;
581 TEST_AND_RETURN_FALSE(fd_->Open(path_.c_str(), flags));
582
583 // Need to write end-AVB_FOOTER_SIZE to end.
584 static_assert(AVB_FOOTER_SIZE > 0);
585 off64_t offset = fd_->Seek(-AVB_FOOTER_SIZE, SEEK_END);
586 TEST_AND_RETURN_FALSE_ERRNO(offset >= 0);
587 uint64_t write_size = AVB_FOOTER_SIZE;
588 LOG(INFO) << "Zeroing " << path_ << " @ [" << offset << ", "
589 << (offset + write_size) << "] (" << write_size << " bytes)";
590 brillo::Blob zeros(write_size);
591 TEST_AND_RETURN_FALSE(utils::WriteAll(fd_, zeros.data(), zeros.size()));
592 return true;
593 }
594 ~AvbFooterEraser() {
595 TEST_AND_RETURN(fd_ != nullptr && fd_->IsOpen());
596 if (!fd_->Close()) {
597 LOG(WARNING) << "Failed to close fd for " << path_;
598 }
599 }
600
601 private:
602 std::string path_;
603 FileDescriptorPtr fd_;
604};
605
606} // namespace
607
608std::optional<bool>
609DynamicPartitionControlAndroid::IsAvbEnabledOnSystemOther() {
610 auto prefix = GetProperty(kPostinstallFstabPrefix, "");
611 if (prefix.empty()) {
612 LOG(WARNING) << "Cannot get " << kPostinstallFstabPrefix;
613 return std::nullopt;
614 }
615 auto path = base::FilePath(prefix).Append("etc/fstab.postinstall").value();
616 return IsAvbEnabledInFstab(path);
617}
618
619std::optional<bool> DynamicPartitionControlAndroid::IsAvbEnabledInFstab(
620 const std::string& path) {
621 Fstab fstab;
622 if (!ReadFstabFromFile(path, &fstab)) {
Yifan Hong93cde302020-04-27 12:59:29 -0700623 PLOG(WARNING) << "Cannot read fstab from " << path;
624 if (errno == ENOENT) {
625 return false;
626 }
Yifan Hong29692902020-03-26 12:47:05 -0700627 return std::nullopt;
628 }
629 for (const auto& entry : fstab) {
630 if (!entry.avb_keys.empty()) {
631 return true;
632 }
633 }
634 return false;
635}
636
637bool DynamicPartitionControlAndroid::GetSystemOtherPath(
638 uint32_t source_slot,
639 uint32_t target_slot,
640 const std::string& partition_name_suffix,
641 std::string* path,
642 bool* should_unmap) {
643 path->clear();
644 *should_unmap = false;
645
P.Adarsh Reddy13e4195d2020-06-08 23:17:36 +0530646 // Check that AVB is enabled on system_other before erasing.
647 auto has_avb = IsAvbEnabledOnSystemOther();
648 TEST_AND_RETURN_FALSE(has_avb.has_value());
649 if (!has_avb.value()) {
650 LOG(INFO) << "AVB is not enabled on system_other. Skip erasing.";
651 return true;
652 }
Yifan Hong29692902020-03-26 12:47:05 -0700653
P.Adarsh Reddy13e4195d2020-06-08 23:17:36 +0530654 if (!IsRecovery()) {
Yifan Hong29692902020-03-26 12:47:05 -0700655 // Found unexpected avb_keys for system_other on devices retrofitting
656 // dynamic partitions. Previous crash in update_engine may leave logical
657 // partitions mapped on physical system_other partition. It is difficult to
658 // handle these cases. Just fail.
659 if (GetDynamicPartitionsFeatureFlag().IsRetrofit()) {
660 LOG(ERROR) << "Cannot erase AVB footer on system_other on devices with "
661 << "retrofit dynamic partitions. They should not have AVB "
662 << "enabled on system_other.";
663 return false;
664 }
665 }
666
667 std::string device_dir_str;
668 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
669 base::FilePath device_dir(device_dir_str);
670
671 // On devices without dynamic partition, search for static partitions.
672 if (!GetDynamicPartitionsFeatureFlag().IsEnabled()) {
673 *path = device_dir.Append(partition_name_suffix).value();
674 TEST_AND_RETURN_FALSE(DeviceExists(*path));
675 return true;
676 }
677
678 auto source_super_device =
679 device_dir.Append(GetSuperPartitionName(source_slot)).value();
680
681 auto builder = LoadMetadataBuilder(source_super_device, source_slot);
682 if (builder == nullptr) {
683 if (IsRecovery()) {
684 // It might be corrupted for some reason. It should still be able to
685 // sideload.
686 LOG(WARNING) << "Super partition metadata cannot be read from the source "
687 << "slot, skip erasing.";
688 return true;
689 } else {
690 // Device has booted into Android mode, indicating that the super
691 // partition metadata should be there.
692 LOG(ERROR) << "Super partition metadata cannot be read from the source "
693 << "slot. This is unexpected on devices with dynamic "
694 << "partitions enabled.";
695 return false;
696 }
697 }
698 auto p = builder->FindPartition(partition_name_suffix);
699 if (p == nullptr) {
700 // If the source slot is flashed without system_other, it does not exist
701 // in super partition metadata at source slot. It is safe to skip it.
702 LOG(INFO) << "Can't find " << partition_name_suffix
703 << " in metadata source slot, skip erasing.";
704 return true;
705 }
706 // System_other created by flashing tools should be erased.
707 // If partition is created by update_engine (via NewForUpdate), it is a
708 // left-over partition from the previous update and does not contain
709 // system_other, hence there is no need to erase.
710 // Note the reverse is not necessary true. If the flag is not set, we don't
711 // know if the partition is created by update_engine or by flashing tools
712 // because older versions of super partition metadata does not contain this
713 // flag. It is okay to erase the AVB footer anyways.
714 if (p->attributes() & LP_PARTITION_ATTR_UPDATED) {
715 LOG(INFO) << partition_name_suffix
716 << " does not contain system_other, skip erasing.";
717 return true;
718 }
719
Yifan Hong64331b32020-05-13 16:50:40 -0700720 if (p->size() < AVB_FOOTER_SIZE) {
721 LOG(INFO) << partition_name_suffix << " has length " << p->size()
722 << "( < AVB_FOOTER_SIZE " << AVB_FOOTER_SIZE
723 << "), skip erasing.";
724 return true;
725 }
726
Yifan Hong29692902020-03-26 12:47:05 -0700727 // Delete any pre-existing device with name |partition_name_suffix| and
728 // also remove it from |mapped_devices_|.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700729 // In recovery, metadata might not be mounted, and
730 // UnmapPartitionOnDeviceMapper might fail. However,
731 // it is unusual that system_other has already been mapped. Hence, just skip.
Yifan Hong29692902020-03-26 12:47:05 -0700732 TEST_AND_RETURN_FALSE(UnmapPartitionOnDeviceMapper(partition_name_suffix));
733 // Use CreateLogicalPartition directly to avoid mapping with existing
734 // snapshots.
735 CreateLogicalPartitionParams params = {
736 .block_device = source_super_device,
737 .metadata_slot = source_slot,
738 .partition_name = partition_name_suffix,
739 .force_writable = true,
740 .timeout_ms = kMapTimeout,
741 };
742 TEST_AND_RETURN_FALSE(CreateLogicalPartition(params, path));
743 *should_unmap = true;
744 return true;
745}
746
747bool DynamicPartitionControlAndroid::EraseSystemOtherAvbFooter(
748 uint32_t source_slot, uint32_t target_slot) {
749 LOG(INFO) << "Erasing AVB footer of system_other partition before update.";
750
751 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
752 const std::string partition_name_suffix = "system" + target_suffix;
753
754 std::string path;
755 bool should_unmap = false;
756
757 TEST_AND_RETURN_FALSE(GetSystemOtherPath(
758 source_slot, target_slot, partition_name_suffix, &path, &should_unmap));
759
760 if (path.empty()) {
761 return true;
762 }
763
764 bool ret = AvbFooterEraser(path).Erase();
765
766 // Delete |partition_name_suffix| from device mapper and from
767 // |mapped_devices_| again so that it does not interfere with update process.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700768 // In recovery, metadata might not be mounted, and
769 // UnmapPartitionOnDeviceMapper might fail. However, DestroyLogicalPartition
770 // should be called. If DestroyLogicalPartition does fail, it is still okay
771 // to skip the error here and let Prepare*() fail later.
Yifan Hong29692902020-03-26 12:47:05 -0700772 if (should_unmap) {
773 TEST_AND_RETURN_FALSE(UnmapPartitionOnDeviceMapper(partition_name_suffix));
774 }
775
776 return ret;
777}
778
Yifan Hong420db9b2019-07-23 20:50:33 -0700779bool DynamicPartitionControlAndroid::PrepareDynamicPartitionsForUpdate(
780 uint32_t source_slot,
781 uint32_t target_slot,
Yifan Hongbae27842019-10-24 16:56:12 -0700782 const DeltaArchiveManifest& manifest,
783 bool delete_source) {
Yifan Hong012508e2019-07-22 18:30:40 -0700784 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
785
786 // Unmap all the target dynamic partitions because they would become
787 // inconsistent with the new metadata.
Yifan Hong13d41cb2019-09-16 13:18:22 -0700788 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
789 for (const auto& partition_name : group.partition_names()) {
790 if (!UnmapPartitionOnDeviceMapper(partition_name + target_suffix)) {
Yifan Hong012508e2019-07-22 18:30:40 -0700791 return false;
792 }
793 }
794 }
795
796 std::string device_dir_str;
797 if (!GetDeviceDir(&device_dir_str)) {
798 return false;
799 }
800 base::FilePath device_dir(device_dir_str);
801 auto source_device =
Yifan Hong700d7c12019-07-23 20:49:16 -0700802 device_dir.Append(GetSuperPartitionName(source_slot)).value();
Yifan Hong012508e2019-07-22 18:30:40 -0700803
804 auto builder = LoadMetadataBuilder(source_device, source_slot, target_slot);
805 if (builder == nullptr) {
806 LOG(ERROR) << "No metadata at "
807 << BootControlInterface::SlotName(source_slot);
808 return false;
809 }
810
Yifan Hongbae27842019-10-24 16:56:12 -0700811 if (delete_source) {
812 TEST_AND_RETURN_FALSE(
813 DeleteSourcePartitions(builder.get(), source_slot, manifest));
814 }
815
Yifan Hong13d41cb2019-09-16 13:18:22 -0700816 if (!UpdatePartitionMetadata(builder.get(), target_slot, manifest)) {
Yifan Hong012508e2019-07-22 18:30:40 -0700817 return false;
818 }
819
820 auto target_device =
Yifan Hong700d7c12019-07-23 20:49:16 -0700821 device_dir.Append(GetSuperPartitionName(target_slot)).value();
Yifan Hong012508e2019-07-22 18:30:40 -0700822 return StoreMetadata(target_device, builder.get(), target_slot);
823}
824
Yifan Hong420db9b2019-07-23 20:50:33 -0700825bool DynamicPartitionControlAndroid::PrepareSnapshotPartitionsForUpdate(
826 uint32_t source_slot,
827 uint32_t target_slot,
Yifan Hongf033ecb2020-01-07 18:13:56 -0800828 const DeltaArchiveManifest& manifest,
829 uint64_t* required_size) {
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700830 TEST_AND_RETURN_FALSE(ExpectMetadataMounted());
Yifan Hong420db9b2019-07-23 20:50:33 -0700831 if (!snapshot_->BeginUpdate()) {
832 LOG(ERROR) << "Cannot begin new update.";
833 return false;
834 }
Yifan Hongf033ecb2020-01-07 18:13:56 -0800835 auto ret = snapshot_->CreateUpdateSnapshots(manifest);
836 if (!ret) {
837 LOG(ERROR) << "Cannot create update snapshots: " << ret.string();
838 if (required_size != nullptr &&
Yifan Hong0850bca2020-01-16 15:14:07 -0800839 ret.error_code() == Return::ErrorCode::NO_SPACE) {
Yifan Hongf033ecb2020-01-07 18:13:56 -0800840 *required_size = ret.required_size();
841 }
Yifan Hong420db9b2019-07-23 20:50:33 -0700842 return false;
843 }
844 return true;
845}
846
Yifan Hong700d7c12019-07-23 20:49:16 -0700847std::string DynamicPartitionControlAndroid::GetSuperPartitionName(
848 uint32_t slot) {
849 return fs_mgr_get_super_partition_name(slot);
850}
851
Yifan Hong012508e2019-07-22 18:30:40 -0700852bool DynamicPartitionControlAndroid::UpdatePartitionMetadata(
853 MetadataBuilder* builder,
854 uint32_t target_slot,
Yifan Hong13d41cb2019-09-16 13:18:22 -0700855 const DeltaArchiveManifest& manifest) {
Yifan Hong8d6df9a2020-08-13 13:59:54 -0700856 // Check preconditions.
857 CHECK(!GetVirtualAbFeatureFlag().IsEnabled() || IsRecovery())
858 << "UpdatePartitionMetadata is called on a Virtual A/B device "
859 "but source partitions is not deleted. This is not allowed.";
860
Yifan Honga4e7da32019-09-30 18:25:03 -0700861 // If applying downgrade from Virtual A/B to non-Virtual A/B, the left-over
862 // COW group needs to be deleted to ensure there are enough space to create
863 // target partitions.
864 builder->RemoveGroupAndPartitions(android::snapshot::kCowGroupName);
865
Yifan Hong012508e2019-07-22 18:30:40 -0700866 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
867 DeleteGroupsWithSuffix(builder, target_suffix);
868
869 uint64_t total_size = 0;
Yifan Hong13d41cb2019-09-16 13:18:22 -0700870 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
871 total_size += group.size();
Yifan Hong012508e2019-07-22 18:30:40 -0700872 }
873
874 std::string expr;
875 uint64_t allocatable_space = builder->AllocatableSpace();
Yifan Hong8d6df9a2020-08-13 13:59:54 -0700876 // On device retrofitting dynamic partitions, allocatable_space = super.
877 // On device launching dynamic partitions w/o VAB,
878 // allocatable_space = super / 2.
879 // On device launching dynamic partitions with VAB, allocatable_space = super.
880 if (!GetDynamicPartitionsFeatureFlag().IsRetrofit() &&
881 !GetVirtualAbFeatureFlag().IsEnabled()) {
Yifan Hong012508e2019-07-22 18:30:40 -0700882 allocatable_space /= 2;
883 expr = "half of ";
884 }
885 if (total_size > allocatable_space) {
886 LOG(ERROR) << "The maximum size of all groups with suffix " << target_suffix
887 << " (" << total_size << ") has exceeded " << expr
888 << "allocatable space for dynamic partitions "
889 << allocatable_space << ".";
890 return false;
891 }
892
Yifan Hong13d41cb2019-09-16 13:18:22 -0700893 // name of partition(e.g. "system") -> size in bytes
894 std::map<std::string, uint64_t> partition_sizes;
895 for (const auto& partition : manifest.partitions()) {
896 partition_sizes.emplace(partition.partition_name(),
897 partition.new_partition_info().size());
898 }
899
900 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
901 auto group_name_suffix = group.name() + target_suffix;
902 if (!builder->AddGroup(group_name_suffix, group.size())) {
Yifan Hong012508e2019-07-22 18:30:40 -0700903 LOG(ERROR) << "Cannot add group " << group_name_suffix << " with size "
Yifan Hong13d41cb2019-09-16 13:18:22 -0700904 << group.size();
Yifan Hong012508e2019-07-22 18:30:40 -0700905 return false;
906 }
907 LOG(INFO) << "Added group " << group_name_suffix << " with size "
Yifan Hong13d41cb2019-09-16 13:18:22 -0700908 << group.size();
Yifan Hong012508e2019-07-22 18:30:40 -0700909
Yifan Hong13d41cb2019-09-16 13:18:22 -0700910 for (const auto& partition_name : group.partition_names()) {
911 auto partition_sizes_it = partition_sizes.find(partition_name);
912 if (partition_sizes_it == partition_sizes.end()) {
913 // TODO(tbao): Support auto-filling partition info for framework-only
914 // OTA.
915 LOG(ERROR) << "dynamic_partition_metadata contains partition "
916 << partition_name << " but it is not part of the manifest. "
917 << "This is not supported.";
918 return false;
919 }
920 uint64_t partition_size = partition_sizes_it->second;
921
922 auto partition_name_suffix = partition_name + target_suffix;
Yifan Hong012508e2019-07-22 18:30:40 -0700923 Partition* p = builder->AddPartition(
924 partition_name_suffix, group_name_suffix, LP_PARTITION_ATTR_READONLY);
925 if (!p) {
926 LOG(ERROR) << "Cannot add partition " << partition_name_suffix
927 << " to group " << group_name_suffix;
928 return false;
929 }
Yifan Hong13d41cb2019-09-16 13:18:22 -0700930 if (!builder->ResizePartition(p, partition_size)) {
Yifan Hong012508e2019-07-22 18:30:40 -0700931 LOG(ERROR) << "Cannot resize partition " << partition_name_suffix
Yifan Hong13d41cb2019-09-16 13:18:22 -0700932 << " to size " << partition_size << ". Not enough space?";
Yifan Hong012508e2019-07-22 18:30:40 -0700933 return false;
934 }
935 LOG(INFO) << "Added partition " << partition_name_suffix << " to group "
Yifan Hong13d41cb2019-09-16 13:18:22 -0700936 << group_name_suffix << " with size " << partition_size;
Yifan Hong012508e2019-07-22 18:30:40 -0700937 }
938 }
939
940 return true;
941}
942
Yifan Hong7b3910a2020-03-24 17:47:32 -0700943bool DynamicPartitionControlAndroid::FinishUpdate(bool powerwash_required) {
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700944 if (ExpectMetadataMounted()) {
945 if (snapshot_->GetUpdateState() == UpdateState::Initiated) {
946 LOG(INFO) << "Snapshot writes are done.";
947 return snapshot_->FinishedSnapshotWrites(powerwash_required);
948 }
949 } else {
950 LOG(INFO) << "Skip FinishedSnapshotWrites() because /metadata is not "
951 << "mounted";
Yifan Hongf0f4a912019-09-26 17:51:33 -0700952 }
953 return true;
Yifan Honga33bca42019-09-03 20:29:45 -0700954}
955
Yifan Hong3a1a5612019-11-05 16:34:32 -0800956bool DynamicPartitionControlAndroid::GetPartitionDevice(
957 const std::string& partition_name,
958 uint32_t slot,
959 uint32_t current_slot,
Tianjie51a5a392020-06-03 14:39:32 -0700960 bool not_in_payload,
961 std::string* device,
962 bool* is_dynamic) {
Yifan Hong3a1a5612019-11-05 16:34:32 -0800963 const auto& partition_name_suffix =
964 partition_name + SlotSuffixForSlotNumber(slot);
965 std::string device_dir_str;
966 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
967 base::FilePath device_dir(device_dir_str);
968
Tianjie51a5a392020-06-03 14:39:32 -0700969 if (is_dynamic) {
970 *is_dynamic = false;
971 }
972
Yifan Hong3a1a5612019-11-05 16:34:32 -0800973 // When looking up target partition devices, treat them as static if the
974 // current payload doesn't encode them as dynamic partitions. This may happen
975 // when applying a retrofit update on top of a dynamic-partitions-enabled
976 // build.
977 if (GetDynamicPartitionsFeatureFlag().IsEnabled() &&
978 (slot == current_slot || is_target_dynamic_)) {
Tianjie51a5a392020-06-03 14:39:32 -0700979 switch (GetDynamicPartitionDevice(device_dir,
980 partition_name_suffix,
981 slot,
982 current_slot,
983 not_in_payload,
984 device)) {
Yifan Hong3a1a5612019-11-05 16:34:32 -0800985 case DynamicPartitionDeviceStatus::SUCCESS:
Tianjie51a5a392020-06-03 14:39:32 -0700986 if (is_dynamic) {
987 *is_dynamic = true;
988 }
Yifan Hong3a1a5612019-11-05 16:34:32 -0800989 return true;
990 case DynamicPartitionDeviceStatus::TRY_STATIC:
991 break;
992 case DynamicPartitionDeviceStatus::ERROR: // fallthrough
993 default:
994 return false;
995 }
996 }
997 base::FilePath path = device_dir.Append(partition_name_suffix);
998 if (!DeviceExists(path.value())) {
999 LOG(ERROR) << "Device file " << path.value() << " does not exist.";
1000 return false;
1001 }
1002
1003 *device = path.value();
1004 return true;
1005}
1006
Tianjie51a5a392020-06-03 14:39:32 -07001007bool DynamicPartitionControlAndroid::GetPartitionDevice(
1008 const std::string& partition_name,
1009 uint32_t slot,
1010 uint32_t current_slot,
1011 std::string* device) {
1012 return GetPartitionDevice(
1013 partition_name, slot, current_slot, false, device, nullptr);
1014}
1015
Yifan Hong3a1a5612019-11-05 16:34:32 -08001016bool DynamicPartitionControlAndroid::IsSuperBlockDevice(
1017 const base::FilePath& device_dir,
1018 uint32_t current_slot,
1019 const std::string& partition_name_suffix) {
1020 std::string source_device =
1021 device_dir.Append(GetSuperPartitionName(current_slot)).value();
1022 auto source_metadata = LoadMetadataBuilder(source_device, current_slot);
1023 return source_metadata->HasBlockDevice(partition_name_suffix);
1024}
1025
1026DynamicPartitionControlAndroid::DynamicPartitionDeviceStatus
1027DynamicPartitionControlAndroid::GetDynamicPartitionDevice(
1028 const base::FilePath& device_dir,
1029 const std::string& partition_name_suffix,
1030 uint32_t slot,
1031 uint32_t current_slot,
Tianjie51a5a392020-06-03 14:39:32 -07001032 bool not_in_payload,
Yifan Hong3a1a5612019-11-05 16:34:32 -08001033 std::string* device) {
1034 std::string super_device =
1035 device_dir.Append(GetSuperPartitionName(slot)).value();
1036
1037 auto builder = LoadMetadataBuilder(super_device, slot);
1038 if (builder == nullptr) {
1039 LOG(ERROR) << "No metadata in slot "
1040 << BootControlInterface::SlotName(slot);
1041 return DynamicPartitionDeviceStatus::ERROR;
1042 }
1043 if (builder->FindPartition(partition_name_suffix) == nullptr) {
1044 LOG(INFO) << partition_name_suffix
1045 << " is not in super partition metadata.";
1046
1047 if (IsSuperBlockDevice(device_dir, current_slot, partition_name_suffix)) {
1048 LOG(ERROR) << "The static partition " << partition_name_suffix
1049 << " is a block device for current metadata."
1050 << "It cannot be used as a logical partition.";
1051 return DynamicPartitionDeviceStatus::ERROR;
1052 }
1053
1054 return DynamicPartitionDeviceStatus::TRY_STATIC;
1055 }
1056
1057 if (slot == current_slot) {
1058 if (GetState(partition_name_suffix) != DmDeviceState::ACTIVE) {
1059 LOG(WARNING) << partition_name_suffix << " is at current slot but it is "
1060 << "not mapped. Now try to map it.";
1061 } else {
1062 if (GetDmDevicePathByName(partition_name_suffix, device)) {
1063 LOG(INFO) << partition_name_suffix
1064 << " is mapped on device mapper: " << *device;
1065 return DynamicPartitionDeviceStatus::SUCCESS;
1066 }
1067 LOG(ERROR) << partition_name_suffix << "is mapped but path is unknown.";
1068 return DynamicPartitionDeviceStatus::ERROR;
1069 }
1070 }
1071
Tianjie51a5a392020-06-03 14:39:32 -07001072 bool force_writable = (slot != current_slot) && !not_in_payload;
Yifan Hong3a1a5612019-11-05 16:34:32 -08001073 if (MapPartitionOnDeviceMapper(
1074 super_device, partition_name_suffix, slot, force_writable, device)) {
1075 return DynamicPartitionDeviceStatus::SUCCESS;
1076 }
1077 return DynamicPartitionDeviceStatus::ERROR;
1078}
1079
Yifan Hong6eec9952019-12-04 13:12:01 -08001080void DynamicPartitionControlAndroid::set_fake_mapped_devices(
1081 const std::set<std::string>& fake) {
1082 mapped_devices_ = fake;
1083}
1084
Yifan Hongbae27842019-10-24 16:56:12 -07001085bool DynamicPartitionControlAndroid::IsRecovery() {
Kelvin Zhanga22ef552020-10-12 19:03:52 -04001086 return constants::kIsRecovery;
Yifan Hongbae27842019-10-24 16:56:12 -07001087}
1088
1089static bool IsIncrementalUpdate(const DeltaArchiveManifest& manifest) {
1090 const auto& partitions = manifest.partitions();
1091 return std::any_of(partitions.begin(), partitions.end(), [](const auto& p) {
1092 return p.has_old_partition_info();
1093 });
1094}
1095
1096bool DynamicPartitionControlAndroid::DeleteSourcePartitions(
1097 MetadataBuilder* builder,
1098 uint32_t source_slot,
1099 const DeltaArchiveManifest& manifest) {
1100 TEST_AND_RETURN_FALSE(IsRecovery());
1101
1102 if (IsIncrementalUpdate(manifest)) {
1103 LOG(ERROR) << "Cannot sideload incremental OTA because snapshots cannot "
1104 << "be created.";
1105 if (GetVirtualAbFeatureFlag().IsLaunch()) {
1106 LOG(ERROR) << "Sideloading incremental updates on devices launches "
1107 << " Virtual A/B is not supported.";
1108 }
1109 return false;
1110 }
1111
1112 LOG(INFO) << "Will overwrite existing partitions. Slot "
1113 << BootControlInterface::SlotName(source_slot)
1114 << "may be unbootable until update finishes!";
1115 const std::string source_suffix = SlotSuffixForSlotNumber(source_slot);
1116 DeleteGroupsWithSuffix(builder, source_suffix);
1117
1118 return true;
1119}
1120
Yifan Hong90965502020-02-19 15:22:47 -08001121std::unique_ptr<AbstractAction>
1122DynamicPartitionControlAndroid::GetCleanupPreviousUpdateAction(
1123 BootControlInterface* boot_control,
1124 PrefsInterface* prefs,
1125 CleanupPreviousUpdateActionDelegateInterface* delegate) {
1126 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1127 return std::make_unique<NoOpAction>();
1128 }
1129 return std::make_unique<CleanupPreviousUpdateAction>(
1130 prefs, boot_control, snapshot_.get(), delegate);
1131}
1132
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001133bool DynamicPartitionControlAndroid::ResetUpdate(PrefsInterface* prefs) {
1134 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1135 return true;
1136 }
1137
1138 LOG(INFO) << __func__ << " resetting update state and deleting snapshots.";
1139 TEST_AND_RETURN_FALSE(prefs != nullptr);
1140
1141 // If the device has already booted into the target slot,
1142 // ResetUpdateProgress may pass but CancelUpdate fails.
1143 // This is expected. A scheduled CleanupPreviousUpdateAction should free
1144 // space when it is done.
1145 TEST_AND_RETURN_FALSE(DeltaPerformer::ResetUpdateProgress(
1146 prefs, false /* quick */, false /* skip dynamic partitions metadata */));
1147
Yifan Hong4d7c5eb2020-04-03 11:31:50 -07001148 if (ExpectMetadataMounted()) {
1149 TEST_AND_RETURN_FALSE(snapshot_->CancelUpdate());
1150 } else {
1151 LOG(INFO) << "Skip cancelling update in ResetUpdate because /metadata is "
1152 << "not mounted";
1153 }
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001154
1155 return true;
1156}
1157
Tianjie99d570d2020-06-04 14:57:19 -07001158bool DynamicPartitionControlAndroid::ListDynamicPartitionsForSlot(
1159 uint32_t current_slot, std::vector<std::string>* partitions) {
1160 if (!GetDynamicPartitionsFeatureFlag().IsEnabled()) {
1161 LOG(ERROR) << "Dynamic partition is not enabled";
1162 return false;
1163 }
1164
1165 std::string device_dir_str;
1166 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
1167 base::FilePath device_dir(device_dir_str);
1168 auto super_device =
1169 device_dir.Append(GetSuperPartitionName(current_slot)).value();
1170 auto builder = LoadMetadataBuilder(super_device, current_slot);
1171 TEST_AND_RETURN_FALSE(builder != nullptr);
1172
1173 std::vector<std::string> result;
1174 auto suffix = SlotSuffixForSlotNumber(current_slot);
1175 for (const auto& group : builder->ListGroups()) {
1176 for (const auto& partition : builder->ListPartitionsInGroup(group)) {
1177 std::string_view partition_name = partition->name();
1178 if (!android::base::ConsumeSuffix(&partition_name, suffix)) {
1179 continue;
1180 }
1181 result.emplace_back(partition_name);
1182 }
1183 }
1184 *partitions = std::move(result);
1185 return true;
1186}
1187
Tianjie24f96092020-06-30 12:26:25 -07001188bool DynamicPartitionControlAndroid::VerifyExtentsForUntouchedPartitions(
1189 uint32_t source_slot,
1190 uint32_t target_slot,
1191 const std::vector<std::string>& partitions) {
1192 std::string device_dir_str;
1193 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
1194 base::FilePath device_dir(device_dir_str);
1195
1196 auto source_super_device =
1197 device_dir.Append(GetSuperPartitionName(source_slot)).value();
1198 auto source_builder = LoadMetadataBuilder(source_super_device, source_slot);
1199 TEST_AND_RETURN_FALSE(source_builder != nullptr);
1200
1201 auto target_super_device =
1202 device_dir.Append(GetSuperPartitionName(target_slot)).value();
1203 auto target_builder = LoadMetadataBuilder(target_super_device, target_slot);
1204 TEST_AND_RETURN_FALSE(target_builder != nullptr);
1205
1206 return MetadataBuilder::VerifyExtentsAgainstSourceMetadata(
1207 *source_builder, source_slot, *target_builder, target_slot, partitions);
1208}
1209
Yifan Hong4d7c5eb2020-04-03 11:31:50 -07001210bool DynamicPartitionControlAndroid::ExpectMetadataMounted() {
1211 // No need to mount metadata for non-Virtual A/B devices.
1212 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1213 return false;
1214 }
1215 // Intentionally not checking |metadata_device_| in Android mode.
1216 // /metadata should always be mounted in Android mode. If it isn't, let caller
1217 // fails when calling into SnapshotManager.
1218 if (!IsRecovery()) {
1219 return true;
1220 }
1221 // In recovery mode, explicitly check |metadata_device_|.
1222 return metadata_device_ != nullptr;
1223}
1224
1225bool DynamicPartitionControlAndroid::EnsureMetadataMounted() {
1226 // No need to mount metadata for non-Virtual A/B devices.
1227 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1228 return true;
1229 }
1230
1231 if (metadata_device_ == nullptr) {
1232 metadata_device_ = snapshot_->EnsureMetadataMounted();
1233 }
1234 return metadata_device_ != nullptr;
1235}
1236
Kelvin Zhang34618522020-09-28 09:21:02 -04001237std::unique_ptr<android::snapshot::ISnapshotWriter>
1238DynamicPartitionControlAndroid::OpenCowWriter(
1239 const std::string& partition_name,
1240 const std::optional<std::string>& source_path,
1241 bool is_append) {
1242 auto suffix = SlotSuffixForSlotNumber(target_slot_);
1243
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -04001244 auto super_device = GetSuperDevice();
1245 if (!super_device.has_value()) {
Kelvin Zhang34618522020-09-28 09:21:02 -04001246 return nullptr;
1247 }
Kelvin Zhang34618522020-09-28 09:21:02 -04001248 CreateLogicalPartitionParams params = {
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -04001249 .block_device = super_device->value(),
Kelvin Zhang34618522020-09-28 09:21:02 -04001250 .metadata_slot = target_slot_,
1251 .partition_name = partition_name + suffix,
1252 .force_writable = true,
Kelvin Zhang877ddbe2020-11-09 13:37:56 -05001253 .timeout_ms = kMapSnapshotTimeout};
Kelvin Zhang34618522020-09-28 09:21:02 -04001254 // TODO(zhangkelvin) Open an APPEND mode CowWriter once there's an API to do
1255 // it.
1256 return snapshot_->OpenSnapshotWriter(params, std::move(source_path));
Kelvin Zhang877ddbe2020-11-09 13:37:56 -05001257} // namespace chromeos_update_engine
Kelvin Zhang34618522020-09-28 09:21:02 -04001258
Kelvin Zhangc82511c2020-11-06 16:01:24 -05001259FileDescriptorPtr DynamicPartitionControlAndroid::OpenCowReader(
1260 const std::string& unsuffixed_partition_name,
1261 const std::optional<std::string>& source_path,
1262 bool is_append) {
1263 auto cow_writer =
1264 OpenCowWriter(unsuffixed_partition_name, source_path, is_append);
1265 if (cow_writer == nullptr) {
1266 return nullptr;
1267 }
1268 return cow_writer->OpenReader();
1269}
1270
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -04001271std::optional<base::FilePath> DynamicPartitionControlAndroid::GetSuperDevice() {
1272 std::string device_dir_str;
1273 if (!GetDeviceDir(&device_dir_str)) {
1274 LOG(ERROR) << "Failed to get device dir!";
1275 return {};
1276 }
1277 base::FilePath device_dir(device_dir_str);
1278 auto super_device = device_dir.Append(GetSuperPartitionName(target_slot_));
1279 return super_device;
1280}
1281
1282bool DynamicPartitionControlAndroid::MapAllPartitions() {
Kelvin Zhang877ddbe2020-11-09 13:37:56 -05001283 return snapshot_->MapAllSnapshots(kMapSnapshotTimeout);
Kelvin Zhang9d87d6d2020-10-23 17:03:59 -04001284}
1285
Kelvin Zhangeb9de162020-11-16 15:47:28 -05001286bool DynamicPartitionControlAndroid::IsDynamicPartition(
1287 const std::string& partition_name) {
1288 if (dynamic_partition_list_.empty() &&
1289 GetDynamicPartitionsFeatureFlag().IsEnabled()) {
1290 CHECK(ListDynamicPartitionsForSlot(source_slot_, &dynamic_partition_list_));
1291 }
1292 return std::find(dynamic_partition_list_.begin(),
1293 dynamic_partition_list_.end(),
1294 partition_name) != dynamic_partition_list_.end();
1295}
Yifan Hong537802d2018-08-15 13:15:42 -07001296} // namespace chromeos_update_engine