blob: 6817c21e15f88ac884cc4705a892b503dc2eac87 [file] [log] [blame]
Yifan Hong537802d2018-08-15 13:15:42 -07001//
2// Copyright (C) 2018 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
16
17#include "update_engine/dynamic_partition_control_android.h"
18
Yifan Hong420db9b2019-07-23 20:50:33 -070019#include <chrono> // NOLINT(build/c++11) - using libsnapshot / liblp API
Yifan Hong13d41cb2019-09-16 13:18:22 -070020#include <map>
Yifan Hong537802d2018-08-15 13:15:42 -070021#include <memory>
22#include <set>
23#include <string>
Tianjie99d570d2020-06-04 14:57:19 -070024#include <string_view>
25#include <utility>
Yifan Hong012508e2019-07-22 18:30:40 -070026#include <vector>
Yifan Hong537802d2018-08-15 13:15:42 -070027
28#include <android-base/properties.h>
29#include <android-base/strings.h>
30#include <base/files/file_util.h>
31#include <base/logging.h>
Yifan Hong012508e2019-07-22 18:30:40 -070032#include <base/strings/string_util.h>
Yifan Hong537802d2018-08-15 13:15:42 -070033#include <bootloader_message/bootloader_message.h>
Yifan Hong012508e2019-07-22 18:30:40 -070034#include <fs_mgr.h>
Yifan Hong537802d2018-08-15 13:15:42 -070035#include <fs_mgr_dm_linear.h>
Yifan Hong3a1a5612019-11-05 16:34:32 -080036#include <fs_mgr_overlayfs.h>
Yifan Hong29692902020-03-26 12:47:05 -070037#include <libavb/libavb.h>
Yifan Hong3a1a5612019-11-05 16:34:32 -080038#include <libdm/dm.h>
Yifan Hong420db9b2019-07-23 20:50:33 -070039#include <libsnapshot/snapshot.h>
Yifan Hongf9cb4492020-04-15 13:00:20 -070040#include <libsnapshot/snapshot_stub.h>
Yifan Hong537802d2018-08-15 13:15:42 -070041
Yifan Hong90965502020-02-19 15:22:47 -080042#include "update_engine/cleanup_previous_update_action.h"
Yifan Hong537802d2018-08-15 13:15:42 -070043#include "update_engine/common/boot_control_interface.h"
44#include "update_engine/common/utils.h"
Yifan Hong012508e2019-07-22 18:30:40 -070045#include "update_engine/dynamic_partition_utils.h"
Yifan Hong6a6d0f12020-03-11 13:20:52 -070046#include "update_engine/payload_consumer/delta_performer.h"
Yifan Hong537802d2018-08-15 13:15:42 -070047
48using android::base::GetBoolProperty;
Yifan Hong29692902020-03-26 12:47:05 -070049using android::base::GetProperty;
Yifan Hong537802d2018-08-15 13:15:42 -070050using android::base::Join;
51using android::dm::DeviceMapper;
52using android::dm::DmDeviceState;
53using android::fs_mgr::CreateLogicalPartition;
David Andersonbb90dfb2019-08-13 14:14:56 -070054using android::fs_mgr::CreateLogicalPartitionParams;
Yifan Hong537802d2018-08-15 13:15:42 -070055using android::fs_mgr::DestroyLogicalPartition;
Yifan Hong29692902020-03-26 12:47:05 -070056using android::fs_mgr::Fstab;
Yifan Hong537802d2018-08-15 13:15:42 -070057using android::fs_mgr::MetadataBuilder;
Yifan Hong012508e2019-07-22 18:30:40 -070058using android::fs_mgr::Partition;
Yifan Hong6e706b12018-11-09 16:50:51 -080059using android::fs_mgr::PartitionOpener;
Yifan Hong012508e2019-07-22 18:30:40 -070060using android::fs_mgr::SlotSuffixForSlotNumber;
Yifan Hongf5261562020-03-10 10:28:10 -070061using android::snapshot::OptimizeSourceCopyOperation;
Yifan Hong0850bca2020-01-16 15:14:07 -080062using android::snapshot::Return;
Yifan Hongf033ecb2020-01-07 18:13:56 -080063using android::snapshot::SnapshotManager;
Yifan Hongf9cb4492020-04-15 13:00:20 -070064using android::snapshot::SnapshotManagerStub;
Yifan Hong2257ee12020-01-13 18:33:00 -080065using android::snapshot::UpdateState;
Yifan Hong537802d2018-08-15 13:15:42 -070066
67namespace chromeos_update_engine {
68
Yifan Hong6e706b12018-11-09 16:50:51 -080069constexpr char kUseDynamicPartitions[] = "ro.boot.dynamic_partitions";
70constexpr char kRetrfoitDynamicPartitions[] =
71 "ro.boot.dynamic_partitions_retrofit";
Yifan Hong413d5722019-07-23 14:21:09 -070072constexpr char kVirtualAbEnabled[] = "ro.virtual_ab.enabled";
73constexpr char kVirtualAbRetrofit[] = "ro.virtual_ab.retrofit";
Yifan Hong29692902020-03-26 12:47:05 -070074constexpr char kPostinstallFstabPrefix[] = "ro.postinstall.fstab.prefix";
Yifan Hong420db9b2019-07-23 20:50:33 -070075// Map timeout for dynamic partitions.
76constexpr std::chrono::milliseconds kMapTimeout{1000};
77// Map timeout for dynamic partitions with snapshots. Since several devices
78// needs to be mapped, this timeout is longer than |kMapTimeout|.
79constexpr std::chrono::milliseconds kMapSnapshotTimeout{5000};
80
Yifan Hongbae27842019-10-24 16:56:12 -070081#ifdef __ANDROID_RECOVERY__
82constexpr bool kIsRecovery = true;
83#else
84constexpr bool kIsRecovery = false;
85#endif
86
Yifan Hong537802d2018-08-15 13:15:42 -070087DynamicPartitionControlAndroid::~DynamicPartitionControlAndroid() {
Yifan Hongbae27842019-10-24 16:56:12 -070088 Cleanup();
Yifan Hong537802d2018-08-15 13:15:42 -070089}
90
Yifan Hong186bb682019-07-23 14:04:39 -070091static FeatureFlag GetFeatureFlag(const char* enable_prop,
92 const char* retrofit_prop) {
93 bool retrofit = GetBoolProperty(retrofit_prop, false);
94 bool enabled = GetBoolProperty(enable_prop, false);
95 if (retrofit && !enabled) {
96 LOG(ERROR) << retrofit_prop << " is true but " << enable_prop
97 << " is not. These sysprops are inconsistent. Assume that "
98 << enable_prop << " is true from now on.";
99 }
100 if (retrofit) {
101 return FeatureFlag(FeatureFlag::Value::RETROFIT);
102 }
103 if (enabled) {
104 return FeatureFlag(FeatureFlag::Value::LAUNCH);
105 }
106 return FeatureFlag(FeatureFlag::Value::NONE);
Yifan Hong537802d2018-08-15 13:15:42 -0700107}
108
Yifan Hongb38e1af2019-10-17 14:59:22 -0700109DynamicPartitionControlAndroid::DynamicPartitionControlAndroid()
110 : dynamic_partitions_(
111 GetFeatureFlag(kUseDynamicPartitions, kRetrfoitDynamicPartitions)),
112 virtual_ab_(GetFeatureFlag(kVirtualAbEnabled, kVirtualAbRetrofit)) {
113 if (GetVirtualAbFeatureFlag().IsEnabled()) {
Yifan Hongf033ecb2020-01-07 18:13:56 -0800114 snapshot_ = SnapshotManager::New();
Yifan Hongf9cb4492020-04-15 13:00:20 -0700115 } else {
116 snapshot_ = SnapshotManagerStub::New();
Yifan Hongb38e1af2019-10-17 14:59:22 -0700117 }
Yifan Hongf9cb4492020-04-15 13:00:20 -0700118 CHECK(snapshot_ != nullptr) << "Cannot initialize SnapshotManager.";
Yifan Hongb38e1af2019-10-17 14:59:22 -0700119}
120
Yifan Hong186bb682019-07-23 14:04:39 -0700121FeatureFlag DynamicPartitionControlAndroid::GetDynamicPartitionsFeatureFlag() {
Yifan Hongb38e1af2019-10-17 14:59:22 -0700122 return dynamic_partitions_;
Yifan Hong6e706b12018-11-09 16:50:51 -0800123}
124
Yifan Hong413d5722019-07-23 14:21:09 -0700125FeatureFlag DynamicPartitionControlAndroid::GetVirtualAbFeatureFlag() {
Yifan Hongb38e1af2019-10-17 14:59:22 -0700126 return virtual_ab_;
Yifan Hong413d5722019-07-23 14:21:09 -0700127}
128
Yifan Hongf5261562020-03-10 10:28:10 -0700129bool DynamicPartitionControlAndroid::OptimizeOperation(
130 const std::string& partition_name,
131 const InstallOperation& operation,
132 InstallOperation* optimized) {
Alessio Balsini2a3b4a22019-11-25 16:46:51 +0000133 switch (operation.type()) {
134 case InstallOperation::SOURCE_COPY:
135 return target_supports_snapshot_ &&
136 GetVirtualAbFeatureFlag().IsEnabled() &&
Yifan Hong6eec9952019-12-04 13:12:01 -0800137 mapped_devices_.count(partition_name +
138 SlotSuffixForSlotNumber(target_slot_)) > 0 &&
Yifan Hongf5261562020-03-10 10:28:10 -0700139 OptimizeSourceCopyOperation(operation, optimized);
Alessio Balsini2a3b4a22019-11-25 16:46:51 +0000140 break;
141 default:
142 break;
143 }
Alessio Balsini14980e22019-11-26 11:46:06 +0000144 return false;
145}
146
Yifan Hong8546a712019-03-28 14:42:53 -0700147bool DynamicPartitionControlAndroid::MapPartitionInternal(
Yifan Hong537802d2018-08-15 13:15:42 -0700148 const std::string& super_device,
149 const std::string& target_partition_name,
150 uint32_t slot,
Yifan Hongaf65ef12018-10-29 11:09:06 -0700151 bool force_writable,
Yifan Hong537802d2018-08-15 13:15:42 -0700152 std::string* path) {
David Andersonbb90dfb2019-08-13 14:14:56 -0700153 CreateLogicalPartitionParams params = {
154 .block_device = super_device,
155 .metadata_slot = slot,
156 .partition_name = target_partition_name,
157 .force_writable = force_writable,
David Andersonbb90dfb2019-08-13 14:14:56 -0700158 };
Yifan Hong420db9b2019-07-23 20:50:33 -0700159 bool success = false;
Yifan Hongf0f4a912019-09-26 17:51:33 -0700160 if (GetVirtualAbFeatureFlag().IsEnabled() && target_supports_snapshot_ &&
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700161 force_writable && ExpectMetadataMounted()) {
Yifan Hong420db9b2019-07-23 20:50:33 -0700162 // Only target partitions are mapped with force_writable. On Virtual
163 // A/B devices, target partitions may overlap with source partitions, so
164 // they must be mapped with snapshot.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700165 // One exception is when /metadata is not mounted. Fallback to
166 // CreateLogicalPartition as snapshots are not created in the first place.
Yifan Hong420db9b2019-07-23 20:50:33 -0700167 params.timeout_ms = kMapSnapshotTimeout;
168 success = snapshot_->MapUpdateSnapshot(params, path);
169 } else {
170 params.timeout_ms = kMapTimeout;
171 success = CreateLogicalPartition(params, path);
172 }
David Andersonbb90dfb2019-08-13 14:14:56 -0700173
Yifan Hong420db9b2019-07-23 20:50:33 -0700174 if (!success) {
Yifan Hong537802d2018-08-15 13:15:42 -0700175 LOG(ERROR) << "Cannot map " << target_partition_name << " in "
176 << super_device << " on device mapper.";
177 return false;
178 }
179 LOG(INFO) << "Succesfully mapped " << target_partition_name
Yifan Hongaf65ef12018-10-29 11:09:06 -0700180 << " to device mapper (force_writable = " << force_writable
181 << "); device path at " << *path;
Yifan Hong537802d2018-08-15 13:15:42 -0700182 mapped_devices_.insert(target_partition_name);
183 return true;
184}
185
Yifan Hong8546a712019-03-28 14:42:53 -0700186bool DynamicPartitionControlAndroid::MapPartitionOnDeviceMapper(
187 const std::string& super_device,
188 const std::string& target_partition_name,
189 uint32_t slot,
190 bool force_writable,
191 std::string* path) {
192 DmDeviceState state = GetState(target_partition_name);
193 if (state == DmDeviceState::ACTIVE) {
194 if (mapped_devices_.find(target_partition_name) != mapped_devices_.end()) {
195 if (GetDmDevicePathByName(target_partition_name, path)) {
196 LOG(INFO) << target_partition_name
197 << " is mapped on device mapper: " << *path;
198 return true;
199 }
200 LOG(ERROR) << target_partition_name << " is mapped but path is unknown.";
201 return false;
202 }
203 // If target_partition_name is not in mapped_devices_ but state is ACTIVE,
204 // the device might be mapped incorrectly before. Attempt to unmap it.
205 // Note that for source partitions, if GetState() == ACTIVE, callers (e.g.
206 // BootControlAndroid) should not call MapPartitionOnDeviceMapper, but
207 // should directly call GetDmDevicePathByName.
David Anderson4c891c92019-06-21 17:45:23 -0700208 if (!UnmapPartitionOnDeviceMapper(target_partition_name)) {
Yifan Hong8546a712019-03-28 14:42:53 -0700209 LOG(ERROR) << target_partition_name
210 << " is mapped before the update, and it cannot be unmapped.";
211 return false;
212 }
213 state = GetState(target_partition_name);
214 if (state != DmDeviceState::INVALID) {
215 LOG(ERROR) << target_partition_name << " is unmapped but state is "
216 << static_cast<std::underlying_type_t<DmDeviceState>>(state);
217 return false;
218 }
219 }
220 if (state == DmDeviceState::INVALID) {
221 return MapPartitionInternal(
222 super_device, target_partition_name, slot, force_writable, path);
223 }
224
225 LOG(ERROR) << target_partition_name
226 << " is mapped on device mapper but state is unknown: "
227 << static_cast<std::underlying_type_t<DmDeviceState>>(state);
228 return false;
229}
230
Yifan Hong537802d2018-08-15 13:15:42 -0700231bool DynamicPartitionControlAndroid::UnmapPartitionOnDeviceMapper(
David Anderson4c891c92019-06-21 17:45:23 -0700232 const std::string& target_partition_name) {
Yifan Hong537802d2018-08-15 13:15:42 -0700233 if (DeviceMapper::Instance().GetState(target_partition_name) !=
234 DmDeviceState::INVALID) {
Yifan Hong420db9b2019-07-23 20:50:33 -0700235 // Partitions at target slot on non-Virtual A/B devices are mapped as
236 // dm-linear. Also, on Virtual A/B devices, system_other may be mapped for
237 // preopt apps as dm-linear.
238 // Call DestroyLogicalPartition to handle these cases.
239 bool success = DestroyLogicalPartition(target_partition_name);
240
241 // On a Virtual A/B device, |target_partition_name| may be a leftover from
242 // a paused update. Clean up any underlying devices.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700243 if (ExpectMetadataMounted()) {
Yifan Hong420db9b2019-07-23 20:50:33 -0700244 success &= snapshot_->UnmapUpdateSnapshot(target_partition_name);
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700245 } else {
246 LOG(INFO) << "Skip UnmapUpdateSnapshot(" << target_partition_name
247 << ") because metadata is not mounted";
Yifan Hong420db9b2019-07-23 20:50:33 -0700248 }
249
250 if (!success) {
Yifan Hong537802d2018-08-15 13:15:42 -0700251 LOG(ERROR) << "Cannot unmap " << target_partition_name
252 << " from device mapper.";
253 return false;
254 }
255 LOG(INFO) << "Successfully unmapped " << target_partition_name
256 << " from device mapper.";
257 }
258 mapped_devices_.erase(target_partition_name);
259 return true;
260}
261
Yifan Hongbae27842019-10-24 16:56:12 -0700262void DynamicPartitionControlAndroid::UnmapAllPartitions() {
Tao Bao8c4d0082019-08-08 08:56:16 -0700263 if (mapped_devices_.empty()) {
264 return;
265 }
Yifan Hong537802d2018-08-15 13:15:42 -0700266 // UnmapPartitionOnDeviceMapper removes objects from mapped_devices_, hence
267 // a copy is needed for the loop.
268 std::set<std::string> mapped = mapped_devices_;
269 LOG(INFO) << "Destroying [" << Join(mapped, ", ") << "] from device mapper";
270 for (const auto& partition_name : mapped) {
David Anderson4c891c92019-06-21 17:45:23 -0700271 ignore_result(UnmapPartitionOnDeviceMapper(partition_name));
Yifan Hong537802d2018-08-15 13:15:42 -0700272 }
273}
274
275void DynamicPartitionControlAndroid::Cleanup() {
Yifan Hongbae27842019-10-24 16:56:12 -0700276 UnmapAllPartitions();
277 metadata_device_.reset();
Yifan Hong537802d2018-08-15 13:15:42 -0700278}
279
280bool DynamicPartitionControlAndroid::DeviceExists(const std::string& path) {
281 return base::PathExists(base::FilePath(path));
282}
283
284android::dm::DmDeviceState DynamicPartitionControlAndroid::GetState(
285 const std::string& name) {
286 return DeviceMapper::Instance().GetState(name);
287}
288
289bool DynamicPartitionControlAndroid::GetDmDevicePathByName(
290 const std::string& name, std::string* path) {
291 return DeviceMapper::Instance().GetDmDevicePathByName(name, path);
292}
293
294std::unique_ptr<MetadataBuilder>
295DynamicPartitionControlAndroid::LoadMetadataBuilder(
Yifan Hong012508e2019-07-22 18:30:40 -0700296 const std::string& super_device, uint32_t source_slot) {
297 return LoadMetadataBuilder(
298 super_device, source_slot, BootControlInterface::kInvalidSlot);
299}
300
301std::unique_ptr<MetadataBuilder>
302DynamicPartitionControlAndroid::LoadMetadataBuilder(
Yifan Hong6e706b12018-11-09 16:50:51 -0800303 const std::string& super_device,
304 uint32_t source_slot,
305 uint32_t target_slot) {
Yifan Hong30fa5f52019-08-05 16:39:59 -0700306 std::unique_ptr<MetadataBuilder> builder;
307 if (target_slot == BootControlInterface::kInvalidSlot) {
308 builder =
309 MetadataBuilder::New(PartitionOpener(), super_device, source_slot);
310 } else {
Yifan Hong50a56c62019-10-14 19:35:05 -0700311 bool always_keep_source_slot = !target_supports_snapshot_;
312 builder = MetadataBuilder::NewForUpdate(PartitionOpener(),
313 super_device,
314 source_slot,
315 target_slot,
316 always_keep_source_slot);
Yifan Hong30fa5f52019-08-05 16:39:59 -0700317 }
Yifan Hong6e706b12018-11-09 16:50:51 -0800318
Yifan Hong537802d2018-08-15 13:15:42 -0700319 if (builder == nullptr) {
320 LOG(WARNING) << "No metadata slot "
321 << BootControlInterface::SlotName(source_slot) << " in "
322 << super_device;
Yifan Hongf48a0052018-10-29 16:30:43 -0700323 return nullptr;
Yifan Hong537802d2018-08-15 13:15:42 -0700324 }
325 LOG(INFO) << "Loaded metadata from slot "
326 << BootControlInterface::SlotName(source_slot) << " in "
327 << super_device;
328 return builder;
329}
330
331bool DynamicPartitionControlAndroid::StoreMetadata(
332 const std::string& super_device,
333 MetadataBuilder* builder,
334 uint32_t target_slot) {
335 auto metadata = builder->Export();
336 if (metadata == nullptr) {
337 LOG(ERROR) << "Cannot export metadata to slot "
338 << BootControlInterface::SlotName(target_slot) << " in "
339 << super_device;
340 return false;
341 }
342
Yifan Hong186bb682019-07-23 14:04:39 -0700343 if (GetDynamicPartitionsFeatureFlag().IsRetrofit()) {
Yifan Hong6e706b12018-11-09 16:50:51 -0800344 if (!FlashPartitionTable(super_device, *metadata)) {
345 LOG(ERROR) << "Cannot write metadata to " << super_device;
346 return false;
347 }
348 LOG(INFO) << "Written metadata to " << super_device;
349 } else {
350 if (!UpdatePartitionTable(super_device, *metadata, target_slot)) {
351 LOG(ERROR) << "Cannot write metadata to slot "
352 << BootControlInterface::SlotName(target_slot) << " in "
353 << super_device;
354 return false;
355 }
356 LOG(INFO) << "Copied metadata to slot "
357 << BootControlInterface::SlotName(target_slot) << " in "
358 << super_device;
Yifan Hong537802d2018-08-15 13:15:42 -0700359 }
360
Yifan Hong537802d2018-08-15 13:15:42 -0700361 return true;
362}
363
364bool DynamicPartitionControlAndroid::GetDeviceDir(std::string* out) {
365 // We can't use fs_mgr to look up |partition_name| because fstab
366 // doesn't list every slot partition (it uses the slotselect option
367 // to mask the suffix).
368 //
369 // We can however assume that there's an entry for the /misc mount
370 // point and use that to get the device file for the misc
371 // partition. This helps us locate the disk that |partition_name|
372 // resides on. From there we'll assume that a by-name scheme is used
373 // so we can just replace the trailing "misc" by the given
374 // |partition_name| and suffix corresponding to |slot|, e.g.
375 //
376 // /dev/block/platform/soc.0/7824900.sdhci/by-name/misc ->
377 // /dev/block/platform/soc.0/7824900.sdhci/by-name/boot_a
378 //
379 // If needed, it's possible to relax the by-name assumption in the
380 // future by trawling /sys/block looking for the appropriate sibling
381 // of misc and then finding an entry in /dev matching the sysfs
382 // entry.
383
384 std::string err, misc_device = get_bootloader_message_blk_device(&err);
385 if (misc_device.empty()) {
386 LOG(ERROR) << "Unable to get misc block device: " << err;
387 return false;
388 }
389
390 if (!utils::IsSymlink(misc_device.c_str())) {
391 LOG(ERROR) << "Device file " << misc_device << " for /misc "
392 << "is not a symlink.";
393 return false;
394 }
395 *out = base::FilePath(misc_device).DirName().value();
396 return true;
397}
Yifan Hong012508e2019-07-22 18:30:40 -0700398
399bool DynamicPartitionControlAndroid::PreparePartitionsForUpdate(
400 uint32_t source_slot,
401 uint32_t target_slot,
Yifan Hongf0f4a912019-09-26 17:51:33 -0700402 const DeltaArchiveManifest& manifest,
Yifan Hongf033ecb2020-01-07 18:13:56 -0800403 bool update,
404 uint64_t* required_size) {
Yifan Hong6eec9952019-12-04 13:12:01 -0800405 source_slot_ = source_slot;
406 target_slot_ = target_slot;
Yifan Hongf033ecb2020-01-07 18:13:56 -0800407 if (required_size != nullptr) {
408 *required_size = 0;
409 }
Yifan Hong6eec9952019-12-04 13:12:01 -0800410
Yifan Hong3a1a5612019-11-05 16:34:32 -0800411 if (fs_mgr_overlayfs_is_setup()) {
412 // Non DAP devices can use overlayfs as well.
413 LOG(WARNING)
414 << "overlayfs overrides are active and can interfere with our "
415 "resources.\n"
416 << "run adb enable-verity to deactivate if required and try again.";
417 }
418
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700419 // If metadata is erased but not formatted, it is possible to not mount
420 // it in recovery. It is acceptable to skip mounting and choose fallback path
421 // (PrepareDynamicPartitionsForUpdate) when sideloading full OTAs.
422 TEST_AND_RETURN_FALSE(EnsureMetadataMounted() || IsRecovery());
Yifan Hong29692902020-03-26 12:47:05 -0700423
424 if (update) {
425 TEST_AND_RETURN_FALSE(EraseSystemOtherAvbFooter(source_slot, target_slot));
426 }
427
Yifan Hong3a1a5612019-11-05 16:34:32 -0800428 if (!GetDynamicPartitionsFeatureFlag().IsEnabled()) {
429 return true;
430 }
431
432 if (target_slot == source_slot) {
433 LOG(ERROR) << "Cannot call PreparePartitionsForUpdate on current slot.";
434 return false;
435 }
436
437 // Although the current build supports dynamic partitions, the given payload
438 // doesn't use it for target partitions. This could happen when applying a
439 // retrofit update. Skip updating the partition metadata for the target slot.
440 is_target_dynamic_ = !manifest.dynamic_partition_metadata().groups().empty();
441 if (!is_target_dynamic_) {
442 return true;
443 }
444
Yifan Hongf0f4a912019-09-26 17:51:33 -0700445 target_supports_snapshot_ =
446 manifest.dynamic_partition_metadata().snapshot_enabled();
447
448 if (!update)
449 return true;
450
Yifan Hongbae27842019-10-24 16:56:12 -0700451 bool delete_source = false;
452
Yifan Hong6d888562019-10-01 13:00:31 -0700453 if (GetVirtualAbFeatureFlag().IsEnabled()) {
454 // On Virtual A/B device, either CancelUpdate() or BeginUpdate() must be
455 // called before calling UnmapUpdateSnapshot.
456 // - If target_supports_snapshot_, PrepareSnapshotPartitionsForUpdate()
457 // calls BeginUpdate() which resets update state
Yifan Hongbae27842019-10-24 16:56:12 -0700458 // - If !target_supports_snapshot_ or PrepareSnapshotPartitionsForUpdate
459 // failed in recovery, explicitly CancelUpdate().
Yifan Hong6d888562019-10-01 13:00:31 -0700460 if (target_supports_snapshot_) {
Yifan Hongbae27842019-10-24 16:56:12 -0700461 if (PrepareSnapshotPartitionsForUpdate(
462 source_slot, target_slot, manifest, required_size)) {
463 return true;
464 }
465
466 // Virtual A/B device doing Virtual A/B update in Android mode must use
467 // snapshots.
468 if (!IsRecovery()) {
469 LOG(ERROR) << "PrepareSnapshotPartitionsForUpdate failed in Android "
470 << "mode";
471 return false;
472 }
473
474 delete_source = true;
475 LOG(INFO) << "PrepareSnapshotPartitionsForUpdate failed in recovery. "
476 << "Attempt to overwrite existing partitions if possible";
477 } else {
478 // Downgrading to an non-Virtual A/B build or is secondary OTA.
479 LOG(INFO) << "Using regular A/B on Virtual A/B because package disabled "
480 << "snapshots.";
Yifan Hong6d888562019-10-01 13:00:31 -0700481 }
Yifan Hongbae27842019-10-24 16:56:12 -0700482
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700483 // In recovery, if /metadata is not mounted, it is likely that metadata
484 // partition is erased and not formatted yet. After sideloading, when
485 // rebooting into the new version, init will erase metadata partition,
486 // hence the failure of CancelUpdate() can be ignored here.
487 // However, if metadata is mounted and CancelUpdate fails, sideloading
488 // should not proceed because during next boot, snapshots will overlay on
489 // the devices incorrectly.
490 if (ExpectMetadataMounted()) {
491 TEST_AND_RETURN_FALSE(snapshot_->CancelUpdate());
492 } else {
493 LOG(INFO) << "Skip canceling previous update because metadata is not "
494 << "mounted";
Yifan Hong6d888562019-10-01 13:00:31 -0700495 }
Yifan Hong420db9b2019-07-23 20:50:33 -0700496 }
Yifan Hongbae27842019-10-24 16:56:12 -0700497
Yifan Hong5c5743f2020-04-16 12:59:07 -0700498 TEST_AND_RETURN_FALSE(PrepareDynamicPartitionsForUpdate(
499 source_slot, target_slot, manifest, delete_source));
500
501 if (required_size != nullptr) {
502 *required_size = 0;
503 }
504 return true;
Yifan Hong420db9b2019-07-23 20:50:33 -0700505}
506
Yifan Hong29692902020-03-26 12:47:05 -0700507namespace {
508// Try our best to erase AVB footer.
509class AvbFooterEraser {
510 public:
511 explicit AvbFooterEraser(const std::string& path) : path_(path) {}
512 bool Erase() {
513 // Try to mark the block device read-only. Ignore any
514 // failure since this won't work when passing regular files.
515 ignore_result(utils::SetBlockDeviceReadOnly(path_, false /* readonly */));
516
517 fd_.reset(new EintrSafeFileDescriptor());
518 int flags = O_WRONLY | O_TRUNC | O_CLOEXEC | O_SYNC;
519 TEST_AND_RETURN_FALSE(fd_->Open(path_.c_str(), flags));
520
521 // Need to write end-AVB_FOOTER_SIZE to end.
522 static_assert(AVB_FOOTER_SIZE > 0);
523 off64_t offset = fd_->Seek(-AVB_FOOTER_SIZE, SEEK_END);
524 TEST_AND_RETURN_FALSE_ERRNO(offset >= 0);
525 uint64_t write_size = AVB_FOOTER_SIZE;
526 LOG(INFO) << "Zeroing " << path_ << " @ [" << offset << ", "
527 << (offset + write_size) << "] (" << write_size << " bytes)";
528 brillo::Blob zeros(write_size);
529 TEST_AND_RETURN_FALSE(utils::WriteAll(fd_, zeros.data(), zeros.size()));
530 return true;
531 }
532 ~AvbFooterEraser() {
533 TEST_AND_RETURN(fd_ != nullptr && fd_->IsOpen());
534 if (!fd_->Close()) {
535 LOG(WARNING) << "Failed to close fd for " << path_;
536 }
537 }
538
539 private:
540 std::string path_;
541 FileDescriptorPtr fd_;
542};
543
544} // namespace
545
546std::optional<bool>
547DynamicPartitionControlAndroid::IsAvbEnabledOnSystemOther() {
548 auto prefix = GetProperty(kPostinstallFstabPrefix, "");
549 if (prefix.empty()) {
550 LOG(WARNING) << "Cannot get " << kPostinstallFstabPrefix;
551 return std::nullopt;
552 }
553 auto path = base::FilePath(prefix).Append("etc/fstab.postinstall").value();
554 return IsAvbEnabledInFstab(path);
555}
556
557std::optional<bool> DynamicPartitionControlAndroid::IsAvbEnabledInFstab(
558 const std::string& path) {
559 Fstab fstab;
560 if (!ReadFstabFromFile(path, &fstab)) {
Yifan Hong93cde302020-04-27 12:59:29 -0700561 PLOG(WARNING) << "Cannot read fstab from " << path;
562 if (errno == ENOENT) {
563 return false;
564 }
Yifan Hong29692902020-03-26 12:47:05 -0700565 return std::nullopt;
566 }
567 for (const auto& entry : fstab) {
568 if (!entry.avb_keys.empty()) {
569 return true;
570 }
571 }
572 return false;
573}
574
575bool DynamicPartitionControlAndroid::GetSystemOtherPath(
576 uint32_t source_slot,
577 uint32_t target_slot,
578 const std::string& partition_name_suffix,
579 std::string* path,
580 bool* should_unmap) {
581 path->clear();
582 *should_unmap = false;
583
P.Adarsh Reddy13e4195d2020-06-08 23:17:36 +0530584 // Check that AVB is enabled on system_other before erasing.
585 auto has_avb = IsAvbEnabledOnSystemOther();
586 TEST_AND_RETURN_FALSE(has_avb.has_value());
587 if (!has_avb.value()) {
588 LOG(INFO) << "AVB is not enabled on system_other. Skip erasing.";
589 return true;
590 }
Yifan Hong29692902020-03-26 12:47:05 -0700591
P.Adarsh Reddy13e4195d2020-06-08 23:17:36 +0530592 if (!IsRecovery()) {
Yifan Hong29692902020-03-26 12:47:05 -0700593 // Found unexpected avb_keys for system_other on devices retrofitting
594 // dynamic partitions. Previous crash in update_engine may leave logical
595 // partitions mapped on physical system_other partition. It is difficult to
596 // handle these cases. Just fail.
597 if (GetDynamicPartitionsFeatureFlag().IsRetrofit()) {
598 LOG(ERROR) << "Cannot erase AVB footer on system_other on devices with "
599 << "retrofit dynamic partitions. They should not have AVB "
600 << "enabled on system_other.";
601 return false;
602 }
603 }
604
605 std::string device_dir_str;
606 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
607 base::FilePath device_dir(device_dir_str);
608
609 // On devices without dynamic partition, search for static partitions.
610 if (!GetDynamicPartitionsFeatureFlag().IsEnabled()) {
611 *path = device_dir.Append(partition_name_suffix).value();
612 TEST_AND_RETURN_FALSE(DeviceExists(*path));
613 return true;
614 }
615
616 auto source_super_device =
617 device_dir.Append(GetSuperPartitionName(source_slot)).value();
618
619 auto builder = LoadMetadataBuilder(source_super_device, source_slot);
620 if (builder == nullptr) {
621 if (IsRecovery()) {
622 // It might be corrupted for some reason. It should still be able to
623 // sideload.
624 LOG(WARNING) << "Super partition metadata cannot be read from the source "
625 << "slot, skip erasing.";
626 return true;
627 } else {
628 // Device has booted into Android mode, indicating that the super
629 // partition metadata should be there.
630 LOG(ERROR) << "Super partition metadata cannot be read from the source "
631 << "slot. This is unexpected on devices with dynamic "
632 << "partitions enabled.";
633 return false;
634 }
635 }
636 auto p = builder->FindPartition(partition_name_suffix);
637 if (p == nullptr) {
638 // If the source slot is flashed without system_other, it does not exist
639 // in super partition metadata at source slot. It is safe to skip it.
640 LOG(INFO) << "Can't find " << partition_name_suffix
641 << " in metadata source slot, skip erasing.";
642 return true;
643 }
644 // System_other created by flashing tools should be erased.
645 // If partition is created by update_engine (via NewForUpdate), it is a
646 // left-over partition from the previous update and does not contain
647 // system_other, hence there is no need to erase.
648 // Note the reverse is not necessary true. If the flag is not set, we don't
649 // know if the partition is created by update_engine or by flashing tools
650 // because older versions of super partition metadata does not contain this
651 // flag. It is okay to erase the AVB footer anyways.
652 if (p->attributes() & LP_PARTITION_ATTR_UPDATED) {
653 LOG(INFO) << partition_name_suffix
654 << " does not contain system_other, skip erasing.";
655 return true;
656 }
657
Yifan Hong64331b32020-05-13 16:50:40 -0700658 if (p->size() < AVB_FOOTER_SIZE) {
659 LOG(INFO) << partition_name_suffix << " has length " << p->size()
660 << "( < AVB_FOOTER_SIZE " << AVB_FOOTER_SIZE
661 << "), skip erasing.";
662 return true;
663 }
664
Yifan Hong29692902020-03-26 12:47:05 -0700665 // Delete any pre-existing device with name |partition_name_suffix| and
666 // also remove it from |mapped_devices_|.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700667 // In recovery, metadata might not be mounted, and
668 // UnmapPartitionOnDeviceMapper might fail. However,
669 // it is unusual that system_other has already been mapped. Hence, just skip.
Yifan Hong29692902020-03-26 12:47:05 -0700670 TEST_AND_RETURN_FALSE(UnmapPartitionOnDeviceMapper(partition_name_suffix));
671 // Use CreateLogicalPartition directly to avoid mapping with existing
672 // snapshots.
673 CreateLogicalPartitionParams params = {
674 .block_device = source_super_device,
675 .metadata_slot = source_slot,
676 .partition_name = partition_name_suffix,
677 .force_writable = true,
678 .timeout_ms = kMapTimeout,
679 };
680 TEST_AND_RETURN_FALSE(CreateLogicalPartition(params, path));
681 *should_unmap = true;
682 return true;
683}
684
685bool DynamicPartitionControlAndroid::EraseSystemOtherAvbFooter(
686 uint32_t source_slot, uint32_t target_slot) {
687 LOG(INFO) << "Erasing AVB footer of system_other partition before update.";
688
689 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
690 const std::string partition_name_suffix = "system" + target_suffix;
691
692 std::string path;
693 bool should_unmap = false;
694
695 TEST_AND_RETURN_FALSE(GetSystemOtherPath(
696 source_slot, target_slot, partition_name_suffix, &path, &should_unmap));
697
698 if (path.empty()) {
699 return true;
700 }
701
702 bool ret = AvbFooterEraser(path).Erase();
703
704 // Delete |partition_name_suffix| from device mapper and from
705 // |mapped_devices_| again so that it does not interfere with update process.
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700706 // In recovery, metadata might not be mounted, and
707 // UnmapPartitionOnDeviceMapper might fail. However, DestroyLogicalPartition
708 // should be called. If DestroyLogicalPartition does fail, it is still okay
709 // to skip the error here and let Prepare*() fail later.
Yifan Hong29692902020-03-26 12:47:05 -0700710 if (should_unmap) {
711 TEST_AND_RETURN_FALSE(UnmapPartitionOnDeviceMapper(partition_name_suffix));
712 }
713
714 return ret;
715}
716
Yifan Hong420db9b2019-07-23 20:50:33 -0700717bool DynamicPartitionControlAndroid::PrepareDynamicPartitionsForUpdate(
718 uint32_t source_slot,
719 uint32_t target_slot,
Yifan Hongbae27842019-10-24 16:56:12 -0700720 const DeltaArchiveManifest& manifest,
721 bool delete_source) {
Yifan Hong012508e2019-07-22 18:30:40 -0700722 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
723
724 // Unmap all the target dynamic partitions because they would become
725 // inconsistent with the new metadata.
Yifan Hong13d41cb2019-09-16 13:18:22 -0700726 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
727 for (const auto& partition_name : group.partition_names()) {
728 if (!UnmapPartitionOnDeviceMapper(partition_name + target_suffix)) {
Yifan Hong012508e2019-07-22 18:30:40 -0700729 return false;
730 }
731 }
732 }
733
734 std::string device_dir_str;
735 if (!GetDeviceDir(&device_dir_str)) {
736 return false;
737 }
738 base::FilePath device_dir(device_dir_str);
739 auto source_device =
Yifan Hong700d7c12019-07-23 20:49:16 -0700740 device_dir.Append(GetSuperPartitionName(source_slot)).value();
Yifan Hong012508e2019-07-22 18:30:40 -0700741
742 auto builder = LoadMetadataBuilder(source_device, source_slot, target_slot);
743 if (builder == nullptr) {
744 LOG(ERROR) << "No metadata at "
745 << BootControlInterface::SlotName(source_slot);
746 return false;
747 }
748
Yifan Hongbae27842019-10-24 16:56:12 -0700749 if (delete_source) {
750 TEST_AND_RETURN_FALSE(
751 DeleteSourcePartitions(builder.get(), source_slot, manifest));
752 }
753
Yifan Hong13d41cb2019-09-16 13:18:22 -0700754 if (!UpdatePartitionMetadata(builder.get(), target_slot, manifest)) {
Yifan Hong012508e2019-07-22 18:30:40 -0700755 return false;
756 }
757
758 auto target_device =
Yifan Hong700d7c12019-07-23 20:49:16 -0700759 device_dir.Append(GetSuperPartitionName(target_slot)).value();
Yifan Hong012508e2019-07-22 18:30:40 -0700760 return StoreMetadata(target_device, builder.get(), target_slot);
761}
762
Yifan Hong420db9b2019-07-23 20:50:33 -0700763bool DynamicPartitionControlAndroid::PrepareSnapshotPartitionsForUpdate(
764 uint32_t source_slot,
765 uint32_t target_slot,
Yifan Hongf033ecb2020-01-07 18:13:56 -0800766 const DeltaArchiveManifest& manifest,
767 uint64_t* required_size) {
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700768 TEST_AND_RETURN_FALSE(ExpectMetadataMounted());
Yifan Hong420db9b2019-07-23 20:50:33 -0700769 if (!snapshot_->BeginUpdate()) {
770 LOG(ERROR) << "Cannot begin new update.";
771 return false;
772 }
Yifan Hongf033ecb2020-01-07 18:13:56 -0800773 auto ret = snapshot_->CreateUpdateSnapshots(manifest);
774 if (!ret) {
775 LOG(ERROR) << "Cannot create update snapshots: " << ret.string();
776 if (required_size != nullptr &&
Yifan Hong0850bca2020-01-16 15:14:07 -0800777 ret.error_code() == Return::ErrorCode::NO_SPACE) {
Yifan Hongf033ecb2020-01-07 18:13:56 -0800778 *required_size = ret.required_size();
779 }
Yifan Hong420db9b2019-07-23 20:50:33 -0700780 return false;
781 }
782 return true;
783}
784
Yifan Hong700d7c12019-07-23 20:49:16 -0700785std::string DynamicPartitionControlAndroid::GetSuperPartitionName(
786 uint32_t slot) {
787 return fs_mgr_get_super_partition_name(slot);
788}
789
Yifan Hong012508e2019-07-22 18:30:40 -0700790bool DynamicPartitionControlAndroid::UpdatePartitionMetadata(
791 MetadataBuilder* builder,
792 uint32_t target_slot,
Yifan Hong13d41cb2019-09-16 13:18:22 -0700793 const DeltaArchiveManifest& manifest) {
Yifan Honga4e7da32019-09-30 18:25:03 -0700794 // If applying downgrade from Virtual A/B to non-Virtual A/B, the left-over
795 // COW group needs to be deleted to ensure there are enough space to create
796 // target partitions.
797 builder->RemoveGroupAndPartitions(android::snapshot::kCowGroupName);
798
Yifan Hong012508e2019-07-22 18:30:40 -0700799 const std::string target_suffix = SlotSuffixForSlotNumber(target_slot);
800 DeleteGroupsWithSuffix(builder, target_suffix);
801
802 uint64_t total_size = 0;
Yifan Hong13d41cb2019-09-16 13:18:22 -0700803 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
804 total_size += group.size();
Yifan Hong012508e2019-07-22 18:30:40 -0700805 }
806
807 std::string expr;
808 uint64_t allocatable_space = builder->AllocatableSpace();
Yifan Hong186bb682019-07-23 14:04:39 -0700809 if (!GetDynamicPartitionsFeatureFlag().IsRetrofit()) {
Yifan Hong012508e2019-07-22 18:30:40 -0700810 allocatable_space /= 2;
811 expr = "half of ";
812 }
813 if (total_size > allocatable_space) {
814 LOG(ERROR) << "The maximum size of all groups with suffix " << target_suffix
815 << " (" << total_size << ") has exceeded " << expr
816 << "allocatable space for dynamic partitions "
817 << allocatable_space << ".";
818 return false;
819 }
820
Yifan Hong13d41cb2019-09-16 13:18:22 -0700821 // name of partition(e.g. "system") -> size in bytes
822 std::map<std::string, uint64_t> partition_sizes;
823 for (const auto& partition : manifest.partitions()) {
824 partition_sizes.emplace(partition.partition_name(),
825 partition.new_partition_info().size());
826 }
827
828 for (const auto& group : manifest.dynamic_partition_metadata().groups()) {
829 auto group_name_suffix = group.name() + target_suffix;
830 if (!builder->AddGroup(group_name_suffix, group.size())) {
Yifan Hong012508e2019-07-22 18:30:40 -0700831 LOG(ERROR) << "Cannot add group " << group_name_suffix << " with size "
Yifan Hong13d41cb2019-09-16 13:18:22 -0700832 << group.size();
Yifan Hong012508e2019-07-22 18:30:40 -0700833 return false;
834 }
835 LOG(INFO) << "Added group " << group_name_suffix << " with size "
Yifan Hong13d41cb2019-09-16 13:18:22 -0700836 << group.size();
Yifan Hong012508e2019-07-22 18:30:40 -0700837
Yifan Hong13d41cb2019-09-16 13:18:22 -0700838 for (const auto& partition_name : group.partition_names()) {
839 auto partition_sizes_it = partition_sizes.find(partition_name);
840 if (partition_sizes_it == partition_sizes.end()) {
841 // TODO(tbao): Support auto-filling partition info for framework-only
842 // OTA.
843 LOG(ERROR) << "dynamic_partition_metadata contains partition "
844 << partition_name << " but it is not part of the manifest. "
845 << "This is not supported.";
846 return false;
847 }
848 uint64_t partition_size = partition_sizes_it->second;
849
850 auto partition_name_suffix = partition_name + target_suffix;
Yifan Hong012508e2019-07-22 18:30:40 -0700851 Partition* p = builder->AddPartition(
852 partition_name_suffix, group_name_suffix, LP_PARTITION_ATTR_READONLY);
853 if (!p) {
854 LOG(ERROR) << "Cannot add partition " << partition_name_suffix
855 << " to group " << group_name_suffix;
856 return false;
857 }
Yifan Hong13d41cb2019-09-16 13:18:22 -0700858 if (!builder->ResizePartition(p, partition_size)) {
Yifan Hong012508e2019-07-22 18:30:40 -0700859 LOG(ERROR) << "Cannot resize partition " << partition_name_suffix
Yifan Hong13d41cb2019-09-16 13:18:22 -0700860 << " to size " << partition_size << ". Not enough space?";
Yifan Hong012508e2019-07-22 18:30:40 -0700861 return false;
862 }
863 LOG(INFO) << "Added partition " << partition_name_suffix << " to group "
Yifan Hong13d41cb2019-09-16 13:18:22 -0700864 << group_name_suffix << " with size " << partition_size;
Yifan Hong012508e2019-07-22 18:30:40 -0700865 }
866 }
867
868 return true;
869}
870
Yifan Hong7b3910a2020-03-24 17:47:32 -0700871bool DynamicPartitionControlAndroid::FinishUpdate(bool powerwash_required) {
Yifan Hong4d7c5eb2020-04-03 11:31:50 -0700872 if (ExpectMetadataMounted()) {
873 if (snapshot_->GetUpdateState() == UpdateState::Initiated) {
874 LOG(INFO) << "Snapshot writes are done.";
875 return snapshot_->FinishedSnapshotWrites(powerwash_required);
876 }
877 } else {
878 LOG(INFO) << "Skip FinishedSnapshotWrites() because /metadata is not "
879 << "mounted";
Yifan Hongf0f4a912019-09-26 17:51:33 -0700880 }
881 return true;
Yifan Honga33bca42019-09-03 20:29:45 -0700882}
883
Yifan Hong3a1a5612019-11-05 16:34:32 -0800884bool DynamicPartitionControlAndroid::GetPartitionDevice(
885 const std::string& partition_name,
886 uint32_t slot,
887 uint32_t current_slot,
Tianjie51a5a392020-06-03 14:39:32 -0700888 bool not_in_payload,
889 std::string* device,
890 bool* is_dynamic) {
Yifan Hong3a1a5612019-11-05 16:34:32 -0800891 const auto& partition_name_suffix =
892 partition_name + SlotSuffixForSlotNumber(slot);
893 std::string device_dir_str;
894 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
895 base::FilePath device_dir(device_dir_str);
896
Tianjie51a5a392020-06-03 14:39:32 -0700897 if (is_dynamic) {
898 *is_dynamic = false;
899 }
900
Yifan Hong3a1a5612019-11-05 16:34:32 -0800901 // When looking up target partition devices, treat them as static if the
902 // current payload doesn't encode them as dynamic partitions. This may happen
903 // when applying a retrofit update on top of a dynamic-partitions-enabled
904 // build.
905 if (GetDynamicPartitionsFeatureFlag().IsEnabled() &&
906 (slot == current_slot || is_target_dynamic_)) {
Tianjie51a5a392020-06-03 14:39:32 -0700907 switch (GetDynamicPartitionDevice(device_dir,
908 partition_name_suffix,
909 slot,
910 current_slot,
911 not_in_payload,
912 device)) {
Yifan Hong3a1a5612019-11-05 16:34:32 -0800913 case DynamicPartitionDeviceStatus::SUCCESS:
Tianjie51a5a392020-06-03 14:39:32 -0700914 if (is_dynamic) {
915 *is_dynamic = true;
916 }
Yifan Hong3a1a5612019-11-05 16:34:32 -0800917 return true;
918 case DynamicPartitionDeviceStatus::TRY_STATIC:
919 break;
920 case DynamicPartitionDeviceStatus::ERROR: // fallthrough
921 default:
922 return false;
923 }
924 }
925 base::FilePath path = device_dir.Append(partition_name_suffix);
926 if (!DeviceExists(path.value())) {
927 LOG(ERROR) << "Device file " << path.value() << " does not exist.";
928 return false;
929 }
930
931 *device = path.value();
932 return true;
933}
934
Tianjie51a5a392020-06-03 14:39:32 -0700935bool DynamicPartitionControlAndroid::GetPartitionDevice(
936 const std::string& partition_name,
937 uint32_t slot,
938 uint32_t current_slot,
939 std::string* device) {
940 return GetPartitionDevice(
941 partition_name, slot, current_slot, false, device, nullptr);
942}
943
Yifan Hong3a1a5612019-11-05 16:34:32 -0800944bool DynamicPartitionControlAndroid::IsSuperBlockDevice(
945 const base::FilePath& device_dir,
946 uint32_t current_slot,
947 const std::string& partition_name_suffix) {
948 std::string source_device =
949 device_dir.Append(GetSuperPartitionName(current_slot)).value();
950 auto source_metadata = LoadMetadataBuilder(source_device, current_slot);
951 return source_metadata->HasBlockDevice(partition_name_suffix);
952}
953
954DynamicPartitionControlAndroid::DynamicPartitionDeviceStatus
955DynamicPartitionControlAndroid::GetDynamicPartitionDevice(
956 const base::FilePath& device_dir,
957 const std::string& partition_name_suffix,
958 uint32_t slot,
959 uint32_t current_slot,
Tianjie51a5a392020-06-03 14:39:32 -0700960 bool not_in_payload,
Yifan Hong3a1a5612019-11-05 16:34:32 -0800961 std::string* device) {
962 std::string super_device =
963 device_dir.Append(GetSuperPartitionName(slot)).value();
964
965 auto builder = LoadMetadataBuilder(super_device, slot);
966 if (builder == nullptr) {
967 LOG(ERROR) << "No metadata in slot "
968 << BootControlInterface::SlotName(slot);
969 return DynamicPartitionDeviceStatus::ERROR;
970 }
971 if (builder->FindPartition(partition_name_suffix) == nullptr) {
972 LOG(INFO) << partition_name_suffix
973 << " is not in super partition metadata.";
974
975 if (IsSuperBlockDevice(device_dir, current_slot, partition_name_suffix)) {
976 LOG(ERROR) << "The static partition " << partition_name_suffix
977 << " is a block device for current metadata."
978 << "It cannot be used as a logical partition.";
979 return DynamicPartitionDeviceStatus::ERROR;
980 }
981
982 return DynamicPartitionDeviceStatus::TRY_STATIC;
983 }
984
985 if (slot == current_slot) {
986 if (GetState(partition_name_suffix) != DmDeviceState::ACTIVE) {
987 LOG(WARNING) << partition_name_suffix << " is at current slot but it is "
988 << "not mapped. Now try to map it.";
989 } else {
990 if (GetDmDevicePathByName(partition_name_suffix, device)) {
991 LOG(INFO) << partition_name_suffix
992 << " is mapped on device mapper: " << *device;
993 return DynamicPartitionDeviceStatus::SUCCESS;
994 }
995 LOG(ERROR) << partition_name_suffix << "is mapped but path is unknown.";
996 return DynamicPartitionDeviceStatus::ERROR;
997 }
998 }
999
Tianjie51a5a392020-06-03 14:39:32 -07001000 bool force_writable = (slot != current_slot) && !not_in_payload;
Yifan Hong3a1a5612019-11-05 16:34:32 -08001001 if (MapPartitionOnDeviceMapper(
1002 super_device, partition_name_suffix, slot, force_writable, device)) {
1003 return DynamicPartitionDeviceStatus::SUCCESS;
1004 }
1005 return DynamicPartitionDeviceStatus::ERROR;
1006}
1007
Yifan Hong6eec9952019-12-04 13:12:01 -08001008void DynamicPartitionControlAndroid::set_fake_mapped_devices(
1009 const std::set<std::string>& fake) {
1010 mapped_devices_ = fake;
1011}
1012
Yifan Hongbae27842019-10-24 16:56:12 -07001013bool DynamicPartitionControlAndroid::IsRecovery() {
1014 return kIsRecovery;
1015}
1016
1017static bool IsIncrementalUpdate(const DeltaArchiveManifest& manifest) {
1018 const auto& partitions = manifest.partitions();
1019 return std::any_of(partitions.begin(), partitions.end(), [](const auto& p) {
1020 return p.has_old_partition_info();
1021 });
1022}
1023
1024bool DynamicPartitionControlAndroid::DeleteSourcePartitions(
1025 MetadataBuilder* builder,
1026 uint32_t source_slot,
1027 const DeltaArchiveManifest& manifest) {
1028 TEST_AND_RETURN_FALSE(IsRecovery());
1029
1030 if (IsIncrementalUpdate(manifest)) {
1031 LOG(ERROR) << "Cannot sideload incremental OTA because snapshots cannot "
1032 << "be created.";
1033 if (GetVirtualAbFeatureFlag().IsLaunch()) {
1034 LOG(ERROR) << "Sideloading incremental updates on devices launches "
1035 << " Virtual A/B is not supported.";
1036 }
1037 return false;
1038 }
1039
1040 LOG(INFO) << "Will overwrite existing partitions. Slot "
1041 << BootControlInterface::SlotName(source_slot)
1042 << "may be unbootable until update finishes!";
1043 const std::string source_suffix = SlotSuffixForSlotNumber(source_slot);
1044 DeleteGroupsWithSuffix(builder, source_suffix);
1045
1046 return true;
1047}
1048
Yifan Hong90965502020-02-19 15:22:47 -08001049std::unique_ptr<AbstractAction>
1050DynamicPartitionControlAndroid::GetCleanupPreviousUpdateAction(
1051 BootControlInterface* boot_control,
1052 PrefsInterface* prefs,
1053 CleanupPreviousUpdateActionDelegateInterface* delegate) {
1054 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1055 return std::make_unique<NoOpAction>();
1056 }
1057 return std::make_unique<CleanupPreviousUpdateAction>(
1058 prefs, boot_control, snapshot_.get(), delegate);
1059}
1060
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001061bool DynamicPartitionControlAndroid::ResetUpdate(PrefsInterface* prefs) {
1062 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1063 return true;
1064 }
1065
1066 LOG(INFO) << __func__ << " resetting update state and deleting snapshots.";
1067 TEST_AND_RETURN_FALSE(prefs != nullptr);
1068
1069 // If the device has already booted into the target slot,
1070 // ResetUpdateProgress may pass but CancelUpdate fails.
1071 // This is expected. A scheduled CleanupPreviousUpdateAction should free
1072 // space when it is done.
1073 TEST_AND_RETURN_FALSE(DeltaPerformer::ResetUpdateProgress(
1074 prefs, false /* quick */, false /* skip dynamic partitions metadata */));
1075
Yifan Hong4d7c5eb2020-04-03 11:31:50 -07001076 if (ExpectMetadataMounted()) {
1077 TEST_AND_RETURN_FALSE(snapshot_->CancelUpdate());
1078 } else {
1079 LOG(INFO) << "Skip cancelling update in ResetUpdate because /metadata is "
1080 << "not mounted";
1081 }
Yifan Hong6a6d0f12020-03-11 13:20:52 -07001082
1083 return true;
1084}
1085
Tianjie99d570d2020-06-04 14:57:19 -07001086bool DynamicPartitionControlAndroid::ListDynamicPartitionsForSlot(
1087 uint32_t current_slot, std::vector<std::string>* partitions) {
1088 if (!GetDynamicPartitionsFeatureFlag().IsEnabled()) {
1089 LOG(ERROR) << "Dynamic partition is not enabled";
1090 return false;
1091 }
1092
1093 std::string device_dir_str;
1094 TEST_AND_RETURN_FALSE(GetDeviceDir(&device_dir_str));
1095 base::FilePath device_dir(device_dir_str);
1096 auto super_device =
1097 device_dir.Append(GetSuperPartitionName(current_slot)).value();
1098 auto builder = LoadMetadataBuilder(super_device, current_slot);
1099 TEST_AND_RETURN_FALSE(builder != nullptr);
1100
1101 std::vector<std::string> result;
1102 auto suffix = SlotSuffixForSlotNumber(current_slot);
1103 for (const auto& group : builder->ListGroups()) {
1104 for (const auto& partition : builder->ListPartitionsInGroup(group)) {
1105 std::string_view partition_name = partition->name();
1106 if (!android::base::ConsumeSuffix(&partition_name, suffix)) {
1107 continue;
1108 }
1109 result.emplace_back(partition_name);
1110 }
1111 }
1112 *partitions = std::move(result);
1113 return true;
1114}
1115
Yifan Hong4d7c5eb2020-04-03 11:31:50 -07001116bool DynamicPartitionControlAndroid::ExpectMetadataMounted() {
1117 // No need to mount metadata for non-Virtual A/B devices.
1118 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1119 return false;
1120 }
1121 // Intentionally not checking |metadata_device_| in Android mode.
1122 // /metadata should always be mounted in Android mode. If it isn't, let caller
1123 // fails when calling into SnapshotManager.
1124 if (!IsRecovery()) {
1125 return true;
1126 }
1127 // In recovery mode, explicitly check |metadata_device_|.
1128 return metadata_device_ != nullptr;
1129}
1130
1131bool DynamicPartitionControlAndroid::EnsureMetadataMounted() {
1132 // No need to mount metadata for non-Virtual A/B devices.
1133 if (!GetVirtualAbFeatureFlag().IsEnabled()) {
1134 return true;
1135 }
1136
1137 if (metadata_device_ == nullptr) {
1138 metadata_device_ = snapshot_->EnsureMetadataMounted();
1139 }
1140 return metadata_device_ != nullptr;
1141}
1142
Yifan Hong537802d2018-08-15 13:15:42 -07001143} // namespace chromeos_update_engine