blob: 06e574539f1a514bc20593cc9b5b6ab99db753d0 [file] [log] [blame]
Yifan Hong537802d2018-08-15 13:15:42 -07001//
2// Copyright (C) 2018 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
16
17#include "update_engine/dynamic_partition_control_android.h"
18
Yifan Hong420db9b2019-07-23 20:50:33 -070019#include <chrono> // NOLINT(build/c++11) - using libsnapshot / liblp API
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
Yifan Hong90965502020-02-19 15:22:47 -080045#include "update_engine/cleanup_previous_update_action.h"
Yifan Hong537802d2018-08-15 13:15:42 -070046#include "update_engine/common/boot_control_interface.h"
47#include "update_engine/common/utils.h"
Yifan Hong012508e2019-07-22 18:30:40 -070048#include "update_engine/dynamic_partition_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
Yifan Hongbae27842019-10-24 16:56:12 -0700276void DynamicPartitionControlAndroid::UnmapAllPartitions() {
Tao Bao8c4d0082019-08-08 08:56:16 -0700277 if (mapped_devices_.empty()) {
278 return;
279 }
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 }
287}
288
289void DynamicPartitionControlAndroid::Cleanup() {
Yifan Hongbae27842019-10-24 16:56:12 -0700290 UnmapAllPartitions();
291 metadata_device_.reset();
Yifan Hong537802d2018-08-15 13:15:42 -0700292}
293
294bool DynamicPartitionControlAndroid::DeviceExists(const std::string& path) {
295 return base::PathExists(base::FilePath(path));
296}
297
298android::dm::DmDeviceState DynamicPartitionControlAndroid::GetState(
299 const std::string& name) {
300 return DeviceMapper::Instance().GetState(name);
301}
302
303bool DynamicPartitionControlAndroid::GetDmDevicePathByName(
304 const std::string& name, std::string* path) {
305 return DeviceMapper::Instance().GetDmDevicePathByName(name, path);
306}
307
308std::unique_ptr<MetadataBuilder>
309DynamicPartitionControlAndroid::LoadMetadataBuilder(
Tianjie24f96092020-06-30 12:26:25 -0700310 const std::string& super_device, uint32_t slot) {
311 auto builder = MetadataBuilder::New(PartitionOpener(), super_device, slot);
312 if (builder == nullptr) {
313 LOG(WARNING) << "No metadata slot " << BootControlInterface::SlotName(slot)
314 << " in " << super_device;
315 return nullptr;
316 }
317 LOG(INFO) << "Loaded metadata from slot "
318 << BootControlInterface::SlotName(slot) << " in " << super_device;
319 return builder;
Yifan Hong012508e2019-07-22 18:30:40 -0700320}
321
322std::unique_ptr<MetadataBuilder>
323DynamicPartitionControlAndroid::LoadMetadataBuilder(
Yifan Hong6e706b12018-11-09 16:50:51 -0800324 const std::string& super_device,
325 uint32_t source_slot,
326 uint32_t target_slot) {
Tianjie24f96092020-06-30 12:26:25 -0700327 bool always_keep_source_slot = !target_supports_snapshot_;
328 auto builder = MetadataBuilder::NewForUpdate(PartitionOpener(),
329 super_device,
330 source_slot,
331 target_slot,
332 always_keep_source_slot);
Yifan Hong537802d2018-08-15 13:15:42 -0700333 if (builder == nullptr) {
334 LOG(WARNING) << "No metadata slot "
335 << BootControlInterface::SlotName(source_slot) << " in "
336 << super_device;
Yifan Hongf48a0052018-10-29 16:30:43 -0700337 return nullptr;
Yifan Hong537802d2018-08-15 13:15:42 -0700338 }
Tianjie24f96092020-06-30 12:26:25 -0700339 LOG(INFO) << "Created metadata for new update from slot "
Yifan Hong537802d2018-08-15 13:15:42 -0700340 << BootControlInterface::SlotName(source_slot) << " in "
341 << super_device;
342 return builder;
343}
344
345bool DynamicPartitionControlAndroid::StoreMetadata(
346 const std::string& super_device,
347 MetadataBuilder* builder,
348 uint32_t target_slot) {
349 auto metadata = builder->Export();
350 if (metadata == nullptr) {
351 LOG(ERROR) << "Cannot export metadata to slot "
352 << BootControlInterface::SlotName(target_slot) << " in "
353 << super_device;
354 return false;
355 }
356
Yifan Hong186bb682019-07-23 14:04:39 -0700357 if (GetDynamicPartitionsFeatureFlag().IsRetrofit()) {
Yifan Hong6e706b12018-11-09 16:50:51 -0800358 if (!FlashPartitionTable(super_device, *metadata)) {
359 LOG(ERROR) << "Cannot write metadata to " << super_device;
360 return false;
361 }
362 LOG(INFO) << "Written metadata to " << super_device;
363 } else {
364 if (!UpdatePartitionTable(super_device, *metadata, target_slot)) {
365 LOG(ERROR) << "Cannot write metadata to slot "
366 << BootControlInterface::SlotName(target_slot) << " in "
367 << super_device;
368 return false;
369 }
370 LOG(INFO) << "Copied metadata to slot "
371 << BootControlInterface::SlotName(target_slot) << " in "
372 << super_device;
Yifan Hong537802d2018-08-15 13:15:42 -0700373 }
374
Yifan Hong537802d2018-08-15 13:15:42 -0700375 return true;
376}
377
378bool DynamicPartitionControlAndroid::GetDeviceDir(std::string* out) {
379 // We can't use fs_mgr to look up |partition_name| because fstab
380 // doesn't list every slot partition (it uses the slotselect option
381 // to mask the suffix).
382 //
383 // We can however assume that there's an entry for the /misc mount
384 // point and use that to get the device file for the misc
385 // partition. This helps us locate the disk that |partition_name|
386 // resides on. From there we'll assume that a by-name scheme is used
387 // so we can just replace the trailing "misc" by the given
388 // |partition_name| and suffix corresponding to |slot|, e.g.
389 //
390 // /dev/block/platform/soc.0/7824900.sdhci/by-name/misc ->
391 // /dev/block/platform/soc.0/7824900.sdhci/by-name/boot_a
392 //
393 // If needed, it's possible to relax the by-name assumption in the
394 // future by trawling /sys/block looking for the appropriate sibling
395 // of misc and then finding an entry in /dev matching the sysfs
396 // entry.
397
398 std::string err, misc_device = get_bootloader_message_blk_device(&err);
399 if (misc_device.empty()) {
400 LOG(ERROR) << "Unable to get misc block device: " << err;
401 return false;
402 }
403
404 if (!utils::IsSymlink(misc_device.c_str())) {
405 LOG(ERROR) << "Device file " << misc_device << " for /misc "
406 << "is not a symlink.";
407 return false;
408 }
409 *out = base::FilePath(misc_device).DirName().value();
410 return true;
411}
Yifan Hong012508e2019-07-22 18:30:40 -0700412
413bool DynamicPartitionControlAndroid::PreparePartitionsForUpdate(
414 uint32_t source_slot,
415 uint32_t target_slot,
Yifan Hongf0f4a912019-09-26 17:51:33 -0700416 const DeltaArchiveManifest& manifest,
Yifan Hongf033ecb2020-01-07 18:13:56 -0800417 bool update,
418 uint64_t* required_size) {
Yifan Hong6eec9952019-12-04 13:12:01 -0800419 source_slot_ = source_slot;
420 target_slot_ = target_slot;
Yifan Hongf033ecb2020-01-07 18:13:56 -0800421 if (required_size != nullptr) {
422 *required_size = 0;
423 }
Yifan Hong6eec9952019-12-04 13:12:01 -0800424
Yifan Hong3a1a5612019-11-05 16:34:32 -0800425 if (fs_mgr_overlayfs_is_setup()) {
426 // Non DAP devices can use overlayfs as well.
427 LOG(WARNING)
428 << "overlayfs overrides are active and can interfere with our "
429 "resources.\n"
430 << "run adb enable-verity to deactivate if required and try again.";
431 }
432
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700433 // If metadata is erased but not formatted, it is possible to not mount
434 // it in recovery. It is acceptable to skip mounting and choose fallback path
435 // (PrepareDynamicPartitionsForUpdate) when sideloading full OTAs.
436 TEST_AND_RETURN_FALSE(EnsureMetadataMounted() || IsRecovery());
Yifan Hong29692902020-03-26 12:47:05 -0700437
438 if (update) {
439 TEST_AND_RETURN_FALSE(EraseSystemOtherAvbFooter(source_slot, target_slot));
440 }
441
Yifan Hong3a1a5612019-11-05 16:34:32 -0800442 if (!GetDynamicPartitionsFeatureFlag().IsEnabled()) {
443 return true;
444 }
445
446 if (target_slot == source_slot) {
447 LOG(ERROR) << "Cannot call PreparePartitionsForUpdate on current slot.";
448 return false;
449 }
450
Yifan Hongf6f75c22020-07-31 15:20:25 -0700451 if (!SetTargetBuildVars(manifest)) {
452 return false;
453 }
454
Yifan Hong3a1a5612019-11-05 16:34:32 -0800455 // Although the current build supports dynamic partitions, the given payload
456 // doesn't use it for target partitions. This could happen when applying a
457 // retrofit update. Skip updating the partition metadata for the target slot.
Yifan Hong3a1a5612019-11-05 16:34:32 -0800458 if (!is_target_dynamic_) {
459 return true;
460 }
461
Yifan Hongf0f4a912019-09-26 17:51:33 -0700462 if (!update)
463 return true;
464
Yifan Hongbae27842019-10-24 16:56:12 -0700465 bool delete_source = false;
466
Yifan Hong6d888562019-10-01 13:00:31 -0700467 if (GetVirtualAbFeatureFlag().IsEnabled()) {
468 // On Virtual A/B device, either CancelUpdate() or BeginUpdate() must be
469 // called before calling UnmapUpdateSnapshot.
470 // - If target_supports_snapshot_, PrepareSnapshotPartitionsForUpdate()
471 // calls BeginUpdate() which resets update state
Yifan Hongbae27842019-10-24 16:56:12 -0700472 // - If !target_supports_snapshot_ or PrepareSnapshotPartitionsForUpdate
473 // failed in recovery, explicitly CancelUpdate().
Yifan Hong6d888562019-10-01 13:00:31 -0700474 if (target_supports_snapshot_) {
Yifan Hongbae27842019-10-24 16:56:12 -0700475 if (PrepareSnapshotPartitionsForUpdate(
476 source_slot, target_slot, manifest, required_size)) {
477 return true;
478 }
479
480 // Virtual A/B device doing Virtual A/B update in Android mode must use
481 // snapshots.
482 if (!IsRecovery()) {
483 LOG(ERROR) << "PrepareSnapshotPartitionsForUpdate failed in Android "
484 << "mode";
485 return false;
486 }
487
488 delete_source = true;
489 LOG(INFO) << "PrepareSnapshotPartitionsForUpdate failed in recovery. "
490 << "Attempt to overwrite existing partitions if possible";
491 } else {
492 // Downgrading to an non-Virtual A/B build or is secondary OTA.
493 LOG(INFO) << "Using regular A/B on Virtual A/B because package disabled "
494 << "snapshots.";
Yifan Hong6d888562019-10-01 13:00:31 -0700495 }
Yifan Hongbae27842019-10-24 16:56:12 -0700496
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700497 // In recovery, if /metadata is not mounted, it is likely that metadata
498 // partition is erased and not formatted yet. After sideloading, when
499 // rebooting into the new version, init will erase metadata partition,
500 // hence the failure of CancelUpdate() can be ignored here.
501 // However, if metadata is mounted and CancelUpdate fails, sideloading
502 // should not proceed because during next boot, snapshots will overlay on
503 // the devices incorrectly.
504 if (ExpectMetadataMounted()) {
505 TEST_AND_RETURN_FALSE(snapshot_->CancelUpdate());
506 } else {
507 LOG(INFO) << "Skip canceling previous update because metadata is not "
508 << "mounted";
Yifan Hong6d888562019-10-01 13:00:31 -0700509 }
Yifan Hong420db9b2019-07-23 20:50:33 -0700510 }
Yifan Hongbae27842019-10-24 16:56:12 -0700511
Tianjie24f96092020-06-30 12:26:25 -0700512 // TODO(xunchang) support partial update on non VAB enabled devices.
Yifan Hong5c5743f2020-04-16 12:59:07 -0700513 TEST_AND_RETURN_FALSE(PrepareDynamicPartitionsForUpdate(
514 source_slot, target_slot, manifest, delete_source));
515
516 if (required_size != nullptr) {
517 *required_size = 0;
518 }
519 return true;
Yifan Hong420db9b2019-07-23 20:50:33 -0700520}
521
Yifan Hongf6f75c22020-07-31 15:20:25 -0700522bool DynamicPartitionControlAndroid::SetTargetBuildVars(
523 const DeltaArchiveManifest& manifest) {
524 // Precondition: current build supports dynamic partition.
525 CHECK(GetDynamicPartitionsFeatureFlag().IsEnabled());
526
527 bool is_target_dynamic =
528 !manifest.dynamic_partition_metadata().groups().empty();
529 bool target_supports_snapshot =
530 manifest.dynamic_partition_metadata().snapshot_enabled();
531
532 if (manifest.partial_update()) {
533 // Partial updates requires DAP. On partial updates that does not involve
534 // dynamic partitions, groups() can be empty, so also assume
535 // is_target_dynamic in this case. This assumption should be safe because we
536 // also check target_supports_snapshot below, which presumably also implies
537 // target build supports dynamic partition.
538 if (!is_target_dynamic) {
539 LOG(INFO) << "Assuming target build supports dynamic partitions for "
540 "partial updates.";
541 is_target_dynamic = true;
542 }
543
544 // Partial updates requires Virtual A/B. Double check that both current
545 // build and target build supports Virtual A/B.
546 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
547 LOG(ERROR) << "Partial update cannot be applied on a device that does "
548 "not support snapshots.";
549 return false;
550 }
551 if (!target_supports_snapshot) {
552 LOG(ERROR) << "Cannot apply partial update to a build that does not "
553 "support snapshots.";
554 return false;
555 }
556 }
557
558 // Store the flags.
559 is_target_dynamic_ = is_target_dynamic;
560 // If !is_target_dynamic_, leave target_supports_snapshot_ unset because
561 // snapshots would not work without dynamic partition.
562 if (is_target_dynamic_) {
563 target_supports_snapshot_ = target_supports_snapshot;
564 }
565 return true;
566}
567
Yifan Hong29692902020-03-26 12:47:05 -0700568namespace {
569// Try our best to erase AVB footer.
570class AvbFooterEraser {
571 public:
572 explicit AvbFooterEraser(const std::string& path) : path_(path) {}
573 bool Erase() {
574 // Try to mark the block device read-only. Ignore any
575 // failure since this won't work when passing regular files.
576 ignore_result(utils::SetBlockDeviceReadOnly(path_, false /* readonly */));
577
578 fd_.reset(new EintrSafeFileDescriptor());
579 int flags = O_WRONLY | O_TRUNC | O_CLOEXEC | O_SYNC;
580 TEST_AND_RETURN_FALSE(fd_->Open(path_.c_str(), flags));
581
582 // Need to write end-AVB_FOOTER_SIZE to end.
583 static_assert(AVB_FOOTER_SIZE > 0);
584 off64_t offset = fd_->Seek(-AVB_FOOTER_SIZE, SEEK_END);
585 TEST_AND_RETURN_FALSE_ERRNO(offset >= 0);
586 uint64_t write_size = AVB_FOOTER_SIZE;
587 LOG(INFO) << "Zeroing " << path_ << " @ [" << offset << ", "
588 << (offset + write_size) << "] (" << write_size << " bytes)";
589 brillo::Blob zeros(write_size);
590 TEST_AND_RETURN_FALSE(utils::WriteAll(fd_, zeros.data(), zeros.size()));
591 return true;
592 }
593 ~AvbFooterEraser() {
594 TEST_AND_RETURN(fd_ != nullptr && fd_->IsOpen());
595 if (!fd_->Close()) {
596 LOG(WARNING) << "Failed to close fd for " << path_;
597 }
598 }
599
600 private:
601 std::string path_;
602 FileDescriptorPtr fd_;
603};
604
605} // namespace
606
607std::optional<bool>
608DynamicPartitionControlAndroid::IsAvbEnabledOnSystemOther() {
609 auto prefix = GetProperty(kPostinstallFstabPrefix, "");
610 if (prefix.empty()) {
611 LOG(WARNING) << "Cannot get " << kPostinstallFstabPrefix;
612 return std::nullopt;
613 }
614 auto path = base::FilePath(prefix).Append("etc/fstab.postinstall").value();
615 return IsAvbEnabledInFstab(path);
616}
617
618std::optional<bool> DynamicPartitionControlAndroid::IsAvbEnabledInFstab(
619 const std::string& path) {
620 Fstab fstab;
621 if (!ReadFstabFromFile(path, &fstab)) {
Yifan Hong93cde302020-04-27 12:59:29 -0700622 PLOG(WARNING) << "Cannot read fstab from " << path;
623 if (errno == ENOENT) {
624 return false;
625 }
Yifan Hong29692902020-03-26 12:47:05 -0700626 return std::nullopt;
627 }
628 for (const auto& entry : fstab) {
629 if (!entry.avb_keys.empty()) {
630 return true;
631 }
632 }
633 return false;
634}
635
636bool DynamicPartitionControlAndroid::GetSystemOtherPath(
637 uint32_t source_slot,
638 uint32_t target_slot,
639 const std::string& partition_name_suffix,
640 std::string* path,
641 bool* should_unmap) {
642 path->clear();
643 *should_unmap = false;
644
P.Adarsh Reddy13e4195d2020-06-08 23:17:36 +0530645 // Check that AVB is enabled on system_other before erasing.
646 auto has_avb = IsAvbEnabledOnSystemOther();
647 TEST_AND_RETURN_FALSE(has_avb.has_value());
648 if (!has_avb.value()) {
649 LOG(INFO) << "AVB is not enabled on system_other. Skip erasing.";
650 return true;
651 }
Yifan Hong29692902020-03-26 12:47:05 -0700652
P.Adarsh Reddy13e4195d2020-06-08 23:17:36 +0530653 if (!IsRecovery()) {
Yifan Hong29692902020-03-26 12:47:05 -0700654 // Found unexpected avb_keys for system_other on devices retrofitting
655 // dynamic partitions. Previous crash in update_engine may leave logical
656 // partitions mapped on physical system_other partition. It is difficult to
657 // handle these cases. Just fail.
658 if (GetDynamicPartitionsFeatureFlag().IsRetrofit()) {
659 LOG(ERROR) << "Cannot erase AVB footer on system_other on devices with "
660 << "retrofit dynamic partitions. They should not have AVB "
661 << "enabled on system_other.";
662 return false;
663 }
664 }
665
666 std::string device_dir_str;
667 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
668 base::FilePath device_dir(device_dir_str);
669
670 // On devices without dynamic partition, search for static partitions.
671 if (!GetDynamicPartitionsFeatureFlag().IsEnabled()) {
672 *path = device_dir.Append(partition_name_suffix).value();
673 TEST_AND_RETURN_FALSE(DeviceExists(*path));
674 return true;
675 }
676
677 auto source_super_device =
678 device_dir.Append(GetSuperPartitionName(source_slot)).value();
679
680 auto builder = LoadMetadataBuilder(source_super_device, source_slot);
681 if (builder == nullptr) {
682 if (IsRecovery()) {
683 // It might be corrupted for some reason. It should still be able to
684 // sideload.
685 LOG(WARNING) << "Super partition metadata cannot be read from the source "
686 << "slot, skip erasing.";
687 return true;
688 } else {
689 // Device has booted into Android mode, indicating that the super
690 // partition metadata should be there.
691 LOG(ERROR) << "Super partition metadata cannot be read from the source "
692 << "slot. This is unexpected on devices with dynamic "
693 << "partitions enabled.";
694 return false;
695 }
696 }
697 auto p = builder->FindPartition(partition_name_suffix);
698 if (p == nullptr) {
699 // If the source slot is flashed without system_other, it does not exist
700 // in super partition metadata at source slot. It is safe to skip it.
701 LOG(INFO) << "Can't find " << partition_name_suffix
702 << " in metadata source slot, skip erasing.";
703 return true;
704 }
705 // System_other created by flashing tools should be erased.
706 // If partition is created by update_engine (via NewForUpdate), it is a
707 // left-over partition from the previous update and does not contain
708 // system_other, hence there is no need to erase.
709 // Note the reverse is not necessary true. If the flag is not set, we don't
710 // know if the partition is created by update_engine or by flashing tools
711 // because older versions of super partition metadata does not contain this
712 // flag. It is okay to erase the AVB footer anyways.
713 if (p->attributes() & LP_PARTITION_ATTR_UPDATED) {
714 LOG(INFO) << partition_name_suffix
715 << " does not contain system_other, skip erasing.";
716 return true;
717 }
718
Yifan Hong64331b32020-05-13 16:50:40 -0700719 if (p->size() < AVB_FOOTER_SIZE) {
720 LOG(INFO) << partition_name_suffix << " has length " << p->size()
721 << "( < AVB_FOOTER_SIZE " << AVB_FOOTER_SIZE
722 << "), skip erasing.";
723 return true;
724 }
725
Yifan Hong29692902020-03-26 12:47:05 -0700726 // Delete any pre-existing device with name |partition_name_suffix| and
727 // also remove it from |mapped_devices_|.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700728 // In recovery, metadata might not be mounted, and
729 // UnmapPartitionOnDeviceMapper might fail. However,
730 // it is unusual that system_other has already been mapped. Hence, just skip.
Yifan Hong29692902020-03-26 12:47:05 -0700731 TEST_AND_RETURN_FALSE(UnmapPartitionOnDeviceMapper(partition_name_suffix));
732 // Use CreateLogicalPartition directly to avoid mapping with existing
733 // snapshots.
734 CreateLogicalPartitionParams params = {
735 .block_device = source_super_device,
736 .metadata_slot = source_slot,
737 .partition_name = partition_name_suffix,
738 .force_writable = true,
739 .timeout_ms = kMapTimeout,
740 };
741 TEST_AND_RETURN_FALSE(CreateLogicalPartition(params, path));
742 *should_unmap = true;
743 return true;
744}
745
746bool DynamicPartitionControlAndroid::EraseSystemOtherAvbFooter(
747 uint32_t source_slot, uint32_t target_slot) {
748 LOG(INFO) << "Erasing AVB footer of system_other partition before update.";
749
750 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
751 const std::string partition_name_suffix = "system" + target_suffix;
752
753 std::string path;
754 bool should_unmap = false;
755
756 TEST_AND_RETURN_FALSE(GetSystemOtherPath(
757 source_slot, target_slot, partition_name_suffix, &path, &should_unmap));
758
759 if (path.empty()) {
760 return true;
761 }
762
763 bool ret = AvbFooterEraser(path).Erase();
764
765 // Delete |partition_name_suffix| from device mapper and from
766 // |mapped_devices_| again so that it does not interfere with update process.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700767 // In recovery, metadata might not be mounted, and
768 // UnmapPartitionOnDeviceMapper might fail. However, DestroyLogicalPartition
769 // should be called. If DestroyLogicalPartition does fail, it is still okay
770 // to skip the error here and let Prepare*() fail later.
Yifan Hong29692902020-03-26 12:47:05 -0700771 if (should_unmap) {
772 TEST_AND_RETURN_FALSE(UnmapPartitionOnDeviceMapper(partition_name_suffix));
773 }
774
775 return ret;
776}
777
Yifan Hong420db9b2019-07-23 20:50:33 -0700778bool DynamicPartitionControlAndroid::PrepareDynamicPartitionsForUpdate(
779 uint32_t source_slot,
780 uint32_t target_slot,
Yifan Hongbae27842019-10-24 16:56:12 -0700781 const DeltaArchiveManifest& manifest,
782 bool delete_source) {
Yifan Hong012508e2019-07-22 18:30:40 -0700783 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
784
785 // Unmap all the target dynamic partitions because they would become
786 // inconsistent with the new metadata.
Yifan Hong13d41cb2019-09-16 13:18:22 -0700787 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
788 for (const auto& partition_name : group.partition_names()) {
789 if (!UnmapPartitionOnDeviceMapper(partition_name + target_suffix)) {
Yifan Hong012508e2019-07-22 18:30:40 -0700790 return false;
791 }
792 }
793 }
794
795 std::string device_dir_str;
796 if (!GetDeviceDir(&device_dir_str)) {
797 return false;
798 }
799 base::FilePath device_dir(device_dir_str);
800 auto source_device =
Yifan Hong700d7c12019-07-23 20:49:16 -0700801 device_dir.Append(GetSuperPartitionName(source_slot)).value();
Yifan Hong012508e2019-07-22 18:30:40 -0700802
803 auto builder = LoadMetadataBuilder(source_device, source_slot, target_slot);
804 if (builder == nullptr) {
805 LOG(ERROR) << "No metadata at "
806 << BootControlInterface::SlotName(source_slot);
807 return false;
808 }
809
Yifan Hongbae27842019-10-24 16:56:12 -0700810 if (delete_source) {
811 TEST_AND_RETURN_FALSE(
812 DeleteSourcePartitions(builder.get(), source_slot, manifest));
813 }
814
Yifan Hong13d41cb2019-09-16 13:18:22 -0700815 if (!UpdatePartitionMetadata(builder.get(), target_slot, manifest)) {
Yifan Hong012508e2019-07-22 18:30:40 -0700816 return false;
817 }
818
819 auto target_device =
Yifan Hong700d7c12019-07-23 20:49:16 -0700820 device_dir.Append(GetSuperPartitionName(target_slot)).value();
Yifan Hong012508e2019-07-22 18:30:40 -0700821 return StoreMetadata(target_device, builder.get(), target_slot);
822}
823
Yifan Hong420db9b2019-07-23 20:50:33 -0700824bool DynamicPartitionControlAndroid::PrepareSnapshotPartitionsForUpdate(
825 uint32_t source_slot,
826 uint32_t target_slot,
Yifan Hongf033ecb2020-01-07 18:13:56 -0800827 const DeltaArchiveManifest& manifest,
828 uint64_t* required_size) {
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700829 TEST_AND_RETURN_FALSE(ExpectMetadataMounted());
Yifan Hong420db9b2019-07-23 20:50:33 -0700830 if (!snapshot_->BeginUpdate()) {
831 LOG(ERROR) << "Cannot begin new update.";
832 return false;
833 }
Yifan Hongf033ecb2020-01-07 18:13:56 -0800834 auto ret = snapshot_->CreateUpdateSnapshots(manifest);
835 if (!ret) {
836 LOG(ERROR) << "Cannot create update snapshots: " << ret.string();
837 if (required_size != nullptr &&
Yifan Hong0850bca2020-01-16 15:14:07 -0800838 ret.error_code() == Return::ErrorCode::NO_SPACE) {
Yifan Hongf033ecb2020-01-07 18:13:56 -0800839 *required_size = ret.required_size();
840 }
Yifan Hong420db9b2019-07-23 20:50:33 -0700841 return false;
842 }
843 return true;
844}
845
Yifan Hong700d7c12019-07-23 20:49:16 -0700846std::string DynamicPartitionControlAndroid::GetSuperPartitionName(
847 uint32_t slot) {
848 return fs_mgr_get_super_partition_name(slot);
849}
850
Yifan Hong012508e2019-07-22 18:30:40 -0700851bool DynamicPartitionControlAndroid::UpdatePartitionMetadata(
852 MetadataBuilder* builder,
853 uint32_t target_slot,
Yifan Hong13d41cb2019-09-16 13:18:22 -0700854 const DeltaArchiveManifest& manifest) {
Yifan Hong8d6df9a2020-08-13 13:59:54 -0700855 // Check preconditions.
856 CHECK(!GetVirtualAbFeatureFlag().IsEnabled() || IsRecovery())
857 << "UpdatePartitionMetadata is called on a Virtual A/B device "
858 "but source partitions is not deleted. This is not allowed.";
859
Yifan Honga4e7da32019-09-30 18:25:03 -0700860 // If applying downgrade from Virtual A/B to non-Virtual A/B, the left-over
861 // COW group needs to be deleted to ensure there are enough space to create
862 // target partitions.
863 builder->RemoveGroupAndPartitions(android::snapshot::kCowGroupName);
864
Yifan Hong012508e2019-07-22 18:30:40 -0700865 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
866 DeleteGroupsWithSuffix(builder, target_suffix);
867
868 uint64_t total_size = 0;
Yifan Hong13d41cb2019-09-16 13:18:22 -0700869 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
870 total_size += group.size();
Yifan Hong012508e2019-07-22 18:30:40 -0700871 }
872
873 std::string expr;
874 uint64_t allocatable_space = builder->AllocatableSpace();
Yifan Hong8d6df9a2020-08-13 13:59:54 -0700875 // On device retrofitting dynamic partitions, allocatable_space = super.
876 // On device launching dynamic partitions w/o VAB,
877 // allocatable_space = super / 2.
878 // On device launching dynamic partitions with VAB, allocatable_space = super.
879 if (!GetDynamicPartitionsFeatureFlag().IsRetrofit() &&
880 !GetVirtualAbFeatureFlag().IsEnabled()) {
Yifan Hong012508e2019-07-22 18:30:40 -0700881 allocatable_space /= 2;
882 expr = "half of ";
883 }
884 if (total_size > allocatable_space) {
885 LOG(ERROR) << "The maximum size of all groups with suffix " << target_suffix
886 << " (" << total_size << ") has exceeded " << expr
887 << "allocatable space for dynamic partitions "
888 << allocatable_space << ".";
889 return false;
890 }
891
Yifan Hong13d41cb2019-09-16 13:18:22 -0700892 // name of partition(e.g. "system") -> size in bytes
893 std::map<std::string, uint64_t> partition_sizes;
894 for (const auto& partition : manifest.partitions()) {
895 partition_sizes.emplace(partition.partition_name(),
896 partition.new_partition_info().size());
897 }
898
899 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
900 auto group_name_suffix = group.name() + target_suffix;
901 if (!builder->AddGroup(group_name_suffix, group.size())) {
Yifan Hong012508e2019-07-22 18:30:40 -0700902 LOG(ERROR) << "Cannot add group " << group_name_suffix << " with size "
Yifan Hong13d41cb2019-09-16 13:18:22 -0700903 << group.size();
Yifan Hong012508e2019-07-22 18:30:40 -0700904 return false;
905 }
906 LOG(INFO) << "Added group " << group_name_suffix << " with size "
Yifan Hong13d41cb2019-09-16 13:18:22 -0700907 << group.size();
Yifan Hong012508e2019-07-22 18:30:40 -0700908
Yifan Hong13d41cb2019-09-16 13:18:22 -0700909 for (const auto& partition_name : group.partition_names()) {
910 auto partition_sizes_it = partition_sizes.find(partition_name);
911 if (partition_sizes_it == partition_sizes.end()) {
912 // TODO(tbao): Support auto-filling partition info for framework-only
913 // OTA.
914 LOG(ERROR) << "dynamic_partition_metadata contains partition "
915 << partition_name << " but it is not part of the manifest. "
916 << "This is not supported.";
917 return false;
918 }
919 uint64_t partition_size = partition_sizes_it->second;
920
921 auto partition_name_suffix = partition_name + target_suffix;
Yifan Hong012508e2019-07-22 18:30:40 -0700922 Partition* p = builder->AddPartition(
923 partition_name_suffix, group_name_suffix, LP_PARTITION_ATTR_READONLY);
924 if (!p) {
925 LOG(ERROR) << "Cannot add partition " << partition_name_suffix
926 << " to group " << group_name_suffix;
927 return false;
928 }
Yifan Hong13d41cb2019-09-16 13:18:22 -0700929 if (!builder->ResizePartition(p, partition_size)) {
Yifan Hong012508e2019-07-22 18:30:40 -0700930 LOG(ERROR) << "Cannot resize partition " << partition_name_suffix
Yifan Hong13d41cb2019-09-16 13:18:22 -0700931 << " to size " << partition_size << ". Not enough space?";
Yifan Hong012508e2019-07-22 18:30:40 -0700932 return false;
933 }
934 LOG(INFO) << "Added partition " << partition_name_suffix << " to group "
Yifan Hong13d41cb2019-09-16 13:18:22 -0700935 << group_name_suffix << " with size " << partition_size;
Yifan Hong012508e2019-07-22 18:30:40 -0700936 }
937 }
938
939 return true;
940}
941
Yifan Hong7b3910a2020-03-24 17:47:32 -0700942bool DynamicPartitionControlAndroid::FinishUpdate(bool powerwash_required) {
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700943 if (ExpectMetadataMounted()) {
944 if (snapshot_->GetUpdateState() == UpdateState::Initiated) {
945 LOG(INFO) << "Snapshot writes are done.";
946 return snapshot_->FinishedSnapshotWrites(powerwash_required);
947 }
948 } else {
949 LOG(INFO) << "Skip FinishedSnapshotWrites() because /metadata is not "
950 << "mounted";
Yifan Hongf0f4a912019-09-26 17:51:33 -0700951 }
952 return true;
Yifan Honga33bca42019-09-03 20:29:45 -0700953}
954
Yifan Hong3a1a5612019-11-05 16:34:32 -0800955bool DynamicPartitionControlAndroid::GetPartitionDevice(
956 const std::string& partition_name,
957 uint32_t slot,
958 uint32_t current_slot,
Tianjie51a5a392020-06-03 14:39:32 -0700959 bool not_in_payload,
960 std::string* device,
961 bool* is_dynamic) {
Yifan Hong3a1a5612019-11-05 16:34:32 -0800962 const auto& partition_name_suffix =
963 partition_name + SlotSuffixForSlotNumber(slot);
964 std::string device_dir_str;
965 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
966 base::FilePath device_dir(device_dir_str);
967
Tianjie51a5a392020-06-03 14:39:32 -0700968 if (is_dynamic) {
969 *is_dynamic = false;
970 }
971
Yifan Hong3a1a5612019-11-05 16:34:32 -0800972 // When looking up target partition devices, treat them as static if the
973 // current payload doesn't encode them as dynamic partitions. This may happen
974 // when applying a retrofit update on top of a dynamic-partitions-enabled
975 // build.
976 if (GetDynamicPartitionsFeatureFlag().IsEnabled() &&
977 (slot == current_slot || is_target_dynamic_)) {
Tianjie51a5a392020-06-03 14:39:32 -0700978 switch (GetDynamicPartitionDevice(device_dir,
979 partition_name_suffix,
980 slot,
981 current_slot,
982 not_in_payload,
983 device)) {
Yifan Hong3a1a5612019-11-05 16:34:32 -0800984 case DynamicPartitionDeviceStatus::SUCCESS:
Tianjie51a5a392020-06-03 14:39:32 -0700985 if (is_dynamic) {
986 *is_dynamic = true;
987 }
Yifan Hong3a1a5612019-11-05 16:34:32 -0800988 return true;
989 case DynamicPartitionDeviceStatus::TRY_STATIC:
990 break;
991 case DynamicPartitionDeviceStatus::ERROR: // fallthrough
992 default:
993 return false;
994 }
995 }
996 base::FilePath path = device_dir.Append(partition_name_suffix);
997 if (!DeviceExists(path.value())) {
998 LOG(ERROR) << "Device file " << path.value() << " does not exist.";
999 return false;
1000 }
1001
1002 *device = path.value();
1003 return true;
1004}
1005
Tianjie51a5a392020-06-03 14:39:32 -07001006bool DynamicPartitionControlAndroid::GetPartitionDevice(
1007 const std::string& partition_name,
1008 uint32_t slot,
1009 uint32_t current_slot,
1010 std::string* device) {
1011 return GetPartitionDevice(
1012 partition_name, slot, current_slot, false, device, nullptr);
1013}
1014
Yifan Hong3a1a5612019-11-05 16:34:32 -08001015bool DynamicPartitionControlAndroid::IsSuperBlockDevice(
1016 const base::FilePath& device_dir,
1017 uint32_t current_slot,
1018 const std::string& partition_name_suffix) {
1019 std::string source_device =
1020 device_dir.Append(GetSuperPartitionName(current_slot)).value();
1021 auto source_metadata = LoadMetadataBuilder(source_device, current_slot);
1022 return source_metadata->HasBlockDevice(partition_name_suffix);
1023}
1024
1025DynamicPartitionControlAndroid::DynamicPartitionDeviceStatus
1026DynamicPartitionControlAndroid::GetDynamicPartitionDevice(
1027 const base::FilePath& device_dir,
1028 const std::string& partition_name_suffix,
1029 uint32_t slot,
1030 uint32_t current_slot,
Tianjie51a5a392020-06-03 14:39:32 -07001031 bool not_in_payload,
Yifan Hong3a1a5612019-11-05 16:34:32 -08001032 std::string* device) {
1033 std::string super_device =
1034 device_dir.Append(GetSuperPartitionName(slot)).value();
1035
1036 auto builder = LoadMetadataBuilder(super_device, slot);
1037 if (builder == nullptr) {
1038 LOG(ERROR) << "No metadata in slot "
1039 << BootControlInterface::SlotName(slot);
1040 return DynamicPartitionDeviceStatus::ERROR;
1041 }
1042 if (builder->FindPartition(partition_name_suffix) == nullptr) {
1043 LOG(INFO) << partition_name_suffix
1044 << " is not in super partition metadata.";
1045
1046 if (IsSuperBlockDevice(device_dir, current_slot, partition_name_suffix)) {
1047 LOG(ERROR) << "The static partition " << partition_name_suffix
1048 << " is a block device for current metadata."
1049 << "It cannot be used as a logical partition.";
1050 return DynamicPartitionDeviceStatus::ERROR;
1051 }
1052
1053 return DynamicPartitionDeviceStatus::TRY_STATIC;
1054 }
1055
1056 if (slot == current_slot) {
1057 if (GetState(partition_name_suffix) != DmDeviceState::ACTIVE) {
1058 LOG(WARNING) << partition_name_suffix << " is at current slot but it is "
1059 << "not mapped. Now try to map it.";
1060 } else {
1061 if (GetDmDevicePathByName(partition_name_suffix, device)) {
1062 LOG(INFO) << partition_name_suffix
1063 << " is mapped on device mapper: " << *device;
1064 return DynamicPartitionDeviceStatus::SUCCESS;
1065 }
1066 LOG(ERROR) << partition_name_suffix << "is mapped but path is unknown.";
1067 return DynamicPartitionDeviceStatus::ERROR;
1068 }
1069 }
1070
Tianjie51a5a392020-06-03 14:39:32 -07001071 bool force_writable = (slot != current_slot) && !not_in_payload;
Yifan Hong3a1a5612019-11-05 16:34:32 -08001072 if (MapPartitionOnDeviceMapper(
1073 super_device, partition_name_suffix, slot, force_writable, device)) {
1074 return DynamicPartitionDeviceStatus::SUCCESS;
1075 }
1076 return DynamicPartitionDeviceStatus::ERROR;
1077}
1078
Yifan Hong6eec9952019-12-04 13:12:01 -08001079void DynamicPartitionControlAndroid::set_fake_mapped_devices(
1080 const std::set<std::string>& fake) {
1081 mapped_devices_ = fake;
1082}
1083
Yifan Hongbae27842019-10-24 16:56:12 -07001084bool DynamicPartitionControlAndroid::IsRecovery() {
Kelvin Zhanga22ef552020-10-12 19:03:52 -04001085 return constants::kIsRecovery;
Yifan Hongbae27842019-10-24 16:56:12 -07001086}
1087
1088static bool IsIncrementalUpdate(const DeltaArchiveManifest& manifest) {
1089 const auto& partitions = manifest.partitions();
1090 return std::any_of(partitions.begin(), partitions.end(), [](const auto& p) {
1091 return p.has_old_partition_info();
1092 });
1093}
1094
1095bool DynamicPartitionControlAndroid::DeleteSourcePartitions(
1096 MetadataBuilder* builder,
1097 uint32_t source_slot,
1098 const DeltaArchiveManifest& manifest) {
1099 TEST_AND_RETURN_FALSE(IsRecovery());
1100
1101 if (IsIncrementalUpdate(manifest)) {
1102 LOG(ERROR) << "Cannot sideload incremental OTA because snapshots cannot "
1103 << "be created.";
1104 if (GetVirtualAbFeatureFlag().IsLaunch()) {
1105 LOG(ERROR) << "Sideloading incremental updates on devices launches "
1106 << " Virtual A/B is not supported.";
1107 }
1108 return false;
1109 }
1110
1111 LOG(INFO) << "Will overwrite existing partitions. Slot "
1112 << BootControlInterface::SlotName(source_slot)
1113 << "may be unbootable until update finishes!";
1114 const std::string source_suffix = SlotSuffixForSlotNumber(source_slot);
1115 DeleteGroupsWithSuffix(builder, source_suffix);
1116
1117 return true;
1118}
1119
Yifan Hong90965502020-02-19 15:22:47 -08001120std::unique_ptr<AbstractAction>
1121DynamicPartitionControlAndroid::GetCleanupPreviousUpdateAction(
1122 BootControlInterface* boot_control,
1123 PrefsInterface* prefs,
1124 CleanupPreviousUpdateActionDelegateInterface* delegate) {
1125 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1126 return std::make_unique<NoOpAction>();
1127 }
1128 return std::make_unique<CleanupPreviousUpdateAction>(
1129 prefs, boot_control, snapshot_.get(), delegate);
1130}
1131
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001132bool DynamicPartitionControlAndroid::ResetUpdate(PrefsInterface* prefs) {
1133 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1134 return true;
1135 }
1136
1137 LOG(INFO) << __func__ << " resetting update state and deleting snapshots.";
1138 TEST_AND_RETURN_FALSE(prefs != nullptr);
1139
1140 // If the device has already booted into the target slot,
1141 // ResetUpdateProgress may pass but CancelUpdate fails.
1142 // This is expected. A scheduled CleanupPreviousUpdateAction should free
1143 // space when it is done.
1144 TEST_AND_RETURN_FALSE(DeltaPerformer::ResetUpdateProgress(
1145 prefs, false /* quick */, false /* skip dynamic partitions metadata */));
1146
Yifan Hong4d7c5eb2020-04-03 11:31:50 -07001147 if (ExpectMetadataMounted()) {
1148 TEST_AND_RETURN_FALSE(snapshot_->CancelUpdate());
1149 } else {
1150 LOG(INFO) << "Skip cancelling update in ResetUpdate because /metadata is "
1151 << "not mounted";
1152 }
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001153
1154 return true;
1155}
1156
Tianjie99d570d2020-06-04 14:57:19 -07001157bool DynamicPartitionControlAndroid::ListDynamicPartitionsForSlot(
1158 uint32_t current_slot, std::vector<std::string>* partitions) {
1159 if (!GetDynamicPartitionsFeatureFlag().IsEnabled()) {
1160 LOG(ERROR) << "Dynamic partition is not enabled";
1161 return false;
1162 }
1163
1164 std::string device_dir_str;
1165 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
1166 base::FilePath device_dir(device_dir_str);
1167 auto super_device =
1168 device_dir.Append(GetSuperPartitionName(current_slot)).value();
1169 auto builder = LoadMetadataBuilder(super_device, current_slot);
1170 TEST_AND_RETURN_FALSE(builder != nullptr);
1171
1172 std::vector<std::string> result;
1173 auto suffix = SlotSuffixForSlotNumber(current_slot);
1174 for (const auto& group : builder->ListGroups()) {
1175 for (const auto& partition : builder->ListPartitionsInGroup(group)) {
1176 std::string_view partition_name = partition->name();
1177 if (!android::base::ConsumeSuffix(&partition_name, suffix)) {
1178 continue;
1179 }
1180 result.emplace_back(partition_name);
1181 }
1182 }
1183 *partitions = std::move(result);
1184 return true;
1185}
1186
Tianjie24f96092020-06-30 12:26:25 -07001187bool DynamicPartitionControlAndroid::VerifyExtentsForUntouchedPartitions(
1188 uint32_t source_slot,
1189 uint32_t target_slot,
1190 const std::vector<std::string>& partitions) {
1191 std::string device_dir_str;
1192 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
1193 base::FilePath device_dir(device_dir_str);
1194
1195 auto source_super_device =
1196 device_dir.Append(GetSuperPartitionName(source_slot)).value();
1197 auto source_builder = LoadMetadataBuilder(source_super_device, source_slot);
1198 TEST_AND_RETURN_FALSE(source_builder != nullptr);
1199
1200 auto target_super_device =
1201 device_dir.Append(GetSuperPartitionName(target_slot)).value();
1202 auto target_builder = LoadMetadataBuilder(target_super_device, target_slot);
1203 TEST_AND_RETURN_FALSE(target_builder != nullptr);
1204
1205 return MetadataBuilder::VerifyExtentsAgainstSourceMetadata(
1206 *source_builder, source_slot, *target_builder, target_slot, partitions);
1207}
1208
Yifan Hong4d7c5eb2020-04-03 11:31:50 -07001209bool DynamicPartitionControlAndroid::ExpectMetadataMounted() {
1210 // No need to mount metadata for non-Virtual A/B devices.
1211 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1212 return false;
1213 }
1214 // Intentionally not checking |metadata_device_| in Android mode.
1215 // /metadata should always be mounted in Android mode. If it isn't, let caller
1216 // fails when calling into SnapshotManager.
1217 if (!IsRecovery()) {
1218 return true;
1219 }
1220 // In recovery mode, explicitly check |metadata_device_|.
1221 return metadata_device_ != nullptr;
1222}
1223
1224bool DynamicPartitionControlAndroid::EnsureMetadataMounted() {
1225 // No need to mount metadata for non-Virtual A/B devices.
1226 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1227 return true;
1228 }
1229
1230 if (metadata_device_ == nullptr) {
1231 metadata_device_ = snapshot_->EnsureMetadataMounted();
1232 }
1233 return metadata_device_ != nullptr;
1234}
1235
Kelvin Zhang34618522020-09-28 09:21:02 -04001236std::unique_ptr<android::snapshot::ISnapshotWriter>
1237DynamicPartitionControlAndroid::OpenCowWriter(
1238 const std::string& partition_name,
1239 const std::optional<std::string>& source_path,
1240 bool is_append) {
1241 auto suffix = SlotSuffixForSlotNumber(target_slot_);
1242
1243 std::string device_dir_str;
1244 if (!GetDeviceDir(&device_dir_str)) {
1245 LOG(ERROR) << "Failed to get device dir!";
1246 return nullptr;
1247 }
1248 base::FilePath device_dir(device_dir_str);
1249 auto super_device =
1250 device_dir.Append(GetSuperPartitionName(target_slot_)).value();
1251 CreateLogicalPartitionParams params = {
1252 .block_device = super_device,
1253 .metadata_slot = target_slot_,
1254 .partition_name = partition_name + suffix,
1255 .force_writable = true,
1256 };
1257 // TODO(zhangkelvin) Open an APPEND mode CowWriter once there's an API to do
1258 // it.
1259 return snapshot_->OpenSnapshotWriter(params, std::move(source_path));
1260}
1261
Yifan Hong537802d2018-08-15 13:15:42 -07001262} // namespace chromeos_update_engine