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